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