]> git.sesse.net Git - ffmpeg/blob - libavcodec/jpeg2000dec.c
avformat/asfdec: call ff_read_frame_flush() in asf_read_pts()
[ffmpeg] / libavcodec / jpeg2000dec.c
1 /*
2  * JPEG 2000 image decoder
3  * Copyright (c) 2007 Kamil Nowosad
4  * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * JPEG 2000 image decoder
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/common.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
32 #include "avcodec.h"
33 #include "bytestream.h"
34 #include "internal.h"
35 #include "thread.h"
36 #include "jpeg2000.h"
37
38 #define JP2_SIG_TYPE    0x6A502020
39 #define JP2_SIG_VALUE   0x0D0A870A
40 #define JP2_CODESTREAM  0x6A703263
41 #define JP2_HEADER      0x6A703268
42
43 #define HAD_COC 0x01
44 #define HAD_QCC 0x02
45
46 typedef struct Jpeg2000TilePart {
47     uint8_t tile_index;                 // Tile index who refers the tile-part
48     const uint8_t *tp_end;
49     GetByteContext tpg;                 // bit stream in tile-part
50 } Jpeg2000TilePart;
51
52 /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
53  * one per component, so tile_part elements have a size of 3 */
54 typedef struct Jpeg2000Tile {
55     Jpeg2000Component   *comp;
56     uint8_t             properties[4];
57     Jpeg2000CodingStyle codsty[4];
58     Jpeg2000QuantStyle  qntsty[4];
59     Jpeg2000TilePart    tile_part[4];
60     uint16_t tp_idx;                    // Tile-part index
61 } Jpeg2000Tile;
62
63 typedef struct Jpeg2000DecoderContext {
64     AVClass         *class;
65     AVCodecContext  *avctx;
66     GetByteContext  g;
67
68     int             width, height;
69     int             image_offset_x, image_offset_y;
70     int             tile_offset_x, tile_offset_y;
71     uint8_t         cbps[4];    // bits per sample in particular components
72     uint8_t         sgnd[4];    // if a component is signed
73     uint8_t         properties[4];
74     int             cdx[4], cdy[4];
75     int             precision;
76     int             ncomponents;
77     int             colour_space;
78     uint32_t        palette[256];
79     int8_t          pal8;
80     int             cdef[4];
81     int             tile_width, tile_height;
82     unsigned        numXtiles, numYtiles;
83     int             maxtilelen;
84
85     Jpeg2000CodingStyle codsty[4];
86     Jpeg2000QuantStyle  qntsty[4];
87
88     int             bit_index;
89
90     int             curtileno;
91
92     Jpeg2000Tile    *tile;
93
94     /*options parameters*/
95     int             reduction_factor;
96 } Jpeg2000DecoderContext;
97
98 /* get_bits functions for JPEG2000 packet bitstream
99  * It is a get_bit function with a bit-stuffing routine. If the value of the
100  * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
101  * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
102 static int get_bits(Jpeg2000DecoderContext *s, int n)
103 {
104     int res = 0;
105
106     while (--n >= 0) {
107         res <<= 1;
108         if (s->bit_index == 0) {
109             s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
110         }
111         s->bit_index--;
112         res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
113     }
114     return res;
115 }
116
117 static void jpeg2000_flush(Jpeg2000DecoderContext *s)
118 {
119     if (bytestream2_get_byte(&s->g) == 0xff)
120         bytestream2_skip(&s->g, 1);
121     s->bit_index = 8;
122 }
123
124 /* decode the value stored in node */
125 static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
126                            int threshold)
127 {
128     Jpeg2000TgtNode *stack[30];
129     int sp = -1, curval = 0;
130
131     if (!node)
132         return AVERROR_INVALIDDATA;
133
134     while (node && !node->vis) {
135         stack[++sp] = node;
136         node        = node->parent;
137     }
138
139     if (node)
140         curval = node->val;
141     else
142         curval = stack[sp]->val;
143
144     while (curval < threshold && sp >= 0) {
145         if (curval < stack[sp]->val)
146             curval = stack[sp]->val;
147         while (curval < threshold) {
148             int ret;
149             if ((ret = get_bits(s, 1)) > 0) {
150                 stack[sp]->vis++;
151                 break;
152             } else if (!ret)
153                 curval++;
154             else
155                 return ret;
156         }
157         stack[sp]->val = curval;
158         sp--;
159     }
160     return curval;
161 }
162
163 static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
164                          int bpc, uint32_t log2_chroma_wh, int pal8)
165 {
166     int match = 1;
167     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
168
169     if (desc->nb_components != components) {
170         return 0;
171     }
172
173     switch (components) {
174     case 4:
175         match = match && desc->comp[3].depth_minus1 + 1 >= bpc &&
176                          (log2_chroma_wh >> 14 & 3) == 0 &&
177                          (log2_chroma_wh >> 12 & 3) == 0;
178     case 3:
179         match = match && desc->comp[2].depth_minus1 + 1 >= bpc &&
180                          (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
181                          (log2_chroma_wh >>  8 & 3) == desc->log2_chroma_h;
182     case 2:
183         match = match && desc->comp[1].depth_minus1 + 1 >= bpc &&
184                          (log2_chroma_wh >>  6 & 3) == desc->log2_chroma_w &&
185                          (log2_chroma_wh >>  4 & 3) == desc->log2_chroma_h;
186
187     case 1:
188         match = match && desc->comp[0].depth_minus1 + 1 >= bpc &&
189                          (log2_chroma_wh >>  2 & 3) == 0 &&
190                          (log2_chroma_wh       & 3) == 0 &&
191                          (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
192     }
193     return match;
194 }
195
196 // pix_fmts with lower bpp have to be listed before
197 // similar pix_fmts with higher bpp.
198 #define RGB_PIXEL_FORMATS   AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
199 #define GRAY_PIXEL_FORMATS  AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16
200 #define YUV_PIXEL_FORMATS   AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
201                             AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
202                             AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
203                             AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
204                             AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
205                             AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
206                             AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
207                             AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
208                             AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
209                             AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
210                             AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
211 #define XYZ_PIXEL_FORMATS   AV_PIX_FMT_XYZ12
212
213 static const enum AVPixelFormat rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
214 static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
215 static const enum AVPixelFormat yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
216 static const enum AVPixelFormat xyz_pix_fmts[]  = {XYZ_PIXEL_FORMATS};
217 static const enum AVPixelFormat all_pix_fmts[]  = {RGB_PIXEL_FORMATS,
218                                                    GRAY_PIXEL_FORMATS,
219                                                    YUV_PIXEL_FORMATS,
220                                                    XYZ_PIXEL_FORMATS};
221
222 /* marker segments */
223 /* get sizes and offsets of image, tiles; number of components */
224 static int get_siz(Jpeg2000DecoderContext *s)
225 {
226     int i;
227     int ncomponents;
228     uint32_t log2_chroma_wh = 0;
229     const enum AVPixelFormat *possible_fmts = NULL;
230     int possible_fmts_nb = 0;
231
232     if (bytestream2_get_bytes_left(&s->g) < 36)
233         return AVERROR_INVALIDDATA;
234
235     s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
236     s->width          = bytestream2_get_be32u(&s->g); // Width
237     s->height         = bytestream2_get_be32u(&s->g); // Height
238     s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
239     s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
240     s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz
241     s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz
242     s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz
243     s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz
244     ncomponents       = bytestream2_get_be16u(&s->g); // CSiz
245
246     if (ncomponents <= 0) {
247         av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
248                s->ncomponents);
249         return AVERROR_INVALIDDATA;
250     }
251
252     if (ncomponents > 4) {
253         avpriv_request_sample(s->avctx, "Support for %d components",
254                               s->ncomponents);
255         return AVERROR_PATCHWELCOME;
256     }
257
258     s->ncomponents = ncomponents;
259
260     if (s->tile_width <= 0 || s->tile_height <= 0) {
261         av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
262                s->tile_width, s->tile_height);
263         return AVERROR_INVALIDDATA;
264     }
265
266     if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
267         return AVERROR_INVALIDDATA;
268
269     for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
270         uint8_t x    = bytestream2_get_byteu(&s->g);
271         s->cbps[i]   = (x & 0x7f) + 1;
272         s->precision = FFMAX(s->cbps[i], s->precision);
273         s->sgnd[i]   = !!(x & 0x80);
274         s->cdx[i]    = bytestream2_get_byteu(&s->g);
275         s->cdy[i]    = bytestream2_get_byteu(&s->g);
276         if (!s->cdx[i] || !s->cdy[i]) {
277             av_log(s->avctx, AV_LOG_ERROR, "Invalid sample seperation\n");
278             return AVERROR_INVALIDDATA;
279         }
280         log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
281     }
282
283     s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
284     s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
285
286     if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
287         s->numXtiles = s->numYtiles = 0;
288         return AVERROR(EINVAL);
289     }
290
291     s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
292     if (!s->tile) {
293         s->numXtiles = s->numYtiles = 0;
294         return AVERROR(ENOMEM);
295     }
296
297     for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
298         Jpeg2000Tile *tile = s->tile + i;
299
300         tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
301         if (!tile->comp)
302             return AVERROR(ENOMEM);
303     }
304
305     /* compute image size with reduction factor */
306     s->avctx->width  = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,
307                                                s->reduction_factor);
308     s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
309                                                s->reduction_factor);
310
311     if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
312         s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
313         possible_fmts = xyz_pix_fmts;
314         possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
315     } else {
316         switch (s->colour_space) {
317         case 16:
318             possible_fmts = rgb_pix_fmts;
319             possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
320             break;
321         case 17:
322             possible_fmts = gray_pix_fmts;
323             possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
324             break;
325         case 18:
326             possible_fmts = yuv_pix_fmts;
327             possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
328             break;
329         default:
330             possible_fmts = all_pix_fmts;
331             possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
332             break;
333         }
334     }
335     for (i = 0; i < possible_fmts_nb; ++i) {
336         if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
337             s->avctx->pix_fmt = possible_fmts[i];
338             break;
339         }
340     }
341     if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
342         av_log(s->avctx, AV_LOG_ERROR,
343                "Unknown pix_fmt, profile: %d, colour_space: %d, "
344                "components: %d, precision: %d, "
345                "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
346                s->avctx->profile, s->colour_space, ncomponents, s->precision,
347                ncomponents > 2 ? s->cdx[1] : 0,
348                ncomponents > 2 ? s->cdy[1] : 0,
349                ncomponents > 2 ? s->cdx[2] : 0,
350                ncomponents > 2 ? s->cdy[2] : 0);
351     }
352     return 0;
353 }
354
355 /* get common part for COD and COC segments */
356 static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
357 {
358     uint8_t byte;
359
360     if (bytestream2_get_bytes_left(&s->g) < 5)
361         return AVERROR_INVALIDDATA;
362
363     /*  nreslevels = number of resolution levels
364                    = number of decomposition level +1 */
365     c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
366     if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
367         av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
368         return AVERROR_INVALIDDATA;
369     }
370
371     /* compute number of resolution levels to decode */
372     if (c->nreslevels < s->reduction_factor)
373         c->nreslevels2decode = 1;
374     else
375         c->nreslevels2decode = c->nreslevels - s->reduction_factor;
376
377     c->log2_cblk_width  = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
378     c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
379
380     if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
381         c->log2_cblk_width + c->log2_cblk_height > 12) {
382         av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
383         return AVERROR_INVALIDDATA;
384     }
385
386     c->cblk_style = bytestream2_get_byteu(&s->g);
387     if (c->cblk_style != 0) { // cblk style
388         av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
389     }
390     c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
391     /* set integer 9/7 DWT in case of BITEXACT flag */
392     if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
393         c->transform = FF_DWT97_INT;
394
395     if (c->csty & JPEG2000_CSTY_PREC) {
396         int i;
397         for (i = 0; i < c->nreslevels; i++) {
398             byte = bytestream2_get_byte(&s->g);
399             c->log2_prec_widths[i]  =  byte       & 0x0F;    // precinct PPx
400             c->log2_prec_heights[i] = (byte >> 4) & 0x0F;    // precinct PPy
401         }
402     } else {
403         memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
404         memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
405     }
406     return 0;
407 }
408
409 /* get coding parameters for a particular tile or whole image*/
410 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
411                    uint8_t *properties)
412 {
413     Jpeg2000CodingStyle tmp;
414     int compno, ret;
415
416     if (bytestream2_get_bytes_left(&s->g) < 5)
417         return AVERROR_INVALIDDATA;
418
419     tmp.csty = bytestream2_get_byteu(&s->g);
420
421     // get progression order
422     tmp.prog_order = bytestream2_get_byteu(&s->g);
423
424     tmp.nlayers    = bytestream2_get_be16u(&s->g);
425     tmp.mct        = bytestream2_get_byteu(&s->g); // multiple component transformation
426
427     if (tmp.mct && s->ncomponents < 3) {
428         av_log(s->avctx, AV_LOG_ERROR,
429                "MCT %d with too few components (%d)\n",
430                tmp.mct, s->ncomponents);
431         return AVERROR_INVALIDDATA;
432     }
433
434     if ((ret = get_cox(s, &tmp)) < 0)
435         return ret;
436
437     for (compno = 0; compno < s->ncomponents; compno++)
438         if (!(properties[compno] & HAD_COC))
439             memcpy(c + compno, &tmp, sizeof(tmp));
440     return 0;
441 }
442
443 /* Get coding parameters for a component in the whole image or a
444  * particular tile. */
445 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
446                    uint8_t *properties)
447 {
448     int compno, ret;
449
450     if (bytestream2_get_bytes_left(&s->g) < 2)
451         return AVERROR_INVALIDDATA;
452
453     compno = bytestream2_get_byteu(&s->g);
454
455     if (compno >= s->ncomponents) {
456         av_log(s->avctx, AV_LOG_ERROR,
457                "Invalid compno %d. There are %d components in the image.\n",
458                compno, s->ncomponents);
459         return AVERROR_INVALIDDATA;
460     }
461
462     c      += compno;
463     c->csty = bytestream2_get_byteu(&s->g);
464
465     if ((ret = get_cox(s, c)) < 0)
466         return ret;
467
468     properties[compno] |= HAD_COC;
469     return 0;
470 }
471
472 /* Get common part for QCD and QCC segments. */
473 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
474 {
475     int i, x;
476
477     if (bytestream2_get_bytes_left(&s->g) < 1)
478         return AVERROR_INVALIDDATA;
479
480     x = bytestream2_get_byteu(&s->g); // Sqcd
481
482     q->nguardbits = x >> 5;
483     q->quantsty   = x & 0x1f;
484
485     if (q->quantsty == JPEG2000_QSTY_NONE) {
486         n -= 3;
487         if (bytestream2_get_bytes_left(&s->g) < n ||
488             n > JPEG2000_MAX_DECLEVELS*3)
489             return AVERROR_INVALIDDATA;
490         for (i = 0; i < n; i++)
491             q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
492     } else if (q->quantsty == JPEG2000_QSTY_SI) {
493         if (bytestream2_get_bytes_left(&s->g) < 2)
494             return AVERROR_INVALIDDATA;
495         x          = bytestream2_get_be16u(&s->g);
496         q->expn[0] = x >> 11;
497         q->mant[0] = x & 0x7ff;
498         for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
499             int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
500             q->expn[i] = curexpn;
501             q->mant[i] = q->mant[0];
502         }
503     } else {
504         n = (n - 3) >> 1;
505         if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
506             n > JPEG2000_MAX_DECLEVELS*3)
507             return AVERROR_INVALIDDATA;
508         for (i = 0; i < n; i++) {
509             x          = bytestream2_get_be16u(&s->g);
510             q->expn[i] = x >> 11;
511             q->mant[i] = x & 0x7ff;
512         }
513     }
514     return 0;
515 }
516
517 /* Get quantization parameters for a particular tile or a whole image. */
518 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
519                    uint8_t *properties)
520 {
521     Jpeg2000QuantStyle tmp;
522     int compno, ret;
523
524     if ((ret = get_qcx(s, n, &tmp)) < 0)
525         return ret;
526     for (compno = 0; compno < s->ncomponents; compno++)
527         if (!(properties[compno] & HAD_QCC))
528             memcpy(q + compno, &tmp, sizeof(tmp));
529     return 0;
530 }
531
532 /* Get quantization parameters for a component in the whole image
533  * on in a particular tile. */
534 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
535                    uint8_t *properties)
536 {
537     int compno;
538
539     if (bytestream2_get_bytes_left(&s->g) < 1)
540         return AVERROR_INVALIDDATA;
541
542     compno = bytestream2_get_byteu(&s->g);
543
544     if (compno >= s->ncomponents) {
545         av_log(s->avctx, AV_LOG_ERROR,
546                "Invalid compno %d. There are %d components in the image.\n",
547                compno, s->ncomponents);
548         return AVERROR_INVALIDDATA;
549     }
550
551     properties[compno] |= HAD_QCC;
552     return get_qcx(s, n - 1, q + compno);
553 }
554
555 /* Get start of tile segment. */
556 static int get_sot(Jpeg2000DecoderContext *s, int n)
557 {
558     Jpeg2000TilePart *tp;
559     uint16_t Isot;
560     uint32_t Psot;
561     uint8_t TPsot;
562
563     if (bytestream2_get_bytes_left(&s->g) < 8)
564         return AVERROR_INVALIDDATA;
565
566     s->curtileno = 0;
567     Isot = bytestream2_get_be16u(&s->g);        // Isot
568     if (Isot >= s->numXtiles * s->numYtiles)
569         return AVERROR_INVALIDDATA;
570
571     s->curtileno = Isot;
572     Psot  = bytestream2_get_be32u(&s->g);       // Psot
573     TPsot = bytestream2_get_byteu(&s->g);       // TPsot
574
575     /* Read TNSot but not used */
576     bytestream2_get_byteu(&s->g);               // TNsot
577
578     if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
579         av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot);
580         return AVERROR_INVALIDDATA;
581     }
582
583     if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
584         avpriv_request_sample(s->avctx, "Support for %d components", TPsot);
585         return AVERROR_PATCHWELCOME;
586     }
587
588     s->tile[Isot].tp_idx = TPsot;
589     tp             = s->tile[Isot].tile_part + TPsot;
590     tp->tile_index = Isot;
591     tp->tp_end     = s->g.buffer + Psot - n - 2;
592
593     if (!TPsot) {
594         Jpeg2000Tile *tile = s->tile + s->curtileno;
595
596         /* copy defaults */
597         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
598         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
599     }
600
601     return 0;
602 }
603
604 /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
605  * Used to know the number of tile parts and lengths.
606  * There may be multiple TLMs in the header.
607  * TODO: The function is not used for tile-parts management, nor anywhere else.
608  * It can be useful to allocate memory for tile parts, before managing the SOT
609  * markers. Parsing the TLM header is needed to increment the input header
610  * buffer.
611  * This marker is mandatory for DCI. */
612 static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
613 {
614     uint8_t Stlm, ST, SP, tile_tlm, i;
615     bytestream2_get_byte(&s->g);               /* Ztlm: skipped */
616     Stlm = bytestream2_get_byte(&s->g);
617
618     // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
619     ST = (Stlm >> 4) & 0x03;
620     // TODO: Manage case of ST = 0b11 --> raise error
621     SP       = (Stlm >> 6) & 0x01;
622     tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
623     for (i = 0; i < tile_tlm; i++) {
624         switch (ST) {
625         case 0:
626             break;
627         case 1:
628             bytestream2_get_byte(&s->g);
629             break;
630         case 2:
631             bytestream2_get_be16(&s->g);
632             break;
633         case 3:
634             bytestream2_get_be32(&s->g);
635             break;
636         }
637         if (SP == 0) {
638             bytestream2_get_be16(&s->g);
639         } else {
640             bytestream2_get_be32(&s->g);
641         }
642     }
643     return 0;
644 }
645
646 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
647 {
648     int compno;
649     int tilex = tileno % s->numXtiles;
650     int tiley = tileno / s->numXtiles;
651     Jpeg2000Tile *tile = s->tile + tileno;
652
653     if (!tile->comp)
654         return AVERROR(ENOMEM);
655
656     for (compno = 0; compno < s->ncomponents; compno++) {
657         Jpeg2000Component *comp = tile->comp + compno;
658         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
659         Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
660         int ret; // global bandno
661
662         comp->coord_o[0][0] = FFMAX(tilex       * s->tile_width  + s->tile_offset_x, s->image_offset_x);
663         comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width  + s->tile_offset_x, s->width);
664         comp->coord_o[1][0] = FFMAX(tiley       * s->tile_height + s->tile_offset_y, s->image_offset_y);
665         comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
666
667         comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
668         comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
669         comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
670         comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
671
672         if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
673                                              s->cbps[compno], s->cdx[compno],
674                                              s->cdy[compno], s->avctx))
675             return ret;
676     }
677     return 0;
678 }
679
680 /* Read the number of coding passes. */
681 static int getnpasses(Jpeg2000DecoderContext *s)
682 {
683     int num;
684     if (!get_bits(s, 1))
685         return 1;
686     if (!get_bits(s, 1))
687         return 2;
688     if ((num = get_bits(s, 2)) != 3)
689         return num < 0 ? num : 3 + num;
690     if ((num = get_bits(s, 5)) != 31)
691         return num < 0 ? num : 6 + num;
692     num = get_bits(s, 7);
693     return num < 0 ? num : 37 + num;
694 }
695
696 static int getlblockinc(Jpeg2000DecoderContext *s)
697 {
698     int res = 0, ret;
699     while (ret = get_bits(s, 1)) {
700         if (ret < 0)
701             return ret;
702         res++;
703     }
704     return res;
705 }
706
707 static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
708                                   Jpeg2000CodingStyle *codsty,
709                                   Jpeg2000ResLevel *rlevel, int precno,
710                                   int layno, uint8_t *expn, int numgbits)
711 {
712     int bandno, cblkno, ret, nb_code_blocks;
713
714     if (!(ret = get_bits(s, 1))) {
715         jpeg2000_flush(s);
716         return 0;
717     } else if (ret < 0)
718         return ret;
719
720     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
721         Jpeg2000Band *band = rlevel->band + bandno;
722         Jpeg2000Prec *prec = band->prec + precno;
723
724         if (band->coord[0][0] == band->coord[0][1] ||
725             band->coord[1][0] == band->coord[1][1])
726             continue;
727         nb_code_blocks =  prec->nb_codeblocks_height *
728                           prec->nb_codeblocks_width;
729         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
730             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
731             int incl, newpasses, llen;
732
733             if (cblk->npasses)
734                 incl = get_bits(s, 1);
735             else
736                 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
737             if (!incl)
738                 continue;
739             else if (incl < 0)
740                 return incl;
741
742             if (!cblk->npasses) {
743                 int v = expn[bandno] + numgbits - 1 -
744                         tag_tree_decode(s, prec->zerobits + cblkno, 100);
745                 if (v < 0) {
746                     av_log(s->avctx, AV_LOG_ERROR,
747                            "nonzerobits %d invalid\n", v);
748                     return AVERROR_INVALIDDATA;
749                 }
750                 cblk->nonzerobits = v;
751             }
752             if ((newpasses = getnpasses(s)) < 0)
753                 return newpasses;
754             if ((llen = getlblockinc(s)) < 0)
755                 return llen;
756             cblk->lblock += llen;
757             if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
758                 return ret;
759             if (ret > sizeof(cblk->data)) {
760                 avpriv_request_sample(s->avctx,
761                                       "Block with lengthinc greater than %zu",
762                                       sizeof(cblk->data));
763                 return AVERROR_PATCHWELCOME;
764             }
765             cblk->lengthinc = ret;
766             cblk->npasses  += newpasses;
767         }
768     }
769     jpeg2000_flush(s);
770
771     if (codsty->csty & JPEG2000_CSTY_EPH) {
772         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
773             bytestream2_skip(&s->g, 2);
774         else
775             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
776     }
777
778     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
779         Jpeg2000Band *band = rlevel->band + bandno;
780         Jpeg2000Prec *prec = band->prec + precno;
781
782         nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
783         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
784             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
785             if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
786                 || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2
787             )
788                 return AVERROR_INVALIDDATA;
789
790             bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc);
791             cblk->length   += cblk->lengthinc;
792             cblk->lengthinc = 0;
793         }
794     }
795     return 0;
796 }
797
798 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
799 {
800     int ret = 0;
801     int layno, reslevelno, compno, precno, ok_reslevel;
802     int x, y;
803
804     s->bit_index = 8;
805     switch (tile->codsty[0].prog_order) {
806     case JPEG2000_PGOD_RLCP:
807         avpriv_request_sample(s->avctx, "Progression order RLCP");
808
809     case JPEG2000_PGOD_LRCP:
810         for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
811             ok_reslevel = 1;
812             for (reslevelno = 0; ok_reslevel; reslevelno++) {
813                 ok_reslevel = 0;
814                 for (compno = 0; compno < s->ncomponents; compno++) {
815                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
816                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
817                     if (reslevelno < codsty->nreslevels) {
818                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
819                                                 reslevelno;
820                         ok_reslevel = 1;
821                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
822                             if ((ret = jpeg2000_decode_packet(s,
823                                                               codsty, rlevel,
824                                                               precno, layno,
825                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
826                                                               qntsty->nguardbits)) < 0)
827                                 return ret;
828                     }
829                 }
830             }
831         }
832         break;
833
834     case JPEG2000_PGOD_CPRL:
835         for (compno = 0; compno < s->ncomponents; compno++) {
836             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
837             Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
838
839             /* Set bit stream buffer address according to tile-part.
840              * For DCinema one tile-part per component, so can be
841              * indexed by component. */
842             s->g = tile->tile_part[compno].tpg;
843
844             /* Position loop (y axis)
845              * TODO: Automate computing of step 256.
846              * Fixed here, but to be computed before entering here. */
847             for (y = 0; y < s->height; y += 256) {
848                 /* Position loop (y axis)
849                  * TODO: automate computing of step 256.
850                  * Fixed here, but to be computed before entering here. */
851                 for (x = 0; x < s->width; x += 256) {
852                     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
853                         uint16_t prcx, prcy;
854                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
855                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
856
857                         if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
858                               (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
859                             continue;
860
861                         if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
862                               (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
863                             continue;
864
865                         // check if a precinct exists
866                         prcx   = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
867                         prcy   = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
868                         precno = prcx + rlevel->num_precincts_x * prcy;
869                         for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
870                             if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
871                                                               precno, layno,
872                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
873                                                               qntsty->nguardbits)) < 0)
874                                 return ret;
875                         }
876                     }
877                 }
878             }
879         }
880         break;
881
882     case JPEG2000_PGOD_RPCL:
883         avpriv_request_sample(s->avctx, "Progression order RPCL");
884         ret = AVERROR_PATCHWELCOME;
885         break;
886
887     case JPEG2000_PGOD_PCRL:
888         avpriv_request_sample(s->avctx, "Progression order PCRL");
889         ret = AVERROR_PATCHWELCOME;
890         break;
891
892     default:
893         break;
894     }
895
896     /* EOC marker reached */
897     bytestream2_skip(&s->g, 2);
898
899     return ret;
900 }
901
902 /* TIER-1 routines */
903 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
904                            int bpno, int bandno, int bpass_csty_symbol,
905                            int vert_causal_ctx_csty_symbol)
906 {
907     int mask = 3 << (bpno - 1), y0, x, y;
908
909     for (y0 = 0; y0 < height; y0 += 4)
910         for (x = 0; x < width; x++)
911             for (y = y0; y < height && y < y0 + 4; y++) {
912                 if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
913                 && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
914                     int flags_mask = -1;
915                     if (vert_causal_ctx_csty_symbol && y == y0 + 3)
916                         flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
917                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
918                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
919                         if (bpass_csty_symbol)
920                              t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
921                         else
922                              t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
923                                                -mask : mask;
924
925                         ff_jpeg2000_set_significance(t1, x, y,
926                                                      t1->data[y][x] < 0);
927                     }
928                     t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
929                 }
930             }
931 }
932
933 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
934                            int bpno)
935 {
936     int phalf, nhalf;
937     int y0, x, y;
938
939     phalf = 1 << (bpno - 1);
940     nhalf = -phalf;
941
942     for (y0 = 0; y0 < height; y0 += 4)
943         for (x = 0; x < width; x++)
944             for (y = y0; y < height && y < y0 + 4; y++)
945                 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
946                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
947                     int r     = ff_mqc_decode(&t1->mqc,
948                                               t1->mqc.cx_states + ctxno)
949                                 ? phalf : nhalf;
950                     t1->data[y][x]          += t1->data[y][x] < 0 ? -r : r;
951                     t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
952                 }
953 }
954
955 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
956                            int width, int height, int bpno, int bandno,
957                            int seg_symbols, int vert_causal_ctx_csty_symbol)
958 {
959     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
960
961     for (y0 = 0; y0 < height; y0 += 4) {
962         for (x = 0; x < width; x++) {
963             if (y0 + 3 < height &&
964                 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
965                   (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
966                   (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
967                   (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
968                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
969                     continue;
970                 runlen = ff_mqc_decode(&t1->mqc,
971                                        t1->mqc.cx_states + MQC_CX_UNI);
972                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
973                                                        t1->mqc.cx_states +
974                                                        MQC_CX_UNI);
975                 dec = 1;
976             } else {
977                 runlen = 0;
978                 dec    = 0;
979             }
980
981             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
982                 if (!dec) {
983                     if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
984                         int flags_mask = -1;
985                         if (vert_causal_ctx_csty_symbol && y == y0 + 3)
986                             flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
987                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
988                                                                                              bandno));
989                     }
990                 }
991                 if (dec) {
992                     int xorbit;
993                     int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
994                                                         &xorbit);
995                     t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
996                                                     t1->mqc.cx_states + ctxno) ^
997                                       xorbit)
998                                      ? -mask : mask;
999                     ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
1000                 }
1001                 dec = 0;
1002                 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
1003             }
1004         }
1005     }
1006     if (seg_symbols) {
1007         int val;
1008         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1009         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1010         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1011         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1012         if (val != 0xa)
1013             av_log(s->avctx, AV_LOG_ERROR,
1014                    "Segmentation symbol value incorrect\n");
1015     }
1016 }
1017
1018 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
1019                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
1020                        int width, int height, int bandpos)
1021 {
1022     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
1023     int clnpass_cnt = 0;
1024     int bpass_csty_symbol           = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
1025     int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
1026
1027     for (y = 0; y < height; y++)
1028         memset(t1->data[y], 0, width * sizeof(**t1->data));
1029
1030     /* If code-block contains no compressed data: nothing to do. */
1031     if (!cblk->length)
1032         return 0;
1033
1034     for (y = 0; y < height + 2; y++)
1035         memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
1036
1037     cblk->data[cblk->length] = 0xff;
1038     cblk->data[cblk->length+1] = 0xff;
1039     ff_mqc_initdec(&t1->mqc, cblk->data);
1040
1041     while (passno--) {
1042         switch(pass_t) {
1043         case 0:
1044             decode_sigpass(t1, width, height, bpno + 1, bandpos,
1045                            bpass_csty_symbol && (clnpass_cnt >= 4),
1046                            vert_causal_ctx_csty_symbol);
1047             break;
1048         case 1:
1049             decode_refpass(t1, width, height, bpno + 1);
1050             if (bpass_csty_symbol && clnpass_cnt >= 4)
1051                 ff_mqc_initdec(&t1->mqc, cblk->data);
1052             break;
1053         case 2:
1054             decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
1055                            codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1056                            vert_causal_ctx_csty_symbol);
1057             clnpass_cnt = clnpass_cnt + 1;
1058             if (bpass_csty_symbol && clnpass_cnt >= 4)
1059                 ff_mqc_initdec(&t1->mqc, cblk->data);
1060             break;
1061         }
1062
1063         pass_t++;
1064         if (pass_t == 3) {
1065             bpno--;
1066             pass_t = 0;
1067         }
1068     }
1069     return 0;
1070 }
1071
1072 /* TODO: Verify dequantization for lossless case
1073  * comp->data can be float or int
1074  * band->stepsize can be float or int
1075  * depending on the type of DWT transformation.
1076  * see ISO/IEC 15444-1:2002 A.6.1 */
1077
1078 /* Float dequantization of a codeblock.*/
1079 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1080                                  Jpeg2000Component *comp,
1081                                  Jpeg2000T1Context *t1, Jpeg2000Band *band)
1082 {
1083     int i, j;
1084     int w = cblk->coord[0][1] - cblk->coord[0][0];
1085     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1086         float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1087         int *src = t1->data[j];
1088         for (i = 0; i < w; ++i)
1089             datap[i] = src[i] * band->f_stepsize;
1090     }
1091 }
1092
1093 /* Integer dequantization of a codeblock.*/
1094 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1095                                Jpeg2000Component *comp,
1096                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
1097 {
1098     int i, j;
1099     int w = cblk->coord[0][1] - cblk->coord[0][0];
1100     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1101         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1102         int *src = t1->data[j];
1103         for (i = 0; i < w; ++i)
1104             datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15;
1105     }
1106 }
1107
1108 /* Inverse ICT parameters in float and integer.
1109  * int value = (float value) * (1<<16) */
1110 static const float f_ict_params[4] = {
1111     1.402f,
1112     0.34413f,
1113     0.71414f,
1114     1.772f
1115 };
1116 static const int   i_ict_params[4] = {
1117      91881,
1118      22553,
1119      46802,
1120     116130
1121 };
1122
1123 static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1124 {
1125     int i, csize = 1;
1126     int32_t *src[3],  i0,  i1,  i2;
1127     float   *srcf[3], i0f, i1f, i2f;
1128
1129     for (i = 0; i < 3; i++)
1130         if (tile->codsty[0].transform == FF_DWT97)
1131             srcf[i] = tile->comp[i].f_data;
1132         else
1133             src [i] = tile->comp[i].i_data;
1134
1135     for (i = 0; i < 2; i++)
1136         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1137
1138     switch (tile->codsty[0].transform) {
1139     case FF_DWT97:
1140         for (i = 0; i < csize; i++) {
1141             i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
1142             i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
1143                            - (f_ict_params[2] * *srcf[2]);
1144             i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
1145             *srcf[0]++ = i0f;
1146             *srcf[1]++ = i1f;
1147             *srcf[2]++ = i2f;
1148         }
1149         break;
1150     case FF_DWT97_INT:
1151         for (i = 0; i < csize; i++) {
1152             i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
1153             i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
1154                          - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
1155             i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
1156             *src[0]++ = i0;
1157             *src[1]++ = i1;
1158             *src[2]++ = i2;
1159         }
1160         break;
1161     case FF_DWT53:
1162         for (i = 0; i < csize; i++) {
1163             i1 = *src[0] - (*src[2] + *src[1] >> 2);
1164             i0 = i1 + *src[2];
1165             i2 = i1 + *src[1];
1166             *src[0]++ = i0;
1167             *src[1]++ = i1;
1168             *src[2]++ = i2;
1169         }
1170         break;
1171     }
1172 }
1173
1174 static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1175                                 AVFrame *picture)
1176 {
1177     int compno, reslevelno, bandno;
1178     int x, y;
1179
1180     uint8_t *line;
1181     Jpeg2000T1Context t1;
1182
1183     /* Loop on tile components */
1184     for (compno = 0; compno < s->ncomponents; compno++) {
1185         Jpeg2000Component *comp     = tile->comp + compno;
1186         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1187
1188         /* Loop on resolution levels */
1189         for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1190             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1191             /* Loop on bands */
1192             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1193                 int nb_precincts, precno;
1194                 Jpeg2000Band *band = rlevel->band + bandno;
1195                 int cblkno = 0, bandpos;
1196
1197                 bandpos = bandno + (reslevelno > 0);
1198
1199                 if (band->coord[0][0] == band->coord[0][1] ||
1200                     band->coord[1][0] == band->coord[1][1])
1201                     continue;
1202
1203                 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1204                 /* Loop on precincts */
1205                 for (precno = 0; precno < nb_precincts; precno++) {
1206                     Jpeg2000Prec *prec = band->prec + precno;
1207
1208                     /* Loop on codeblocks */
1209                     for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1210                         int x, y;
1211                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1212                         decode_cblk(s, codsty, &t1, cblk,
1213                                     cblk->coord[0][1] - cblk->coord[0][0],
1214                                     cblk->coord[1][1] - cblk->coord[1][0],
1215                                     bandpos);
1216
1217                         x = cblk->coord[0][0];
1218                         y = cblk->coord[1][0];
1219
1220                         if (codsty->transform == FF_DWT97)
1221                             dequantization_float(x, y, cblk, comp, &t1, band);
1222                         else
1223                             dequantization_int(x, y, cblk, comp, &t1, band);
1224                    } /* end cblk */
1225                 } /*end prec */
1226             } /* end band */
1227         } /* end reslevel */
1228
1229         /* inverse DWT */
1230         ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
1231     } /*end comp */
1232
1233     /* inverse MCT transformation */
1234     if (tile->codsty[0].mct)
1235         mct_decode(s, tile);
1236
1237     if (s->cdef[0] < 0) {
1238         for (x = 0; x < s->ncomponents; x++)
1239             s->cdef[x] = x + 1;
1240         if ((s->ncomponents & 1) == 0)
1241             s->cdef[s->ncomponents-1] = 0;
1242     }
1243
1244     if (s->precision <= 8) {
1245         for (compno = 0; compno < s->ncomponents; compno++) {
1246             Jpeg2000Component *comp = tile->comp + compno;
1247             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1248             float *datap = comp->f_data;
1249             int32_t *i_datap = comp->i_data;
1250             int cbps = s->cbps[compno];
1251             int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1252             int planar = !!picture->data[2];
1253             int pixelsize = planar ? 1 : s->ncomponents;
1254             int plane = 0;
1255
1256             if (planar)
1257                 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
1258
1259
1260             y    = tile->comp[compno].coord[1][0] - s->image_offset_y;
1261             line = picture->data[plane] + y * picture->linesize[plane];
1262             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1263                 uint8_t *dst;
1264
1265                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x;
1266                 dst = line + x * pixelsize + compno*!planar;
1267
1268                 if (codsty->transform == FF_DWT97) {
1269                     for (; x < w; x += s->cdx[compno]) {
1270                         int val = lrintf(*datap) + (1 << (cbps - 1));
1271                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1272                         val = av_clip(val, 0, (1 << cbps) - 1);
1273                         *dst = val << (8 - cbps);
1274                         datap++;
1275                         dst += pixelsize;
1276                     }
1277                 } else {
1278                     for (; x < w; x += s->cdx[compno]) {
1279                         int val = *i_datap + (1 << (cbps - 1));
1280                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1281                         val = av_clip(val, 0, (1 << cbps) - 1);
1282                         *dst = val << (8 - cbps);
1283                         i_datap++;
1284                         dst += pixelsize;
1285                     }
1286                 }
1287                 line += picture->linesize[plane];
1288             }
1289         }
1290     } else {
1291         for (compno = 0; compno < s->ncomponents; compno++) {
1292             Jpeg2000Component *comp = tile->comp + compno;
1293             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1294             float *datap = comp->f_data;
1295             int32_t *i_datap = comp->i_data;
1296             uint16_t *linel;
1297             int cbps = s->cbps[compno];
1298             int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1299             int planar = !!picture->data[2];
1300             int pixelsize = planar ? 1 : s->ncomponents;
1301             int plane = 0;
1302
1303             if (planar)
1304                 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
1305
1306             y     = tile->comp[compno].coord[1][0] - s->image_offset_y;
1307             linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1);
1308             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1309                 uint16_t *dst;
1310
1311                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x;
1312                 dst = linel + (x * pixelsize + compno*!planar);
1313                 if (codsty->transform == FF_DWT97) {
1314                     for (; x < w; x += s-> cdx[compno]) {
1315                         int  val = lrintf(*datap) + (1 << (cbps - 1));
1316                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1317                         val = av_clip(val, 0, (1 << cbps) - 1);
1318                         /* align 12 bit values in little-endian mode */
1319                         *dst = val << (16 - cbps);
1320                         datap++;
1321                         dst += pixelsize;
1322                     }
1323                 } else {
1324                     for (; x < w; x += s-> cdx[compno]) {
1325                         int val = *i_datap + (1 << (cbps - 1));
1326                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1327                         val = av_clip(val, 0, (1 << cbps) - 1);
1328                         /* align 12 bit values in little-endian mode */
1329                         *dst = val << (16 - cbps);
1330                         i_datap++;
1331                         dst += pixelsize;
1332                     }
1333                 }
1334                 linel += picture->linesize[plane] >> 1;
1335             }
1336         }
1337     }
1338
1339     return 0;
1340 }
1341
1342 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1343 {
1344     int tileno, compno;
1345     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1346         for (compno = 0; compno < s->ncomponents; compno++) {
1347             Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
1348             Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1349
1350             ff_jpeg2000_cleanup(comp, codsty);
1351         }
1352         av_freep(&s->tile[tileno].comp);
1353     }
1354     av_freep(&s->tile);
1355     s->numXtiles = s->numYtiles = 0;
1356 }
1357
1358 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1359 {
1360     Jpeg2000CodingStyle *codsty = s->codsty;
1361     Jpeg2000QuantStyle *qntsty  = s->qntsty;
1362     uint8_t *properties         = s->properties;
1363
1364     for (;;) {
1365         int len, ret = 0;
1366         uint16_t marker;
1367         int oldpos;
1368
1369         if (bytestream2_get_bytes_left(&s->g) < 2) {
1370             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1371             break;
1372         }
1373
1374         marker = bytestream2_get_be16u(&s->g);
1375         oldpos = bytestream2_tell(&s->g);
1376
1377         if (marker == JPEG2000_SOD) {
1378             Jpeg2000Tile *tile;
1379             Jpeg2000TilePart *tp;
1380
1381             if (s->curtileno < 0) {
1382                 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
1383                 return AVERROR_INVALIDDATA;
1384             }
1385
1386             tile = s->tile + s->curtileno;
1387             tp = tile->tile_part + tile->tp_idx;
1388             if (tp->tp_end < s->g.buffer) {
1389                 av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
1390                 return AVERROR_INVALIDDATA;
1391             }
1392             bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
1393             bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
1394
1395             continue;
1396         }
1397         if (marker == JPEG2000_EOC)
1398             break;
1399
1400         len = bytestream2_get_be16(&s->g);
1401         if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
1402             return AVERROR_INVALIDDATA;
1403
1404         switch (marker) {
1405         case JPEG2000_SIZ:
1406             ret = get_siz(s);
1407             if (!s->tile)
1408                 s->numXtiles = s->numYtiles = 0;
1409             break;
1410         case JPEG2000_COC:
1411             ret = get_coc(s, codsty, properties);
1412             break;
1413         case JPEG2000_COD:
1414             ret = get_cod(s, codsty, properties);
1415             break;
1416         case JPEG2000_QCC:
1417             ret = get_qcc(s, len, qntsty, properties);
1418             break;
1419         case JPEG2000_QCD:
1420             ret = get_qcd(s, len, qntsty, properties);
1421             break;
1422         case JPEG2000_SOT:
1423             if (!(ret = get_sot(s, len))) {
1424                 av_assert1(s->curtileno >= 0);
1425                 codsty = s->tile[s->curtileno].codsty;
1426                 qntsty = s->tile[s->curtileno].qntsty;
1427                 properties = s->tile[s->curtileno].properties;
1428             }
1429             break;
1430         case JPEG2000_COM:
1431             // the comment is ignored
1432             bytestream2_skip(&s->g, len - 2);
1433             break;
1434         case JPEG2000_TLM:
1435             // Tile-part lengths
1436             ret = get_tlm(s, len);
1437             break;
1438         default:
1439             av_log(s->avctx, AV_LOG_ERROR,
1440                    "unsupported marker 0x%.4X at pos 0x%X\n",
1441                    marker, bytestream2_tell(&s->g) - 4);
1442             bytestream2_skip(&s->g, len - 2);
1443             break;
1444         }
1445         if (bytestream2_tell(&s->g) - oldpos != len || ret) {
1446             av_log(s->avctx, AV_LOG_ERROR,
1447                    "error during processing marker segment %.4x\n", marker);
1448             return ret ? ret : -1;
1449         }
1450     }
1451     return 0;
1452 }
1453
1454 /* Read bit stream packets --> T2 operation. */
1455 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1456 {
1457     int ret = 0;
1458     int tileno;
1459
1460     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1461         Jpeg2000Tile *tile = s->tile + tileno;
1462
1463         if (ret = init_tile(s, tileno))
1464             return ret;
1465
1466         s->g = tile->tile_part[0].tpg;
1467         if (ret = jpeg2000_decode_packets(s, tile))
1468             return ret;
1469     }
1470
1471     return 0;
1472 }
1473
1474 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1475 {
1476     uint32_t atom_size, atom, atom_end;
1477     int search_range = 10;
1478
1479     while (search_range
1480            &&
1481            bytestream2_get_bytes_left(&s->g) >= 8) {
1482         atom_size = bytestream2_get_be32u(&s->g);
1483         atom      = bytestream2_get_be32u(&s->g);
1484         atom_end  = bytestream2_tell(&s->g) + atom_size - 8;
1485
1486         if (atom == JP2_CODESTREAM)
1487             return 1;
1488
1489         if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
1490             return 0;
1491
1492         if (atom == JP2_HEADER &&
1493                    atom_size >= 16) {
1494             uint32_t atom2_size, atom2, atom2_end;
1495             do {
1496                 atom2_size = bytestream2_get_be32u(&s->g);
1497                 atom2      = bytestream2_get_be32u(&s->g);
1498                 atom2_end  = bytestream2_tell(&s->g) + atom2_size - 8;
1499                 if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
1500                     break;
1501                 if (atom2 == JP2_CODESTREAM) {
1502                     return 1;
1503                 } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
1504                     int method = bytestream2_get_byteu(&s->g);
1505                     bytestream2_skipu(&s->g, 2);
1506                     if (method == 1) {
1507                         s->colour_space = bytestream2_get_be32u(&s->g);
1508                     }
1509                 } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
1510                     int i, size, colour_count, colour_channels, colour_depth[3];
1511                     uint32_t r, g, b;
1512                     colour_count = bytestream2_get_be16u(&s->g);
1513                     colour_channels = bytestream2_get_byteu(&s->g);
1514                     // FIXME: Do not ignore channel_sign
1515                     colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1516                     colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1517                     colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1518                     size = (colour_depth[0] + 7 >> 3) * colour_count +
1519                            (colour_depth[1] + 7 >> 3) * colour_count +
1520                            (colour_depth[2] + 7 >> 3) * colour_count;
1521                     if (colour_count > 256   ||
1522                         colour_channels != 3 ||
1523                         colour_depth[0] > 16 ||
1524                         colour_depth[1] > 16 ||
1525                         colour_depth[2] > 16 ||
1526                         atom2_size < size) {
1527                         avpriv_request_sample(s->avctx, "Unknown palette");
1528                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
1529                         continue;
1530                     }
1531                     s->pal8 = 1;
1532                     for (i = 0; i < colour_count; i++) {
1533                         if (colour_depth[0] <= 8) {
1534                             r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
1535                             r |= r >> colour_depth[0];
1536                         } else {
1537                             r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
1538                         }
1539                         if (colour_depth[1] <= 8) {
1540                             g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
1541                             r |= r >> colour_depth[1];
1542                         } else {
1543                             g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
1544                         }
1545                         if (colour_depth[2] <= 8) {
1546                             b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
1547                             r |= r >> colour_depth[2];
1548                         } else {
1549                             b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
1550                         }
1551                         s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
1552                     }
1553                 } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
1554                     int n = bytestream2_get_be16u(&s->g);
1555                     for (; n>0; n--) {
1556                         int cn   = bytestream2_get_be16(&s->g);
1557                         int av_unused typ  = bytestream2_get_be16(&s->g);
1558                         int asoc = bytestream2_get_be16(&s->g);
1559                         if (cn < 4 || asoc < 4)
1560                             s->cdef[cn] = asoc;
1561                     }
1562                 }
1563                 bytestream2_seek(&s->g, atom2_end, SEEK_SET);
1564             } while (atom_end - atom2_end >= 8);
1565         } else {
1566             search_range--;
1567         }
1568         bytestream2_seek(&s->g, atom_end, SEEK_SET);
1569     }
1570
1571     return 0;
1572 }
1573
1574 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1575                                  int *got_frame, AVPacket *avpkt)
1576 {
1577     Jpeg2000DecoderContext *s = avctx->priv_data;
1578     ThreadFrame frame = { .f = data };
1579     AVFrame *picture = data;
1580     int tileno, ret;
1581
1582     s->avctx     = avctx;
1583     bytestream2_init(&s->g, avpkt->data, avpkt->size);
1584     s->curtileno = -1;
1585     memset(s->cdef, -1, sizeof(s->cdef));
1586
1587     if (bytestream2_get_bytes_left(&s->g) < 2) {
1588         ret = AVERROR_INVALIDDATA;
1589         goto end;
1590     }
1591
1592     // check if the image is in jp2 format
1593     if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1594        (bytestream2_get_be32u(&s->g) == 12) &&
1595        (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1596        (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
1597         if (!jp2_find_codestream(s)) {
1598             av_log(avctx, AV_LOG_ERROR,
1599                    "Could not find Jpeg2000 codestream atom.\n");
1600             ret = AVERROR_INVALIDDATA;
1601             goto end;
1602         }
1603     } else {
1604         bytestream2_seek(&s->g, 0, SEEK_SET);
1605     }
1606
1607     if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1608         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1609         ret = AVERROR_INVALIDDATA;
1610         goto end;
1611     }
1612     if (ret = jpeg2000_read_main_headers(s))
1613         goto end;
1614
1615     /* get picture buffer */
1616     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1617         goto end;
1618     picture->pict_type = AV_PICTURE_TYPE_I;
1619     picture->key_frame = 1;
1620
1621     if (ret = jpeg2000_read_bitstream_packets(s))
1622         goto end;
1623
1624     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1625         if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
1626             goto end;
1627
1628     jpeg2000_dec_cleanup(s);
1629
1630     *got_frame = 1;
1631
1632     if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
1633         memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
1634
1635     return bytestream2_tell(&s->g);
1636
1637 end:
1638     jpeg2000_dec_cleanup(s);
1639     return ret;
1640 }
1641
1642 static void jpeg2000_init_static_data(AVCodec *codec)
1643 {
1644     ff_jpeg2000_init_tier1_luts();
1645     ff_mqc_init_context_tables();
1646 }
1647
1648 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1649 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1650
1651 static const AVOption options[] = {
1652     { "lowres",  "Lower the decoding resolution by a power of two",
1653         OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1654     { NULL },
1655 };
1656
1657 static const AVProfile profiles[] = {
1658     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0,  "JPEG 2000 codestream restriction 0"   },
1659     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1,  "JPEG 2000 codestream restriction 1"   },
1660     { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1661     { FF_PROFILE_JPEG2000_DCINEMA_2K,             "JPEG 2000 digital cinema 2K"          },
1662     { FF_PROFILE_JPEG2000_DCINEMA_4K,             "JPEG 2000 digital cinema 4K"          },
1663     { FF_PROFILE_UNKNOWN },
1664 };
1665
1666 static const AVClass jpeg2000_class = {
1667     .class_name = "jpeg2000",
1668     .item_name  = av_default_item_name,
1669     .option     = options,
1670     .version    = LIBAVUTIL_VERSION_INT,
1671 };
1672
1673 AVCodec ff_jpeg2000_decoder = {
1674     .name             = "jpeg2000",
1675     .long_name        = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1676     .type             = AVMEDIA_TYPE_VIDEO,
1677     .id               = AV_CODEC_ID_JPEG2000,
1678     .capabilities     = CODEC_CAP_FRAME_THREADS,
1679     .priv_data_size   = sizeof(Jpeg2000DecoderContext),
1680     .init_static_data = jpeg2000_init_static_data,
1681     .decode           = jpeg2000_decode_frame,
1682     .priv_class       = &jpeg2000_class,
1683     .max_lowres       = 5,
1684     .profiles         = NULL_IF_CONFIG_SMALL(profiles)
1685 };