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