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