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