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