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