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