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