28c5f1c6d4d01b8e46cc0162878c7ead83798f7b
[ffmpeg.git] / libavcodec / j2kdec.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  * JPEG2000 image decoder
25  * @file
26  * @author Kamil Nowosad
27  */
28
29 #include "avcodec.h"
30 #include "bytestream.h"
31 #include "internal.h"
32 #include "thread.h"
33 #include "j2k.h"
34 #include "libavutil/common.h"
35
36 #define JP2_SIG_TYPE    0x6A502020
37 #define JP2_SIG_VALUE   0x0D0A870A
38 #define JP2_CODESTREAM  0x6A703263
39
40 #define HAD_COC 0x01
41 #define HAD_QCC 0x02
42
43 typedef struct Jpeg2000Tile {
44     Jpeg2000Component  *comp;
45     uint8_t             properties[4];
46     Jpeg2000CodingStyle codsty[4];
47     Jpeg2000QuantStyle  qntsty[4];
48 } Jpeg2000Tile;
49
50 typedef struct Jpeg2000DecoderContext {
51     AVClass         *class;
52     AVCodecContext  *avctx;
53     AVFrame         *picture;
54     GetByteContext  g;
55
56     int             width, height;
57     int             image_offset_x, image_offset_y;
58     int             tile_offset_x, tile_offset_y;
59     uint8_t         cbps[4];    // bits per sample in particular components
60     uint8_t         sgnd[4];    // if a component is signed
61     uint8_t         properties[4];
62     int             cdx[4], cdy[4];
63     int             precision;
64     int             ncomponents;
65     int             tile_width, tile_height;
66     int             numXtiles, numYtiles;
67     int             maxtilelen;
68
69     Jpeg2000CodingStyle codsty[4];
70     Jpeg2000QuantStyle  qntsty[4];
71
72     int             bit_index;
73
74     int             curtileno;
75
76     Jpeg2000Tile    *tile;
77 } Jpeg2000DecoderContext;
78
79 static int get_bits(Jpeg2000DecoderContext *s, int n)
80 {
81     int res = 0;
82
83     while (--n >= 0) {
84         res <<= 1;
85         if (s->bit_index == 0) {
86             s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
87         }
88         s->bit_index--;
89         res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
90     }
91     return res;
92 }
93
94 static void j2k_flush(Jpeg2000DecoderContext *s)
95 {
96     if (bytestream2_get_byte(&s->g) == 0xff)
97         bytestream2_skip(&s->g, 1);
98     s->bit_index = 8;
99 }
100
101 /* decode the value stored in node */
102 static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
103                            int threshold)
104 {
105     Jpeg2000TgtNode *stack[30];
106     int sp = -1, curval = 0;
107
108     if (!node)
109         return AVERROR(EINVAL);
110
111     while (node && !node->vis) {
112         stack[++sp] = node;
113         node        = node->parent;
114     }
115
116     if (node)
117         curval = node->val;
118     else
119         curval = stack[sp]->val;
120
121     while (curval < threshold && sp >= 0) {
122         if (curval < stack[sp]->val)
123             curval = stack[sp]->val;
124         while (curval < threshold) {
125             int ret;
126             if ((ret = get_bits(s, 1)) > 0) {
127                 stack[sp]->vis++;
128                 break;
129             } else if (!ret)
130                 curval++;
131             else
132                 return ret;
133         }
134         stack[sp]->val = curval;
135         sp--;
136     }
137     return curval;
138 }
139
140 /* marker segments */
141 /* get sizes and offsets of image, tiles; number of components */
142 static int get_siz(Jpeg2000DecoderContext *s)
143 {
144     int i, ret;
145     ThreadFrame frame = { .f = s->picture };
146
147     if (bytestream2_get_bytes_left(&s->g) < 36)
148         return AVERROR(EINVAL);
149
150     s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
151     s->width          = bytestream2_get_be32u(&s->g); // Width
152     s->height         = bytestream2_get_be32u(&s->g); // Height
153     s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
154     s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
155     s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz
156     s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz
157     s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz
158     s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz
159     s->ncomponents    = bytestream2_get_be16u(&s->g); // CSiz
160
161     if (s->ncomponents <= 0 || s->ncomponents > 4) {
162         av_log(s->avctx, AV_LOG_ERROR, "unsupported/invalid ncomponents: %d\n", s->ncomponents);
163         return AVERROR(EINVAL);
164     }
165     if (s->tile_width<=0 || s->tile_height<=0)
166         return AVERROR(EINVAL);
167
168     if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
169         return AVERROR(EINVAL);
170
171     for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
172         uint8_t x = bytestream2_get_byteu(&s->g);
173         s->cbps[i]   = (x & 0x7f) + 1;
174         s->precision = FFMAX(s->cbps[i], s->precision);
175         s->sgnd[i] = !!(x & 0x80);
176         s->cdx[i] = bytestream2_get_byteu(&s->g);
177         s->cdy[i] = bytestream2_get_byteu(&s->g);
178         if (s->cdx[i] != 1 || s->cdy[i] != 1) {
179             av_log(s->avctx, AV_LOG_ERROR, "unsupported/ CDxy values\n");
180         }
181     }
182
183     s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
184     s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
185
186     if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(Jpeg2000Tile))
187         return AVERROR(EINVAL);
188
189     s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(*s->tile));
190     if (!s->tile)
191         return AVERROR(ENOMEM);
192
193     for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
194         Jpeg2000Tile *tile = s->tile + i;
195
196         tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
197         if (!tile->comp)
198             return AVERROR(ENOMEM);
199     }
200
201     s->avctx->width  = s->width  - s->image_offset_x;
202     s->avctx->height = s->height - s->image_offset_y;
203
204     switch(s->ncomponents) {
205     case 1:
206         if (s->precision > 8) {
207             s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
208         } else {
209             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
210         }
211         break;
212     case 3:
213         if (s->precision > 8) {
214             s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
215         } else {
216             s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
217         }
218         break;
219     case 4:
220         s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
221         break;
222     }
223
224
225     if ((ret = ff_thread_get_buffer(s->avctx, &frame, 0)) < 0)
226         return ret;
227
228     s->picture->pict_type = AV_PICTURE_TYPE_I;
229     s->picture->key_frame = 1;
230
231     return 0;
232 }
233
234 /* get common part for COD and COC segments */
235 static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
236 {
237     uint8_t byte;
238
239     if (bytestream2_get_bytes_left(&s->g) < 5)
240         return AVERROR(EINVAL);
241     c->nreslevels = bytestream2_get_byteu(&s->g) + 1; // num of resolution levels - 1
242     if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
243         av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
244         return AVERROR_INVALIDDATA;
245     }
246
247     c->log2_cblk_width  = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
248     c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
249
250     if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
251         c->log2_cblk_width + c->log2_cblk_height > 14) {
252         av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
253         return AVERROR_INVALIDDATA;
254     }
255
256     c->cblk_style = bytestream2_get_byteu(&s->g);
257     if (c->cblk_style != 0) { // cblk style
258         av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
259     }
260     c->transform = bytestream2_get_byteu(&s->g); // transformation
261     if (c->csty & JPEG2000_CSTY_PREC) {
262         int i;
263         for (i = 0; i < c->nreslevels; i++) {
264             byte = bytestream2_get_byte(&s->g);
265             c->log2_prec_widths[i]  =  byte       & 0x0F;    // precinct PPx
266             c->log2_prec_heights[i] = (byte >> 4) & 0x0F;    // precinct PPy
267         }
268     } else {
269         memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
270         memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
271     }
272     return 0;
273 }
274
275 /* get coding parameters for a particular tile or whole image*/
276 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
277                    uint8_t *properties)
278 {
279     Jpeg2000CodingStyle tmp;
280     int compno;
281
282     if (bytestream2_get_bytes_left(&s->g) < 5)
283         return AVERROR(EINVAL);
284
285     tmp.csty = bytestream2_get_byteu(&s->g);
286
287     // get progression order
288     tmp.prog_order = bytestream2_get_byteu(&s->g);
289     if (tmp.prog_order) {
290         av_log(s->avctx, AV_LOG_ERROR, "only LRCP progression supported\n");
291     }
292
293     tmp.nlayers = bytestream2_get_be16u(&s->g);
294     tmp.mct     = bytestream2_get_byteu(&s->g); // multiple component transformation
295
296     get_cox(s, &tmp);
297     for (compno = 0; compno < s->ncomponents; compno++)
298         if (!(properties[compno] & HAD_COC))
299             memcpy(c + compno, &tmp, sizeof(tmp));
300     return 0;
301 }
302
303 /* Get coding parameters for a component in the whole image or a
304  * particular tile. */
305 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
306                    uint8_t *properties)
307 {
308     int compno;
309
310     if (bytestream2_get_bytes_left(&s->g) < 2)
311         return AVERROR(EINVAL);
312
313     compno = bytestream2_get_byteu(&s->g);
314
315     c += compno;
316     c->csty = bytestream2_get_byte(&s->g);
317     get_cox(s, c);
318
319     properties[compno] |= HAD_COC;
320     return 0;
321 }
322
323 /* Get common part for QCD and QCC segments. */
324 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
325 {
326     int i, x;
327
328     if (bytestream2_get_bytes_left(&s->g) < 1)
329         return AVERROR(EINVAL);
330
331     x = bytestream2_get_byteu(&s->g); // Sqcd
332
333     q->nguardbits = x >> 5;
334     q->quantsty   = x & 0x1f;
335
336     if (q->quantsty == JPEG2000_QSTY_NONE) {
337         n -= 3;
338         if (bytestream2_get_bytes_left(&s->g) < n || 32*3 < n)
339             return AVERROR(EINVAL);
340         for (i = 0; i < n; i++)
341             q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
342     } else if (q->quantsty == JPEG2000_QSTY_SI) {
343         if (bytestream2_get_bytes_left(&s->g) < 2)
344             return AVERROR(EINVAL);
345         x          = bytestream2_get_be16u(&s->g);
346         q->expn[0] = x >> 11;
347         q->mant[0] = x & 0x7ff;
348         for (i = 1; i < 32 * 3; i++) {
349             int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
350             q->expn[i] = curexpn;
351             q->mant[i] = q->mant[0];
352         }
353     } else {
354         n = (n - 3) >> 1;
355         if (bytestream2_get_bytes_left(&s->g) < 2 * n || 32*3 < n)
356             return AVERROR(EINVAL);
357         for (i = 0; i < n; i++) {
358             x          = bytestream2_get_be16u(&s->g);
359             q->expn[i] = x >> 11;
360             q->mant[i] = x & 0x7ff;
361         }
362     }
363     return 0;
364 }
365
366 /* Get quantization parameters for a particular tile or a whole image. */
367 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
368                    uint8_t *properties)
369 {
370     Jpeg2000QuantStyle tmp;
371     int compno;
372
373     if (get_qcx(s, n, &tmp))
374         return -1;
375     for (compno = 0; compno < s->ncomponents; compno++)
376         if (!(properties[compno] & HAD_QCC))
377             memcpy(q + compno, &tmp, sizeof(Jpeg2000QuantStyle));
378     return 0;
379 }
380
381 /* Get quantization parameters for a component in the whole image
382  * on in a particular tile. */
383 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
384                    uint8_t *properties)
385 {
386     int compno;
387
388     if (bytestream2_get_bytes_left(&s->g) < 1)
389         return AVERROR(EINVAL);
390
391     compno              = bytestream2_get_byteu(&s->g);
392     properties[compno] |= HAD_QCC;
393     return get_qcx(s, n - 1, q + compno);
394 }
395
396 /** get start of tile segment */
397 static int get_sot(Jpeg2000DecoderContext *s)
398 {
399     if (bytestream2_get_bytes_left(&s->g) < 8)
400         return AVERROR(EINVAL);
401
402     s->curtileno = bytestream2_get_be16u(&s->g); ///< Isot
403     if ((unsigned)s->curtileno >= s->numXtiles * s->numYtiles) {
404         s->curtileno=0;
405         return AVERROR(EINVAL);
406     }
407
408     bytestream2_skipu(&s->g, 4); ///< Psot (ignored)
409
410     if (!bytestream2_get_byteu(&s->g)) { ///< TPsot
411         Jpeg2000Tile *tile = s->tile + s->curtileno;
412
413         /* copy defaults */
414         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
415         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
416     }
417     bytestream2_get_byteu(&s->g); ///< TNsot
418
419     return 0;
420 }
421
422 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
423 {
424     int compno;
425     int tilex = tileno % s->numXtiles;
426     int tiley = tileno / s->numXtiles;
427     Jpeg2000Tile *tile = s->tile + tileno;
428
429     if (!tile->comp)
430         return AVERROR(ENOMEM);
431     for (compno = 0; compno < s->ncomponents; compno++) {
432         Jpeg2000Component *comp = tile->comp + compno;
433         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
434         Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
435         int ret; // global bandno
436
437         comp->coord[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
438         comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width + s->tile_offset_x, s->width);
439         comp->coord[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
440         comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height + s->tile_offset_y, s->height);
441
442         if (ret = ff_j2k_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx))
443             return ret;
444     }
445     return 0;
446 }
447
448 /** read the number of coding passes */
449 static int getnpasses(Jpeg2000DecoderContext *s)
450 {
451     int num;
452     if (!get_bits(s, 1))
453         return 1;
454     if (!get_bits(s, 1))
455         return 2;
456     if ((num = get_bits(s, 2)) != 3)
457         return num < 0 ? num : 3 + num;
458     if ((num = get_bits(s, 5)) != 31)
459         return num < 0 ? num : 6 + num;
460     num = get_bits(s, 7);
461     return num < 0 ? num : 37 + num;
462 }
463
464 static int getlblockinc(Jpeg2000DecoderContext *s)
465 {
466     int res = 0, ret;
467     while (ret = get_bits(s, 1)) {
468         if (ret < 0)
469             return ret;
470         res++;
471     }
472     return res;
473 }
474
475 static int decode_packet(Jpeg2000DecoderContext *s,
476                          Jpeg2000CodingStyle *codsty,
477                          Jpeg2000ResLevel *rlevel, int precno,
478                          int layno, uint8_t *expn, int numgbits)
479 {
480     int bandno, cblkno, ret, nb_code_blocks;
481
482     if (!(ret = get_bits(s, 1))) {
483         j2k_flush(s);
484         return 0;
485     } else if (ret < 0)
486         return ret;
487
488     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
489         Jpeg2000Band *band = rlevel->band + bandno;
490         Jpeg2000Prec *prec = band->prec + precno;
491
492         if (band->coord[0][0] == band->coord[0][1] ||
493             band->coord[1][0] == band->coord[1][1])
494             continue;
495
496         nb_code_blocks =  prec->nb_codeblocks_height *
497                           prec->nb_codeblocks_width;
498         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
499             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
500             int incl, newpasses, llen;
501
502             if (cblk->npasses)
503                 incl = get_bits(s, 1);
504             else
505                 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
506             if (!incl)
507                 continue;
508             else if (incl < 0)
509                 return incl;
510
511             if (!cblk->npasses)
512                 cblk->nonzerobits = expn[bandno] + numgbits - 1 -
513                                     tag_tree_decode(s, prec->zerobits + cblkno,
514                                                     100);
515             if ((newpasses = getnpasses(s)) < 0)
516                 return newpasses;
517             if ((llen = getlblockinc(s)) < 0)
518                 return llen;
519             cblk->lblock += llen;
520             if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
521                 return ret;
522             cblk->lengthinc = ret;
523             cblk->npasses  += newpasses;
524         }
525     }
526     j2k_flush(s);
527
528     if (codsty->csty & JPEG2000_CSTY_EPH) {
529         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
530             bytestream2_skip(&s->g, 2);
531         else
532             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
533     }
534
535     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
536         Jpeg2000Band *band = rlevel->band + bandno;
537         Jpeg2000Prec *prec = band->prec + precno;
538
539         nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
540         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
541             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
542             if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
543                 || sizeof(cblk->data) < cblk->lengthinc
544             )
545                 return AVERROR(EINVAL);
546             /* Code-block data can be empty. In that case initialize data
547              * with 0xFFFF. */
548             if (cblk->lengthinc > 0) {
549                  bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
550             } else {
551                 cblk->data[0] = 0xFF;
552                 cblk->data[1] = 0xFF;
553             }
554             cblk->length   += cblk->lengthinc;
555             cblk->lengthinc = 0;
556         }
557     }
558     return 0;
559 }
560
561 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
562 {
563     int layno, reslevelno, compno, precno, ok_reslevel;
564     s->bit_index = 8;
565     for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
566         ok_reslevel = 1;
567         for (reslevelno = 0; ok_reslevel; reslevelno++) {
568             ok_reslevel = 0;
569             for (compno = 0; compno < s->ncomponents; compno++) {
570                 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
571                 Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
572                 if (reslevelno < codsty->nreslevels) {
573                     Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
574                     ok_reslevel = 1;
575                     for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) {
576                         if (decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn +
577                                           (reslevelno ? 3*(reslevelno-1)+1 : 0), qntsty->nguardbits))
578                             return -1;
579                     }
580                 }
581             }
582         }
583     }
584     return 0;
585 }
586
587 /* TIER-1 routines */
588 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol,
589                            int vert_causal_ctx_csty_symbol)
590 {
591     int mask = 3 << (bpno - 1), y0, x, y;
592
593     for (y0 = 0; y0 < height; y0 += 4)
594         for (x = 0; x < width; x++)
595             for (y = y0; y < height && y < y0+4; y++) {
596                 if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
597                 && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
598                     int flags_mask = -1;
599                     if (vert_causal_ctx_csty_symbol && y == y0 + 3)
600                         flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
601                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
602                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
603                         if (bpass_csty_symbol)
604                              t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
605                         else
606                              t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
607                                                -mask : mask;
608
609                         ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
610                     }
611                     t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
612                 }
613             }
614 }
615
616 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
617                            int bpno)
618 {
619     int phalf, nhalf;
620     int y0, x, y;
621
622     phalf = 1 << (bpno - 1);
623     nhalf = -phalf;
624
625     for (y0 = 0; y0 < height; y0 += 4)
626         for (x = 0; x < width; x++)
627             for (y = y0; y < height && y < y0 + 4; y++)
628                 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
629                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
630                     int r     = ff_mqc_decode(&t1->mqc,
631                                               t1->mqc.cx_states + ctxno)
632                                 ? phalf : nhalf;
633                     t1->data[y][x]          += t1->data[y][x] < 0 ? -r : r;
634                     t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
635                 }
636 }
637
638 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height,
639                            int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol)
640 {
641     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
642
643     for (y0 = 0; y0 < height; y0 += 4) {
644         for (x = 0; x < width; x++) {
645             if (y0 + 3 < height &&
646                 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
647                   (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
648                   (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
649                   (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
650                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
651                     continue;
652                 runlen = ff_mqc_decode(&t1->mqc,
653                                        t1->mqc.cx_states + MQC_CX_UNI);
654                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
655                                                        t1->mqc.cx_states +
656                                                        MQC_CX_UNI);
657                 dec = 1;
658             } else {
659                 runlen = 0;
660                 dec    = 0;
661             }
662
663             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
664                 if (!dec) {
665                     if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
666                         int flags_mask = -1;
667                         if (vert_causal_ctx_csty_symbol && y == y0 + 3)
668                             flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
669                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
670                                                                                              bandno));
671                     }
672                 }
673                 if (dec) {
674                     int xorbit;
675                     int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
676                                                         &xorbit);
677                     t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
678                                                     t1->mqc.cx_states + ctxno) ^
679                                       xorbit)
680                                      ? -mask : mask;
681                     ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
682                 }
683                 dec = 0;
684                 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
685             }
686         }
687     }
688     if (seg_symbols) {
689         int val;
690         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
691         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
692         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
693         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
694         if (val != 0xa)
695             av_log(s->avctx, AV_LOG_ERROR,
696                    "Segmentation symbol value incorrect\n");
697     }
698 }
699
700 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
701                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
702                        int width, int height, int bandpos)
703 {
704     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y, clnpass_cnt = 0;
705     int bpass_csty_symbol = JPEG2000_CBLK_BYPASS & codsty->cblk_style;
706     int vert_causal_ctx_csty_symbol = JPEG2000_CBLK_VSC & codsty->cblk_style;
707
708     for (y = 0; y < height+2; y++)
709         memset(t1->flags[y], 0, (width+2)*sizeof(int));
710
711     for (y = 0; y < height; y++)
712         memset(t1->data[y], 0, width*sizeof(int));
713
714     cblk->data[cblk->length] = 0xff;
715     cblk->data[cblk->length+1] = 0xff;
716     ff_mqc_initdec(&t1->mqc, cblk->data);
717
718     while (passno--) {
719         switch(pass_t) {
720             case 0: decode_sigpass(t1, width, height, bpno+1, bandpos,
721                                   bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol);
722                     break;
723             case 1: decode_refpass(t1, width, height, bpno+1);
724                     if (bpass_csty_symbol && clnpass_cnt >= 4)
725                         ff_mqc_initdec(&t1->mqc, cblk->data);
726                     break;
727             case 2: decode_clnpass(s, t1, width, height, bpno+1, bandpos,
728                                    codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol);
729                     clnpass_cnt = clnpass_cnt + 1;
730                     if (bpass_csty_symbol && clnpass_cnt >= 4)
731                        ff_mqc_initdec(&t1->mqc, cblk->data);
732                     break;
733         }
734
735         pass_t++;
736         if (pass_t == 3) {
737             bpno--;
738             pass_t = 0;
739         }
740     }
741     return 0;
742 }
743
744 static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
745 {
746     int i, *src[3], i0, i1, i2, csize = 1;
747
748     for (i = 0; i < 3; i++)
749         src[i] = tile->comp[i].data;
750
751     for (i = 0; i < 2; i++)
752         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
753
754     if (tile->codsty[0].transform == FF_DWT97) {
755         for (i = 0; i < csize; i++) {
756             i0 = *src[0] + (*src[2] * 46802 >> 16);
757             i1 = *src[0] - (*src[1] * 22553 + *src[2] * 46802 >> 16);
758             i2 = *src[0] + (116130 * *src[1] >> 16);
759             *src[0]++ = i0;
760             *src[1]++ = i1;
761             *src[2]++ = i2;
762         }
763     } else{
764         for (i = 0; i < csize; i++) {
765             i1 = *src[0] - (*src[2] + *src[1] >> 2);
766             i0 = i1 + *src[2];
767             i2 = i1 + *src[1];
768             *src[0]++ = i0;
769             *src[1]++ = i1;
770             *src[2]++ = i2;
771         }
772     }
773 }
774
775 static int decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
776 {
777     int compno, reslevelno, bandno;
778     int x, y, *src[4];
779     uint8_t *line;
780     Jpeg2000T1Context t1;
781
782     /* Loop on tile components */
783     for (compno = 0; compno < s->ncomponents; compno++) {
784         Jpeg2000Component *comp     = tile->comp + compno;
785         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
786
787         /* Loop on resolution levels */
788         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
789             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
790             /* Loop on bands */
791             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
792                 int nb_precincts, precno;
793                 Jpeg2000Band *band = rlevel->band + bandno;
794                 int cblkx, cblky, cblkno=0, bandpos;
795
796                 bandpos = bandno + (reslevelno > 0);
797
798                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
799                     continue;
800
801                 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
802                 /* Loop on precincts */
803                 for (precno = 0; precno < nb_precincts; precno++) {
804                     Jpeg2000Prec *prec = band->prec + precno;
805
806                     /* Loop on codeblocks */
807                     for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
808                         int x, y;
809                         int i, j;
810                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
811                         decode_cblk(s, codsty, &t1, cblk,
812                                     cblk->coord[0][1] - cblk->coord[0][0],
813                                     cblk->coord[1][1] - cblk->coord[1][0],
814                                     bandpos);
815
816                         /* Manage band offsets */
817                         x = cblk->coord[0][0];
818                         y = cblk->coord[1][0];
819
820                         if (codsty->transform == FF_DWT53) {
821                             for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
822                                 int *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * (y+j) + x];
823                                 int *ptr = t1.data[j];
824                                 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
825                                     datap[i] = ptr[i] >> 1;
826                                 }
827                             }
828                         } else{
829                             for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
830                                 int *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * (y+j) + x];
831                                 int *ptr = t1.data[j];
832                                 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
833                                     int tmp = ((int64_t)ptr[i]) * ((int64_t)band->stepsize) >> 16, tmp2;
834                                     tmp2 = FFABS(tmp>>1) + (tmp&1);
835                                     datap[i] = tmp < 0 ? -tmp2 : tmp2;
836                                 }
837                             }
838                         }
839                    } /* end cblk */
840                 } /*end prec */
841             } /* end band */
842         } /* end reslevel */
843
844         ff_dwt_decode(&comp->dwt, comp->data);
845         src[compno] = comp->data;
846     } /*end comp */
847
848     /* inverse MCT transformation */
849     if (tile->codsty[0].mct)
850         mct_decode(s, tile);
851
852     if (s->precision <= 8) {
853         for (compno = 0; compno < s->ncomponents; compno++) {
854             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
855             line = s->picture->data[0] + y * s->picture->linesize[0];
856             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
857                 uint8_t *dst;
858
859                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x;
860                 dst = line + x * s->ncomponents + compno;
861
862                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
863                     *src[compno] += 1 << (s->cbps[compno]-1);
864                     if (*src[compno] < 0)
865                         *src[compno] = 0;
866                     else if (*src[compno] >= (1 << s->cbps[compno]))
867                         *src[compno] = (1 << s->cbps[compno]) - 1;
868                     *dst = *src[compno]++;
869                     dst += s->ncomponents;
870                 }
871                 line += s->picture->linesize[0];
872             }
873         }
874     } else {
875         for (compno = 0; compno < s->ncomponents; compno++) {
876             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
877             line = s->picture->data[0] + y * s->picture->linesize[0];
878             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
879                 uint16_t *dst;
880
881                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
882                 dst = (uint16_t *)(line + (x * s->ncomponents + compno) * 2);
883                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {
884                     int32_t val;
885
886                     val = *src[compno]++ << (16 - s->cbps[compno]);
887                     val += 1 << 15;
888                     val = av_clip(val, 0, (1 << 16) - 1);
889                     *dst = val;
890                     dst += s->ncomponents;
891                 }
892                 line += s->picture->linesize[0];
893             }
894         }
895     }
896     return 0;
897 }
898
899 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
900 {
901     int tileno, compno;
902     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
903         for (compno = 0; compno < s->ncomponents; compno++) {
904             Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
905             Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
906
907             ff_j2k_cleanup(comp, codsty);
908         }
909         av_freep(&s->tile[tileno].comp);
910     }
911     av_freep(&s->tile);
912 }
913
914 static int decode_codestream(Jpeg2000DecoderContext *s)
915 {
916     Jpeg2000CodingStyle *codsty = s->codsty;
917     Jpeg2000QuantStyle *qntsty  = s->qntsty;
918     uint8_t *properties         = s->properties;
919
920     for (;;) {
921         int oldpos, marker, len, ret = 0;
922
923         if (bytestream2_get_bytes_left(&s->g) < 2) {
924             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
925             break;
926         }
927
928         marker = bytestream2_get_be16u(&s->g);
929         av_dlog(s->avctx, "marker 0x%.4X at pos 0x%x\n", marker, bytestream2_tell(&s->g) - 4);
930         oldpos = bytestream2_tell(&s->g);
931
932         if (marker == JPEG2000_SOD) {
933             Jpeg2000Tile *tile = s->tile + s->curtileno;
934             if (ret = init_tile(s, s->curtileno)) {
935                 av_log(s->avctx, AV_LOG_ERROR, "tile initialization failed\n");
936                 return ret;
937             }
938             if (ret = jpeg2000_decode_packets(s, tile)) {
939                 av_log(s->avctx, AV_LOG_ERROR, "packets decoding failed\n");
940                 return ret;
941             }
942             continue;
943         }
944         if (marker == JPEG2000_EOC)
945             break;
946
947         if (bytestream2_get_bytes_left(&s->g) < 2)
948             return AVERROR(EINVAL);
949         len = bytestream2_get_be16u(&s->g);
950         switch (marker) {
951         case JPEG2000_SIZ:
952             ret = get_siz(s);
953             if (!s->tile)
954                 s->numXtiles = s->numYtiles = 0;
955             break;
956         case JPEG2000_COC:
957             ret = get_coc(s, codsty, properties);
958             break;
959         case JPEG2000_COD:
960             ret = get_cod(s, codsty, properties);
961             break;
962         case JPEG2000_QCC:
963             ret = get_qcc(s, len, qntsty, properties);
964             break;
965         case JPEG2000_QCD:
966             ret = get_qcd(s, len, qntsty, properties);
967             break;
968         case JPEG2000_SOT:
969             if (!(ret = get_sot(s))) {
970                 codsty = s->tile[s->curtileno].codsty;
971                 qntsty = s->tile[s->curtileno].qntsty;
972                 properties = s->tile[s->curtileno].properties;
973             }
974             break;
975         case JPEG2000_COM:
976             // the comment is ignored
977             bytestream2_skip(&s->g, len - 2);
978             break;
979         default:
980             av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%x\n", marker, bytestream2_tell(&s->g) - 4);
981             bytestream2_skip(&s->g, len - 2);
982             break;
983         }
984         if (bytestream2_tell(&s->g) - oldpos != len || ret) {
985             av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker);
986             return ret ? ret : -1;
987         }
988     }
989     return 0;
990 }
991
992 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
993 {
994     uint32_t atom_size, atom;
995     int found_codestream = 0, search_range = 10;
996
997     while (!found_codestream && search_range && bytestream2_get_bytes_left(&s->g) >= 8) {
998         atom_size = bytestream2_get_be32u(&s->g);
999         atom      = bytestream2_get_be32u(&s->g);
1000         if (atom == JP2_CODESTREAM) {
1001             found_codestream = 1;
1002         } else {
1003             if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1004                 return 0;
1005             bytestream2_skipu(&s->g, atom_size - 8);
1006             search_range--;
1007         }
1008     }
1009
1010     if (found_codestream)
1011         return 1;
1012     return 0;
1013 }
1014
1015 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1016                                  int *got_frame, AVPacket *avpkt)
1017 {
1018     Jpeg2000DecoderContext *s = avctx->priv_data;
1019     AVFrame *picture = data;
1020     int tileno, ret;
1021
1022     s->picture = picture;
1023
1024     s->avctx     = avctx;
1025     bytestream2_init(&s->g, avpkt->data, avpkt->size);
1026     s->curtileno = -1;
1027
1028     if (bytestream2_get_bytes_left(&s->g) < 2) {
1029         ret = AVERROR(EINVAL);
1030         goto err_out;
1031     }
1032
1033     // check if the image is in jp2 format
1034     if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1035        (bytestream2_get_be32u(&s->g) == 12) &&
1036        (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1037        (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
1038         if (!jp2_find_codestream(s)) {
1039             av_log(avctx, AV_LOG_ERROR, "couldn't find jpeg2k codestream atom\n");
1040             ret = -1;
1041             goto err_out;
1042         }
1043     } else {
1044         bytestream2_seek(&s->g, 0, SEEK_SET);
1045     }
1046
1047     if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1048         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1049         ret = -1;
1050         goto err_out;
1051     }
1052     if (ret = decode_codestream(s))
1053         goto err_out;
1054
1055     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1056         if (ret = decode_tile(s, s->tile + tileno))
1057             goto err_out;
1058
1059     jpeg2000_dec_cleanup(s);
1060
1061     *got_frame = 1;
1062
1063     return bytestream2_tell(&s->g);
1064
1065 err_out:
1066     jpeg2000_dec_cleanup(s);
1067     return ret;
1068 }
1069
1070 static void jpeg2000_init_static_data(AVCodec *codec)
1071 {
1072     ff_jpeg2000_init_tier1_luts();
1073 }
1074
1075 static const AVProfile profiles[] = {
1076     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0,  "JPEG 2000 codestream restriction 0"   },
1077     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1,  "JPEG 2000 codestream restriction 1"   },
1078     { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1079     { FF_PROFILE_JPEG2000_DCINEMA_2K,             "JPEG 2000 digital cinema 2K"          },
1080     { FF_PROFILE_JPEG2000_DCINEMA_4K,             "JPEG 2000 digital cinema 4K"          },
1081     { FF_PROFILE_UNKNOWN },
1082 };
1083
1084 AVCodec ff_j2k_decoder = {
1085     .name             = "j2k",
1086     .long_name        = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1087     .type             = AVMEDIA_TYPE_VIDEO,
1088     .id               = AV_CODEC_ID_JPEG2000,
1089     .capabilities     = CODEC_CAP_EXPERIMENTAL | CODEC_CAP_FRAME_THREADS,
1090     .priv_data_size   = sizeof(Jpeg2000DecoderContext),
1091     .init_static_data = jpeg2000_init_static_data,
1092     .decode           = jpeg2000_decode_frame,
1093     .profiles         = NULL_IF_CONFIG_SMALL(profiles)
1094 };