]> git.sesse.net Git - ffmpeg/blob - libavcodec/libopenjpegdec.c
libopenjpeg: Add support for XYZ colorspace, found in DCINEMA frames
[ffmpeg] / libavcodec / libopenjpegdec.c
1 /*
2  * JPEG 2000 decoding support via OpenJPEG
3  * Copyright (c) 2009 Jaikrishnan Menon <realityman@gmx.net>
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * JPEG 2000 decoder using libopenjpeg
25  */
26
27 #define  OPJ_STATIC
28 #include <openjpeg.h>
29
30 #include "libavutil/common.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/pixfmt.h"
34 #include "libavutil/opt.h"
35 #include "avcodec.h"
36 #include "thread.h"
37
38 #define JP2_SIG_TYPE    0x6A502020
39 #define JP2_SIG_VALUE   0x0D0A870A
40
41 // pix_fmts with lower bpp have to be listed before
42 // similar pix_fmts with higher bpp.
43 #define RGB_PIXEL_FORMATS  AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,  \
44                            AV_PIX_FMT_RGB48
45
46 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8, AV_PIX_FMT_Y400A, \
47                            AV_PIX_FMT_GRAY16
48
49 #define YUV_PIXEL_FORMATS  AV_PIX_FMT_YUV410P,   AV_PIX_FMT_YUV411P,   \
50                            AV_PIX_FMT_YUVA420P, \
51                            AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUV422P,   \
52                            AV_PIX_FMT_YUV440P,   AV_PIX_FMT_YUV444P,   \
53                            AV_PIX_FMT_YUV420P9,  AV_PIX_FMT_YUV422P9,  \
54                            AV_PIX_FMT_YUV444P9, \
55                            AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, \
56                            AV_PIX_FMT_YUV444P10, \
57                            AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, \
58                            AV_PIX_FMT_YUV444P16
59
60 #define XYZ_PIXEL_FORMATS  AV_PIX_FMT_XYZ12
61
62 static const enum AVPixelFormat rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
63 static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
64 static const enum AVPixelFormat yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
65 static const enum AVPixelFormat any_pix_fmts[]  = {RGB_PIXEL_FORMATS,
66                                                  GRAY_PIXEL_FORMATS,
67                                                  YUV_PIXEL_FORMATS,
68                                                  XYZ_PIXEL_FORMATS};
69
70 typedef struct {
71     AVClass *class;
72     opj_dparameters_t dec_params;
73     int lowres;
74     int lowqual;
75 } LibOpenJPEGContext;
76
77 static int libopenjpeg_matches_pix_fmt(const opj_image_t *img,
78                                        enum AVPixelFormat pix_fmt)
79 {
80     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
81     int match = 1;
82
83     if (desc->nb_components != img->numcomps) {
84         return 0;
85     }
86
87     switch (desc->nb_components) {
88     case 4:
89         match = match &&
90             desc->comp[3].depth_minus1 + 1 >= img->comps[3].prec &&
91             1 == img->comps[3].dx &&
92             1 == img->comps[3].dy;
93     case 3:
94         match = match &&
95             desc->comp[2].depth_minus1 + 1 >= img->comps[2].prec &&
96             1 << desc->log2_chroma_w == img->comps[2].dx &&
97             1 << desc->log2_chroma_h == img->comps[2].dy;
98     case 2:
99         match = match &&
100             desc->comp[1].depth_minus1 + 1 >= img->comps[1].prec &&
101             1 << desc->log2_chroma_w == img->comps[1].dx &&
102             1 << desc->log2_chroma_h == img->comps[1].dy;
103     case 1:
104         match = match &&
105             desc->comp[0].depth_minus1 + 1 >= img->comps[0].prec &&
106             1 == img->comps[0].dx &&
107             1 == img->comps[0].dy;
108     default:
109         break;
110     }
111
112     return match;
113 }
114
115 static enum AVPixelFormat libopenjpeg_guess_pix_fmt(const opj_image_t *image)
116 {
117     int index;
118     const enum AVPixelFormat *possible_fmts = NULL;
119     int possible_fmts_nb = 0;
120
121     switch (image->color_space) {
122     case CLRSPC_SRGB:
123         possible_fmts = rgb_pix_fmts;
124         possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
125         break;
126     case CLRSPC_GRAY:
127         possible_fmts = gray_pix_fmts;
128         possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
129         break;
130     case CLRSPC_SYCC:
131         possible_fmts = yuv_pix_fmts;
132         possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
133         break;
134     default:
135         possible_fmts = any_pix_fmts;
136         possible_fmts_nb = FF_ARRAY_ELEMS(any_pix_fmts);
137         break;
138     }
139
140     for (index = 0; index < possible_fmts_nb; ++index) {
141         if (libopenjpeg_matches_pix_fmt(image, possible_fmts[index])) {
142             return possible_fmts[index];
143         }
144     }
145
146     return AV_PIX_FMT_NONE;
147 }
148
149 static inline int libopenjpeg_ispacked(enum AVPixelFormat pix_fmt)
150 {
151     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
152     int i, component_plane;
153
154     if (pix_fmt == AV_PIX_FMT_GRAY16)
155         return 0;
156
157     component_plane = desc->comp[0].plane;
158     for (i = 1; i < desc->nb_components; i++) {
159         if (component_plane != desc->comp[i].plane)
160             return 0;
161     }
162     return 1;
163 }
164
165 static void libopenjpeg_copy_to_packed8(AVFrame *picture, opj_image_t *image)
166 {
167     uint8_t *img_ptr;
168     int index, x, y, c;
169
170     for (y = 0; y < picture->height; y++) {
171         index = y*picture->width;
172         img_ptr = picture->data[0] + y*picture->linesize[0];
173         for (x = 0; x < picture->width; x++, index++) {
174             for (c = 0; c < image->numcomps; c++) {
175                 *img_ptr++ = image->comps[c].data[index];
176             }
177         }
178     }
179 }
180
181 static void libopenjpeg_copy_to_packed16(AVFrame *picture, opj_image_t *image)
182 {
183     uint16_t *img_ptr;
184     int index, x, y, c;
185     int adjust[4];
186
187     for (x = 0; x < image->numcomps; x++)
188         adjust[x] = FFMAX(FFMIN(16 - image->comps[x].prec, 8), 0);
189
190     for (y = 0; y < picture->height; y++) {
191         index = y*picture->width;
192         img_ptr = (uint16_t*) (picture->data[0] + y*picture->linesize[0]);
193         for (x = 0; x < picture->width; x++, index++) {
194             for (c = 0; c < image->numcomps; c++) {
195                 *img_ptr++ = image->comps[c].data[index] << adjust[c];
196             }
197         }
198     }
199 }
200
201 static void libopenjpeg_copyto8(AVFrame *picture, opj_image_t *image)
202 {
203     int *comp_data;
204     uint8_t *img_ptr;
205     int index, x, y;
206
207     for (index = 0; index < image->numcomps; index++) {
208         comp_data = image->comps[index].data;
209         for (y = 0; y < image->comps[index].h; y++) {
210             img_ptr = picture->data[index] + y * picture->linesize[index];
211             for (x = 0; x < image->comps[index].w; x++) {
212                 *img_ptr = (uint8_t) *comp_data;
213                 img_ptr++;
214                 comp_data++;
215             }
216         }
217     }
218 }
219
220 static void libopenjpeg_copyto16(AVFrame *p, opj_image_t *image)
221 {
222     int *comp_data;
223     uint16_t *img_ptr;
224     int index, x, y;
225
226     for (index = 0; index < image->numcomps; index++) {
227         comp_data = image->comps[index].data;
228         for (y = 0; y < image->comps[index].h; y++) {
229             img_ptr = (uint16_t*) (p->data[index] + y * p->linesize[index]);
230             for (x = 0; x < image->comps[index].w; x++) {
231                 *img_ptr = *comp_data;
232                 img_ptr++;
233                 comp_data++;
234             }
235         }
236     }
237 }
238
239 static av_cold int libopenjpeg_decode_init(AVCodecContext *avctx)
240 {
241     LibOpenJPEGContext *ctx = avctx->priv_data;
242
243     opj_set_default_decoder_parameters(&ctx->dec_params);
244     return 0;
245 }
246
247 static int libopenjpeg_decode_frame(AVCodecContext *avctx,
248                                     void *data, int *got_frame,
249                                     AVPacket *avpkt)
250 {
251     uint8_t *buf = avpkt->data;
252     int buf_size = avpkt->size;
253     LibOpenJPEGContext *ctx = avctx->priv_data;
254     ThreadFrame frame = { .f = data };
255     AVFrame *picture  = data;
256     const AVPixFmtDescriptor *desc;
257     opj_dinfo_t *dec;
258     opj_cio_t *stream;
259     opj_image_t *image;
260     int width, height, ret = -1;
261     int pixel_size = 0;
262     int ispacked = 0;
263     int i;
264
265     *got_frame = 0;
266
267     // Check if input is a raw jpeg2k codestream or in jp2 wrapping
268     if ((AV_RB32(buf)     == 12)           &&
269         (AV_RB32(buf + 4) == JP2_SIG_TYPE) &&
270         (AV_RB32(buf + 8) == JP2_SIG_VALUE)) {
271         dec = opj_create_decompress(CODEC_JP2);
272     } else {
273         /* If the AVPacket contains a jp2c box, then skip to
274          * the starting byte of the codestream. */
275         if (AV_RB32(buf + 4) == AV_RB32("jp2c"))
276             buf += 8;
277         dec = opj_create_decompress(CODEC_J2K);
278     }
279
280     if (!dec) {
281         av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");
282         return -1;
283     }
284     opj_set_event_mgr((opj_common_ptr)dec, NULL, NULL);
285
286     ctx->dec_params.cp_limit_decoding = LIMIT_TO_MAIN_HEADER;
287     ctx->dec_params.cp_reduce         = ctx->lowres;
288     ctx->dec_params.cp_layer          = ctx->lowqual;
289     // Tie decoder with decoding parameters
290     opj_setup_decoder(dec, &ctx->dec_params);
291     stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
292
293     if (!stream) {
294         av_log(avctx, AV_LOG_ERROR,
295                "Codestream could not be opened for reading.\n");
296         opj_destroy_decompress(dec);
297         return -1;
298     }
299
300     // Decode the header only.
301     image = opj_decode_with_info(dec, stream, NULL);
302     opj_cio_close(stream);
303
304     if (!image) {
305         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
306         opj_destroy_decompress(dec);
307         return -1;
308     }
309
310     width  = image->x1 - image->x0;
311     height = image->y1 - image->y0;
312
313     if (ctx->lowres) {
314         width  = (width  + (1 << ctx->lowres) - 1) >> ctx->lowres;
315         height = (height + (1 << ctx->lowres) - 1) >> ctx->lowres;
316     }
317
318     if (av_image_check_size(width, height, 0, avctx) < 0) {
319         av_log(avctx, AV_LOG_ERROR,
320                "%dx%d dimension invalid.\n", width, height);
321         goto done;
322     }
323
324     avcodec_set_dimensions(avctx, width, height);
325
326     if (avctx->pix_fmt != AV_PIX_FMT_NONE)
327         if (!libopenjpeg_matches_pix_fmt(image, avctx->pix_fmt))
328             avctx->pix_fmt = AV_PIX_FMT_NONE;
329
330     if (avctx->pix_fmt == AV_PIX_FMT_NONE)
331         avctx->pix_fmt = libopenjpeg_guess_pix_fmt(image);
332
333     if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
334         av_log(avctx, AV_LOG_ERROR, "Unable to determine pixel format\n");
335         ret = AVERROR_INVALIDDATA;
336         goto done;
337     }
338
339     for (i = 0; i < image->numcomps; i++)
340         if (image->comps[i].prec > avctx->bits_per_raw_sample)
341             avctx->bits_per_raw_sample = image->comps[i].prec;
342
343     if (ff_thread_get_buffer(avctx, &frame, 0) < 0) {
344         av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed\n");
345         goto done;
346     }
347
348     ctx->dec_params.cp_limit_decoding = NO_LIMITATION;
349     // Tie decoder with decoding parameters.
350     opj_setup_decoder(dec, &ctx->dec_params);
351     stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
352     if (!stream) {
353         av_log(avctx, AV_LOG_ERROR,
354                "Codestream could not be opened for reading.\n");
355         goto done;
356     }
357
358     opj_image_destroy(image);
359     // Decode the codestream
360     image = opj_decode_with_info(dec, stream, NULL);
361     opj_cio_close(stream);
362
363     if (!image) {
364         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
365         goto done;
366     }
367
368     desc = av_pix_fmt_desc_get(avctx->pix_fmt);
369     pixel_size = desc->comp[0].step_minus1 + 1;
370     ispacked = libopenjpeg_ispacked(avctx->pix_fmt);
371
372     switch (pixel_size) {
373     case 1:
374         if (ispacked) {
375             libopenjpeg_copy_to_packed8(picture, image);
376         } else {
377             libopenjpeg_copyto8(picture, image);
378         }
379         break;
380     case 2:
381         if (ispacked) {
382             libopenjpeg_copy_to_packed8(picture, image);
383         } else {
384             libopenjpeg_copyto16(picture, image);
385         }
386         break;
387     case 3:
388     case 4:
389         if (ispacked) {
390             libopenjpeg_copy_to_packed8(picture, image);
391         }
392         break;
393     case 6:
394     case 8:
395         if (ispacked) {
396             libopenjpeg_copy_to_packed16(picture, image);
397         }
398         break;
399     default:
400         av_log(avctx, AV_LOG_ERROR, "unsupported pixel size %d\n", pixel_size);
401         goto done;
402     }
403
404     *got_frame = 1;
405     ret        = buf_size;
406
407 done:
408     opj_image_destroy(image);
409     opj_destroy_decompress(dec);
410     return ret;
411 }
412
413 #define OFFSET(x) offsetof(LibOpenJPEGContext, x)
414 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
415
416 static const AVOption options[] = {
417     { "lowqual", "Limit the number of layers used for decoding",    OFFSET(lowqual), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
418     { "lowres",  "Lower the decoding resolution by a power of two", OFFSET(lowres),  AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
419     { NULL },
420 };
421
422 static const AVClass class = {
423     .class_name = "libopenjpeg",
424     .item_name  = av_default_item_name,
425     .option     = options,
426     .version    = LIBAVUTIL_VERSION_INT,
427 };
428
429 AVCodec ff_libopenjpeg_decoder = {
430     .name             = "libopenjpeg",
431     .type             = AVMEDIA_TYPE_VIDEO,
432     .id               = AV_CODEC_ID_JPEG2000,
433     .priv_data_size   = sizeof(LibOpenJPEGContext),
434     .init             = libopenjpeg_decode_init,
435     .decode           = libopenjpeg_decode_frame,
436     .capabilities     = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
437     .long_name        = NULL_IF_CONFIG_SMALL("OpenJPEG JPEG 2000"),
438     .priv_class       = &class,
439 };