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