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