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