]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kdec.c
j2k/jpeg2000: check cblk size
[ffmpeg] / 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, 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     s->avctx->profile = 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
237     c->log2_cblk_width  = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
238     c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
239
240     if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
241         c->log2_cblk_width + c->log2_cblk_height > 14) {
242         av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
243         return AVERROR_INVALIDDATA;
244     }
245
246     c->cblk_style = bytestream2_get_byteu(&s->g);
247     if (c->cblk_style != 0) { // cblk style
248         av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
249     }
250     c->transform = bytestream2_get_byteu(&s->g); // transformation
251     if (c->csty & JPEG2000_CSTY_PREC) {
252         int i;
253
254         for (i = 0; i < c->nreslevels; i++)
255             bytestream2_get_byte(&s->g);
256     }
257     return 0;
258 }
259
260 /** get coding parameters for a particular tile or whole image*/
261 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties)
262 {
263     Jpeg2000CodingStyle tmp;
264     int compno;
265
266     if (bytestream2_get_bytes_left(&s->g) < 5)
267         return AVERROR(EINVAL);
268
269     tmp.log2_prec_width  =
270     tmp.log2_prec_height = 15;
271
272     tmp.csty = bytestream2_get_byteu(&s->g);
273
274     // get progression order
275     tmp.prog_order = bytestream2_get_byteu(&s->g);
276     if (tmp.prog_order) {
277         av_log(s->avctx, AV_LOG_ERROR, "only LRCP progression supported\n");
278     }
279
280     tmp.nlayers = bytestream2_get_be16u(&s->g);
281         tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
282
283     get_cox(s, &tmp);
284     for (compno = 0; compno < s->ncomponents; compno++) {
285         if (!(properties[compno] & HAD_COC))
286             memcpy(c + compno, &tmp, sizeof(Jpeg2000CodingStyle));
287     }
288     return 0;
289 }
290
291 /** get coding parameters for a component in the whole image on a particular tile */
292 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties)
293 {
294     int compno;
295
296     if (bytestream2_get_bytes_left(&s->g) < 2)
297         return AVERROR(EINVAL);
298
299     compno = bytestream2_get_byteu(&s->g);
300
301     c += compno;
302     c->csty = bytestream2_get_byte(&s->g);
303     get_cox(s, c);
304
305     properties[compno] |= HAD_COC;
306     return 0;
307 }
308
309 /** get common part for QCD and QCC segments */
310 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
311 {
312     int i, x;
313
314     if (bytestream2_get_bytes_left(&s->g) < 1)
315         return AVERROR(EINVAL);
316
317     x = bytestream2_get_byteu(&s->g); // Sqcd
318
319     q->nguardbits = x >> 5;
320       q->quantsty = x & 0x1f;
321
322     if (q->quantsty == JPEG2000_QSTY_NONE) {
323         n -= 3;
324         if (bytestream2_get_bytes_left(&s->g) < n || 32*3 < n)
325             return AVERROR(EINVAL);
326         for (i = 0; i < n; i++)
327             q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
328     } else if (q->quantsty == JPEG2000_QSTY_SI) {
329         if (bytestream2_get_bytes_left(&s->g) < 2)
330             return AVERROR(EINVAL);
331         x = bytestream2_get_be16u(&s->g);
332         q->expn[0] = x >> 11;
333         q->mant[0] = x & 0x7ff;
334         for (i = 1; i < 32 * 3; i++) {
335             int curexpn = FFMAX(0, q->expn[0] - (i-1)/3);
336             q->expn[i] = curexpn;
337             q->mant[i] = q->mant[0];
338         }
339     } else{
340         n = (n - 3) >> 1;
341         if (bytestream2_get_bytes_left(&s->g) < 2 * n || 32*3 < n)
342             return AVERROR(EINVAL);
343         for (i = 0; i < n; i++) {
344             x = bytestream2_get_be16u(&s->g);
345             q->expn[i] = x >> 11;
346             q->mant[i] = x & 0x7ff;
347         }
348     }
349     return 0;
350 }
351
352 /** get quantization parameters for a particular tile or a whole image */
353 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties)
354 {
355     Jpeg2000QuantStyle tmp;
356     int compno;
357
358     if (get_qcx(s, n, &tmp))
359         return -1;
360     for (compno = 0; compno < s->ncomponents; compno++)
361         if (!(properties[compno] & HAD_QCC))
362             memcpy(q + compno, &tmp, sizeof(Jpeg2000QuantStyle));
363     return 0;
364 }
365
366 /** get quantization parameters for a component in the whole image on in a particular tile */
367 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties)
368 {
369     int compno;
370
371     if (bytestream2_get_bytes_left(&s->g) < 1)
372         return AVERROR(EINVAL);
373
374     compno = bytestream2_get_byteu(&s->g);
375     properties[compno] |= HAD_QCC;
376     return get_qcx(s, n-1, q+compno);
377 }
378
379 /** get start of tile segment */
380 static int get_sot(Jpeg2000DecoderContext *s)
381 {
382     if (bytestream2_get_bytes_left(&s->g) < 8)
383         return AVERROR(EINVAL);
384
385     s->curtileno = bytestream2_get_be16u(&s->g); ///< Isot
386     if ((unsigned)s->curtileno >= s->numXtiles * s->numYtiles) {
387         s->curtileno=0;
388         return AVERROR(EINVAL);
389     }
390
391     bytestream2_skipu(&s->g, 4); ///< Psot (ignored)
392
393     if (!bytestream2_get_byteu(&s->g)) { ///< TPsot
394         Jpeg2000Tile *tile = s->tile + s->curtileno;
395
396         /* copy defaults */
397         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
398         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
399     }
400     bytestream2_get_byteu(&s->g); ///< TNsot
401
402     return 0;
403 }
404
405 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
406 {
407     int compno,
408         tilex = tileno % s->numXtiles,
409         tiley = tileno / s->numXtiles;
410     Jpeg2000Tile *tile = s->tile + tileno;
411
412     if (!tile->comp)
413         return AVERROR(ENOMEM);
414     for (compno = 0; compno < s->ncomponents; compno++) {
415         Jpeg2000Component *comp = tile->comp + compno;
416         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
417         Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
418         int ret; // global bandno
419
420         comp->coord[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
421         comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width + s->tile_offset_x, s->width);
422         comp->coord[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
423         comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height + s->tile_offset_y, s->height);
424
425         if (ret = ff_j2k_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno]))
426             return ret;
427     }
428     return 0;
429 }
430
431 /** read the number of coding passes */
432 static int getnpasses(Jpeg2000DecoderContext *s)
433 {
434     int num;
435     if (!get_bits(s, 1))
436         return 1;
437     if (!get_bits(s, 1))
438         return 2;
439     if ((num = get_bits(s, 2)) != 3)
440         return num < 0 ? num : 3 + num;
441     if ((num = get_bits(s, 5)) != 31)
442         return num < 0 ? num : 6 + num;
443     num = get_bits(s, 7);
444     return num < 0 ? num : 37 + num;
445 }
446
447 static int getlblockinc(Jpeg2000DecoderContext *s)
448 {
449     int res = 0, ret;
450     while (ret = get_bits(s, 1)) {
451         if (ret < 0)
452             return ret;
453         res++;
454     }
455     return res;
456 }
457
458 static int decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno,
459                          int layno, uint8_t *expn, int numgbits)
460 {
461     int bandno, cblkny, cblknx, cblkno, ret;
462
463     if (!(ret = get_bits(s, 1))) {
464         j2k_flush(s);
465         return 0;
466     } else if (ret < 0)
467         return ret;
468
469     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
470         Jpeg2000Band *band = rlevel->band + bandno;
471         Jpeg2000Prec *prec = band->prec + precno;
472         int pos = 0;
473
474         if (band->coord[0][0] == band->coord[0][1]
475         ||  band->coord[1][0] == band->coord[1][1])
476             continue;
477
478         for (cblkny = prec->yi0; cblkny < prec->yi1; cblkny++)
479             for (cblknx = prec->xi0, cblkno = cblkny * band->cblknx + cblknx; cblknx < prec->xi1; cblknx++, cblkno++, pos++) {
480                 Jpeg2000Cblk *cblk = band->cblk + cblkno;
481                 int incl, newpasses, llen;
482
483                 if (cblk->npasses)
484                     incl = get_bits(s, 1);
485                 else
486                     incl = tag_tree_decode(s, prec->cblkincl + pos, layno+1) == layno;
487                 if (!incl)
488                     continue;
489                 else if (incl < 0)
490                     return incl;
491
492                 if (!cblk->npasses)
493                     cblk->nonzerobits = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + pos, 100);
494                 if ((newpasses = getnpasses(s)) < 0)
495                     return newpasses;
496                 if ((llen = getlblockinc(s)) < 0)
497                     return llen;
498                 cblk->lblock += llen;
499                 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
500                     return ret;
501                 cblk->lengthinc = ret;
502                 cblk->npasses += newpasses;
503             }
504     }
505     j2k_flush(s);
506
507     if (codsty->csty & JPEG2000_CSTY_EPH) {
508         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) {
509             bytestream2_skip(&s->g, 2);
510         } else {
511             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
512         }
513     }
514
515     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
516         Jpeg2000Band *band = rlevel->band + bandno;
517         int yi, cblknw = band->prec[precno].xi1 - band->prec[precno].xi0;
518         for (yi = band->prec[precno].yi0; yi < band->prec[precno].yi1; yi++) {
519             int xi;
520             for (xi = band->prec[precno].xi0; xi < band->prec[precno].xi1; xi++) {
521                 Jpeg2000Cblk *cblk = band->cblk + yi * cblknw + xi;
522                 if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
523                     || sizeof(cblk->data) < cblk->lengthinc
524                 )
525                     return AVERROR(EINVAL);
526                 bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
527                 cblk->length += cblk->lengthinc;
528                 cblk->lengthinc = 0;
529             }
530         }
531     }
532     return 0;
533 }
534
535 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
536 {
537     int layno, reslevelno, compno, precno, ok_reslevel;
538     s->bit_index = 8;
539     for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
540         ok_reslevel = 1;
541         for (reslevelno = 0; ok_reslevel; reslevelno++) {
542             ok_reslevel = 0;
543             for (compno = 0; compno < s->ncomponents; compno++) {
544                 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
545                 Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
546                 if (reslevelno < codsty->nreslevels) {
547                     Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
548                     ok_reslevel = 1;
549                     for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) {
550                         if (decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn +
551                                           (reslevelno ? 3*(reslevelno-1)+1 : 0), qntsty->nguardbits))
552                             return -1;
553                     }
554                 }
555             }
556         }
557     }
558     return 0;
559 }
560
561 /* TIER-1 routines */
562 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol,
563                            int vert_causal_ctx_csty_symbol)
564 {
565     int mask = 3 << (bpno - 1), y0, x, y;
566
567     for (y0 = 0; y0 < height; y0 += 4)
568         for (x = 0; x < width; x++)
569             for (y = y0; y < height && y < y0+4; y++) {
570                 if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
571                 && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
572                     int flags_mask = -1;
573                     if (vert_causal_ctx_csty_symbol && y == y0 + 3)
574                         flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
575                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
576                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
577                         if (bpass_csty_symbol)
578                              t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
579                         else
580                              t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
581                                                -mask : mask;
582
583                         ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
584                     }
585                     t1->flags[y+1][x+1] |= JPEG2000_T1_VIS;
586                 }
587             }
588 }
589
590 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height, int bpno)
591 {
592     int phalf, nhalf;
593     int y0, x, y;
594
595     phalf = 1 << (bpno - 1);
596     nhalf = -phalf;
597
598     for (y0 = 0; y0 < height; y0 += 4)
599         for (x = 0; x < width; x++)
600             for (y = y0; y < height && y < y0+4; y++) {
601                 if ((t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
602                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y+1][x+1]);
603                     int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf;
604                     t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
605                     t1->flags[y+1][x+1] |= JPEG2000_T1_REF;
606                 }
607             }
608 }
609
610 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height,
611                            int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol)
612 {
613     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
614
615     for (y0 = 0; y0 < height; y0 += 4) {
616         for (x = 0; x < width; x++) {
617             if (y0 + 3 < height && !(
618             (t1->flags[y0+1][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
619             (t1->flags[y0+2][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
620             (t1->flags[y0+3][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
621             (t1->flags[y0+4][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
622                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
623                     continue;
624                 runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
625                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
626                 dec = 1;
627             } else{
628                 runlen = 0;
629                 dec = 0;
630             }
631
632             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
633                 if (!dec) {
634                     if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
635                         int flags_mask = -1;
636                         if (vert_causal_ctx_csty_symbol && y == y0 + 3)
637                             flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
638                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
639                                                                                              bandno));
640                     }
641                 }
642                 if (dec) {
643                     int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
644                     t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask;
645                     ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
646                 }
647                 dec = 0;
648                 t1->flags[y+1][x+1] &= ~JPEG2000_T1_VIS;
649             }
650         }
651     }
652     if (seg_symbols) {
653         int val;
654         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
655         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
656         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
657         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
658         if (val != 0xa) {
659             av_log(s->avctx, AV_LOG_ERROR,"Segmentation symbol value incorrect\n");
660         }
661     }
662 }
663
664 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
665                        int width, int height, int bandpos)
666 {
667     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y, clnpass_cnt = 0;
668     int bpass_csty_symbol = JPEG2000_CBLK_BYPASS & codsty->cblk_style;
669     int vert_causal_ctx_csty_symbol = JPEG2000_CBLK_VSC & codsty->cblk_style;
670
671     for (y = 0; y < height+2; y++)
672         memset(t1->flags[y], 0, (width+2)*sizeof(int));
673
674     for (y = 0; y < height; y++)
675         memset(t1->data[y], 0, width*sizeof(int));
676
677     cblk->data[cblk->length] = 0xff;
678     cblk->data[cblk->length+1] = 0xff;
679     ff_mqc_initdec(&t1->mqc, cblk->data);
680
681     while (passno--) {
682         switch(pass_t) {
683             case 0: decode_sigpass(t1, width, height, bpno+1, bandpos,
684                                   bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol);
685                     break;
686             case 1: decode_refpass(t1, width, height, bpno+1);
687                     if (bpass_csty_symbol && clnpass_cnt >= 4)
688                         ff_mqc_initdec(&t1->mqc, cblk->data);
689                     break;
690             case 2: decode_clnpass(s, t1, width, height, bpno+1, bandpos,
691                                    codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol);
692                     clnpass_cnt = clnpass_cnt + 1;
693                     if (bpass_csty_symbol && clnpass_cnt >= 4)
694                        ff_mqc_initdec(&t1->mqc, cblk->data);
695                     break;
696         }
697
698         pass_t++;
699         if (pass_t == 3) {
700             bpno--;
701             pass_t = 0;
702         }
703     }
704     return 0;
705 }
706
707 static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
708 {
709     int i, *src[3], i0, i1, i2, csize = 1;
710
711     for (i = 0; i < 3; i++)
712         src[i] = tile->comp[i].data;
713
714     for (i = 0; i < 2; i++)
715         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
716
717     if (tile->codsty[0].transform == FF_DWT97) {
718         for (i = 0; i < csize; i++) {
719             i0 = *src[0] + (*src[2] * 46802 >> 16);
720             i1 = *src[0] - (*src[1] * 22553 + *src[2] * 46802 >> 16);
721             i2 = *src[0] + (116130 * *src[1] >> 16);
722             *src[0]++ = i0;
723             *src[1]++ = i1;
724             *src[2]++ = i2;
725         }
726     } else{
727         for (i = 0; i < csize; i++) {
728             i1 = *src[0] - (*src[2] + *src[1] >> 2);
729             i0 = i1 + *src[2];
730             i2 = i1 + *src[1];
731             *src[0]++ = i0;
732             *src[1]++ = i1;
733             *src[2]++ = i2;
734         }
735     }
736 }
737
738 static int decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
739 {
740     int compno, reslevelno, bandno;
741     int x, y, *src[4];
742     uint8_t *line;
743     Jpeg2000T1Context t1;
744
745     for (compno = 0; compno < s->ncomponents; compno++) {
746         Jpeg2000Component *comp     = tile->comp + compno;
747         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
748
749         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
750             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
751             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
752                 Jpeg2000Band *band = rlevel->band + bandno;
753                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
754
755                 bandpos = bandno + (reslevelno > 0);
756
757                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
758                 y0 = yy0;
759                 yy1 = FFMIN(ff_jpeg2000_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,
760                             band->coord[1][1]) - band->coord[1][0] + yy0;
761
762                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
763                     continue;
764
765                 for (cblky = 0; cblky < band->cblkny; cblky++) {
766                     if (reslevelno == 0 || bandno == 1)
767                         xx0 = 0;
768                     else
769                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
770                     x0 = xx0;
771                     xx1 = FFMIN(ff_jpeg2000_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,
772                                 band->coord[0][1]) - band->coord[0][0] + xx0;
773
774                     for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++) {
775                         int y, x;
776                         decode_cblk(s, codsty, &t1, band->cblk + cblkno, xx1 - xx0, yy1 - yy0, bandpos);
777                         if (codsty->transform == FF_DWT53) {
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                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = *ptr++ >> 1;
782                                 }
783                             }
784                         } else{
785                             for (y = yy0; y < yy1; y+=s->cdy[compno]) {
786                                 int *ptr = t1.data[y-yy0];
787                                 for (x = xx0; x < xx1; x+=s->cdx[compno]) {
788                                     int tmp = ((int64_t)*ptr++) * ((int64_t)band->stepsize) >> 13, tmp2;
789                                     tmp2 = FFABS(tmp>>1) + (tmp&1);
790                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = tmp < 0 ? -tmp2 : tmp2;
791                                 }
792                             }
793                         }
794                         xx0 = xx1;
795                         xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);
796                     }
797                     yy0 = yy1;
798                     yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);
799                 }
800             }
801         }
802         ff_j2k_dwt_decode(&comp->dwt, comp->data);
803         src[compno] = comp->data;
804     }
805     if (tile->codsty[0].mct)
806         mct_decode(s, tile);
807
808     if (s->precision <= 8) {
809         for (compno = 0; compno < s->ncomponents; compno++) {
810             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
811             line = s->picture->data[0] + y * s->picture->linesize[0];
812             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
813                 uint8_t *dst;
814
815                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
816                 dst = line + x * s->ncomponents + compno;
817
818                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
819                     *src[compno] += 1 << (s->cbps[compno]-1);
820                     if (*src[compno] < 0)
821                         *src[compno] = 0;
822                     else if (*src[compno] >= (1 << s->cbps[compno]))
823                         *src[compno] = (1 << s->cbps[compno]) - 1;
824                     *dst = *src[compno]++;
825                     dst += s->ncomponents;
826                 }
827                 line += s->picture->linesize[0];
828             }
829         }
830     } else {
831         for (compno = 0; compno < s->ncomponents; compno++) {
832             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
833             line = s->picture->data[0] + y * s->picture->linesize[0];
834             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
835                 uint16_t *dst;
836
837                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
838                 dst = (uint16_t *)(line + (x * s->ncomponents + compno) * 2);
839                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {
840                     int32_t val;
841
842                     val = *src[compno]++ << (16 - s->cbps[compno]);
843                     val += 1 << 15;
844                     val = av_clip(val, 0, (1 << 16) - 1);
845                     *dst = val;
846                     dst += s->ncomponents;
847                 }
848                 line += s->picture->linesize[0];
849             }
850         }
851     }
852     return 0;
853 }
854
855 static void cleanup(Jpeg2000DecoderContext *s)
856 {
857     int tileno, compno;
858     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
859         for (compno = 0; compno < s->ncomponents; compno++) {
860             Jpeg2000Component *comp = s->tile[tileno].comp + compno;
861             Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
862
863             ff_j2k_cleanup(comp, codsty);
864         }
865         av_freep(&s->tile[tileno].comp);
866     }
867     av_freep(&s->tile);
868 }
869
870 static int decode_codestream(Jpeg2000DecoderContext *s)
871 {
872     Jpeg2000CodingStyle *codsty = s->codsty;
873     Jpeg2000QuantStyle  *qntsty = s->qntsty;
874     uint8_t *properties = s->properties;
875
876     for (;;) {
877         int oldpos, marker, len, ret = 0;
878
879         if (bytestream2_get_bytes_left(&s->g) < 2) {
880             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
881             break;
882         }
883
884         marker = bytestream2_get_be16u(&s->g);
885         av_dlog(s->avctx, "marker 0x%.4X at pos 0x%x\n", marker, bytestream2_tell(&s->g) - 4);
886         oldpos = bytestream2_tell(&s->g);
887
888         if (marker == JPEG2000_SOD) {
889             Jpeg2000Tile *tile = s->tile + s->curtileno;
890             if (ret = init_tile(s, s->curtileno)) {
891                 av_log(s->avctx, AV_LOG_ERROR, "tile initialization failed\n");
892                 return ret;
893             }
894             if (ret = jpeg2000_decode_packets(s, tile)) {
895                 av_log(s->avctx, AV_LOG_ERROR, "packets decoding failed\n");
896                 return ret;
897             }
898             continue;
899         }
900         if (marker == JPEG2000_EOC)
901             break;
902
903         if (bytestream2_get_bytes_left(&s->g) < 2)
904             return AVERROR(EINVAL);
905         len = bytestream2_get_be16u(&s->g);
906         switch (marker) {
907         case JPEG2000_SIZ:
908             ret = get_siz(s);
909             if (!s->tile)
910                 s->numXtiles = s->numYtiles = 0;
911             break;
912         case JPEG2000_COC:
913             ret = get_coc(s, codsty, properties);
914             break;
915         case JPEG2000_COD:
916             ret = get_cod(s, codsty, properties);
917             break;
918         case JPEG2000_QCC:
919             ret = get_qcc(s, len, qntsty, properties);
920             break;
921         case JPEG2000_QCD:
922             ret = get_qcd(s, len, qntsty, properties);
923             break;
924         case JPEG2000_SOT:
925             if (!(ret = get_sot(s))) {
926                 codsty = s->tile[s->curtileno].codsty;
927                 qntsty = s->tile[s->curtileno].qntsty;
928                 properties = s->tile[s->curtileno].properties;
929             }
930             break;
931         case JPEG2000_COM:
932             // the comment is ignored
933             bytestream2_skip(&s->g, len - 2);
934             break;
935         default:
936             av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%x\n", marker, bytestream2_tell(&s->g) - 4);
937             bytestream2_skip(&s->g, len - 2);
938             break;
939         }
940         if (bytestream2_tell(&s->g) - oldpos != len || ret) {
941             av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker);
942             return ret ? ret : -1;
943         }
944     }
945     return 0;
946 }
947
948 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
949 {
950     uint32_t atom_size, atom;
951     int found_codestream = 0, search_range = 10;
952
953     while (!found_codestream && search_range && bytestream2_get_bytes_left(&s->g) >= 8) {
954         atom_size = bytestream2_get_be32u(&s->g);
955         atom      = bytestream2_get_be32u(&s->g);
956         if (atom == JP2_CODESTREAM) {
957             found_codestream = 1;
958         } else {
959             if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
960                 return 0;
961             bytestream2_skipu(&s->g, atom_size - 8);
962             search_range--;
963         }
964     }
965
966     if (found_codestream)
967         return 1;
968     return 0;
969 }
970
971 static int decode_frame(AVCodecContext *avctx,
972                         void *data, int *got_frame,
973                         AVPacket *avpkt)
974 {
975     Jpeg2000DecoderContext *s = avctx->priv_data;
976     AVFrame *picture = data;
977     int tileno, ret;
978
979     s->picture = picture;
980
981     s->avctx     = avctx;
982     bytestream2_init(&s->g, avpkt->data, avpkt->size);
983     s->curtileno = -1;
984
985     if (bytestream2_get_bytes_left(&s->g) < 2) {
986         ret = AVERROR(EINVAL);
987         goto err_out;
988     }
989
990     // check if the image is in jp2 format
991     if (bytestream2_get_bytes_left(&s->g) >= 12 &&
992        (bytestream2_get_be32u(&s->g) == 12) &&
993        (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
994        (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
995         if (!jp2_find_codestream(s)) {
996             av_log(avctx, AV_LOG_ERROR, "couldn't find jpeg2k codestream atom\n");
997             ret = -1;
998             goto err_out;
999         }
1000     } else {
1001         bytestream2_seek(&s->g, 0, SEEK_SET);
1002     }
1003
1004     if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1005         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1006         ret = -1;
1007         goto err_out;
1008     }
1009     if (ret = decode_codestream(s))
1010         goto err_out;
1011
1012     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1013         if (ret = decode_tile(s, s->tile + tileno))
1014             goto err_out;
1015
1016     cleanup(s);
1017
1018     *got_frame = 1;
1019
1020     return bytestream2_tell(&s->g);
1021
1022 err_out:
1023     cleanup(s);
1024     return ret;
1025 }
1026
1027 static void jpeg2000_init_static_data(AVCodec *codec)
1028 {
1029     ff_jpeg2000_init_tier1_luts();
1030 }
1031
1032 static const AVProfile profiles[] = {
1033     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0,  "JPEG 2000 codestream restriction 0"   },
1034     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1,  "JPEG 2000 codestream restriction 1"   },
1035     { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1036     { FF_PROFILE_JPEG2000_DCINEMA_2K,             "JPEG 2000 digital cinema 2K"          },
1037     { FF_PROFILE_JPEG2000_DCINEMA_4K,             "JPEG 2000 digital cinema 4K"          },
1038     { FF_PROFILE_UNKNOWN },
1039 };
1040
1041 AVCodec ff_j2k_decoder = {
1042     .name             = "j2k",
1043     .long_name        = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1044     .type             = AVMEDIA_TYPE_VIDEO,
1045     .id               = AV_CODEC_ID_JPEG2000,
1046     .capabilities     = CODEC_CAP_EXPERIMENTAL | CODEC_CAP_FRAME_THREADS,
1047     .priv_data_size   = sizeof(Jpeg2000DecoderContext),
1048     .init_static_data = jpeg2000_init_static_data,
1049     .decode           = decode_frame,
1050     .profiles         = NULL_IF_CONFIG_SMALL(profiles)
1051 };