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