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