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