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