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