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