libavcodec/libopenjpegdec.c
9a77d59a
 /*
  * JPEG 2000 decoding support via OpenJPEG
  * Copyright (c) 2009 Jaikrishnan Menon <realityman@gmx.net>
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
51a5ddfa
  * @file
  * JPEG 2000 decoder using libopenjpeg
  */
 
 #define  OPJ_STATIC
9a77d59a
 
7ebe3962
 #include "libavutil/common.h"
7ffe76e5
 #include "libavutil/imgutils.h"
1ea9fa15
 #include "libavutil/intreadwrite.h"
51a5ddfa
 #include "libavutil/opt.h"
1ea9fa15
 #include "libavutil/pixfmt.h"
 
51a5ddfa
 #include "avcodec.h"
967cd6fa
 #include "internal.h"
f65c6f75
 #include "thread.h"
9a77d59a
 
e749b5dd
 #if HAVE_OPENJPEG_1_5_OPENJPEG_H
 # include <openjpeg-1.5/openjpeg.h>
 #else
 # include <openjpeg.h>
 #endif
 
9a77d59a
 #define JP2_SIG_TYPE    0x6A502020
 #define JP2_SIG_VALUE   0x0D0A870A
 
6d376346
 // pix_fmts with lower bpp have to be listed before
 // similar pix_fmts with higher bpp.
1ea9fa15
 #define RGB_PIXEL_FORMATS  AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,                 \
543a46e0
                            AV_PIX_FMT_RGB48, AV_PIX_FMT_RGBA64
716d413c
 
e96c3b81
 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8, AV_PIX_FMT_YA8,                  \
f018b1f3
                            AV_PIX_FMT_GRAY16, AV_PIX_FMT_YA16
716d413c
 
543a46e0
 #define YUV_PIXEL_FORMATS  AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUVA420P, \
                            AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUVA422P, \
                            AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA444P, \
                            AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9, \
                            AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA444P9, \
                            AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10, \
                            AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA444P10, \
                            AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12, \
                            AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV444P14, \
                            AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16, \
                            AV_PIX_FMT_YUVA420P16, AV_PIX_FMT_YUVA422P16, AV_PIX_FMT_YUVA444P16
ac627b3d
 
28a807e2
 #define XYZ_PIXEL_FORMATS  AV_PIX_FMT_XYZ12
 
543a46e0
 static const enum AVPixelFormat libopenjpeg_rgb_pix_fmts[]  = {
1ea9fa15
     RGB_PIXEL_FORMATS
 };
543a46e0
 static const enum AVPixelFormat libopenjpeg_gray_pix_fmts[] = {
1ea9fa15
     GRAY_PIXEL_FORMATS
 };
543a46e0
 static const enum AVPixelFormat libopenjpeg_yuv_pix_fmts[]  = {
1ea9fa15
     YUV_PIXEL_FORMATS
 };
543a46e0
 static const enum AVPixelFormat libopenjpeg_all_pix_fmts[]  = {
1ea9fa15
     RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS
 };
b7a928b2
 
7f9f771e
 typedef struct LibOpenJPEGContext {
ce64e5bf
     AVClass *class;
9a77d59a
     opj_dparameters_t dec_params;
ce64e5bf
     int lowqual;
9a77d59a
 } LibOpenJPEGContext;
 
ac627b3d
 static inline int libopenjpeg_matches_pix_fmt(const opj_image_t *image, enum AVPixelFormat pix_fmt)
9a77d59a
 {
50ba57e0
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
b7a928b2
     int match = 1;
d76864d9
 
af7dd79a
     if (desc->nb_components != image->numcomps) {
b7a928b2
         return 0;
eb511ef6
     }
 
50ba57e0
     switch (desc->nb_components) {
44dc9c6a
     case 4:
         match = match &&
543a46e0
                 desc->comp[3].depth_minus1 + 1 >= image->comps[3].prec &&
                 1 == image->comps[3].dx &&
                 1 == image->comps[3].dy;
44dc9c6a
     case 3:
         match = match &&
543a46e0
                 desc->comp[2].depth_minus1 + 1 >= image->comps[2].prec &&
                 1 << desc->log2_chroma_w == image->comps[2].dx &&
                 1 << desc->log2_chroma_h == image->comps[2].dy;
44dc9c6a
     case 2:
         match = match &&
543a46e0
                 desc->comp[1].depth_minus1 + 1 >= image->comps[1].prec &&
                 1 << desc->log2_chroma_w == image->comps[1].dx &&
                 1 << desc->log2_chroma_h == image->comps[1].dy;
44dc9c6a
     case 1:
         match = match &&
543a46e0
                 desc->comp[0].depth_minus1 + 1 >= image->comps[0].prec &&
                 1 == image->comps[0].dx &&
                 1 == image->comps[0].dy;
b7a928b2
     default:
         break;
eb511ef6
     }
 
b7a928b2
     return match;
 }
eb511ef6
 
ac627b3d
 static inline enum AVPixelFormat libopenjpeg_guess_pix_fmt(const opj_image_t *image) {
b7a928b2
     int index;
716d413c
     const enum AVPixelFormat *possible_fmts = NULL;
b7a928b2
     int possible_fmts_nb = 0;
 
     switch (image->color_space) {
     case CLRSPC_SRGB:
543a46e0
         possible_fmts    = libopenjpeg_rgb_pix_fmts;
32759812
         possible_fmts_nb = FF_ARRAY_ELEMS(libopenjpeg_rgb_pix_fmts);
b7a928b2
         break;
     case CLRSPC_GRAY:
543a46e0
         possible_fmts    = libopenjpeg_gray_pix_fmts;
32759812
         possible_fmts_nb = FF_ARRAY_ELEMS(libopenjpeg_gray_pix_fmts);
b7a928b2
         break;
     case CLRSPC_SYCC:
543a46e0
         possible_fmts    = libopenjpeg_yuv_pix_fmts;
32759812
         possible_fmts_nb = FF_ARRAY_ELEMS(libopenjpeg_yuv_pix_fmts);
b7a928b2
         break;
     default:
543a46e0
         possible_fmts    = libopenjpeg_all_pix_fmts;
32759812
         possible_fmts_nb = FF_ARRAY_ELEMS(libopenjpeg_all_pix_fmts);
b7a928b2
         break;
eb511ef6
     }
0d4a7747
 
1ea9fa15
     for (index = 0; index < possible_fmts_nb; ++index)
b7a928b2
         if (libopenjpeg_matches_pix_fmt(image, possible_fmts[index])) {
             return possible_fmts[index];
         }
0d4a7747
 
716d413c
     return AV_PIX_FMT_NONE;
eb511ef6
 }
 
716d413c
 static inline int libopenjpeg_ispacked(enum AVPixelFormat pix_fmt)
44dc9c6a
 {
50ba57e0
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
eb511ef6
     int i, component_plane;
a6501620
 
716d413c
     if (pix_fmt == AV_PIX_FMT_GRAY16)
a6501620
         return 0;
 
50ba57e0
     component_plane = desc->comp[0].plane;
1ea9fa15
     for (i = 1; i < desc->nb_components; i++)
50ba57e0
         if (component_plane != desc->comp[i].plane)
eb511ef6
             return 0;
     return 1;
 }
 
 static inline void libopenjpeg_copy_to_packed8(AVFrame *picture, opj_image_t *image) {
     uint8_t *img_ptr;
     int index, x, y, c;
9023de34
     for (y = 0; y < picture->height; y++) {
1ea9fa15
         index   = y * picture->width;
         img_ptr = picture->data[0] + y * picture->linesize[0];
         for (x = 0; x < picture->width; x++, index++)
             for (c = 0; c < image->numcomps; c++)
8b7cce44
                 *img_ptr++ = 0x80 * image->comps[c].sgnd + image->comps[c].data[index];
eb511ef6
     }
 }
 
0d4a7747
 static inline void libopenjpeg_copy_to_packed16(AVFrame *picture, opj_image_t *image) {
     uint16_t *img_ptr;
ff6b0814
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(picture->format);
0d4a7747
     int index, x, y, c;
     int adjust[4];
9023de34
     for (x = 0; x < image->numcomps; x++)
ff6b0814
         adjust[x] = FFMAX(FFMIN(desc->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0) + desc->comp[x].shift;
9023de34
 
0d4a7747
     for (y = 0; y < picture->height; y++) {
1ea9fa15
         index   = y * picture->width;
         img_ptr = (uint16_t *) (picture->data[0] + y * picture->linesize[0]);
         for (x = 0; x < picture->width; x++, index++)
             for (c = 0; c < image->numcomps; c++)
05e5bb61
                 *img_ptr++ = (1 << image->comps[c].prec - 1) * image->comps[c].sgnd +
                              (unsigned)image->comps[c].data[index] << adjust[c];
0d4a7747
     }
 }
 
eb511ef6
 static inline void libopenjpeg_copyto8(AVFrame *picture, opj_image_t *image) {
     int *comp_data;
     uint8_t *img_ptr;
     int index, x, y;
 
9023de34
     for (index = 0; index < image->numcomps; index++) {
eb511ef6
         comp_data = image->comps[index].data;
9023de34
         for (y = 0; y < image->comps[index].h; y++) {
d1669e5f
             img_ptr = picture->data[index] + y * picture->linesize[index];
9023de34
             for (x = 0; x < image->comps[index].w; x++) {
8b7cce44
                 *img_ptr = 0x80 * image->comps[index].sgnd + *comp_data;
eb511ef6
                 img_ptr++;
                 comp_data++;
             }
         }
     }
 }
 
 static inline void libopenjpeg_copyto16(AVFrame *picture, opj_image_t *image) {
     int *comp_data;
     uint16_t *img_ptr;
ff6b0814
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(picture->format);
eb511ef6
     int index, x, y;
7412a4a4
     int adjust[4];
     for (x = 0; x < image->numcomps; x++)
ff6b0814
         adjust[x] = FFMAX(FFMIN(desc->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0) + desc->comp[x].shift;
7412a4a4
 
9023de34
     for (index = 0; index < image->numcomps; index++) {
eb511ef6
         comp_data = image->comps[index].data;
9023de34
         for (y = 0; y < image->comps[index].h; y++) {
543a46e0
             img_ptr = (uint16_t *)(picture->data[index] + y * picture->linesize[index]);
9023de34
             for (x = 0; x < image->comps[index].w; x++) {
05e5bb61
                 *img_ptr = (1 << image->comps[index].prec - 1) * image->comps[index].sgnd +
                            (unsigned)*comp_data << adjust[index];
eb511ef6
                 img_ptr++;
                 comp_data++;
             }
         }
     }
9a77d59a
 }
 
 static av_cold int libopenjpeg_decode_init(AVCodecContext *avctx)
 {
     LibOpenJPEGContext *ctx = avctx->priv_data;
 
     opj_set_default_decoder_parameters(&ctx->dec_params);
f65c6f75
     return 0;
 }
 
9a77d59a
 static int libopenjpeg_decode_frame(AVCodecContext *avctx,
df9b9567
                                     void *data, int *got_frame,
7a00bbad
                                     AVPacket *avpkt)
9a77d59a
 {
1ea9fa15
     uint8_t *buf            = avpkt->data;
     int buf_size            = avpkt->size;
9a77d59a
     LibOpenJPEGContext *ctx = avctx->priv_data;
1ea9fa15
     ThreadFrame frame       = { .f = data };
     AVFrame *picture        = data;
50ba57e0
     const AVPixFmtDescriptor *desc;
9a77d59a
     opj_dinfo_t *dec;
     opj_cio_t *stream;
     opj_image_t *image;
5c0a0983
     int width, height, ret;
eb511ef6
     int pixel_size = 0;
1ea9fa15
     int ispacked   = 0;
1f2f031c
     int i;
9a77d59a
 
df9b9567
     *got_frame = 0;
9a77d59a
 
     // Check if input is a raw jpeg2k codestream or in jp2 wrapping
1ea9fa15
     if ((AV_RB32(buf) == 12) &&
51a5ddfa
         (AV_RB32(buf + 4) == JP2_SIG_TYPE) &&
         (AV_RB32(buf + 8) == JP2_SIG_VALUE)) {
b70b1588
         dec = opj_create_decompress(CODEC_JP2);
9a77d59a
     } else {
51a5ddfa
         /* If the AVPacket contains a jp2c box, then skip to
          * the starting byte of the codestream. */
09bad7e3
         if (AV_RB32(buf + 4) == AV_RB32("jp2c"))
             buf += 8;
b70b1588
         dec = opj_create_decompress(CODEC_J2K);
9a77d59a
     }
 
51a5ddfa
     if (!dec) {
9a77d59a
         av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");
5c0a0983
         return AVERROR_UNKNOWN;
9a77d59a
     }
1ea9fa15
     opj_set_event_mgr((opj_common_ptr) dec, NULL, NULL);
f65c6f75
     ctx->dec_params.cp_limit_decoding = LIMIT_TO_MAIN_HEADER;
51a5ddfa
     ctx->dec_params.cp_layer          = ctx->lowqual;
9a77d59a
     // Tie decoder with decoding parameters
     opj_setup_decoder(dec, &ctx->dec_params);
1ea9fa15
     stream = opj_cio_open((opj_common_ptr) dec, buf, buf_size);
51a5ddfa
 
     if (!stream) {
         av_log(avctx, AV_LOG_ERROR,
                "Codestream could not be opened for reading.\n");
9a77d59a
         opj_destroy_decompress(dec);
5c0a0983
         return AVERROR_UNKNOWN;
9a77d59a
     }
 
51a5ddfa
     // Decode the header only.
9a77d59a
     image = opj_decode_with_info(dec, stream, NULL);
     opj_cio_close(stream);
51a5ddfa
 
     if (!image) {
9a77d59a
         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
         opj_destroy_decompress(dec);
5c0a0983
         return AVERROR_UNKNOWN;
9a77d59a
     }
51a5ddfa
 
f65c6f75
     width  = image->x1 - image->x0;
     height = image->y1 - image->y0;
ce64e5bf
 
967cd6fa
     ret = ff_set_dimensions(avctx, width, height);
     if (ret < 0)
9a77d59a
         goto done;
 
716d413c
     if (avctx->pix_fmt != AV_PIX_FMT_NONE)
44dc9c6a
         if (!libopenjpeg_matches_pix_fmt(image, avctx->pix_fmt))
716d413c
             avctx->pix_fmt = AV_PIX_FMT_NONE;
b7a928b2
 
716d413c
     if (avctx->pix_fmt == AV_PIX_FMT_NONE)
b7a928b2
         avctx->pix_fmt = libopenjpeg_guess_pix_fmt(image);
 
716d413c
     if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
b7a928b2
         av_log(avctx, AV_LOG_ERROR, "Unable to determine pixel format\n");
         goto done;
9a77d59a
     }
1f2f031c
     for (i = 0; i < image->numcomps; i++)
         if (image->comps[i].prec > avctx->bits_per_raw_sample)
             avctx->bits_per_raw_sample = image->comps[i].prec;
9a77d59a
 
4427fe7e
     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
3dc0b9d6
         goto done;
9a77d59a
 
f65c6f75
     ctx->dec_params.cp_limit_decoding = NO_LIMITATION;
70d54392
     ctx->dec_params.cp_reduce = avctx->lowres;
51a5ddfa
     // Tie decoder with decoding parameters.
f65c6f75
     opj_setup_decoder(dec, &ctx->dec_params);
1ea9fa15
     stream = opj_cio_open((opj_common_ptr) dec, buf, buf_size);
51a5ddfa
     if (!stream) {
         av_log(avctx, AV_LOG_ERROR,
                "Codestream could not be opened for reading.\n");
5c0a0983
         ret = AVERROR_UNKNOWN;
3dc0b9d6
         goto done;
9a77d59a
     }
 
3dc0b9d6
     opj_image_destroy(image);
44dc9c6a
     // Decode the codestream
f65c6f75
     image = opj_decode_with_info(dec, stream, NULL);
     opj_cio_close(stream);
b8bb9c02
 
9023de34
     if (!image) {
02fb320a
         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
5c0a0983
         ret = AVERROR_UNKNOWN;
3dc0b9d6
         goto done;
02fb320a
     }
f65c6f75
 
c7ef69c2
     for (i = 0; i < image->numcomps; i++) {
         if (!image->comps[i].data) {
             av_log(avctx, AV_LOG_ERROR,
                    "Image component %d contains no data.\n", i);
             ret = AVERROR_INVALIDDATA;
             goto done;
         }
     }
 
1ea9fa15
     desc       = av_pix_fmt_desc_get(avctx->pix_fmt);
50ba57e0
     pixel_size = desc->comp[0].step_minus1 + 1;
1ea9fa15
     ispacked   = libopenjpeg_ispacked(avctx->pix_fmt);
9a77d59a
 
eb511ef6
     switch (pixel_size) {
     case 1:
         if (ispacked) {
             libopenjpeg_copy_to_packed8(picture, image);
         } else {
             libopenjpeg_copyto8(picture, image);
9a77d59a
         }
eb511ef6
         break;
     case 2:
ec0d02e4
         if (ispacked) {
             libopenjpeg_copy_to_packed8(picture, image);
         } else {
             libopenjpeg_copyto16(picture, image);
         }
eb511ef6
         break;
     case 3:
3f07ef1d
     case 4:
eb511ef6
         if (ispacked) {
             libopenjpeg_copy_to_packed8(picture, image);
         }
         break;
0d4a7747
     case 6:
d76864d9
     case 8:
0d4a7747
         if (ispacked) {
             libopenjpeg_copy_to_packed16(picture, image);
         }
         break;
eb511ef6
     default:
         av_log(avctx, AV_LOG_ERROR, "unsupported pixel size %d\n", pixel_size);
5c0a0983
         ret = AVERROR_PATCHWELCOME;
eb511ef6
         goto done;
9a77d59a
     }
 
df9b9567
     *got_frame = 1;
51a5ddfa
     ret        = buf_size;
9a77d59a
 
 done:
     opj_image_destroy(image);
     opj_destroy_decompress(dec);
     return ret;
 }
 
ce64e5bf
 #define OFFSET(x) offsetof(LibOpenJPEGContext, x)
 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
 
 static const AVOption options[] = {
1ea9fa15
     { "lowqual", "Limit the number of layers used for decoding",
         OFFSET(lowqual), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
ce64e5bf
     { NULL },
 };
 
bf18abb2
 static const AVClass openjpeg_class = {
ce64e5bf
     .class_name = "libopenjpeg",
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
9a77d59a
 
e7e2df27
 AVCodec ff_libopenjpeg_decoder = {
1ea9fa15
     .name           = "libopenjpeg",
     .long_name      = NULL_IF_CONFIG_SMALL("OpenJPEG JPEG 2000"),
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = AV_CODEC_ID_JPEG2000,
     .priv_data_size = sizeof(LibOpenJPEGContext),
     .init           = libopenjpeg_decode_init,
     .decode         = libopenjpeg_decode_frame,
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
543a46e0
     .max_lowres     = 31,
     .priv_class     = &openjpeg_class,
86714887
 };