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