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