]> git.sesse.net Git - ffmpeg/blob - libavcodec/jpeg2000dec.c
avcodec/cdgraphics: check buffer size before use
[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/common.h"
29 #include "libavutil/opt.h"
30 #include "avcodec.h"
31 #include "bytestream.h"
32 #include "internal.h"
33 #include "thread.h"
34 #include "jpeg2000.h"
35
36 #define JP2_SIG_TYPE    0x6A502020
37 #define JP2_SIG_VALUE   0x0D0A870A
38 #define JP2_CODESTREAM  0x6A703263
39
40 #define HAD_COC 0x01
41 #define HAD_QCC 0x02
42
43 typedef struct Jpeg2000TilePart {
44     uint16_t tp_idx;                    // Tile-part index
45     uint8_t tile_index;                 // Tile index who refers the tile-part
46     uint32_t tp_len;                    // Length of tile-part
47     const uint8_t *tp_start_bstrm;      // Start address bit stream in tile-part
48     const uint8_t *tp_end_bstrm;        // End address of the bit stream tile part
49 } Jpeg2000TilePart;
50
51 /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
52  * one per component, so tile_part elements have a size of 3 */
53 typedef struct Jpeg2000Tile {
54     Jpeg2000Component   *comp;
55     uint8_t             properties[4];
56     Jpeg2000CodingStyle codsty[4];
57     Jpeg2000QuantStyle  qntsty[4];
58     Jpeg2000TilePart    tile_part[3];
59 } Jpeg2000Tile;
60
61 typedef struct Jpeg2000DecoderContext {
62     AVClass         *class;
63     AVCodecContext  *avctx;
64
65     int             width, height;
66     int             image_offset_x, image_offset_y;
67     int             tile_offset_x, tile_offset_y;
68     uint8_t         cbps[4];    // bits per sample in particular components
69     uint8_t         sgnd[4];    // if a component is signed
70     uint8_t         properties[4];
71     int             cdx[4], cdy[4];
72     int             precision;
73     int             ncomponents;
74     int             tile_width, tile_height;
75     int             numXtiles, numYtiles;
76     int             maxtilelen;
77
78     Jpeg2000CodingStyle codsty[4];
79     Jpeg2000QuantStyle  qntsty[4];
80
81     const uint8_t   *buf_start;
82     const uint8_t   *buf;
83     const uint8_t   *buf_end;
84     int             bit_index;
85
86     int16_t         curtileno;
87     Jpeg2000Tile    *tile;
88
89     /*options parameters*/
90     int16_t         lowres;
91     int16_t         reduction_factor;
92 } Jpeg2000DecoderContext;
93
94 /* get_bits functions for JPEG2000 packet bitstream
95  * It is a get_bit function with a bit-stuffing routine. If the value of the
96  * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
97  * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
98 static int get_bits(Jpeg2000DecoderContext *s, int n)
99 {
100     int res = 0;
101     if (s->buf_end - s->buf < ((n - s->bit_index) >> 8))
102         return AVERROR(EINVAL);
103     while (--n >= 0) {
104         res <<= 1;
105         if (s->bit_index == 0) {
106             s->bit_index = 7 + (*s->buf != 0xff);
107             s->buf++;
108         }
109         s->bit_index--;
110         res |= (*s->buf >> s->bit_index) & 1;
111     }
112     return res;
113 }
114
115 static void jpeg2000_flush(Jpeg2000DecoderContext *s)
116 {
117     if (*s->buf == 0xff)
118         s->buf++;
119     s->bit_index = 8;
120     s->buf++;
121 }
122
123 /* decode the value stored in node */
124 static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
125                            int threshold)
126 {
127     Jpeg2000TgtNode *stack[30];
128     int sp = -1, curval = 0;
129
130     while (node && !node->vis) {
131         stack[++sp] = node;
132         node        = node->parent;
133     }
134
135     if (node)
136         curval = node->val;
137     else
138         curval = stack[sp]->val;
139
140     while (curval < threshold && sp >= 0) {
141         if (curval < stack[sp]->val)
142             curval = stack[sp]->val;
143         while (curval < threshold) {
144             int ret;
145             if ((ret = get_bits(s, 1)) > 0) {
146                 stack[sp]->vis++;
147                 break;
148             } else if (!ret)
149                 curval++;
150             else
151                 return ret;
152         }
153         stack[sp]->val = curval;
154         sp--;
155     }
156     return curval;
157 }
158
159 /* marker segments */
160 /* get sizes and offsets of image, tiles; number of components */
161 static int get_siz(Jpeg2000DecoderContext *s)
162 {
163     int i;
164
165     if (s->buf_end - s->buf < 36)
166         return AVERROR(EINVAL);
167
168     s->avctx->profile = bytestream_get_be16(&s->buf); // Rsiz
169     s->width          = bytestream_get_be32(&s->buf); // Width
170     s->height         = bytestream_get_be32(&s->buf); // Height
171     s->image_offset_x = bytestream_get_be32(&s->buf); // X0Siz
172     s->image_offset_y = bytestream_get_be32(&s->buf); // Y0Siz
173     s->tile_width     = bytestream_get_be32(&s->buf); // XTSiz
174     s->tile_height    = bytestream_get_be32(&s->buf); // YTSiz
175     s->tile_offset_x  = bytestream_get_be32(&s->buf); // XT0Siz
176     s->tile_offset_y  = bytestream_get_be32(&s->buf); // YT0Siz
177     s->ncomponents    = bytestream_get_be16(&s->buf); // CSiz
178
179     if (s->buf_end - s->buf < 2 * s->ncomponents)
180         return AVERROR(EINVAL);
181
182     for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
183         uint8_t x = bytestream_get_byte(&s->buf);
184         s->cbps[i]   = (x & 0x7f) + 1;
185         s->precision = FFMAX(s->cbps[i], s->precision);
186         s->sgnd[i]   = (x & 0x80) == 1;
187         s->cdx[i]    = bytestream_get_byte(&s->buf);
188         s->cdy[i]    = bytestream_get_byte(&s->buf);
189     }
190
191     s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
192     s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
193
194     s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(*s->tile));
195     if (!s->tile)
196         return AVERROR(ENOMEM);
197
198     for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
199         Jpeg2000Tile *tile = s->tile + i;
200
201         tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
202         if (!tile->comp)
203             return AVERROR(ENOMEM);
204     }
205
206     /* compute image size with reduction factor */
207     s->avctx->width  = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,
208                                                s->reduction_factor);
209     s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
210                                                s->reduction_factor);
211
212     switch (s->avctx->profile) {
213     case FF_PROFILE_JPEG2000_DCINEMA_2K:
214     case FF_PROFILE_JPEG2000_DCINEMA_4K:
215         /* XYZ color-space for digital cinema profiles */
216         s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;
217         break;
218     default:
219         /* For other profiles selects color-space according number of
220          * components and bit depth precision. */
221         switch (s->ncomponents) {
222         case 1:
223             if (s->precision > 8)
224                 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
225             else
226                 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
227             break;
228         case 3:
229             if (s->precision > 8)
230                 s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
231             else
232                 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
233             break;
234         case 4:
235             s->avctx->pix_fmt = AV_PIX_FMT_BGRA;
236             break;
237         default:
238             /* pixel format can not be identified */
239             s->avctx->pix_fmt = AV_PIX_FMT_NONE;
240             break;
241         }
242         break;
243     }
244     return 0;
245 }
246
247 /* get common part for COD and COC segments */
248 static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
249 {
250     uint8_t byte;
251
252     if (s->buf_end - s->buf < 5)
253         return AVERROR(EINVAL);
254     c->nreslevels = bytestream_get_byte(&s->buf) + 1; // num of resolution levels - 1
255
256     /* compute number of resolution levels to decode */
257     if (c->nreslevels < s->reduction_factor)
258         c->nreslevels2decode = 1;
259     else
260         c->nreslevels2decode = c->nreslevels - s->reduction_factor;
261
262     c->log2_cblk_width  = bytestream_get_byte(&s->buf) + 2; // cblk width
263     c->log2_cblk_height = bytestream_get_byte(&s->buf) + 2; // cblk height
264
265     c->cblk_style = bytestream_get_byte(&s->buf);
266     if (c->cblk_style != 0) { // cblk style
267         av_log(s->avctx, AV_LOG_ERROR, "no extra cblk styles supported\n");
268         return -1;
269     }
270     c->transform = bytestream_get_byte(&s->buf); // DWT transformation type
271     /* set integer 9/7 DWT in case of BITEXACT flag */
272     if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
273         c->transform = FF_DWT97_INT;
274
275     if (c->csty & JPEG2000_CSTY_PREC) {
276         int i;
277         for (i = 0; i < c->nreslevels; i++) {
278             byte = bytestream_get_byte(&s->buf);
279             c->log2_prec_widths[i]  =  byte       & 0x0F;    // precinct PPx
280             c->log2_prec_heights[i] = (byte >> 4) & 0x0F;    // precinct PPy
281         }
282     }
283     return 0;
284 }
285
286 /* get coding parameters for a particular tile or whole image*/
287 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
288                    uint8_t *properties)
289 {
290     Jpeg2000CodingStyle tmp;
291     int compno;
292
293     if (s->buf_end - s->buf < 5)
294         return AVERROR(EINVAL);
295
296     tmp.log2_prec_width  =
297     tmp.log2_prec_height = 15;
298
299     tmp.csty = bytestream_get_byte(&s->buf);
300
301     // get progression order
302     tmp.prog_order = bytestream_get_byte(&s->buf);
303
304     tmp.nlayers = bytestream_get_be16(&s->buf);
305     tmp.mct     = bytestream_get_byte(&s->buf); // multiple component transformation
306
307     get_cox(s, &tmp);
308     for (compno = 0; compno < s->ncomponents; compno++)
309         if (!(properties[compno] & HAD_COC))
310             memcpy(c + compno, &tmp, sizeof(tmp));
311     return 0;
312 }
313
314 /* Get coding parameters for a component in the whole image or a
315  * particular tile. */
316 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
317                    uint8_t *properties)
318 {
319     int compno;
320
321     if (s->buf_end - s->buf < 2)
322         return AVERROR(EINVAL);
323
324     compno = bytestream_get_byte(&s->buf);
325
326     c      += compno;
327     c->csty = bytestream_get_byte(&s->buf);
328     get_cox(s, c);
329
330     properties[compno] |= HAD_COC;
331     return 0;
332 }
333
334 /* Get common part for QCD and QCC segments. */
335 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
336 {
337     int i, x;
338
339     if (s->buf_end - s->buf < 1)
340         return AVERROR(EINVAL);
341
342     x = bytestream_get_byte(&s->buf); // Sqcd
343
344     q->nguardbits = x >> 5;
345     q->quantsty   = x & 0x1f;
346
347     if (q->quantsty == JPEG2000_QSTY_NONE) {
348         n -= 3;
349         if (s->buf_end - s->buf < n)
350             return AVERROR(EINVAL);
351         for (i = 0; i < n; i++)
352             q->expn[i] = bytestream_get_byte(&s->buf) >> 3;
353     } else if (q->quantsty == JPEG2000_QSTY_SI) {
354         if (s->buf_end - s->buf < 2)
355             return AVERROR(EINVAL);
356         x          = bytestream_get_be16(&s->buf);
357         q->expn[0] = x >> 11;
358         q->mant[0] = x & 0x7ff;
359         for (i = 1; i < 32 * 3; i++) {
360             int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
361             q->expn[i] = curexpn;
362             q->mant[i] = q->mant[0];
363         }
364     } else {
365         n = (n - 3) >> 1;
366         if (s->buf_end - s->buf < n)
367             return AVERROR(EINVAL);
368         for (i = 0; i < n; i++) {
369             x          = bytestream_get_be16(&s->buf);
370             q->expn[i] = x >> 11;
371             q->mant[i] = x & 0x7ff;
372         }
373     }
374     return 0;
375 }
376
377 /* Get quantization parameters for a particular tile or a whole image. */
378 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
379                    uint8_t *properties)
380 {
381     Jpeg2000QuantStyle tmp;
382     int compno;
383
384     if (get_qcx(s, n, &tmp))
385         return -1;
386     for (compno = 0; compno < s->ncomponents; compno++)
387         if (!(properties[compno] & HAD_QCC))
388             memcpy(q + compno, &tmp, sizeof(tmp));
389     return 0;
390 }
391
392 /* Get quantization parameters for a component in the whole image
393  * on in a particular tile. */
394 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
395                    uint8_t *properties)
396 {
397     int compno;
398
399     if (s->buf_end - s->buf < 1)
400         return AVERROR(EINVAL);
401
402     compno              = bytestream_get_byte(&s->buf);
403     properties[compno] |= HAD_QCC;
404     return get_qcx(s, n - 1, q + compno);
405 }
406
407 /* Get start of tile segment. */
408 static uint8_t get_sot(Jpeg2000DecoderContext *s, int n)
409 {
410     Jpeg2000TilePart *tp;
411     uint16_t Isot;
412     uint32_t Psot;
413     uint8_t TPsot;
414
415     if (s->buf_end - s->buf < 4)
416         return AVERROR(EINVAL);
417
418     Isot = bytestream_get_be16(&s->buf);        // Isot
419     if (Isot) {
420         av_log(s->avctx, AV_LOG_ERROR,
421                "Not a DCINEMA JP2K file: more than one tile\n");
422         return -1;
423     }
424     Psot  = bytestream_get_be32(&s->buf);       // Psot
425     TPsot = bytestream_get_byte(&s->buf);       // TPsot
426
427     /* Read TNSot but not used */
428     bytestream_get_byte(&s->buf);               // TNsot
429
430     tp             = s->tile[s->curtileno].tile_part + TPsot;
431     tp->tile_index = Isot;
432     tp->tp_len     = Psot;
433     tp->tp_idx     = TPsot;
434
435     /* Start of bit stream. Pointer to SOD marker
436      * Check SOD marker is present. */
437     if (JPEG2000_SOD == bytestream_get_be16(&s->buf))
438         tp->tp_start_bstrm = s->buf;
439     else {
440         av_log(s->avctx, AV_LOG_ERROR, "SOD marker not found \n");
441         return -1;
442     }
443
444     /* End address of bit stream =
445      *     start address + (Psot - size of SOT HEADER(n)
446      *     - size of SOT MARKER(2)  - size of SOD marker(2) */
447     tp->tp_end_bstrm = s->buf + (tp->tp_len - n - 4);
448
449     // set buffer pointer to end of tile part header
450     s->buf = tp->tp_end_bstrm;
451
452     return 0;
453 }
454
455 /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
456  * Used to know the number of tile parts and lengths.
457  * There may be multiple TLMs in the header.
458  * TODO: The function is not used for tile-parts management, nor anywhere else.
459  * It can be useful to allocate memory for tile parts, before managing the SOT
460  * markers. Parsing the TLM header is needed to increment the input header
461  * buffer.
462  * This marker is mandatory for DCI. */
463 static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
464 {
465     uint8_t Stlm, ST, SP, tile_tlm, i;
466     bytestream_get_byte(&s->buf);               /* Ztlm: skipped */
467     Stlm = bytestream_get_byte(&s->buf);
468
469     // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
470     ST = (Stlm >> 4) & 0x03;
471     // TODO: Manage case of ST = 0b11 --> raise error
472     SP       = (Stlm >> 6) & 0x01;
473     tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
474     for (i = 0; i < tile_tlm; i++) {
475         switch (ST) {
476         case 0:
477             break;
478         case 1:
479             bytestream_get_byte(&s->buf);
480             break;
481         case 2:
482             bytestream_get_be16(&s->buf);
483             break;
484         case 3:
485             bytestream_get_be32(&s->buf);
486             break;
487         }
488         if (SP == 0) {
489             bytestream_get_be16(&s->buf);
490         } else {
491             bytestream_get_be32(&s->buf);
492         }
493     }
494     return 0;
495 }
496
497 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
498 {
499     int compno;
500     int tilex = tileno % s->numXtiles;
501     int tiley = tileno / s->numXtiles;
502     Jpeg2000Tile *tile = s->tile + tileno;
503     Jpeg2000CodingStyle *codsty;
504     Jpeg2000QuantStyle  *qntsty;
505
506     if (!tile->comp)
507         return AVERROR(ENOMEM);
508
509     /* copy codsty, qnsty to tile. TODO: Is it the best way?
510      * codsty, qnsty is an array of 4 structs Jpeg2000CodingStyle
511      * and Jpeg2000QuantStyle */
512     memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(*codsty));
513     memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(*qntsty));
514
515     for (compno = 0; compno < s->ncomponents; compno++) {
516         Jpeg2000Component *comp = tile->comp + compno;
517         int ret; // global bandno
518         codsty = tile->codsty + compno;
519         qntsty = tile->qntsty + compno;
520
521         comp->coord_o[0][0] = FFMAX(tilex       * s->tile_width  + s->tile_offset_x, s->image_offset_x);
522         comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width  + s->tile_offset_x, s->width);
523         comp->coord_o[1][0] = FFMAX(tiley       * s->tile_height + s->tile_offset_y, s->image_offset_y);
524         comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
525
526         // FIXME: add a dcinema profile check ?
527         // value is guaranteed by profile (orig=0, 1 tile)
528         comp->coord[0][0] = 0;
529         comp->coord[0][1] = s->avctx->width;
530         comp->coord[1][0] = 0;
531         comp->coord[1][1] = s->avctx->height;
532
533         if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
534                                              s->cbps[compno], s->cdx[compno],
535                                              s->cdy[compno], s->avctx))
536             return ret;
537     }
538     return 0;
539 }
540
541 /* Read the number of coding passes. */
542 static int getnpasses(Jpeg2000DecoderContext *s)
543 {
544     int num;
545     if (!get_bits(s, 1))
546         return 1;
547     if (!get_bits(s, 1))
548         return 2;
549     if ((num = get_bits(s, 2)) != 3)
550         return num < 0 ? num : 3 + num;
551     if ((num = get_bits(s, 5)) != 31)
552         return num < 0 ? num : 6 + num;
553     num = get_bits(s, 7);
554     return num < 0 ? num : 37 + num;
555 }
556
557 static int getlblockinc(Jpeg2000DecoderContext *s)
558 {
559     int res = 0, ret;
560     while (ret = get_bits(s, 1)) {
561         if (ret < 0)
562             return ret;
563         res++;
564     }
565     return res;
566 }
567
568 static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
569                                   Jpeg2000CodingStyle *codsty,
570                                   Jpeg2000ResLevel *rlevel, int precno,
571                                   int layno, uint8_t *expn, int numgbits)
572 {
573     int bandno, cblkno, ret, nb_code_blocks;
574
575     if (!(ret = get_bits(s, 1))) {
576         jpeg2000_flush(s);
577         return 0;
578     } else if (ret < 0)
579         return ret;
580
581     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
582         Jpeg2000Band *band = rlevel->band + bandno;
583         Jpeg2000Prec *prec = band->prec + precno;
584
585         if (band->coord[0][0] == band->coord[0][1] ||
586             band->coord[1][0] == band->coord[1][1])
587             continue;
588         prec->yi0 = 0;
589         prec->xi0 = 0;
590         nb_code_blocks =  prec->nb_codeblocks_height *
591                           prec->nb_codeblocks_width;
592         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
593             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
594             int incl, newpasses, llen;
595
596             if (cblk->npasses)
597                 incl = get_bits(s, 1);
598             else
599                 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
600             if (!incl)
601                 continue;
602             else if (incl < 0)
603                 return incl;
604
605             if (!cblk->npasses)
606                 cblk->nonzerobits = expn[bandno] + numgbits - 1 -
607                                     tag_tree_decode(s, prec->zerobits + cblkno,
608                                                     100);
609             if ((newpasses = getnpasses(s)) < 0)
610                 return newpasses;
611             if ((llen = getlblockinc(s)) < 0)
612                 return llen;
613             cblk->lblock += llen;
614             if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
615                 return ret;
616             cblk->lengthinc = ret;
617             cblk->npasses  += newpasses;
618         }
619     }
620     jpeg2000_flush(s);
621
622     if (codsty->csty & JPEG2000_CSTY_EPH) {
623         if (AV_RB16(s->buf) == JPEG2000_EPH)
624             s->buf += 2;
625         else
626             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
627     }
628
629     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
630         Jpeg2000Band *band = rlevel->band + bandno;
631         Jpeg2000Prec *prec = band->prec + precno;
632
633         nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
634         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
635             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
636             if (s->buf_end - s->buf < cblk->lengthinc)
637                 return AVERROR(EINVAL);
638             /* Code-block data can be empty. In that case initialize data
639              * with 0xFFFF. */
640             if (cblk->lengthinc > 0) {
641                 bytestream_get_buffer(&s->buf, cblk->data, cblk->lengthinc);
642             } else {
643                 cblk->data[0] = 0xFF;
644                 cblk->data[1] = 0xFF;
645             }
646             cblk->length   += cblk->lengthinc;
647             cblk->lengthinc = 0;
648         }
649     }
650     return 0;
651 }
652
653 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
654 {
655     int layno, reslevelno, compno, precno, ok_reslevel;
656     uint8_t prog_order = tile->codsty[0].prog_order;
657     uint16_t x;
658     uint16_t y;
659
660     s->bit_index = 8;
661     switch (prog_order) {
662     case JPEG2000_PGOD_LRCP:
663         for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
664             ok_reslevel = 1;
665             for (reslevelno = 0; ok_reslevel; reslevelno++) {
666                 ok_reslevel = 0;
667                 for (compno = 0; compno < s->ncomponents; compno++) {
668                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
669                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
670                     if (reslevelno < codsty->nreslevels) {
671                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
672                                                    reslevelno;
673                         ok_reslevel = 1;
674                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
675                             if (jpeg2000_decode_packet(s,
676                                                        codsty, rlevel,
677                                                        precno, layno,
678                                                        qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
679                                                        qntsty->nguardbits))
680                                 return -1;
681                     }
682                 }
683             }
684         }
685         break;
686
687     case JPEG2000_PGOD_CPRL:
688         for (compno = 0; compno < s->ncomponents; compno++) {
689             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
690             Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
691
692             /* Set bit stream buffer address according to tile-part.
693              * For DCinema one tile-part per component, so can be
694              * indexed by component. */
695             s->buf = tile->tile_part[compno].tp_start_bstrm;
696
697             /* Position loop (y axis)
698              * TODO: Automate computing of step 256.
699              * Fixed here, but to be computed before entering here. */
700             for (y = 0; y < s->height; y += 256) {
701                 /* Position loop (y axis)
702                  * TODO: automate computing of step 256.
703                  * Fixed here, but to be computed before entering here. */
704                 for (x = 0; x < s->width; x += 256) {
705                     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
706                         uint16_t prcx, prcy;
707                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
708                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
709
710                         if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
711                               (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
712                             continue;
713
714                         if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
715                               (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
716                             continue;
717
718                         // check if a precinct exists
719                         prcx   = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
720                         prcy   = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
721                         precno = prcx + rlevel->num_precincts_x * prcy;
722                         for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
723                             if (jpeg2000_decode_packet(s, codsty, rlevel,
724                                                        precno, layno,
725                                                        qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
726                                                        qntsty->nguardbits))
727                                 return -1;
728                         }
729                     }
730                 }
731             }
732         }
733         break;
734
735     default:
736         break;
737     }
738
739     /* EOC marker reached */
740     s->buf += 2;
741
742     return 0;
743 }
744
745 /* TIER-1 routines */
746 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
747                            int bpno, int bandno)
748 {
749     int mask = 3 << (bpno - 1), y0, x, y;
750
751     for (y0 = 0; y0 < height; y0 += 4)
752         for (x = 0; x < width; x++)
753             for (y = y0; y < height && y < y0 + 4; y++)
754                 if ((t1->flags[y + 1][x + 1] & JPEG2000_T1_SIG_NB)
755                     && !(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
756                     if (ff_mqc_decode(&t1->mqc,
757                                       t1->mqc.cx_states +
758                                       ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
759                                                              bandno))) {
760                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
761                                                                     &xorbit);
762
763                         t1->data[y][x] =
764                             (ff_mqc_decode(&t1->mqc,
765                                            t1->mqc.cx_states + ctxno) ^ xorbit)
766                             ? -mask : mask;
767
768                         ff_jpeg2000_set_significance(t1, x, y,
769                                                      t1->data[y][x] < 0);
770                     }
771                     t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
772                 }
773 }
774
775 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
776                            int bpno)
777 {
778     int phalf, nhalf;
779     int y0, x, y;
780
781     phalf = 1 << (bpno - 1);
782     nhalf = -phalf;
783
784     for (y0 = 0; y0 < height; y0 += 4)
785         for (x = 0; x < width; x++)
786             for (y = y0; y < height && y < y0 + 4; y++)
787                 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
788                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
789                     int r     = ff_mqc_decode(&t1->mqc,
790                                               t1->mqc.cx_states + ctxno)
791                                 ? phalf : nhalf;
792                     t1->data[y][x]          += t1->data[y][x] < 0 ? -r : r;
793                     t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
794                 }
795 }
796
797 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
798                            int width, int height, int bpno, int bandno,
799                            int seg_symbols)
800 {
801     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
802
803     for (y0 = 0; y0 < height; y0 += 4)
804         for (x = 0; x < width; x++) {
805             if (y0 + 3 < height &&
806                 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
807                   (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
808                   (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
809                   (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
810                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
811                     continue;
812                 runlen = ff_mqc_decode(&t1->mqc,
813                                        t1->mqc.cx_states + MQC_CX_UNI);
814                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
815                                                        t1->mqc.cx_states +
816                                                        MQC_CX_UNI);
817                 dec = 1;
818             } else {
819                 runlen = 0;
820                 dec    = 0;
821             }
822
823             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
824                 if (!dec) {
825                     if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))
826                         dec = ff_mqc_decode(&t1->mqc,
827                                             t1->mqc.cx_states +
828                                             ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
829                                                                    bandno));
830                 }
831                 if (dec) {
832                     int xorbit;
833                     int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
834                                                         &xorbit);
835                     t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
836                                                     t1->mqc.cx_states + ctxno) ^
837                                       xorbit)
838                                      ? -mask : mask;
839                     ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
840                 }
841                 dec = 0;
842                 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
843             }
844         }
845     if (seg_symbols) {
846         int val;
847         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
848         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
849         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
850         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
851         if (val != 0xa)
852             av_log(s->avctx, AV_LOG_ERROR,
853                    "Segmentation symbol value incorrect\n");
854     }
855 }
856
857 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
858                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
859                        int width, int height, int bandpos)
860 {
861     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
862
863     for (y = 0; y < height; y++)
864         memset(t1->data[y], 0, width * sizeof(width));
865
866     /* If code-block contains no compressed data: nothing to do. */
867     if (!cblk->length)
868         return 0;
869     for (y = 0; y < height + 2; y++)
870         memset(t1->flags[y], 0, (width + 2) * sizeof(width));
871
872     ff_mqc_initdec(&t1->mqc, cblk->data);
873     cblk->data[cblk->length]     = 0xff;
874     cblk->data[cblk->length + 1] = 0xff;
875
876     while (passno--) {
877         switch (pass_t) {
878         case 0:
879             decode_sigpass(t1, width, height, bpno + 1, bandpos);
880             break;
881         case 1:
882             decode_refpass(t1, width, height, bpno + 1);
883             break;
884         case 2:
885             decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
886                            codsty->cblk_style & JPEG2000_CBLK_SEGSYM);
887             break;
888         }
889
890         pass_t++;
891         if (pass_t == 3) {
892             bpno--;
893             pass_t = 0;
894         }
895     }
896     return 0;
897 }
898
899 /* TODO: Verify dequantization for lossless case
900  * comp->data can be float or int
901  * band->stepsize can be float or int
902  * depending on the type of DWT transformation.
903  * see ISO/IEC 15444-1:2002 A.6.1 */
904
905 /* Float dequantization of a codeblock.*/
906 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
907                                  Jpeg2000Component *comp,
908                                  Jpeg2000T1Context *t1, Jpeg2000Band *band)
909 {
910     int i, j, idx;
911     float *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
912     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
913         for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
914             idx        = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
915             datap[idx] = (float)(t1->data[j][i]) * ((float)band->stepsize);
916         }
917     return;
918 }
919
920 /* Integer dequantization of a codeblock.*/
921 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
922                                Jpeg2000Component *comp,
923                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
924 {
925     int i, j, idx;
926     int32_t *datap =
927         (int32_t *) &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
928     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
929         for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
930             idx        = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
931             datap[idx] =
932                 ((int32_t)(t1->data[j][i]) * ((int32_t)band->stepsize) + (1 << 15)) >> 16;
933         }
934     return;
935 }
936
937 /* Inverse ICT parameters in float and integer.
938  * int value = (float value) * (1<<16) */
939 static const float f_ict_params[4] = {
940     1.402f,
941     0.34413f,
942     0.71414f,
943     1.772f
944 };
945 static const int   i_ict_params[4] = {
946      91881,
947      22553,
948      46802,
949     116130
950 };
951
952 static int mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
953 {
954     int i, csize = 1;
955     int ret = 0;
956     int32_t *src[3],  i0,  i1,  i2;
957     float   *srcf[3], i0f, i1f, i2f;
958
959     for (i = 0; i < 3; i++)
960         if (tile->codsty[0].transform == FF_DWT97)
961             srcf[i] = tile->comp[i].data;
962         else
963             src[i] = (int32_t *)tile->comp[i].data;
964
965     for (i = 0; i < 2; i++)
966         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
967     switch (tile->codsty[0].transform) {
968     case FF_DWT97:
969         for (i = 0; i < csize; i++) {
970             i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
971             i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
972                            - (f_ict_params[2] * *srcf[2]);
973             i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
974             *srcf[0]++ = i0f;
975             *srcf[1]++ = i1f;
976             *srcf[2]++ = i2f;
977         }
978         break;
979     case FF_DWT97_INT:
980         for (i = 0; i < csize; i++) {
981             i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
982             i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
983                          - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
984             i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
985             *src[0]++ = i0;
986             *src[1]++ = i1;
987             *src[2]++ = i2;
988         }
989         break;
990     case FF_DWT53:
991         for (i = 0; i < csize; i++) {
992             i1 = *src[0] - (*src[2] + *src[1] >> 2);
993             i0 = i1 + *src[2];
994             i2 = i1 + *src[1];
995             *src[0]++ = i0;
996             *src[1]++ = i1;
997             *src[2]++ = i2;
998         }
999         break;
1000     }
1001     return ret;
1002 }
1003
1004 static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1005                                 AVFrame *picture)
1006 {
1007     int compno, reslevelno, bandno;
1008     int x, y;
1009
1010     uint8_t *line;
1011     Jpeg2000T1Context t1;
1012     /* Loop on tile components */
1013
1014     for (compno = 0; compno < s->ncomponents; compno++) {
1015         Jpeg2000Component *comp     = tile->comp + compno;
1016         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1017         /* Loop on resolution levels */
1018         for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1019             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1020             /* Loop on bands */
1021             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1022                 uint16_t nb_precincts, precno;
1023                 Jpeg2000Band *band = rlevel->band + bandno;
1024                 int cblkno = 0, bandpos;
1025                 bandpos = bandno + (reslevelno > 0);
1026
1027                 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1028                 /* Loop on precincts */
1029                 for (precno = 0; precno < nb_precincts; precno++) {
1030                     Jpeg2000Prec *prec = band->prec + precno;
1031
1032                     /* Loop on codeblocks */
1033                     for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1034                         int x, y;
1035                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1036                         decode_cblk(s, codsty, &t1, cblk,
1037                                     cblk->coord[0][1] - cblk->coord[0][0],
1038                                     cblk->coord[1][1] - cblk->coord[1][0],
1039                                     bandpos);
1040
1041                         /* Manage band offsets */
1042                         x = cblk->coord[0][0];
1043                         y = cblk->coord[1][0];
1044                         if ((reslevelno > 0) && ((bandno + 1) & 1)) {
1045                             Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1046                             x += pres->coord[0][1] - pres->coord[0][0];
1047                         }
1048                         if ((reslevelno > 0) && ((bandno + 1) & 2)) {
1049                             Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1050                             y += pres->coord[1][1] - pres->coord[1][0];
1051                         }
1052
1053                         if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1054                             dequantization_int(x, y, cblk, comp, &t1, band);
1055                         else
1056                             dequantization_float(x, y, cblk, comp, &t1, band);
1057                    } /* end cblk */
1058                 } /*end prec */
1059             } /* end band */
1060         } /* end reslevel */
1061
1062         /* inverse DWT */
1063         ff_dwt_decode(&comp->dwt, comp->data);
1064     } /*end comp */
1065
1066     /* inverse MCT transformation */
1067     if (tile->codsty[0].mct)
1068         mct_decode(s, tile);
1069
1070     if (s->avctx->pix_fmt == PIX_FMT_BGRA) // RGBA -> BGRA
1071         FFSWAP(float *, tile->comp[0].data, tile->comp[2].data);
1072
1073     if (s->precision <= 8) {
1074         for (compno = 0; compno < s->ncomponents; compno++) {
1075             Jpeg2000Component *comp = tile->comp + compno;
1076             int32_t *datap = (int32_t *)comp->data;
1077             y    = tile->comp[compno].coord[1][0] - s->image_offset_y;
1078             line = picture->data[0] + y * picture->linesize[0];
1079             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1080                 uint8_t *dst;
1081
1082                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x;
1083                 dst = line + x * s->ncomponents + compno;
1084
1085                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
1086                     *datap += 1 << (s->cbps[compno] - 1);
1087                     if (*datap < 0)
1088                         *datap = 0;
1089                     else if (*datap >= (1 << s->cbps[compno]))
1090                         *datap = (1 << s->cbps[compno]) - 1;
1091                     *dst = *datap++;
1092                     dst += s->ncomponents;
1093                 }
1094                 line += picture->linesize[0];
1095             }
1096         }
1097     } else {
1098         for (compno = 0; compno < s->ncomponents; compno++) {
1099             Jpeg2000Component *comp = tile->comp + compno;
1100             float *datap = comp->data;
1101             int32_t *i_datap = (int32_t *) comp->data;
1102             uint16_t *linel;
1103
1104             y     = tile->comp[compno].coord[1][0] - s->image_offset_y;
1105             linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
1106             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1107                 uint16_t *dst;
1108                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x;
1109                 dst = linel + (x * s->ncomponents + compno);
1110                 for (; x < s->avctx->width; x += s->cdx[compno]) {
1111                     int16_t val;
1112                     /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1113                     if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1114                         val = *i_datap + (1 << (s->cbps[compno] - 1));
1115                     else
1116                         val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
1117                     val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
1118                     /* align 12 bit values in little-endian mode */
1119                     *dst = val << 4;
1120                     datap++;
1121                     i_datap++;
1122                     dst += s->ncomponents;
1123                 }
1124                 linel += picture->linesize[0] >> 1;
1125             }
1126         }
1127     }
1128     return 0;
1129 }
1130
1131 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1132 {
1133     int tileno, compno;
1134     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1135         for (compno = 0; compno < s->ncomponents; compno++) {
1136             Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
1137             Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1138
1139             ff_jpeg2000_cleanup(comp, codsty);
1140         }
1141         av_freep(&s->tile[tileno].comp);
1142     }
1143     av_freep(&s->tile);
1144 }
1145
1146 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1147 {
1148     Jpeg2000CodingStyle *codsty = s->codsty;
1149     Jpeg2000QuantStyle *qntsty  = s->qntsty;
1150     uint8_t *properties         = s->properties;
1151
1152     for (;;) {
1153         int len, ret = 0;
1154         uint16_t marker;
1155         const uint8_t *oldbuf;
1156
1157         if (s->buf_end - s->buf < 2) {
1158             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1159             break;
1160         }
1161
1162         marker = bytestream_get_be16(&s->buf);
1163         oldbuf = s->buf;
1164
1165         if (marker == JPEG2000_EOC)
1166             break;
1167
1168         if (s->buf_end - s->buf < 2)
1169             return AVERROR(EINVAL);
1170         len = bytestream_get_be16(&s->buf);
1171         switch (marker) {
1172         case JPEG2000_SIZ:
1173             ret = get_siz(s);
1174             break;
1175         case JPEG2000_COC:
1176             ret = get_coc(s, codsty, properties);
1177             break;
1178         case JPEG2000_COD:
1179             ret = get_cod(s, codsty, properties);
1180             break;
1181         case JPEG2000_QCC:
1182             ret = get_qcc(s, len, qntsty, properties);
1183             break;
1184         case JPEG2000_QCD:
1185             ret = get_qcd(s, len, qntsty, properties);
1186             break;
1187         case JPEG2000_SOT:
1188             ret = get_sot(s, len);
1189             break;
1190         case JPEG2000_COM:
1191             // the comment is ignored
1192             s->buf += len - 2;
1193             break;
1194         case JPEG2000_TLM:
1195             // Tile-part lengths
1196             ret = get_tlm(s, len);
1197             break;
1198         default:
1199             av_log(s->avctx, AV_LOG_ERROR,
1200                    "unsupported marker 0x%.4X at pos 0x%lX\n",
1201                    marker, (uint64_t)(s->buf - s->buf_start - 4));
1202             s->buf += len - 2;
1203             break;
1204         }
1205         if (((s->buf - oldbuf != len) && (marker != JPEG2000_SOT)) || ret) {
1206             av_log(s->avctx, AV_LOG_ERROR,
1207                    "error during processing marker segment %.4x\n", marker);
1208             return ret ? ret : -1;
1209         }
1210     }
1211     return 0;
1212 }
1213
1214 /* Read bit stream packets --> T2 operation. */
1215 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1216 {
1217     int ret = 0;
1218     Jpeg2000Tile *tile = s->tile + s->curtileno;
1219
1220     if (ret = init_tile(s, s->curtileno))
1221         return ret;
1222     if (ret = jpeg2000_decode_packets(s, tile))
1223         return ret;
1224
1225     return 0;
1226 }
1227
1228 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1229 {
1230     int32_t atom_size;
1231     int found_codestream = 0, search_range = 10;
1232
1233     // Skip JPEG 2000 signature atom.
1234     s->buf += 12;
1235
1236     while (!found_codestream && search_range) {
1237         atom_size = AV_RB32(s->buf);
1238         if (AV_RB32(s->buf + 4) == JP2_CODESTREAM) {
1239             found_codestream = 1;
1240             s->buf += 8;
1241         } else {
1242             s->buf += atom_size;
1243             search_range--;
1244         }
1245     }
1246
1247     if (found_codestream)
1248         return 1;
1249     return 0;
1250 }
1251
1252 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1253                                  int *got_frame, AVPacket *avpkt)
1254 {
1255     Jpeg2000DecoderContext *s = avctx->priv_data;
1256     ThreadFrame frame = { .f = data };
1257     AVFrame *picture = data;
1258     int tileno, ret;
1259
1260     s->avctx     = avctx;
1261     s->buf       = s->buf_start = avpkt->data;
1262     s->buf_end   = s->buf_start + avpkt->size;
1263     s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1264
1265     // reduction factor, i.e number of resolution levels to skip
1266     s->reduction_factor = s->lowres;
1267
1268     ff_jpeg2000_init_tier1_luts();
1269
1270     if (s->buf_end - s->buf < 2)
1271         return AVERROR(EINVAL);
1272
1273     // check if the image is in jp2 format
1274     if ((AV_RB32(s->buf) == 12) &&
1275         (AV_RB32(s->buf + 4) == JP2_SIG_TYPE) &&
1276         (AV_RB32(s->buf + 8) == JP2_SIG_VALUE)) {
1277         if (!jp2_find_codestream(s)) {
1278             av_log(avctx, AV_LOG_ERROR,
1279                    "couldn't find jpeg2k codestream atom\n");
1280             return -1;
1281         }
1282     } else if (AV_RB16(s->buf) != JPEG2000_SOC && AV_RB32(s->buf + 4) == JP2_CODESTREAM) {
1283         s->buf += 8;
1284     }
1285
1286     if (bytestream_get_be16(&s->buf) != JPEG2000_SOC) {
1287         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1288         return -1;
1289     }
1290     if (ret = jpeg2000_read_main_headers(s))
1291         goto fail;
1292
1293     /* get picture buffer */
1294     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1295         av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
1296         goto fail;
1297     }
1298     picture->pict_type = AV_PICTURE_TYPE_I;
1299     picture->key_frame = 1;
1300
1301     if (ret = jpeg2000_read_bitstream_packets(s))
1302         goto fail;
1303     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1304         if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
1305             goto fail;
1306     jpeg2000_dec_cleanup(s);
1307
1308     *got_frame = 1;
1309
1310     return s->buf - s->buf_start;
1311 fail:
1312     jpeg2000_dec_cleanup(s);
1313     return ret;
1314 }
1315
1316 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1317 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1318
1319 static const AVOption options[] = {
1320     { "lowres",  "Lower the decoding resolution by a power of two",
1321         OFFSET(lowres), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1322     { NULL },
1323 };
1324
1325 static const AVProfile profiles[] = {
1326     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0,  "JPEG 2000 codestream restriction 0"   },
1327     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1,  "JPEG 2000 codestream restriction 1"   },
1328     { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1329     { FF_PROFILE_JPEG2000_DCINEMA_2K,             "JPEG 2000 digital cinema 2K"          },
1330     { FF_PROFILE_JPEG2000_DCINEMA_4K,             "JPEG 2000 digital cinema 4K"          },
1331     { FF_PROFILE_UNKNOWN },
1332 };
1333
1334 static const AVClass class = {
1335     .class_name = "jpeg2000",
1336     .item_name  = av_default_item_name,
1337     .option     = options,
1338     .version    = LIBAVUTIL_VERSION_INT,
1339 };
1340
1341 AVCodec ff_jpeg2000_decoder = {
1342     .name           = "jpeg2000",
1343     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1344     .type           = AVMEDIA_TYPE_VIDEO,
1345     .id             = AV_CODEC_ID_JPEG2000,
1346     .capabilities   = CODEC_CAP_FRAME_THREADS,
1347     .priv_data_size = sizeof(Jpeg2000DecoderContext),
1348     .decode         = jpeg2000_decode_frame,
1349     .priv_class     = &class,
1350     .pix_fmts       = (enum PixelFormat[]) { AV_PIX_FMT_XYZ12,
1351                                              AV_PIX_FMT_GRAY8,
1352                                              -1 },
1353     .profiles       = NULL_IF_CONFIG_SMALL(profiles)
1354 };