OSDN Git Service

Merge remote-tracking branch 'qatar/master'
[coroid/ffmpeg_saccubus.git] / 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 #include "avcodec.h"
29 #include "bytestream.h"
30 #include "j2k.h"
31 #include "libavutil/common.h"
32
33 #define JP2_SIG_TYPE    0x6A502020
34 #define JP2_SIG_VALUE   0x0D0A870A
35 #define JP2_CODESTREAM  0x6A703263
36
37 #define HAD_COC 0x01
38 #define HAD_QCC 0x02
39
40 typedef struct {
41    J2kComponent *comp;
42    uint8_t properties[4];
43    J2kCodingStyle codsty[4];
44    J2kQuantStyle  qntsty[4];
45 } J2kTile;
46
47 typedef struct {
48     AVCodecContext *avctx;
49     AVFrame picture;
50
51     int width, height; ///< image width and height
52     int image_offset_x, image_offset_y;
53     int tile_offset_x, tile_offset_y;
54     uint8_t cbps[4]; ///< bits per sample in particular components
55     uint8_t sgnd[4]; ///< if a component is signed
56     uint8_t properties[4];
57     int cdx[4], cdy[4];
58     int precision;
59     int ncomponents;
60     int tile_width, tile_height; ///< tile size
61     int numXtiles, numYtiles;
62     int maxtilelen;
63
64     J2kCodingStyle codsty[4];
65     J2kQuantStyle  qntsty[4];
66
67     uint8_t *buf_start;
68     uint8_t *buf;
69     uint8_t *buf_end;
70     int bit_index;
71
72     int16_t curtileno;
73
74     J2kTile *tile;
75 } J2kDecoderContext;
76
77 static int get_bits(J2kDecoderContext *s, int n)
78 {
79     int res = 0;
80     if (s->buf_end - s->buf < ((n - s->bit_index) >> 8))
81         return AVERROR(EINVAL);
82     while (--n >= 0){
83         res <<= 1;
84         if (s->bit_index == 0){
85             s->bit_index = 7 + (*s->buf != 0xff);
86             s->buf++;
87         }
88         s->bit_index--;
89         res |= (*s->buf >> s->bit_index) & 1;
90     }
91     return res;
92 }
93
94 static void j2k_flush(J2kDecoderContext *s)
95 {
96     if (*s->buf == 0xff)
97         s->buf++;
98     s->bit_index = 8;
99     s->buf++;
100 }
101 #if 0
102 void printcomp(J2kComponent *comp)
103 {
104     int i;
105     for (i = 0; i < comp->y1 - comp->y0; i++)
106         ff_j2k_printv(comp->data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
107 }
108
109 static void nspaces(FILE *fd, int n)
110 {
111     while(n--) putc(' ', fd);
112 }
113
114 static void dump(J2kDecoderContext *s, FILE *fd)
115 {
116     int tileno, compno, reslevelno, bandno, precno;
117     fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
118                 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
119                 "tiles:\n",
120             s->width, s->height, s->tile_width, s->tile_height,
121             s->numXtiles, s->numYtiles, s->ncomponents);
122     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
123         J2kTile *tile = s->tile + tileno;
124         nspaces(fd, 2);
125         fprintf(fd, "tile %d:\n", tileno);
126         for(compno = 0; compno < s->ncomponents; compno++){
127             J2kComponent *comp = tile->comp + compno;
128             nspaces(fd, 4);
129             fprintf(fd, "component %d:\n", compno);
130             nspaces(fd, 4);
131             fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
132                         comp->x0, comp->x1, comp->y0, comp->y1);
133             for(reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
134                 J2kResLevel *reslevel = comp->reslevel + reslevelno;
135                 nspaces(fd, 6);
136                 fprintf(fd, "reslevel %d:\n", reslevelno);
137                 nspaces(fd, 6);
138                 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
139                         reslevel->x0, reslevel->x1, reslevel->y0,
140                         reslevel->y1, reslevel->nbands);
141                 for(bandno = 0; bandno < reslevel->nbands; bandno++){
142                     J2kBand *band = reslevel->band + bandno;
143                     nspaces(fd, 8);
144                     fprintf(fd, "band %d:\n", bandno);
145                     nspaces(fd, 8);
146                     fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
147                                 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
148                                 band->x0, band->x1,
149                                 band->y0, band->y1,
150                                 band->codeblock_width, band->codeblock_height,
151                                 band->cblknx, band->cblkny);
152                     for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
153                         J2kPrec *prec = band->prec + precno;
154                         nspaces(fd, 10);
155                         fprintf(fd, "prec %d:\n", precno);
156                         nspaces(fd, 10);
157                         fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
158                                      prec->xi0, prec->xi1, prec->yi0, prec->yi1);
159                     }
160                 }
161             }
162         }
163     }
164 }
165 #endif
166
167 /** decode the value stored in node */
168 static int tag_tree_decode(J2kDecoderContext *s, J2kTgtNode *node, int threshold)
169 {
170     J2kTgtNode *stack[30];
171     int sp = -1, curval = 0;
172
173     while(node && !node->vis){
174         stack[++sp] = node;
175         node = node->parent;
176     }
177
178     if (node)
179         curval = node->val;
180     else
181         curval = stack[sp]->val;
182
183     while(curval < threshold && sp >= 0){
184         if (curval < stack[sp]->val)
185             curval = stack[sp]->val;
186         while (curval < threshold){
187             int ret;
188             if ((ret = get_bits(s, 1)) > 0){
189                 stack[sp]->vis++;
190                 break;
191             } else if (!ret)
192                 curval++;
193             else
194                 return ret;
195         }
196         stack[sp]->val = curval;
197         sp--;
198     }
199     return curval;
200 }
201
202 /* marker segments */
203 /** get sizes and offsets of image, tiles; number of components */
204 static int get_siz(J2kDecoderContext *s)
205 {
206     int i, ret;
207
208     if (s->buf_end - s->buf < 36)
209         return AVERROR(EINVAL);
210
211                         bytestream_get_be16(&s->buf); // Rsiz (skipped)
212              s->width = bytestream_get_be32(&s->buf); // width
213             s->height = bytestream_get_be32(&s->buf); // height
214     s->image_offset_x = bytestream_get_be32(&s->buf); // X0Siz
215     s->image_offset_y = bytestream_get_be32(&s->buf); // Y0Siz
216
217         s->tile_width = bytestream_get_be32(&s->buf); // XTSiz
218        s->tile_height = bytestream_get_be32(&s->buf); // YTSiz
219      s->tile_offset_x = bytestream_get_be32(&s->buf); // XT0Siz
220      s->tile_offset_y = bytestream_get_be32(&s->buf); // YT0Siz
221        s->ncomponents = bytestream_get_be16(&s->buf); // CSiz
222
223     if (s->buf_end - s->buf < 2 * s->ncomponents)
224         return AVERROR(EINVAL);
225
226     for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
227         uint8_t x = bytestream_get_byte(&s->buf);
228         s->cbps[i] = (x & 0x7f) + 1;
229         s->precision = FFMAX(s->cbps[i], s->precision);
230         s->sgnd[i] = (x & 0x80) == 1;
231         s->cdx[i] = bytestream_get_byte(&s->buf);
232         s->cdy[i] = bytestream_get_byte(&s->buf);
233     }
234
235     s->numXtiles = ff_j2k_ceildiv(s->width - s->tile_offset_x, s->tile_width);
236     s->numYtiles = ff_j2k_ceildiv(s->height - s->tile_offset_y, s->tile_height);
237
238     s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(J2kTile));
239     if (!s->tile)
240         return AVERROR(ENOMEM);
241
242     for (i = 0; i < s->numXtiles * s->numYtiles; i++){
243         J2kTile *tile = s->tile + i;
244
245         tile->comp = av_mallocz(s->ncomponents * sizeof(J2kComponent));
246         if (!tile->comp)
247             return AVERROR(ENOMEM);
248     }
249
250     s->avctx->width = s->width - s->image_offset_x;
251     s->avctx->height = s->height - s->image_offset_y;
252
253     switch(s->ncomponents){
254         case 1: if (s->precision > 8) {
255                     s->avctx->pix_fmt    = PIX_FMT_GRAY16;
256                 } else s->avctx->pix_fmt = PIX_FMT_GRAY8;
257                 break;
258         case 3: if (s->precision > 8) {
259                     s->avctx->pix_fmt    = PIX_FMT_RGB48;
260                 } else s->avctx->pix_fmt = PIX_FMT_RGB24;
261                 break;
262         case 4: s->avctx->pix_fmt = PIX_FMT_BGRA; break;
263     }
264
265     if (s->picture.data[0])
266         s->avctx->release_buffer(s->avctx, &s->picture);
267
268     if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0)
269         return ret;
270
271     s->picture.pict_type = FF_I_TYPE;
272     s->picture.key_frame = 1;
273
274     return 0;
275 }
276
277 /** get common part for COD and COC segments */
278 static int get_cox(J2kDecoderContext *s, J2kCodingStyle *c)
279 {
280     if (s->buf_end - s->buf < 5)
281         return AVERROR(EINVAL);
282           c->nreslevels = bytestream_get_byte(&s->buf) + 1; // num of resolution levels - 1
283      c->log2_cblk_width = bytestream_get_byte(&s->buf) + 2; // cblk width
284     c->log2_cblk_height = bytestream_get_byte(&s->buf) + 2; // cblk height
285
286     c->cblk_style = bytestream_get_byte(&s->buf);
287     if (c->cblk_style != 0){ // cblk style
288         av_log(s->avctx, AV_LOG_ERROR, "no extra cblk styles supported\n");
289         return -1;
290     }
291     c->transform = bytestream_get_byte(&s->buf); // transformation
292     if (c->csty & J2K_CSTY_PREC) {
293         int i;
294         for (i = 0; i < c->nreslevels; i++)
295             bytestream_get_byte(&s->buf);
296     }
297     return 0;
298 }
299
300 /** get coding parameters for a particular tile or whole image*/
301 static int get_cod(J2kDecoderContext *s, J2kCodingStyle *c, uint8_t *properties)
302 {
303     J2kCodingStyle tmp;
304     int compno;
305
306     if (s->buf_end - s->buf < 5)
307         return AVERROR(EINVAL);
308
309     tmp.log2_prec_width  =
310     tmp.log2_prec_height = 15;
311
312     tmp.csty = bytestream_get_byte(&s->buf);
313
314     if (bytestream_get_byte(&s->buf)){ // progression level
315         av_log(s->avctx, AV_LOG_ERROR, "only LRCP progression supported\n");
316         return -1;
317     }
318
319     tmp.nlayers = bytestream_get_be16(&s->buf);
320         tmp.mct = bytestream_get_byte(&s->buf); // multiple component transformation
321
322     get_cox(s, &tmp);
323     for (compno = 0; compno < s->ncomponents; compno++){
324         if (!(properties[compno] & HAD_COC))
325             memcpy(c + compno, &tmp, sizeof(J2kCodingStyle));
326     }
327     return 0;
328 }
329
330 /** get coding parameters for a component in the whole image on a particular tile */
331 static int get_coc(J2kDecoderContext *s, J2kCodingStyle *c, uint8_t *properties)
332 {
333     int compno;
334
335     if (s->buf_end - s->buf < 2)
336         return AVERROR(EINVAL);
337
338     compno = bytestream_get_byte(&s->buf);
339
340     c += compno;
341     c->csty = bytestream_get_byte(&s->buf);
342     get_cox(s, c);
343
344     properties[compno] |= HAD_COC;
345     return 0;
346 }
347
348 /** get common part for QCD and QCC segments */
349 static int get_qcx(J2kDecoderContext *s, int n, J2kQuantStyle *q)
350 {
351     int i, x;
352
353     if (s->buf_end - s->buf < 1)
354         return AVERROR(EINVAL);
355
356     x = bytestream_get_byte(&s->buf); // Sqcd
357
358     q->nguardbits = x >> 5;
359       q->quantsty = x & 0x1f;
360
361     if (q->quantsty == J2K_QSTY_NONE){
362         n -= 3;
363         if (s->buf_end - s->buf < n)
364             return AVERROR(EINVAL);
365         for (i = 0; i < n; i++)
366             q->expn[i] = bytestream_get_byte(&s->buf) >> 3;
367     } else if (q->quantsty == J2K_QSTY_SI){
368         if (s->buf_end - s->buf < 2)
369             return AVERROR(EINVAL);
370         x = bytestream_get_be16(&s->buf);
371         q->expn[0] = x >> 11;
372         q->mant[0] = x & 0x7ff;
373         for (i = 1; i < 32 * 3; i++){
374             int curexpn = FFMAX(0, q->expn[0] - (i-1)/3);
375             q->expn[i] = curexpn;
376             q->mant[i] = q->mant[0];
377         }
378     } else{
379         n = (n - 3) >> 1;
380         if (s->buf_end - s->buf < n)
381             return AVERROR(EINVAL);
382         for (i = 0; i < n; i++){
383             x = bytestream_get_be16(&s->buf);
384             q->expn[i] = x >> 11;
385             q->mant[i] = x & 0x7ff;
386         }
387     }
388     return 0;
389 }
390
391 /** get quantization parameters for a particular tile or a whole image */
392 static int get_qcd(J2kDecoderContext *s, int n, J2kQuantStyle *q, uint8_t *properties)
393 {
394     J2kQuantStyle tmp;
395     int compno;
396
397     if (get_qcx(s, n, &tmp))
398         return -1;
399     for (compno = 0; compno < s->ncomponents; compno++)
400         if (!(properties[compno] & HAD_QCC))
401             memcpy(q + compno, &tmp, sizeof(J2kQuantStyle));
402     return 0;
403 }
404
405 /** get quantization parameters for a component in the whole image on in a particular tile */
406 static int get_qcc(J2kDecoderContext *s, int n, J2kQuantStyle *q, uint8_t *properties)
407 {
408     int compno;
409
410     if (s->buf_end - s->buf < 1)
411         return AVERROR(EINVAL);
412
413     compno = bytestream_get_byte(&s->buf);
414     properties[compno] |= HAD_QCC;
415     return get_qcx(s, n-1, q+compno);
416 }
417
418 /** get start of tile segment */
419 static uint8_t get_sot(J2kDecoderContext *s)
420 {
421     if (s->buf_end - s->buf < 4)
422         return AVERROR(EINVAL);
423
424     s->curtileno = bytestream_get_be16(&s->buf); ///< Isot
425
426     s->buf += 4; ///< Psot (ignored)
427
428     if (!bytestream_get_byte(&s->buf)){ ///< TPsot
429         J2kTile *tile = s->tile + s->curtileno;
430
431         /* copy defaults */
432         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(J2kCodingStyle));
433         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(J2kQuantStyle));
434     }
435     bytestream_get_byte(&s->buf); ///< TNsot
436
437     return 0;
438 }
439
440 static int init_tile(J2kDecoderContext *s, int tileno)
441 {
442     int compno,
443         tilex = tileno % s->numXtiles,
444         tiley = tileno / s->numXtiles;
445     J2kTile *tile = s->tile + tileno;
446
447     if (!tile->comp)
448         return AVERROR(ENOMEM);
449     for (compno = 0; compno < s->ncomponents; compno++){
450         J2kComponent *comp = tile->comp + compno;
451         J2kCodingStyle *codsty = tile->codsty + compno;
452         J2kQuantStyle  *qntsty = tile->qntsty + compno;
453         int ret; // global bandno
454
455         comp->coord[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
456         comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width + s->tile_offset_x, s->width);
457         comp->coord[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
458         comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height + s->tile_offset_y, s->height);
459
460         if (ret = ff_j2k_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno]))
461             return ret;
462     }
463     return 0;
464 }
465
466 /** read the number of coding passes */
467 static int getnpasses(J2kDecoderContext *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(J2kDecoderContext *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(J2kDecoderContext *s, J2kCodingStyle *codsty, J2kResLevel *rlevel, int precno,
494                          int layno, uint8_t *expn, int numgbits)
495 {
496     int bandno, cblkny, cblknx, cblkno, ret;
497
498     if (!(ret = get_bits(s, 1))){
499         j2k_flush(s);
500         return 0;
501     } else if (ret < 0)
502         return ret;
503
504     for (bandno = 0; bandno < rlevel->nbands; bandno++){
505         J2kBand *band = rlevel->band + bandno;
506         J2kPrec *prec = band->prec + precno;
507         int pos = 0;
508
509         if (band->coord[0][0] == band->coord[0][1]
510         ||  band->coord[1][0] == band->coord[1][1])
511             continue;
512
513         for (cblkny = prec->yi0; cblkny < prec->yi1; cblkny++)
514             for(cblknx = prec->xi0, cblkno = cblkny * band->cblknx + cblknx; cblknx < prec->xi1; cblknx++, cblkno++, pos++){
515                 J2kCblk *cblk = band->cblk + cblkno;
516                 int incl, newpasses, llen;
517
518                 if (cblk->npasses)
519                     incl = get_bits(s, 1);
520                 else
521                     incl = tag_tree_decode(s, prec->cblkincl + pos, layno+1) == layno;
522                 if (!incl)
523                     continue;
524                 else if (incl < 0)
525                     return incl;
526
527                 if (!cblk->npasses)
528                     cblk->nonzerobits = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + pos, 100);
529                 if ((newpasses = getnpasses(s)) < 0)
530                     return newpasses;
531                 if ((llen = getlblockinc(s)) < 0)
532                     return llen;
533                 cblk->lblock += llen;
534                 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
535                     return ret;
536                 cblk->lengthinc = ret;
537                 cblk->npasses += newpasses;
538             }
539     }
540     j2k_flush(s);
541
542     if (codsty->csty & J2K_CSTY_EPH) {
543         if (AV_RB16(s->buf) == J2K_EPH) {
544             s->buf += 2;
545         } else {
546             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
547         }
548     }
549
550     for (bandno = 0; bandno < rlevel->nbands; bandno++){
551         J2kBand *band = rlevel->band + bandno;
552         int yi, cblknw = band->prec[precno].xi1 - band->prec[precno].xi0;
553         for (yi = band->prec[precno].yi0; yi < band->prec[precno].yi1; yi++){
554             int xi;
555             for (xi = band->prec[precno].xi0; xi < band->prec[precno].xi1; xi++){
556                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
557                 if (s->buf_end - s->buf < cblk->lengthinc)
558                     return AVERROR(EINVAL);
559                 bytestream_get_buffer(&s->buf, cblk->data, cblk->lengthinc);
560                 cblk->length += cblk->lengthinc;
561                 cblk->lengthinc = 0;
562             }
563         }
564     }
565     return 0;
566 }
567
568 static int decode_packets(J2kDecoderContext *s, J2kTile *tile)
569 {
570     int layno, reslevelno, compno, precno, ok_reslevel;
571     s->bit_index = 8;
572     for (layno = 0; layno < tile->codsty[0].nlayers; layno++){
573         ok_reslevel = 1;
574         for (reslevelno = 0; ok_reslevel; reslevelno++){
575             ok_reslevel = 0;
576             for (compno = 0; compno < s->ncomponents; compno++){
577                 J2kCodingStyle *codsty = tile->codsty + compno;
578                 J2kQuantStyle  *qntsty = tile->qntsty + compno;
579                 if (reslevelno < codsty->nreslevels){
580                     J2kResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
581                     ok_reslevel = 1;
582                     for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++){
583                         if (decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn +
584                                           (reslevelno ? 3*(reslevelno-1)+1 : 0), qntsty->nguardbits))
585                             return -1;
586                     }
587                 }
588             }
589         }
590     }
591     return 0;
592 }
593
594 /* TIER-1 routines */
595 static void decode_sigpass(J2kT1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol,
596                            int vert_causal_ctx_csty_symbol)
597 {
598     int mask = 3 << (bpno - 1), y0, x, y;
599
600     for (y0 = 0; y0 < height; y0 += 4)
601         for (x = 0; x < width; x++)
602             for (y = y0; y < height && y < y0+4; y++){
603                 if ((t1->flags[y+1][x+1] & J2K_T1_SIG_NB)
604                 && !(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
605                     int vert_causal_ctx_csty_loc_symbol = vert_causal_ctx_csty_symbol && (x == 3 && y == 3);
606                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno,
607                                       vert_causal_ctx_csty_loc_symbol))){
608                         int xorbit, ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
609                         if (bpass_csty_symbol)
610                              t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
611                         else
612                              t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
613                                                -mask : mask;
614
615                         ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
616                     }
617                     t1->flags[y+1][x+1] |= J2K_T1_VIS;
618                 }
619             }
620 }
621
622 static void decode_refpass(J2kT1Context *t1, int width, int height, int bpno)
623 {
624     int phalf, nhalf;
625     int y0, x, y;
626
627     phalf = 1 << (bpno - 1);
628     nhalf = -phalf;
629
630     for (y0 = 0; y0 < height; y0 += 4)
631         for (x = 0; x < width; x++)
632             for (y = y0; y < height && y < y0+4; y++){
633                 if ((t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)) == J2K_T1_SIG){
634                     int ctxno = ff_j2k_getrefctxno(t1->flags[y+1][x+1]);
635                     int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf;
636                     t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
637                     t1->flags[y+1][x+1] |= J2K_T1_REF;
638                 }
639             }
640 }
641
642 static void decode_clnpass(J2kDecoderContext *s, J2kT1Context *t1, int width, int height,
643                            int bpno, int bandno, int seg_symbols)
644 {
645     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
646
647     for (y0 = 0; y0 < height; y0 += 4) {
648         for (x = 0; x < width; x++){
649             if (y0 + 3 < height && !(
650             (t1->flags[y0+1][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
651             (t1->flags[y0+2][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
652             (t1->flags[y0+3][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
653             (t1->flags[y0+4][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)))){
654                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
655                     continue;
656                 runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
657                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
658                 dec = 1;
659             } else{
660                 runlen = 0;
661                 dec = 0;
662             }
663
664             for (y = y0 + runlen; y < y0 + 4 && y < height; y++){
665                 if (!dec){
666                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)))
667                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_j2k_getnbctxno(t1->flags[y+1][x+1],
668                                                                                              bandno, 0));
669                 }
670                 if (dec){
671                     int xorbit, ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
672                     t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask;
673                     ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
674                 }
675                 dec = 0;
676                 t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
677             }
678         }
679     }
680     if (seg_symbols) {
681         int val;
682         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
683         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
684         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
685         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
686         if (val != 0xa) {
687             av_log(s->avctx, AV_LOG_ERROR,"Segmentation symbol value incorrect\n");
688         }
689     }
690 }
691
692 static int decode_cblk(J2kDecoderContext *s, J2kCodingStyle *codsty, J2kT1Context *t1, J2kCblk *cblk,
693                        int width, int height, int bandpos)
694 {
695     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y, clnpass_cnt = 0;
696
697     for (y = 0; y < height+2; y++)
698         memset(t1->flags[y], 0, (width+2)*sizeof(int));
699
700     for (y = 0; y < height; y++)
701         memset(t1->data[y], 0, width*sizeof(int));
702
703     ff_mqc_initdec(&t1->mqc, cblk->data);
704     cblk->data[cblk->length] = 0xff;
705     cblk->data[cblk->length+1] = 0xff;
706
707     int bpass_csty_symbol = J2K_CBLK_BYPASS & codsty->cblk_style;
708     int vert_causal_ctx_csty_symbol = J2K_CBLK_VSC & codsty->cblk_style;
709
710     while(passno--){
711         switch(pass_t){
712             case 0: decode_sigpass(t1, width, height, bpno+1, bandpos,
713                                   bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol);
714                     break;
715             case 1: decode_refpass(t1, width, height, bpno+1);
716                     if (bpass_csty_symbol && clnpass_cnt >= 4)
717                         ff_mqc_initdec(&t1->mqc, cblk->data);
718                     break;
719             case 2: decode_clnpass(s, t1, width, height, bpno+1, bandpos,
720                                    codsty->cblk_style & J2K_CBLK_SEGSYM);
721                     clnpass_cnt = clnpass_cnt + 1;
722                     if (bpass_csty_symbol && clnpass_cnt >= 4)
723                        ff_mqc_initdec(&t1->mqc, cblk->data);
724                     break;
725         }
726
727         pass_t++;
728         if (pass_t == 3){
729             bpno--;
730             pass_t = 0;
731         }
732     }
733     return 0;
734 }
735
736 static void mct_decode(J2kDecoderContext *s, J2kTile *tile)
737 {
738     int i, *src[3], i0, i1, i2, csize = 1;
739
740     for (i = 0; i < 3; i++)
741         src[i] = tile->comp[i].data;
742
743     for (i = 0; i < 2; i++)
744         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
745
746     if (tile->codsty[0].transform == FF_DWT97){
747         for (i = 0; i < csize; i++){
748             i0 = *src[0] + (*src[2] * 46802 >> 16);
749             i1 = *src[0] - (*src[1] * 22553 + *src[2] * 46802 >> 16);
750             i2 = *src[0] + (116130 * *src[1] >> 16);
751             *src[0]++ = i0;
752             *src[1]++ = i1;
753             *src[2]++ = i2;
754         }
755     } else{
756         for (i = 0; i < csize; i++){
757             i1 = *src[0] - (*src[2] + *src[1] >> 2);
758             i0 = i1 + *src[2];
759             i2 = i1 + *src[1];
760             *src[0]++ = i0;
761             *src[1]++ = i1;
762             *src[2]++ = i2;
763         }
764     }
765 }
766
767 static int decode_tile(J2kDecoderContext *s, J2kTile *tile)
768 {
769     int compno, reslevelno, bandno;
770     int x, y, *src[4];
771     uint8_t *line;
772     J2kT1Context t1;
773
774     for (compno = 0; compno < s->ncomponents; compno++){
775         J2kComponent *comp = tile->comp + compno;
776         J2kCodingStyle *codsty = tile->codsty + compno;
777
778         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
779             J2kResLevel *rlevel = comp->reslevel + reslevelno;
780             for (bandno = 0; bandno < rlevel->nbands; bandno++){
781                 J2kBand *band = rlevel->band + bandno;
782                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
783
784                 bandpos = bandno + (reslevelno > 0);
785
786                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
787                 y0 = yy0;
788                 yy1 = FFMIN(ff_j2k_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,
789                             band->coord[1][1]) - band->coord[1][0] + yy0;
790
791                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
792                     continue;
793
794                 for (cblky = 0; cblky < band->cblkny; cblky++){
795                     if (reslevelno == 0 || bandno == 1)
796                         xx0 = 0;
797                     else
798                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
799                     x0 = xx0;
800                     xx1 = FFMIN(ff_j2k_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,
801                                 band->coord[0][1]) - band->coord[0][0] + xx0;
802
803                     for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++){
804                         int y, x;
805                         decode_cblk(s, codsty, &t1, band->cblk + cblkno, xx1 - xx0, yy1 - yy0, bandpos);
806                         if (codsty->transform == FF_DWT53){
807                             for (y = yy0; y < yy1; y+=s->cdy[compno]){
808                                 int *ptr = t1.data[y-yy0];
809                                 for (x = xx0; x < xx1; x+=s->cdx[compno]){
810                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = *ptr++ >> 1;
811                                 }
812                             }
813                         } else{
814                             for (y = yy0; y < yy1; y+=s->cdy[compno]){
815                                 int *ptr = t1.data[y-yy0];
816                                 for (x = xx0; x < xx1; x+=s->cdx[compno]){
817                                     int tmp = ((int64_t)*ptr++) * ((int64_t)band->stepsize) >> 13, tmp2;
818                                     tmp2 = FFABS(tmp>>1) + FFABS(tmp&1);
819                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = tmp < 0 ? -tmp2 : tmp2;
820                                 }
821                             }
822                         }
823                         xx0 = xx1;
824                         xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);
825                     }
826                     yy0 = yy1;
827                     yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);
828                 }
829             }
830         }
831         ff_j2k_dwt_decode(&comp->dwt, comp->data);
832         src[compno] = comp->data;
833     }
834     if (tile->codsty[0].mct)
835         mct_decode(s, tile);
836
837     if (s->avctx->pix_fmt == PIX_FMT_BGRA) // RGBA -> BGRA
838         FFSWAP(int *, src[0], src[2]);
839
840     if (s->precision <= 8) {
841         for (compno = 0; compno < s->ncomponents; compno++){
842             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
843             line = s->picture.data[0] + y * s->picture.linesize[0];
844             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]){
845                 uint8_t *dst;
846
847                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
848                 dst = line + x * s->ncomponents + compno;
849
850                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
851                     *src[compno] += 1 << (s->cbps[compno]-1);
852                     if (*src[compno] < 0)
853                         *src[compno] = 0;
854                     else if (*src[compno] >= (1 << s->cbps[compno]))
855                         *src[compno] = (1 << s->cbps[compno]) - 1;
856                     *dst = *src[compno]++;
857                     dst += s->ncomponents;
858                 }
859                 line += s->picture.linesize[0];
860             }
861         }
862     } else {
863         for (compno = 0; compno < s->ncomponents; compno++) {
864             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
865             line = s->picture.data[0] + y * s->picture.linesize[0];
866             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
867                 uint16_t *dst;
868                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
869                 dst = line + (x * s->ncomponents + compno) * 2;
870                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {
871                     int32_t val;
872                     val = *src[compno]++ << (16 - s->cbps[compno]);
873                     val += 1 << 15;
874                     val = av_clip(val, 0, (1 << 16) - 1);
875                     *dst = val;
876                     dst += s->ncomponents;
877                 }
878                 line += s->picture.linesize[0];
879             }
880         }
881     }
882     return 0;
883 }
884
885 static void cleanup(J2kDecoderContext *s)
886 {
887     int tileno, compno;
888     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
889         for (compno = 0; compno < s->ncomponents; compno++){
890             J2kComponent *comp = s->tile[tileno].comp + compno;
891             J2kCodingStyle *codsty = s->tile[tileno].codsty + compno;
892
893             ff_j2k_cleanup(comp, codsty);
894         }
895         av_freep(&s->tile[tileno].comp);
896     }
897     av_freep(&s->tile);
898 }
899
900 static int decode_codestream(J2kDecoderContext *s)
901 {
902     J2kCodingStyle *codsty = s->codsty;
903     J2kQuantStyle  *qntsty = s->qntsty;
904     uint8_t *properties = s->properties;
905
906     for (;;){
907         int marker, len, ret = 0;
908         uint8_t *oldbuf;
909         if (s->buf_end - s->buf < 2){
910             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
911             break;
912         }
913
914         marker = bytestream_get_be16(&s->buf);
915         oldbuf = s->buf;
916
917         if (marker == J2K_SOD){
918             J2kTile *tile = s->tile + s->curtileno;
919             if (ret = init_tile(s, s->curtileno))
920                 return ret;
921             if (ret = decode_packets(s, tile))
922                 return ret;
923             continue;
924         }
925         if (marker == J2K_EOC)
926             break;
927
928         if (s->buf_end - s->buf < 2)
929             return AVERROR(EINVAL);
930         len = bytestream_get_be16(&s->buf);
931         switch(marker){
932             case J2K_SIZ:
933                 ret = get_siz(s); break;
934             case J2K_COC:
935                 ret = get_coc(s, codsty, properties); break;
936             case J2K_COD:
937                 ret = get_cod(s, codsty, properties); break;
938             case J2K_QCC:
939                 ret = get_qcc(s, len, qntsty, properties); break;
940             case J2K_QCD:
941                 ret = get_qcd(s, len, qntsty, properties); break;
942             case J2K_SOT:
943                 if (!(ret = get_sot(s))){
944                     codsty = s->tile[s->curtileno].codsty;
945                     qntsty = s->tile[s->curtileno].qntsty;
946                     properties = s->tile[s->curtileno].properties;
947                 }
948                 break;
949             case J2K_COM:
950                 // the comment is ignored
951                 s->buf += len - 2; break;
952             default:
953                 av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%x\n", marker, s->buf - s->buf_start - 4);
954                 s->buf += len - 2; break;
955         }
956         if (s->buf - oldbuf != len || ret){
957             av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker);
958             return ret ? ret : -1;
959         }
960     }
961     return 0;
962 }
963
964 static int jp2_find_codestream(J2kDecoderContext *s)
965 {
966     int32_t atom_size;
967     int found_codestream = 0, search_range = 10;
968
969     // skip jpeg2k signature atom
970     s->buf += 12;
971
972     while(!found_codestream && search_range) {
973         atom_size = AV_RB32(s->buf);
974         if(AV_RB32(s->buf + 4) == JP2_CODESTREAM) {
975             found_codestream = 1;
976             s->buf += 8;
977         } else {
978             s->buf += atom_size;
979             search_range--;
980         }
981     }
982
983     if(found_codestream)
984         return 1;
985     return 0;
986 }
987
988 static int decode_frame(AVCodecContext *avctx,
989                         void *data, int *data_size,
990                         AVPacket *avpkt)
991 {
992     J2kDecoderContext *s = avctx->priv_data;
993     AVFrame *picture = data;
994     int tileno, ret;
995
996     s->avctx = avctx;
997     av_log(s->avctx, AV_LOG_DEBUG, "start\n");
998
999     // init
1000     s->buf = s->buf_start = avpkt->data;
1001     s->buf_end = s->buf_start + avpkt->size;
1002     s->curtileno = -1;
1003
1004     ff_j2k_init_tier1_luts();
1005
1006     if (s->buf_end - s->buf < 2)
1007         return AVERROR(EINVAL);
1008
1009     // check if the image is in jp2 format
1010     if((AV_RB32(s->buf) == 12) && (AV_RB32(s->buf + 4) == JP2_SIG_TYPE) &&
1011        (AV_RB32(s->buf + 8) == JP2_SIG_VALUE)) {
1012         if(!jp2_find_codestream(s)) {
1013             av_log(avctx, AV_LOG_ERROR, "couldn't find jpeg2k codestream atom\n");
1014             return -1;
1015         }
1016     }
1017
1018     if (bytestream_get_be16(&s->buf) != J2K_SOC){
1019         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1020         return -1;
1021     }
1022     if (ret = decode_codestream(s))
1023         return ret;
1024
1025     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1026         if (ret = decode_tile(s, s->tile + tileno))
1027             return ret;
1028
1029     cleanup(s);
1030     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1031
1032     *data_size = sizeof(AVPicture);
1033     *picture = s->picture;
1034
1035     return s->buf - s->buf_start;
1036 }
1037
1038 static av_cold int j2kdec_init(AVCodecContext *avctx)
1039 {
1040     J2kDecoderContext *s = avctx->priv_data;
1041
1042     avcodec_get_frame_defaults((AVFrame*)&s->picture);
1043     avctx->coded_frame = (AVFrame*)&s->picture;
1044     return 0;
1045 }
1046
1047 static av_cold int decode_end(AVCodecContext *avctx)
1048 {
1049     J2kDecoderContext *s = avctx->priv_data;
1050
1051     if (s->picture.data[0])
1052         avctx->release_buffer(avctx, &s->picture);
1053
1054     return 0;
1055 }
1056
1057 AVCodec ff_jpeg2000_decoder = {
1058     "j2k",
1059     AVMEDIA_TYPE_VIDEO,
1060     CODEC_ID_JPEG2000,
1061     sizeof(J2kDecoderContext),
1062     j2kdec_init,
1063     NULL,
1064     decode_end,
1065     decode_frame,
1066     .capabilities = CODEC_CAP_EXPERIMENTAL,
1067     .pix_fmts =
1068         (enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_RGB24, -1}
1069 };