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