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