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