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
  */
 
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
 
279dc407
 #include <openjpeg.h>
e749b5dd
 
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;
 
12a83bc0
 static void error_callback(const char *msg, void *data)
 {
     av_log(data, AV_LOG_ERROR, "%s", msg);
 }
 
 static void warning_callback(const char *msg, void *data)
 {
     av_log(data, AV_LOG_WARNING, "%s", msg);
 }
 
 static void info_callback(const char *msg, void *data)
 {
     av_log(data, AV_LOG_DEBUG, "%s", msg);
 }
 
99eabcdd
 typedef struct BufferReader {
     int pos;
     int size;
     const uint8_t *buffer;
 } BufferReader;
 
 static OPJ_SIZE_T stream_read(void *out_buffer, OPJ_SIZE_T nb_bytes, void *user_data)
 {
     BufferReader *reader = user_data;
21cd0228
     int remaining;
 
99eabcdd
     if (reader->pos == reader->size) {
         return (OPJ_SIZE_T)-1;
     }
21cd0228
     remaining = reader->size - reader->pos;
99eabcdd
     if (nb_bytes > remaining) {
         nb_bytes = remaining;
     }
     memcpy(out_buffer, reader->buffer + reader->pos, nb_bytes);
     reader->pos += (int)nb_bytes;
     return nb_bytes;
 }
 
 static OPJ_OFF_T stream_skip(OPJ_OFF_T nb_bytes, void *user_data)
 {
     BufferReader *reader = user_data;
     if (nb_bytes < 0) {
         if (reader->pos == 0) {
             return (OPJ_SIZE_T)-1;
         }
         if (nb_bytes + reader->pos < 0) {
             nb_bytes = -reader->pos;
         }
     } else {
21cd0228
         int remaining;
 
99eabcdd
         if (reader->pos == reader->size) {
             return (OPJ_SIZE_T)-1;
         }
21cd0228
         remaining = reader->size - reader->pos;
99eabcdd
         if (nb_bytes > remaining) {
             nb_bytes = remaining;
         }
     }
     reader->pos += (int)nb_bytes;
     return nb_bytes;
 }
 
 static OPJ_BOOL stream_seek(OPJ_OFF_T nb_bytes, void *user_data)
 {
     BufferReader *reader = user_data;
     if (nb_bytes < 0 || nb_bytes > reader->size) {
         return OPJ_FALSE;
     }
     reader->pos = (int)nb_bytes;
     return OPJ_TRUE;
 }
 
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 &&
151aa2eb
                 desc->comp[3].depth >= image->comps[3].prec &&
543a46e0
                 1 == image->comps[3].dx &&
                 1 == image->comps[3].dy;
44dc9c6a
     case 3:
         match = match &&
151aa2eb
                 desc->comp[2].depth >= image->comps[2].prec &&
543a46e0
                 1 << desc->log2_chroma_w == image->comps[2].dx &&
                 1 << desc->log2_chroma_h == image->comps[2].dy;
44dc9c6a
     case 2:
         match = match &&
151aa2eb
                 desc->comp[1].depth >= image->comps[1].prec &&
543a46e0
                 1 << desc->log2_chroma_w == image->comps[1].dx &&
                 1 << desc->log2_chroma_h == image->comps[1].dy;
44dc9c6a
     case 1:
         match = match &&
151aa2eb
                 desc->comp[0].depth >= image->comps[0].prec &&
543a46e0
                 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) {
279dc407
     case OPJ_CLRSPC_SRGB:
543a46e0
         possible_fmts    = libopenjpeg_rgb_pix_fmts;
32759812
         possible_fmts_nb = FF_ARRAY_ELEMS(libopenjpeg_rgb_pix_fmts);
b7a928b2
         break;
279dc407
     case OPJ_CLRSPC_GRAY:
543a46e0
         possible_fmts    = libopenjpeg_gray_pix_fmts;
32759812
         possible_fmts_nb = FF_ARRAY_ELEMS(libopenjpeg_gray_pix_fmts);
b7a928b2
         break;
279dc407
     case OPJ_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++)
5d8e836d
         adjust[x] = FFMAX(FFMIN(desc->comp[x].depth - 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++)
5d8e836d
         adjust[x] = FFMAX(FFMIN(desc->comp[x].depth - 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;
5c0a0983
     int width, height, ret;
eb511ef6
     int pixel_size = 0;
1ea9fa15
     int ispacked   = 0;
1f2f031c
     int i;
99eabcdd
     opj_image_t *image = NULL;
     BufferReader reader = {0, avpkt->size, avpkt->data};
     opj_codec_t *dec = NULL;
     opj_stream_t *stream = NULL;
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)) {
279dc407
         dec = opj_create_decompress(OPJ_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;
279dc407
         dec = opj_create_decompress(OPJ_CODEC_J2K);
9a77d59a
     }
 
51a5ddfa
     if (!dec) {
9a77d59a
         av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");
99eabcdd
         ret = AVERROR_EXTERNAL;
         goto done;
9a77d59a
     }
99eabcdd
 
     if (!opj_set_error_handler(dec, error_callback, avctx) ||
         !opj_set_warning_handler(dec, warning_callback, avctx) ||
         !opj_set_info_handler(dec, info_callback, avctx)) {
         av_log(avctx, AV_LOG_ERROR, "Error setting decoder handlers.\n");
         ret = AVERROR_EXTERNAL;
         goto done;
     }
 
     ctx->dec_params.cp_layer = ctx->lowqual;
     ctx->dec_params.cp_reduce = avctx->lowres;
 
9a77d59a
     // Tie decoder with decoding parameters
     opj_setup_decoder(dec, &ctx->dec_params);
99eabcdd
 
     stream = opj_stream_default_create(OPJ_STREAM_READ);
51a5ddfa
 
     if (!stream) {
         av_log(avctx, AV_LOG_ERROR,
                "Codestream could not be opened for reading.\n");
99eabcdd
         ret = AVERROR_EXTERNAL;
         goto done;
9a77d59a
     }
 
99eabcdd
     opj_stream_set_read_function(stream, stream_read);
     opj_stream_set_skip_function(stream, stream_skip);
     opj_stream_set_seek_function(stream, stream_seek);
     opj_stream_set_user_data(stream, &reader, NULL);
     opj_stream_set_user_data_length(stream, avpkt->size);
     // Decode the header only.
     ret = !opj_read_header(stream, dec, &image);
51a5ddfa
 
99eabcdd
     if (ret) {
         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream header.\n");
         ret = AVERROR_EXTERNAL;
         goto done;
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) {
99eabcdd
         av_log(avctx, AV_LOG_ERROR, "Unable to determine pixel format.\n");
         ret = AVERROR_UNKNOWN;
b7a928b2
         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
 
99eabcdd
     ret = !opj_decode(dec, stream, image);
b8bb9c02
 
99eabcdd
     if (ret) {
02fb320a
         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
99eabcdd
         ret = AVERROR_EXTERNAL;
3dc0b9d6
         goto done;
02fb320a
     }
f65c6f75
 
3ef57029
     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);
2268db2c
     pixel_size = desc->comp[0].step;
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:
67deba8a
         avpriv_report_missing_feature(avctx, "Pixel size %d", pixel_size);
5c0a0983
         ret = AVERROR_PATCHWELCOME;
eb511ef6
         goto done;
9a77d59a
     }
 
df9b9567
     *got_frame = 1;
616513ef
     picture->pict_type = AV_PICTURE_TYPE_I;
     picture->key_frame = 1;
51a5ddfa
     ret        = buf_size;
9a77d59a
 
 done:
     opj_image_destroy(image);
99eabcdd
     opj_stream_destroy(stream);
     opj_destroy_codec(dec);
9a77d59a
     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,
def97856
     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
543a46e0
     .max_lowres     = 31,
     .priv_class     = &openjpeg_class,
b945fed6
     .wrapper_name   = "libopenjpeg",
86714887
 };