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