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