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