OSDN Git Service

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