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