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