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