]> git.sesse.net Git - ffmpeg/blob - libavcodec/libopenjpegdec.c
libopenjpeg: support YUV and deep RGB pixel formats
[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/intreadwrite.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/pixfmt.h"
33 #include "libavutil/opt.h"
34 #include "avcodec.h"
35 #include "thread.h"
36
37 #define JP2_SIG_TYPE    0x6A502020
38 #define JP2_SIG_VALUE   0x0D0A870A
39
40 // pix_fmts with lower bpp have to be listed before
41 // similar pix_fmts with higher bpp.
42 #define RGB_PIXEL_FORMATS  PIX_FMT_RGB24, PIX_FMT_RGBA,  \
43                            PIX_FMT_RGB48
44
45 #define GRAY_PIXEL_FORMATS PIX_FMT_GRAY8, PIX_FMT_Y400A, \
46                            PIX_FMT_GRAY16
47
48 #define YUV_PIXEL_FORMATS  PIX_FMT_YUV410P,   PIX_FMT_YUV411P,   \
49                            PIX_FMT_YUVA420P, \
50                            PIX_FMT_YUV420P,   PIX_FMT_YUV422P,   \
51                            PIX_FMT_YUV440P,   PIX_FMT_YUV444P,   \
52                            PIX_FMT_YUV420P9,  PIX_FMT_YUV422P9,  \
53                            PIX_FMT_YUV444P9, \
54                            PIX_FMT_YUV420P10, PIX_FMT_YUV422P10, \
55                            PIX_FMT_YUV444P10, \
56                            PIX_FMT_YUV420P16, PIX_FMT_YUV422P16, \
57                            PIX_FMT_YUV444P16
58
59 static const enum PixelFormat rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
60 static const enum PixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
61 static const enum PixelFormat yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
62 static const enum PixelFormat any_pix_fmts[]  = {RGB_PIXEL_FORMATS,
63                                                  GRAY_PIXEL_FORMATS,
64                                                  YUV_PIXEL_FORMATS};
65
66 typedef struct {
67     AVClass *class;
68     opj_dparameters_t dec_params;
69     AVFrame image;
70     int lowres;
71     int lowqual;
72 } LibOpenJPEGContext;
73
74 static int libopenjpeg_matches_pix_fmt(const opj_image_t *img,
75                                        enum PixelFormat pix_fmt)
76 {
77     AVPixFmtDescriptor des = av_pix_fmt_descriptors[pix_fmt];
78     int match = 1;
79
80     if (des.nb_components != img->numcomps) {
81         return 0;
82     }
83
84     switch (des.nb_components) {
85     case 4:
86         match = match &&
87             des.comp[3].depth_minus1 + 1 >= img->comps[3].prec &&
88             1 == img->comps[3].dx &&
89             1 == img->comps[3].dy;
90     case 3:
91         match = match &&
92             des.comp[2].depth_minus1 + 1 >= img->comps[2].prec &&
93             1 << des.log2_chroma_w == img->comps[2].dx &&
94             1 << des.log2_chroma_h == img->comps[2].dy;
95     case 2:
96         match = match &&
97             des.comp[1].depth_minus1 + 1 >= img->comps[1].prec &&
98             1 << des.log2_chroma_w == img->comps[1].dx &&
99             1 << des.log2_chroma_h == img->comps[1].dy;
100     case 1:
101         match = match &&
102             des.comp[0].depth_minus1 + 1 >= img->comps[0].prec &&
103             1 == img->comps[0].dx &&
104             1 == img->comps[0].dy;
105     default:
106         break;
107     }
108
109     return match;
110 }
111
112 static enum PixelFormat libopenjpeg_guess_pix_fmt(const opj_image_t *image)
113 {
114     int index;
115     const enum PixelFormat *possible_fmts = NULL;
116     int possible_fmts_nb = 0;
117
118     switch (image->color_space) {
119     case CLRSPC_SRGB:
120         possible_fmts = rgb_pix_fmts;
121         possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
122         break;
123     case CLRSPC_GRAY:
124         possible_fmts = gray_pix_fmts;
125         possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
126         break;
127     case CLRSPC_SYCC:
128         possible_fmts = yuv_pix_fmts;
129         possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
130         break;
131     default:
132         possible_fmts = any_pix_fmts;
133         possible_fmts_nb = FF_ARRAY_ELEMS(any_pix_fmts);
134         break;
135     }
136
137     for (index = 0; index < possible_fmts_nb; ++index) {
138         if (libopenjpeg_matches_pix_fmt(image, possible_fmts[index])) {
139             return possible_fmts[index];
140         }
141     }
142
143     return PIX_FMT_NONE;
144 }
145
146 static inline int libopenjpeg_ispacked(enum PixelFormat pix_fmt)
147 {
148     int i, component_plane;
149
150     if (pix_fmt == PIX_FMT_GRAY16)
151         return 0;
152
153     component_plane = av_pix_fmt_descriptors[pix_fmt].comp[0].plane;
154     for (i = 1; i < av_pix_fmt_descriptors[pix_fmt].nb_components; i++) {
155         if (component_plane != av_pix_fmt_descriptors[pix_fmt].comp[i].plane)
156             return 0;
157     }
158     return 1;
159 }
160
161 static void libopenjpeg_copy_to_packed8(AVFrame *picture, opj_image_t *image)
162 {
163     uint8_t *img_ptr;
164     int index, x, y, c;
165
166     for (y = 0; y < picture->height; y++) {
167         index = y*picture->width;
168         img_ptr = picture->data[0] + y*picture->linesize[0];
169         for (x = 0; x < picture->width; x++, index++) {
170             for (c = 0; c < image->numcomps; c++) {
171                 *img_ptr++ = image->comps[c].data[index];
172             }
173         }
174     }
175 }
176
177 static void libopenjpeg_copy_to_packed16(AVFrame *picture, opj_image_t *image)
178 {
179     uint16_t *img_ptr;
180     int index, x, y, c;
181     int adjust[4];
182
183     for (x = 0; x < image->numcomps; x++)
184         adjust[x] = FFMAX(FFMIN(16 - image->comps[x].prec, 8), 0);
185
186     for (y = 0; y < picture->height; y++) {
187         index = y*picture->width;
188         img_ptr = (uint16_t*) (picture->data[0] + y*picture->linesize[0]);
189         for (x = 0; x < picture->width; x++, index++) {
190             for (c = 0; c < image->numcomps; c++) {
191                 *img_ptr++ = image->comps[c].data[index] << adjust[c];
192             }
193         }
194     }
195 }
196
197 static void libopenjpeg_copyto8(AVFrame *picture, opj_image_t *image)
198 {
199     int *comp_data;
200     uint8_t *img_ptr;
201     int index, x, y;
202
203     for (index = 0; index < image->numcomps; index++) {
204         comp_data = image->comps[index].data;
205         for (y = 0; y < image->comps[index].h; y++) {
206             img_ptr = picture->data[index] + y * picture->linesize[index];
207             for (x = 0; x < image->comps[index].w; x++) {
208                 *img_ptr = (uint8_t) *comp_data;
209                 img_ptr++;
210                 comp_data++;
211             }
212         }
213     }
214 }
215
216 static void libopenjpeg_copyto16(AVFrame *p, opj_image_t *image)
217 {
218     int *comp_data;
219     uint16_t *img_ptr;
220     int index, x, y;
221
222     for (index = 0; index < image->numcomps; index++) {
223         comp_data = image->comps[index].data;
224         for (y = 0; y < image->comps[index].h; y++) {
225             img_ptr = (uint16_t*) (p->data[index] + y * p->linesize[index]);
226             for (x = 0; x < image->comps[index].w; x++) {
227                 *img_ptr = *comp_data;
228                 img_ptr++;
229                 comp_data++;
230             }
231         }
232     }
233 }
234
235 static av_cold int libopenjpeg_decode_init(AVCodecContext *avctx)
236 {
237     LibOpenJPEGContext *ctx = avctx->priv_data;
238
239     opj_set_default_decoder_parameters(&ctx->dec_params);
240     avcodec_get_frame_defaults(&ctx->image);
241     avctx->coded_frame = &ctx->image;
242     return 0;
243 }
244
245 static av_cold int libopenjpeg_decode_init_thread_copy(AVCodecContext *avctx)
246 {
247     LibOpenJPEGContext *ctx = avctx->priv_data;
248
249     avctx->coded_frame = &ctx->image;
250     return 0;
251 }
252
253 static int libopenjpeg_decode_frame(AVCodecContext *avctx,
254                                     void *data, int *data_size,
255                                     AVPacket *avpkt)
256 {
257     uint8_t *buf = avpkt->data;
258     int buf_size = avpkt->size;
259     LibOpenJPEGContext *ctx = avctx->priv_data;
260     AVFrame *picture = &ctx->image, *output = data;
261     opj_dinfo_t *dec;
262     opj_cio_t *stream;
263     opj_image_t *image;
264     int width, height, ret = -1;
265     int pixel_size = 0;
266     int ispacked = 0;
267     int i;
268
269     *data_size = 0;
270
271     // Check if input is a raw jpeg2k codestream or in jp2 wrapping
272     if ((AV_RB32(buf)     == 12)           &&
273         (AV_RB32(buf + 4) == JP2_SIG_TYPE) &&
274         (AV_RB32(buf + 8) == JP2_SIG_VALUE)) {
275         dec = opj_create_decompress(CODEC_JP2);
276     } else {
277         /* If the AVPacket contains a jp2c box, then skip to
278          * the starting byte of the codestream. */
279         if (AV_RB32(buf + 4) == AV_RB32("jp2c"))
280             buf += 8;
281         dec = opj_create_decompress(CODEC_J2K);
282     }
283
284     if (!dec) {
285         av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");
286         return -1;
287     }
288     opj_set_event_mgr((opj_common_ptr)dec, NULL, NULL);
289
290     ctx->dec_params.cp_limit_decoding = LIMIT_TO_MAIN_HEADER;
291     ctx->dec_params.cp_reduce         = ctx->lowres;
292     ctx->dec_params.cp_layer          = ctx->lowqual;
293     // Tie decoder with decoding parameters
294     opj_setup_decoder(dec, &ctx->dec_params);
295     stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
296
297     if (!stream) {
298         av_log(avctx, AV_LOG_ERROR,
299                "Codestream could not be opened for reading.\n");
300         opj_destroy_decompress(dec);
301         return -1;
302     }
303
304     // Decode the header only.
305     image = opj_decode_with_info(dec, stream, NULL);
306     opj_cio_close(stream);
307
308     if (!image) {
309         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
310         opj_destroy_decompress(dec);
311         return -1;
312     }
313
314     width  = image->x1 - image->x0;
315     height = image->y1 - image->y0;
316
317     if (ctx->lowres) {
318         width  = (width  + (1 << ctx->lowres) - 1) >> ctx->lowres;
319         height = (height + (1 << ctx->lowres) - 1) >> ctx->lowres;
320     }
321
322     if (av_image_check_size(width, height, 0, avctx) < 0) {
323         av_log(avctx, AV_LOG_ERROR,
324                "%dx%d dimension invalid.\n", width, height);
325         goto done;
326     }
327
328     avcodec_set_dimensions(avctx, width, height);
329
330     if (avctx->pix_fmt != PIX_FMT_NONE)
331         if (!libopenjpeg_matches_pix_fmt(image, avctx->pix_fmt))
332             avctx->pix_fmt = PIX_FMT_NONE;
333
334     if (avctx->pix_fmt == PIX_FMT_NONE)
335         avctx->pix_fmt = libopenjpeg_guess_pix_fmt(image);
336
337     if (avctx->pix_fmt == PIX_FMT_NONE) {
338         av_log(avctx, AV_LOG_ERROR, "Unable to determine pixel format\n");
339         ret = AVERROR_INVALIDDATA;
340         goto done;
341     }
342
343     for (i = 0; i < image->numcomps; i++)
344         if (image->comps[i].prec > avctx->bits_per_raw_sample)
345             avctx->bits_per_raw_sample = image->comps[i].prec;
346
347     if (picture->data[0])
348         ff_thread_release_buffer(avctx, picture);
349
350     if (ff_thread_get_buffer(avctx, picture) < 0) {
351         av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed\n");
352         goto done;
353     }
354
355     ctx->dec_params.cp_limit_decoding = NO_LIMITATION;
356     // Tie decoder with decoding parameters.
357     opj_setup_decoder(dec, &ctx->dec_params);
358     stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
359     if (!stream) {
360         av_log(avctx, AV_LOG_ERROR,
361                "Codestream could not be opened for reading.\n");
362         goto done;
363     }
364
365     opj_image_destroy(image);
366     // Decode the codestream
367     image = opj_decode_with_info(dec, stream, NULL);
368     opj_cio_close(stream);
369
370     if (!image) {
371         av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
372         goto done;
373     }
374
375     pixel_size =
376         av_pix_fmt_descriptors[avctx->pix_fmt].comp[0].step_minus1 + 1;
377     ispacked = libopenjpeg_ispacked(avctx->pix_fmt);
378
379     switch (pixel_size) {
380     case 1:
381         if (ispacked) {
382             libopenjpeg_copy_to_packed8(picture, image);
383         } else {
384             libopenjpeg_copyto8(picture, image);
385         }
386         break;
387     case 2:
388         if (ispacked) {
389             libopenjpeg_copy_to_packed8(picture, image);
390         } else {
391             libopenjpeg_copyto16(picture, image);
392         }
393         break;
394     case 3:
395     case 4:
396         if (ispacked) {
397             libopenjpeg_copy_to_packed8(picture, image);
398         }
399         break;
400     case 6:
401     case 8:
402         if (ispacked) {
403             libopenjpeg_copy_to_packed16(picture, image);
404         }
405         break;
406     default:
407         av_log(avctx, AV_LOG_ERROR, "unsupported pixel size %d\n", pixel_size);
408         goto done;
409     }
410
411     *output    = ctx->image;
412     *data_size = sizeof(AVPicture);
413     ret        = buf_size;
414
415 done:
416     opj_image_destroy(image);
417     opj_destroy_decompress(dec);
418     return ret;
419 }
420
421 static av_cold int libopenjpeg_decode_close(AVCodecContext *avctx)
422 {
423     LibOpenJPEGContext *ctx = avctx->priv_data;
424
425     if (ctx->image.data[0])
426         ff_thread_release_buffer(avctx, &ctx->image);
427     return 0;
428 }
429
430 #define OFFSET(x) offsetof(LibOpenJPEGContext, x)
431 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
432
433 static const AVOption options[] = {
434     { "lowqual", "Limit the number of layers used for decoding",    OFFSET(lowqual), AV_OPT_TYPE_INT, { 0 }, 0, INT_MAX, VD },
435     { "lowres",  "Lower the decoding resolution by a power of two", OFFSET(lowres),  AV_OPT_TYPE_INT, { 0 }, 0, INT_MAX, VD },
436     { NULL },
437 };
438
439 static const AVClass class = {
440     .class_name = "libopenjpeg",
441     .item_name  = av_default_item_name,
442     .option     = options,
443     .version    = LIBAVUTIL_VERSION_INT,
444 };
445
446 AVCodec ff_libopenjpeg_decoder = {
447     .name             = "libopenjpeg",
448     .type             = AVMEDIA_TYPE_VIDEO,
449     .id               = CODEC_ID_JPEG2000,
450     .priv_data_size   = sizeof(LibOpenJPEGContext),
451     .init             = libopenjpeg_decode_init,
452     .close            = libopenjpeg_decode_close,
453     .decode           = libopenjpeg_decode_frame,
454     .capabilities     = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
455     .long_name        = NULL_IF_CONFIG_SMALL("OpenJPEG based JPEG 2000 decoder"),
456     .priv_class       = &class,
457     .init_thread_copy = ONLY_IF_THREADS_ENABLED(libopenjpeg_decode_init_thread_copy),
458 };