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