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