jpeg2000: Refactor decode_packets
[libav.git] / libavcodec / jpeg2000dec.c
CommitLineData
c81a7063
NB
1/*
2 * JPEG 2000 image decoder
3 * Copyright (c) 2007 Kamil Nowosad
4 * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
5 *
6 * This file is part of Libav.
7 *
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
24 * @file
25 * JPEG 2000 image decoder
26 */
27
cc8163e1
DB
28#include <inttypes.h>
29
fe4d5fe9 30#include "libavutil/attributes.h"
c81a7063
NB
31#include "libavutil/common.h"
32#include "libavutil/opt.h"
33#include "avcodec.h"
34#include "bytestream.h"
35#include "internal.h"
2e2d2466 36#include "thread.h"
c81a7063 37#include "jpeg2000.h"
82f8eb5f 38#include "jpeg2000dsp.h"
c81a7063
NB
39
40#define JP2_SIG_TYPE 0x6A502020
41#define JP2_SIG_VALUE 0x0D0A870A
42#define JP2_CODESTREAM 0x6A703263
43
44#define HAD_COC 0x01
45#define HAD_QCC 0x02
46
47typedef struct Jpeg2000TilePart {
c81a7063 48 uint8_t tile_index; // Tile index who refers the tile-part
aa16bbaf 49 const uint8_t *tp_end;
1a3598aa 50 GetByteContext tpg; // bit stream in tile-part
c81a7063
NB
51} Jpeg2000TilePart;
52
53/* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
54 * one per component, so tile_part elements have a size of 3 */
55typedef struct Jpeg2000Tile {
56 Jpeg2000Component *comp;
57 uint8_t properties[4];
58 Jpeg2000CodingStyle codsty[4];
59 Jpeg2000QuantStyle qntsty[4];
60 Jpeg2000TilePart tile_part[3];
aa16bbaf 61 uint16_t tp_idx; // Tile-part index
c81a7063
NB
62} Jpeg2000Tile;
63
64typedef struct Jpeg2000DecoderContext {
65 AVClass *class;
66 AVCodecContext *avctx;
1a3598aa 67 GetByteContext g;
c81a7063
NB
68
69 int width, height;
70 int image_offset_x, image_offset_y;
71 int tile_offset_x, tile_offset_y;
72 uint8_t cbps[4]; // bits per sample in particular components
73 uint8_t sgnd[4]; // if a component is signed
74 uint8_t properties[4];
75 int cdx[4], cdy[4];
76 int precision;
77 int ncomponents;
78 int tile_width, tile_height;
278a923c 79 unsigned numXtiles, numYtiles;
c81a7063
NB
80 int maxtilelen;
81
82 Jpeg2000CodingStyle codsty[4];
83 Jpeg2000QuantStyle qntsty[4];
84
c81a7063
NB
85 int bit_index;
86
87 int16_t curtileno;
88 Jpeg2000Tile *tile;
82f8eb5f 89 Jpeg2000DSPContext dsp;
c81a7063
NB
90
91 /*options parameters*/
f9581f14 92 int reduction_factor;
c81a7063
NB
93} Jpeg2000DecoderContext;
94
95/* get_bits functions for JPEG2000 packet bitstream
96 * It is a get_bit function with a bit-stuffing routine. If the value of the
97 * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
98 * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
99static int get_bits(Jpeg2000DecoderContext *s, int n)
100{
101 int res = 0;
c81a7063
NB
102 while (--n >= 0) {
103 res <<= 1;
104 if (s->bit_index == 0) {
1a3598aa 105 s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
c81a7063
NB
106 }
107 s->bit_index--;
1a3598aa 108 res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
c81a7063
NB
109 }
110 return res;
111}
112
113static void jpeg2000_flush(Jpeg2000DecoderContext *s)
114{
1a3598aa
MN
115 if (bytestream2_get_byte(&s->g) == 0xff)
116 bytestream2_skip(&s->g, 1);
c81a7063 117 s->bit_index = 8;
c81a7063
NB
118}
119
120/* decode the value stored in node */
121static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
122 int threshold)
123{
124 Jpeg2000TgtNode *stack[30];
125 int sp = -1, curval = 0;
126
09d5929f
MN
127 if (!node)
128 return AVERROR_INVALIDDATA;
129
c81a7063
NB
130 while (node && !node->vis) {
131 stack[++sp] = node;
132 node = node->parent;
133 }
134
135 if (node)
136 curval = node->val;
137 else
138 curval = stack[sp]->val;
139
140 while (curval < threshold && sp >= 0) {
141 if (curval < stack[sp]->val)
142 curval = stack[sp]->val;
143 while (curval < threshold) {
144 int ret;
145 if ((ret = get_bits(s, 1)) > 0) {
146 stack[sp]->vis++;
147 break;
148 } else if (!ret)
149 curval++;
150 else
151 return ret;
152 }
153 stack[sp]->val = curval;
154 sp--;
155 }
156 return curval;
157}
158
159/* marker segments */
160/* get sizes and offsets of image, tiles; number of components */
161static int get_siz(Jpeg2000DecoderContext *s)
162{
163 int i;
278a923c 164 int ncomponents;
c81a7063 165
1a3598aa 166 if (bytestream2_get_bytes_left(&s->g) < 36)
5efadcb8 167 return AVERROR_INVALIDDATA;
c81a7063 168
1a3598aa
MN
169 s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
170 s->width = bytestream2_get_be32u(&s->g); // Width
171 s->height = bytestream2_get_be32u(&s->g); // Height
172 s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
173 s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
174 s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
175 s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
176 s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
177 s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
278a923c
MN
178 ncomponents = bytestream2_get_be16u(&s->g); // CSiz
179
180 if (ncomponents <= 0) {
181 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
182 s->ncomponents);
183 return AVERROR_INVALIDDATA;
184 }
185
cbc808d7 186 if (ncomponents > 4) {
278a923c
MN
187 avpriv_request_sample(s->avctx, "Support for %d components",
188 s->ncomponents);
189 return AVERROR_PATCHWELCOME;
190 }
191
192 s->ncomponents = ncomponents;
193
194 if (s->tile_width <= 0 || s->tile_height <= 0 ||
195 s->tile_width > s->width || s->tile_height > s->height) {
196 av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
197 s->tile_width, s->tile_height);
198 return AVERROR_INVALIDDATA;
199 }
1a3598aa
MN
200
201 if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
5efadcb8 202 return AVERROR_INVALIDDATA;
c81a7063
NB
203
204 for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
1a3598aa 205 uint8_t x = bytestream2_get_byteu(&s->g);
c81a7063
NB
206 s->cbps[i] = (x & 0x7f) + 1;
207 s->precision = FFMAX(s->cbps[i], s->precision);
ac921338 208 s->sgnd[i] = !!(x & 0x80);
1a3598aa
MN
209 s->cdx[i] = bytestream2_get_byteu(&s->g);
210 s->cdy[i] = bytestream2_get_byteu(&s->g);
278a923c
MN
211
212 if (s->cdx[i] != 1 || s->cdy[i] != 1) {
213 avpriv_request_sample(s->avctx,
214 "CDxy values %d %d for component %d",
215 s->cdx[i], s->cdy[i], i);
216 if (!s->cdx[i] || !s->cdy[i])
217 return AVERROR_INVALIDDATA;
218 else
219 return AVERROR_PATCHWELCOME;
220 }
c81a7063
NB
221 }
222
223 s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
224 s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
225
278a923c
MN
226 s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
227 if (!s->tile) {
228 s->numXtiles = s->numYtiles = 0;
c81a7063 229 return AVERROR(ENOMEM);
278a923c 230 }
c81a7063
NB
231
232 for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
233 Jpeg2000Tile *tile = s->tile + i;
234
235 tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
236 if (!tile->comp)
237 return AVERROR(ENOMEM);
238 }
239
240 /* compute image size with reduction factor */
241 s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
242 s->reduction_factor);
243 s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
244 s->reduction_factor);
245
33e665a6
MN
246 switch (s->ncomponents) {
247 case 1:
248 if (s->precision > 8)
249 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
250 else
251 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
c81a7063 252 break;
33e665a6
MN
253 case 3:
254 switch (s->avctx->profile) {
255 case FF_PROFILE_JPEG2000_DCINEMA_2K:
256 case FF_PROFILE_JPEG2000_DCINEMA_4K:
257 /* XYZ color-space for digital cinema profiles */
258 s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;
c81a7063 259 break;
33e665a6 260 default:
c81a7063
NB
261 if (s->precision > 8)
262 s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
263 else
264 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
265 break;
c81a7063
NB
266 }
267 break;
33e665a6
MN
268 case 4:
269 s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
270 break;
271 default:
272 /* pixel format can not be identified */
273 s->avctx->pix_fmt = AV_PIX_FMT_NONE;
274 break;
c81a7063
NB
275 }
276 return 0;
277}
278
279/* get common part for COD and COC segments */
280static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
281{
282 uint8_t byte;
283
1a3598aa
MN
284 if (bytestream2_get_bytes_left(&s->g) < 5)
285 return AVERROR_INVALIDDATA;
286
5650e331
LB
287 /* nreslevels = number of resolution levels
288 = number of decomposition level +1 */
1a3598aa 289 c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
5650e331
LB
290
291 if (c->nreslevels > JPEG2000_MAX_RESLEVELS)
292 return AVERROR_INVALIDDATA;
c81a7063
NB
293
294 /* compute number of resolution levels to decode */
295 if (c->nreslevels < s->reduction_factor)
296 c->nreslevels2decode = 1;
297 else
298 c->nreslevels2decode = c->nreslevels - s->reduction_factor;
299
1a3598aa
MN
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
c81a7063 302
fbcc03db
MN
303 if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
304 c->log2_cblk_width + c->log2_cblk_height > 12) {
305 av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
306 return AVERROR_INVALIDDATA;
307 }
308
1a3598aa 309 c->cblk_style = bytestream2_get_byteu(&s->g);
c81a7063 310 if (c->cblk_style != 0) { // cblk style
5efadcb8
LB
311 avpriv_request_sample(s->avctx, "Support for extra cblk styles");
312 return AVERROR_PATCHWELCOME;
c81a7063 313 }
1a3598aa 314 c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
c81a7063 315 /* set integer 9/7 DWT in case of BITEXACT flag */
7c6eb0a1 316 if ((s->avctx->flags & AV_CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
c81a7063
NB
317 c->transform = FF_DWT97_INT;
318
319 if (c->csty & JPEG2000_CSTY_PREC) {
320 int i;
321 for (i = 0; i < c->nreslevels; i++) {
1a3598aa 322 byte = bytestream2_get_byte(&s->g);
c81a7063
NB
323 c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
324 c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
325 }
86a2602e
MN
326 } else {
327 memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
328 memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
c81a7063
NB
329 }
330 return 0;
331}
332
333/* get coding parameters for a particular tile or whole image*/
334static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
335 uint8_t *properties)
336{
337 Jpeg2000CodingStyle tmp;
ef35d6db 338 int compno, ret;
c81a7063 339
1a3598aa 340 if (bytestream2_get_bytes_left(&s->g) < 5)
5efadcb8 341 return AVERROR_INVALIDDATA;
c81a7063 342
1a3598aa 343 tmp.csty = bytestream2_get_byteu(&s->g);
c81a7063
NB
344
345 // get progression order
1a3598aa 346 tmp.prog_order = bytestream2_get_byteu(&s->g);
c81a7063 347
1a3598aa
MN
348 tmp.nlayers = bytestream2_get_be16u(&s->g);
349 tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
c81a7063 350
cf04af20
MN
351 if (tmp.mct && s->ncomponents < 3) {
352 av_log(s->avctx, AV_LOG_ERROR,
cc8163e1 353 "MCT %"PRIu8" with too few components (%d)\n",
cf04af20
MN
354 tmp.mct, s->ncomponents);
355 return AVERROR_INVALIDDATA;
356 }
357
ef35d6db
MN
358 if ((ret = get_cox(s, &tmp)) < 0)
359 return ret;
360
c81a7063
NB
361 for (compno = 0; compno < s->ncomponents; compno++)
362 if (!(properties[compno] & HAD_COC))
363 memcpy(c + compno, &tmp, sizeof(tmp));
364 return 0;
365}
366
367/* Get coding parameters for a component in the whole image or a
368 * particular tile. */
369static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
370 uint8_t *properties)
371{
ef35d6db 372 int compno, ret;
c81a7063 373
1a3598aa 374 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 375 return AVERROR_INVALIDDATA;
c81a7063 376
1a3598aa 377 compno = bytestream2_get_byteu(&s->g);
c81a7063 378
eae63e3c
MN
379 if (compno >= s->ncomponents) {
380 av_log(s->avctx, AV_LOG_ERROR,
381 "Invalid compno %d. There are %d components in the image.\n",
382 compno, s->ncomponents);
383 return AVERROR_INVALIDDATA;
384 }
385
c81a7063 386 c += compno;
1a3598aa 387 c->csty = bytestream2_get_byteu(&s->g);
ef35d6db
MN
388
389 if ((ret = get_cox(s, c)) < 0)
390 return ret;
c81a7063
NB
391
392 properties[compno] |= HAD_COC;
393 return 0;
394}
395
396/* Get common part for QCD and QCC segments. */
397static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
398{
399 int i, x;
400
1a3598aa 401 if (bytestream2_get_bytes_left(&s->g) < 1)
5efadcb8 402 return AVERROR_INVALIDDATA;
c81a7063 403
1a3598aa 404 x = bytestream2_get_byteu(&s->g); // Sqcd
c81a7063
NB
405
406 q->nguardbits = x >> 5;
407 q->quantsty = x & 0x1f;
408
409 if (q->quantsty == JPEG2000_QSTY_NONE) {
410 n -= 3;
1a3598aa
MN
411 if (bytestream2_get_bytes_left(&s->g) < n ||
412 n > JPEG2000_MAX_DECLEVELS)
5efadcb8 413 return AVERROR_INVALIDDATA;
c81a7063 414 for (i = 0; i < n; i++)
1a3598aa 415 q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
c81a7063 416 } else if (q->quantsty == JPEG2000_QSTY_SI) {
1a3598aa 417 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 418 return AVERROR_INVALIDDATA;
1a3598aa 419 x = bytestream2_get_be16u(&s->g);
c81a7063
NB
420 q->expn[0] = x >> 11;
421 q->mant[0] = x & 0x7ff;
be327100 422 for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
c81a7063
NB
423 int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
424 q->expn[i] = curexpn;
425 q->mant[i] = q->mant[0];
426 }
427 } else {
428 n = (n - 3) >> 1;
1a3598aa
MN
429 if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
430 n > JPEG2000_MAX_DECLEVELS)
5efadcb8 431 return AVERROR_INVALIDDATA;
c81a7063 432 for (i = 0; i < n; i++) {
1a3598aa 433 x = bytestream2_get_be16u(&s->g);
c81a7063
NB
434 q->expn[i] = x >> 11;
435 q->mant[i] = x & 0x7ff;
436 }
437 }
438 return 0;
439}
440
441/* Get quantization parameters for a particular tile or a whole image. */
442static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
443 uint8_t *properties)
444{
445 Jpeg2000QuantStyle tmp;
5efadcb8 446 int compno, ret;
c81a7063 447
5efadcb8
LB
448 if ((ret = get_qcx(s, n, &tmp)) < 0)
449 return ret;
c81a7063
NB
450 for (compno = 0; compno < s->ncomponents; compno++)
451 if (!(properties[compno] & HAD_QCC))
452 memcpy(q + compno, &tmp, sizeof(tmp));
453 return 0;
454}
455
456/* Get quantization parameters for a component in the whole image
457 * on in a particular tile. */
458static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
459 uint8_t *properties)
460{
461 int compno;
462
1a3598aa 463 if (bytestream2_get_bytes_left(&s->g) < 1)
5efadcb8 464 return AVERROR_INVALIDDATA;
c81a7063 465
eae63e3c
MN
466 compno = bytestream2_get_byteu(&s->g);
467
468 if (compno >= s->ncomponents) {
469 av_log(s->avctx, AV_LOG_ERROR,
470 "Invalid compno %d. There are %d components in the image.\n",
471 compno, s->ncomponents);
472 return AVERROR_INVALIDDATA;
473 }
474
c81a7063
NB
475 properties[compno] |= HAD_QCC;
476 return get_qcx(s, n - 1, q + compno);
477}
478
479/* Get start of tile segment. */
5efadcb8 480static int get_sot(Jpeg2000DecoderContext *s, int n)
c81a7063
NB
481{
482 Jpeg2000TilePart *tp;
483 uint16_t Isot;
484 uint32_t Psot;
485 uint8_t TPsot;
486
1a3598aa 487 if (bytestream2_get_bytes_left(&s->g) < 8)
5efadcb8 488 return AVERROR_INVALIDDATA;
c81a7063 489
1a3598aa 490 Isot = bytestream2_get_be16u(&s->g); // Isot
d3cb302b
MN
491 if (Isot >= s->numXtiles * s->numYtiles)
492 return AVERROR_INVALIDDATA;
493
c81a7063 494 if (Isot) {
5efadcb8
LB
495 avpriv_request_sample(s->avctx, "Support for more than one tile");
496 return AVERROR_PATCHWELCOME;
c81a7063 497 }
1a3598aa
MN
498 Psot = bytestream2_get_be32u(&s->g); // Psot
499 TPsot = bytestream2_get_byteu(&s->g); // TPsot
c81a7063
NB
500
501 /* Read TNSot but not used */
1a3598aa 502 bytestream2_get_byteu(&s->g); // TNsot
c81a7063 503
d3cb302b 504 if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
cc8163e1 505 av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);
d3cb302b
MN
506 return AVERROR_INVALIDDATA;
507 }
508
509 if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
cc8163e1 510 avpriv_request_sample(s->avctx, "Support for %"PRIu8" components", TPsot);
d3cb302b
MN
511 return AVERROR_PATCHWELCOME;
512 }
513
aa16bbaf
MN
514 s->tile[Isot].tp_idx = TPsot;
515 tp = s->tile[Isot].tile_part + TPsot;
c81a7063 516 tp->tile_index = Isot;
aa16bbaf 517 tp->tp_end = s->g.buffer + Psot - n - 2;
c81a7063 518
aa16bbaf
MN
519 if (!TPsot) {
520 Jpeg2000Tile *tile = s->tile + s->curtileno;
521
522 /* copy defaults */
523 memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
524 memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
525 }
c81a7063
NB
526
527 return 0;
528}
529
530/* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
531 * Used to know the number of tile parts and lengths.
532 * There may be multiple TLMs in the header.
533 * TODO: The function is not used for tile-parts management, nor anywhere else.
534 * It can be useful to allocate memory for tile parts, before managing the SOT
535 * markers. Parsing the TLM header is needed to increment the input header
536 * buffer.
537 * This marker is mandatory for DCI. */
538static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
539{
540 uint8_t Stlm, ST, SP, tile_tlm, i;
1a3598aa
MN
541 bytestream2_get_byte(&s->g); /* Ztlm: skipped */
542 Stlm = bytestream2_get_byte(&s->g);
c81a7063
NB
543
544 // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
545 ST = (Stlm >> 4) & 0x03;
546 // TODO: Manage case of ST = 0b11 --> raise error
547 SP = (Stlm >> 6) & 0x01;
548 tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
549 for (i = 0; i < tile_tlm; i++) {
550 switch (ST) {
551 case 0:
552 break;
553 case 1:
1a3598aa 554 bytestream2_get_byte(&s->g);
c81a7063
NB
555 break;
556 case 2:
1a3598aa 557 bytestream2_get_be16(&s->g);
c81a7063
NB
558 break;
559 case 3:
1a3598aa 560 bytestream2_get_be32(&s->g);
c81a7063
NB
561 break;
562 }
563 if (SP == 0) {
1a3598aa 564 bytestream2_get_be16(&s->g);
c81a7063 565 } else {
1a3598aa 566 bytestream2_get_be32(&s->g);
c81a7063
NB
567 }
568 }
569 return 0;
570}
571
572static int init_tile(Jpeg2000DecoderContext *s, int tileno)
573{
574 int compno;
575 int tilex = tileno % s->numXtiles;
576 int tiley = tileno / s->numXtiles;
577 Jpeg2000Tile *tile = s->tile + tileno;
c81a7063
NB
578
579 if (!tile->comp)
580 return AVERROR(ENOMEM);
581
c81a7063
NB
582 for (compno = 0; compno < s->ncomponents; compno++) {
583 Jpeg2000Component *comp = tile->comp + compno;
5b73916d
MN
584 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
585 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
c81a7063 586 int ret; // global bandno
c81a7063
NB
587
588 comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
589 comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
590 comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
591 comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
592
f9581f14
MN
593 comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
594 comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
595 comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
596 comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
c81a7063
NB
597
598 if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
599 s->cbps[compno], s->cdx[compno],
600 s->cdy[compno], s->avctx))
601 return ret;
602 }
603 return 0;
604}
605
606/* Read the number of coding passes. */
607static int getnpasses(Jpeg2000DecoderContext *s)
608{
609 int num;
610 if (!get_bits(s, 1))
611 return 1;
612 if (!get_bits(s, 1))
613 return 2;
614 if ((num = get_bits(s, 2)) != 3)
615 return num < 0 ? num : 3 + num;
616 if ((num = get_bits(s, 5)) != 31)
617 return num < 0 ? num : 6 + num;
618 num = get_bits(s, 7);
619 return num < 0 ? num : 37 + num;
620}
621
622static int getlblockinc(Jpeg2000DecoderContext *s)
623{
624 int res = 0, ret;
625 while (ret = get_bits(s, 1)) {
626 if (ret < 0)
627 return ret;
628 res++;
629 }
630 return res;
631}
632
633static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
634 Jpeg2000CodingStyle *codsty,
635 Jpeg2000ResLevel *rlevel, int precno,
636 int layno, uint8_t *expn, int numgbits)
637{
638 int bandno, cblkno, ret, nb_code_blocks;
639
640 if (!(ret = get_bits(s, 1))) {
641 jpeg2000_flush(s);
642 return 0;
643 } else if (ret < 0)
644 return ret;
645
646 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
647 Jpeg2000Band *band = rlevel->band + bandno;
648 Jpeg2000Prec *prec = band->prec + precno;
649
650 if (band->coord[0][0] == band->coord[0][1] ||
651 band->coord[1][0] == band->coord[1][1])
652 continue;
c81a7063
NB
653 nb_code_blocks = prec->nb_codeblocks_height *
654 prec->nb_codeblocks_width;
655 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
656 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
657 int incl, newpasses, llen;
658
659 if (cblk->npasses)
660 incl = get_bits(s, 1);
661 else
662 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
663 if (!incl)
664 continue;
665 else if (incl < 0)
666 return incl;
667
17e5d614
MN
668 if (!cblk->npasses) {
669 int v = expn[bandno] + numgbits - 1 -
670 tag_tree_decode(s, prec->zerobits + cblkno, 100);
671 if (v < 0) {
672 av_log(s->avctx, AV_LOG_ERROR,
673 "nonzerobits %d invalid\n", v);
674 return AVERROR_INVALIDDATA;
675 }
676 cblk->nonzerobits = v;
677 }
c81a7063
NB
678 if ((newpasses = getnpasses(s)) < 0)
679 return newpasses;
680 if ((llen = getlblockinc(s)) < 0)
681 return llen;
682 cblk->lblock += llen;
683 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
684 return ret;
7e201d57
LB
685 if (ret > sizeof(cblk->data)) {
686 avpriv_request_sample(s->avctx,
687 "Block with lengthinc greater than %zu",
688 sizeof(cblk->data));
689 return AVERROR_PATCHWELCOME;
690 }
c81a7063
NB
691 cblk->lengthinc = ret;
692 cblk->npasses += newpasses;
693 }
694 }
695 jpeg2000_flush(s);
696
697 if (codsty->csty & JPEG2000_CSTY_EPH) {
1a3598aa
MN
698 if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
699 bytestream2_skip(&s->g, 2);
c81a7063
NB
700 else
701 av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
702 }
703
704 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
705 Jpeg2000Band *band = rlevel->band + bandno;
706 Jpeg2000Prec *prec = band->prec + precno;
707
708 nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
709 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
710 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1a3598aa 711 if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)
5efadcb8 712 return AVERROR_INVALIDDATA;
28816f9d
NB
713 /* Code-block data can be empty. In that case initialize data
714 * with 0xFFFF. */
715 if (cblk->lengthinc > 0) {
1a3598aa 716 bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
28816f9d
NB
717 } else {
718 cblk->data[0] = 0xFF;
719 cblk->data[1] = 0xFF;
720 }
c81a7063
NB
721 cblk->length += cblk->lengthinc;
722 cblk->lengthinc = 0;
1018a922
LB
723
724 if (cblk->length > sizeof(cblk->data)) {
725 av_log(s->avctx, AV_LOG_ERROR,
cc8163e1 726 "Block length %"PRIu16" > data size %zd\n",
1018a922
LB
727 cblk->length, sizeof(cblk->data));
728 return AVERROR_INVALIDDATA;
729 }
c81a7063
NB
730 }
731 }
732 return 0;
733}
734
1b709f23 735static int decode_pgod_lrcp(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
c81a7063 736{
d57c737a 737 int layno, reslevelno, compno, precno, ok_reslevel;
1b709f23
LB
738 int ret;
739
740 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
741 ok_reslevel = 1;
742 for (reslevelno = 0; ok_reslevel; reslevelno++) {
743 ok_reslevel = 0;
744 for (compno = 0; compno < s->ncomponents; compno++) {
745 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
746 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
747 if (reslevelno < codsty->nreslevels) {
748 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
749 reslevelno;
750 ok_reslevel = 1;
751 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
752 if ((ret = jpeg2000_decode_packet(s,
753 codsty, rlevel,
754 precno, layno,
755 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
756 qntsty->nguardbits)) < 0)
757 return ret;
c81a7063
NB
758 }
759 }
760 }
1b709f23 761 }
c81a7063 762
1b709f23
LB
763 return 0;
764}
765
766static int decode_pgod_cprl(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
767{
768 int layno, reslevelno, compno, precno;
769 int ret, x, y;
770
771 for (compno = 0; compno < s->ncomponents; compno++) {
772 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
773 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
c81a7063 774
1b709f23
LB
775 /* Set bit stream buffer address according to tile-part.
776 * For DCinema one tile-part per component, so can be
777 * indexed by component. */
778 s->g = tile->tile_part[compno].tpg;
c81a7063 779
1b709f23
LB
780 /* Position loop (y axis)
781 * TODO: Automate computing of step 256.
782 * Fixed here, but to be computed before entering here. */
783 for (y = 0; y < s->height; y += 256) {
c81a7063 784 /* Position loop (y axis)
1b709f23 785 * TODO: automate computing of step 256.
c81a7063 786 * Fixed here, but to be computed before entering here. */
1b709f23
LB
787 for (x = 0; x < s->width; x += 256) {
788 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
789 uint16_t prcx, prcy;
790 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
791 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
792
793 if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
794 (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
795 continue;
796
797 if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
798 (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
799 continue;
800
801 // check if a precinct exists
802 prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
803 prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
804 precno = prcx + rlevel->num_precincts_x * prcy;
805 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
806 if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
807 precno, layno,
808 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
809 qntsty->nguardbits)) < 0)
810 return ret;
c81a7063
NB
811 }
812 }
813 }
814 }
1b709f23
LB
815 }
816
817 return 0;
818}
819
820static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
821{
822 int ret = 0;
823
824 s->bit_index = 8;
825 switch (tile->codsty[0].prog_order) {
826 case JPEG2000_PGOD_LRCP:
827 ret = decode_pgod_lrcp(s, tile);
828 break;
829
830 case JPEG2000_PGOD_CPRL:
831 ret = decode_pgod_cprl(s, tile);
c81a7063
NB
832 break;
833
d57c737a
MN
834 case JPEG2000_PGOD_RLCP:
835 avpriv_request_sample(s->avctx, "Progression order RLCP");
836 ret = AVERROR_PATCHWELCOME;
837 break;
838
839 case JPEG2000_PGOD_RPCL:
840 avpriv_request_sample(s->avctx, "Progression order RPCL");
841 ret = AVERROR_PATCHWELCOME;
842 break;
843
844 case JPEG2000_PGOD_PCRL:
845 avpriv_request_sample(s->avctx, "Progression order PCRL");
846 ret = AVERROR_PATCHWELCOME;
847 break;
848
c81a7063
NB
849 default:
850 break;
851 }
852
853 /* EOC marker reached */
1a3598aa 854 bytestream2_skip(&s->g, 2);
c81a7063 855
d57c737a 856 return ret;
c81a7063
NB
857}
858
859/* TIER-1 routines */
860static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
64f6570c
MN
861 int bpno, int bandno, int bpass_csty_symbol,
862 int vert_causal_ctx_csty_symbol)
c81a7063
NB
863{
864 int mask = 3 << (bpno - 1), y0, x, y;
865
866 for (y0 = 0; y0 < height; y0 += 4)
867 for (x = 0; x < width; x++)
64f6570c
MN
868 for (y = y0; y < height && y < y0 + 4; y++) {
869 if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
870 && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
871 int flags_mask = -1;
872 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
873 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
874 if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
875 int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
876 if (bpass_csty_symbol)
877 t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
878 else
879 t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
880 -mask : mask;
c81a7063
NB
881
882 ff_jpeg2000_set_significance(t1, x, y,
883 t1->data[y][x] < 0);
884 }
885 t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
886 }
64f6570c 887 }
c81a7063
NB
888}
889
890static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
891 int bpno)
892{
893 int phalf, nhalf;
894 int y0, x, y;
895
896 phalf = 1 << (bpno - 1);
897 nhalf = -phalf;
898
899 for (y0 = 0; y0 < height; y0 += 4)
900 for (x = 0; x < width; x++)
901 for (y = y0; y < height && y < y0 + 4; y++)
902 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
903 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
904 int r = ff_mqc_decode(&t1->mqc,
905 t1->mqc.cx_states + ctxno)
906 ? phalf : nhalf;
907 t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
908 t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
909 }
910}
911
912static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
913 int width, int height, int bpno, int bandno,
64f6570c 914 int seg_symbols, int vert_causal_ctx_csty_symbol)
c81a7063
NB
915{
916 int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
917
64f6570c 918 for (y0 = 0; y0 < height; y0 += 4) {
c81a7063
NB
919 for (x = 0; x < width; x++) {
920 if (y0 + 3 < height &&
921 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
922 (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
923 (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
924 (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
925 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
926 continue;
927 runlen = ff_mqc_decode(&t1->mqc,
928 t1->mqc.cx_states + MQC_CX_UNI);
929 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
930 t1->mqc.cx_states +
931 MQC_CX_UNI);
932 dec = 1;
933 } else {
934 runlen = 0;
935 dec = 0;
936 }
937
938 for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
939 if (!dec) {
64f6570c
MN
940 if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
941 int flags_mask = -1;
942 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
943 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
944 dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
945 bandno));
946 }
c81a7063
NB
947 }
948 if (dec) {
949 int xorbit;
950 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
951 &xorbit);
952 t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
953 t1->mqc.cx_states + ctxno) ^
954 xorbit)
955 ? -mask : mask;
956 ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
957 }
958 dec = 0;
959 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
960 }
961 }
64f6570c 962 }
c81a7063
NB
963 if (seg_symbols) {
964 int val;
965 val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
966 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
967 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
968 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
969 if (val != 0xa)
970 av_log(s->avctx, AV_LOG_ERROR,
971 "Segmentation symbol value incorrect\n");
972 }
973}
974
975static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
976 Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
977 int width, int height, int bandpos)
978{
979 int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
64f6570c
MN
980 int clnpass_cnt = 0;
981 int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
982 int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
c81a7063 983
c81a7063 984 for (y = 0; y < height; y++)
589e5b52
MN
985 memset(t1->data[y], 0, width * sizeof(**t1->data));
986
28816f9d
NB
987 /* If code-block contains no compressed data: nothing to do. */
988 if (!cblk->length)
989 return 0;
990 for (y = 0; y < height + 2; y++)
589e5b52 991 memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
c81a7063
NB
992
993 ff_mqc_initdec(&t1->mqc, cblk->data);
994 cblk->data[cblk->length] = 0xff;
995 cblk->data[cblk->length + 1] = 0xff;
996
997 while (passno--) {
998 switch (pass_t) {
999 case 0:
64f6570c
MN
1000 decode_sigpass(t1, width, height, bpno + 1, bandpos,
1001 bpass_csty_symbol && (clnpass_cnt >= 4),
1002 vert_causal_ctx_csty_symbol);
c81a7063
NB
1003 break;
1004 case 1:
1005 decode_refpass(t1, width, height, bpno + 1);
64f6570c
MN
1006 if (bpass_csty_symbol && clnpass_cnt >= 4)
1007 ff_mqc_initdec(&t1->mqc, cblk->data);
c81a7063
NB
1008 break;
1009 case 2:
1010 decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
64f6570c
MN
1011 codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1012 vert_causal_ctx_csty_symbol);
1013 clnpass_cnt = clnpass_cnt + 1;
1014 if (bpass_csty_symbol && clnpass_cnt >= 4)
1015 ff_mqc_initdec(&t1->mqc, cblk->data);
c81a7063
NB
1016 break;
1017 }
1018
1019 pass_t++;
1020 if (pass_t == 3) {
1021 bpno--;
1022 pass_t = 0;
1023 }
1024 }
1025 return 0;
1026}
1027
1028/* TODO: Verify dequantization for lossless case
1029 * comp->data can be float or int
1030 * band->stepsize can be float or int
1031 * depending on the type of DWT transformation.
1032 * see ISO/IEC 15444-1:2002 A.6.1 */
1033
1034/* Float dequantization of a codeblock.*/
1035static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1036 Jpeg2000Component *comp,
1037 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1038{
e11099db
MN
1039 int i, j;
1040 int w = cblk->coord[0][1] - cblk->coord[0][0];
1041 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1042 float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1043 int *src = t1->data[j];
1044 for (i = 0; i < w; ++i)
1045 datap[i] = src[i] * band->f_stepsize;
1046 }
c81a7063
NB
1047}
1048
1049/* Integer dequantization of a codeblock.*/
1050static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1051 Jpeg2000Component *comp,
1052 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1053{
e11099db
MN
1054 int i, j;
1055 int w = cblk->coord[0][1] - cblk->coord[0][0];
1056 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1057 int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1058 int *src = t1->data[j];
1059 for (i = 0; i < w; ++i)
1060 datap[i] = (src[i] * band->i_stepsize + (1 << 15)) >> 16;
1061 }
c81a7063
NB
1062}
1063
82f8eb5f 1064static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
c81a7063
NB
1065{
1066 int i, csize = 1;
82f8eb5f 1067 void *src[3];
c81a7063
NB
1068
1069 for (i = 0; i < 3; i++)
1070 if (tile->codsty[0].transform == FF_DWT97)
82f8eb5f 1071 src[i] = tile->comp[i].f_data;
c81a7063 1072 else
82f8eb5f 1073 src[i] = tile->comp[i].i_data;
c81a7063
NB
1074
1075 for (i = 0; i < 2; i++)
1076 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
82f8eb5f
JA
1077
1078 s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
c81a7063
NB
1079}
1080
29b00f88 1081static inline void tile_codeblocks(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
c81a7063 1082{
5788623d
LB
1083 Jpeg2000T1Context t1;
1084
c81a7063 1085 int compno, reslevelno, bandno;
c81a7063 1086
c81a7063
NB
1087 /* Loop on tile components */
1088
1089 for (compno = 0; compno < s->ncomponents; compno++) {
1090 Jpeg2000Component *comp = tile->comp + compno;
1091 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1092 /* Loop on resolution levels */
1093 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1094 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1095 /* Loop on bands */
1096 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1097 uint16_t nb_precincts, precno;
1098 Jpeg2000Band *band = rlevel->band + bandno;
1099 int cblkno = 0, bandpos;
1100 bandpos = bandno + (reslevelno > 0);
1101
53d5d89c
MN
1102 if (band->coord[0][0] == band->coord[0][1] ||
1103 band->coord[1][0] == band->coord[1][1])
1104 continue;
1105
c81a7063
NB
1106 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1107 /* Loop on precincts */
1108 for (precno = 0; precno < nb_precincts; precno++) {
1109 Jpeg2000Prec *prec = band->prec + precno;
1110
1111 /* Loop on codeblocks */
41bcc3d1
LB
1112 for (cblkno = 0;
1113 cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height;
1114 cblkno++) {
c81a7063
NB
1115 int x, y;
1116 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1117 decode_cblk(s, codsty, &t1, cblk,
1118 cblk->coord[0][1] - cblk->coord[0][0],
1119 cblk->coord[1][1] - cblk->coord[1][0],
1120 bandpos);
1121
c81a7063
NB
1122 x = cblk->coord[0][0];
1123 y = cblk->coord[1][0];
c81a7063 1124
a458b91c 1125 if (codsty->transform == FF_DWT97)
c81a7063 1126 dequantization_float(x, y, cblk, comp, &t1, band);
a458b91c
MN
1127 else
1128 dequantization_int(x, y, cblk, comp, &t1, band);
c81a7063
NB
1129 } /* end cblk */
1130 } /*end prec */
1131 } /* end band */
1132 } /* end reslevel */
1133
1134 /* inverse DWT */
5bf208f6 1135 ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
c81a7063 1136 } /*end comp */
5788623d
LB
1137}
1138
29b00f88
LB
1139#define WRITE_FRAME(D, PIXEL) \
1140 static inline void write_frame_ ## D(Jpeg2000DecoderContext * s, Jpeg2000Tile * tile, \
1141 AVFrame * picture) \
1142 { \
1143 int linesize = picture->linesize[0] / sizeof(PIXEL); \
1144 int compno; \
1145 int x, y; \
1146 \
1147 for (compno = 0; compno < s->ncomponents; compno++) { \
1148 Jpeg2000Component *comp = tile->comp + compno; \
1149 Jpeg2000CodingStyle *codsty = tile->codsty + compno; \
1150 PIXEL *line; \
1151 float *datap = comp->f_data; \
1152 int32_t *i_datap = comp->i_data; \
1153 int cbps = s->cbps[compno]; \
1154 int w = tile->comp[compno].coord[0][1] - s->image_offset_x; \
1155 \
1156 y = tile->comp[compno].coord[1][0] - s->image_offset_y; \
1157 line = (PIXEL *)picture->data[0] + y * linesize; \
1158 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { \
1159 PIXEL *dst; \
1160 \
1161 x = tile->comp[compno].coord[0][0] - s->image_offset_x; \
1162 dst = line + x * s->ncomponents + compno; \
1163 \
1164 if (codsty->transform == FF_DWT97) { \
1165 for (; x < w; x += s->cdx[compno]) { \
1166 int val = lrintf(*datap) + (1 << (cbps - 1)); \
1167 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ \
1168 val = av_clip(val, 0, (1 << cbps) - 1); \
1169 *dst = val << (8 * sizeof(PIXEL) - cbps); \
1170 datap++; \
1171 dst += s->ncomponents; \
1172 } \
1173 } else { \
1174 for (; x < w; x += s->cdx[compno]) { \
1175 int val = *i_datap + (1 << (cbps - 1)); \
1176 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ \
1177 val = av_clip(val, 0, (1 << cbps) - 1); \
1178 *dst = val << (8 * sizeof(PIXEL) - cbps); \
1179 i_datap++; \
1180 dst += s->ncomponents; \
1181 } \
1182 } \
1183 line += linesize; \
1184 } \
1185 } \
1186 \
1187 }
1188
1189WRITE_FRAME(8, uint8_t)
1190WRITE_FRAME(16, uint16_t)
1191
1192#undef WRITE_FRAME
1193
5788623d
LB
1194static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1195 AVFrame *picture)
1196{
5788623d 1197 tile_codeblocks(s, tile);
c81a7063
NB
1198
1199 /* inverse MCT transformation */
1200 if (tile->codsty[0].mct)
1201 mct_decode(s, tile);
1202
c81a7063 1203 if (s->precision <= 8) {
29b00f88 1204 write_frame_8(s, tile, picture);
c81a7063 1205 } else {
29b00f88 1206 write_frame_16(s, tile, picture);
c81a7063 1207 }
22e18ea3 1208
c81a7063
NB
1209 return 0;
1210}
1211
1212static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1213{
1214 int tileno, compno;
1215 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1216 for (compno = 0; compno < s->ncomponents; compno++) {
1217 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1218 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1219
1220 ff_jpeg2000_cleanup(comp, codsty);
1221 }
1222 av_freep(&s->tile[tileno].comp);
1223 }
1224 av_freep(&s->tile);
f0552e63 1225 s->numXtiles = s->numYtiles = 0;
c81a7063
NB
1226}
1227
1228static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1229{
1230 Jpeg2000CodingStyle *codsty = s->codsty;
1231 Jpeg2000QuantStyle *qntsty = s->qntsty;
1232 uint8_t *properties = s->properties;
1233
1234 for (;;) {
1235 int len, ret = 0;
1236 uint16_t marker;
1a3598aa 1237 int oldpos;
c81a7063 1238
1a3598aa 1239 if (bytestream2_get_bytes_left(&s->g) < 2) {
c81a7063
NB
1240 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1241 break;
1242 }
1243
1a3598aa
MN
1244 marker = bytestream2_get_be16u(&s->g);
1245 oldpos = bytestream2_tell(&s->g);
c81a7063 1246
b564784a
MN
1247 if (marker == JPEG2000_SOD) {
1248 Jpeg2000Tile *tile;
1249 Jpeg2000TilePart *tp;
1250
1251 if (s->curtileno < 0) {
1252 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
1253 return AVERROR_INVALIDDATA;
1254 }
18a245a2
MS
1255 if (!s->tile) {
1256 av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
1257 return AVERROR_INVALIDDATA;
1258 }
b564784a
MN
1259
1260 tile = s->tile + s->curtileno;
1261 tp = tile->tile_part + tile->tp_idx;
1262 bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
1263 bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
1264
1265 continue;
1266 }
c81a7063
NB
1267 if (marker == JPEG2000_EOC)
1268 break;
1269
1a3598aa 1270 len = bytestream2_get_be16u(&s->g);
fd54dd02
MN
1271 if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
1272 return AVERROR_INVALIDDATA;
1273
c81a7063
NB
1274 switch (marker) {
1275 case JPEG2000_SIZ:
1276 ret = get_siz(s);
1277 break;
1278 case JPEG2000_COC:
1279 ret = get_coc(s, codsty, properties);
1280 break;
1281 case JPEG2000_COD:
1282 ret = get_cod(s, codsty, properties);
1283 break;
1284 case JPEG2000_QCC:
1285 ret = get_qcc(s, len, qntsty, properties);
1286 break;
1287 case JPEG2000_QCD:
1288 ret = get_qcd(s, len, qntsty, properties);
1289 break;
1290 case JPEG2000_SOT:
aa16bbaf
MN
1291 if (!(ret = get_sot(s, len))) {
1292 codsty = s->tile[s->curtileno].codsty;
1293 qntsty = s->tile[s->curtileno].qntsty;
1294 properties = s->tile[s->curtileno].properties;
1295 }
c81a7063 1296 break;
db53a230
LB
1297 case JPEG2000_PLT:
1298 // the PLT marker is ignored
1299 case JPEG2000_PLM:
1300 // the PLM marker is ignored
c81a7063
NB
1301 case JPEG2000_COM:
1302 // the comment is ignored
1a3598aa 1303 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1304 break;
1305 case JPEG2000_TLM:
1306 // Tile-part lengths
1307 ret = get_tlm(s, len);
1308 break;
1309 default:
1310 av_log(s->avctx, AV_LOG_ERROR,
cc8163e1 1311 "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
1a3598aa
MN
1312 marker, bytestream2_tell(&s->g) - 4);
1313 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1314 break;
1315 }
aa16bbaf 1316 if (bytestream2_tell(&s->g) - oldpos != len || ret) {
c81a7063 1317 av_log(s->avctx, AV_LOG_ERROR,
cc8163e1
DB
1318 "error during processing marker segment %.4"PRIx16"\n",
1319 marker);
c81a7063
NB
1320 return ret ? ret : -1;
1321 }
1322 }
1323 return 0;
1324}
1325
1326/* Read bit stream packets --> T2 operation. */
1327static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1328{
1329 int ret = 0;
c1dcbc59 1330 int tileno;
c81a7063 1331
c1dcbc59
MN
1332 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1333 Jpeg2000Tile *tile = s->tile + tileno;
1334
1335 if (ret = init_tile(s, tileno))
1336 return ret;
1337
1338 s->g = tile->tile_part[0].tpg;
1339 if (ret = jpeg2000_decode_packets(s, tile))
1340 return ret;
1341 }
c81a7063
NB
1342
1343 return 0;
1344}
1345
1346static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1347{
1a3598aa 1348 uint32_t atom_size, atom;
c81a7063
NB
1349 int found_codestream = 0, search_range = 10;
1350
1a3598aa
MN
1351 while(!found_codestream && search_range
1352 &&
1353 bytestream2_get_bytes_left(&s->g) >= 8) {
1354 atom_size = bytestream2_get_be32u(&s->g);
1355 atom = bytestream2_get_be32u(&s->g);
1356 if (atom == JP2_CODESTREAM) {
c81a7063 1357 found_codestream = 1;
c81a7063 1358 } else {
1a3598aa
MN
1359 if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1360 return 0;
1361 bytestream2_skipu(&s->g, atom_size - 8);
c81a7063
NB
1362 search_range--;
1363 }
1364 }
1365
1366 if (found_codestream)
1367 return 1;
1368 return 0;
1369}
1370
82f8eb5f
JA
1371static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
1372{
1373 Jpeg2000DecoderContext *s = avctx->priv_data;
1374
1375 ff_jpeg2000dsp_init(&s->dsp);
1376
1377 return 0;
1378}
1379
c81a7063
NB
1380static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1381 int *got_frame, AVPacket *avpkt)
1382{
1383 Jpeg2000DecoderContext *s = avctx->priv_data;
2e2d2466 1384 ThreadFrame frame = { .f = data };
c81a7063
NB
1385 AVFrame *picture = data;
1386 int tileno, ret;
1387
1388 s->avctx = avctx;
1a3598aa 1389 bytestream2_init(&s->g, avpkt->data, avpkt->size);
c81a7063
NB
1390 s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1391
daeb4e30
LB
1392 if (bytestream2_get_bytes_left(&s->g) < 2) {
1393 ret = AVERROR_INVALIDDATA;
1394 goto end;
1395 }
c81a7063
NB
1396
1397 // check if the image is in jp2 format
1a3598aa
MN
1398 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1399 (bytestream2_get_be32u(&s->g) == 12) &&
1400 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1401 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
c81a7063
NB
1402 if (!jp2_find_codestream(s)) {
1403 av_log(avctx, AV_LOG_ERROR,
5efadcb8 1404 "Could not find Jpeg2000 codestream atom.\n");
daeb4e30
LB
1405 ret = AVERROR_INVALIDDATA;
1406 goto end;
c81a7063 1407 }
1a3598aa
MN
1408 } else {
1409 bytestream2_seek(&s->g, 0, SEEK_SET);
c81a7063
NB
1410 }
1411
1a3598aa 1412 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
c81a7063 1413 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
daeb4e30
LB
1414 ret = AVERROR_INVALIDDATA;
1415 goto end;
c81a7063
NB
1416 }
1417 if (ret = jpeg2000_read_main_headers(s))
45a1694f 1418 goto end;
c81a7063
NB
1419
1420 /* get picture buffer */
2e2d2466
NB
1421 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1422 av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
45a1694f 1423 goto end;
c81a7063
NB
1424 }
1425 picture->pict_type = AV_PICTURE_TYPE_I;
1426 picture->key_frame = 1;
1427
1428 if (ret = jpeg2000_read_bitstream_packets(s))
45a1694f 1429 goto end;
c81a7063
NB
1430 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1431 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
45a1694f 1432 goto end;
c81a7063 1433
daeb4e30
LB
1434 jpeg2000_dec_cleanup(s);
1435
c81a7063
NB
1436 *got_frame = 1;
1437
1a3598aa
MN
1438 return bytestream2_tell(&s->g);
1439
45a1694f
JG
1440end:
1441 jpeg2000_dec_cleanup(s);
1a3598aa 1442 return ret;
c81a7063
NB
1443}
1444
fe4d5fe9 1445static av_cold void jpeg2000_init_static_data(AVCodec *codec)
70f96615
JG
1446{
1447 ff_jpeg2000_init_tier1_luts();
f56fe04d 1448 ff_mqc_init_context_tables();
70f96615
JG
1449}
1450
c81a7063
NB
1451#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1452#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1453
1454static const AVOption options[] = {
1455 { "lowres", "Lower the decoding resolution by a power of two",
f9581f14 1456 OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
c81a7063
NB
1457 { NULL },
1458};
1459
1460static const AVProfile profiles[] = {
1461 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1462 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1463 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1464 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1465 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1466 { FF_PROFILE_UNKNOWN },
1467};
1468
1469static const AVClass class = {
1470 .class_name = "jpeg2000",
1471 .item_name = av_default_item_name,
1472 .option = options,
1473 .version = LIBAVUTIL_VERSION_INT,
1474};
1475
1476AVCodec ff_jpeg2000_decoder = {
70f96615
JG
1477 .name = "jpeg2000",
1478 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1479 .type = AVMEDIA_TYPE_VIDEO,
1480 .id = AV_CODEC_ID_JPEG2000,
def97856 1481 .capabilities = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_DR1,
70f96615
JG
1482 .priv_data_size = sizeof(Jpeg2000DecoderContext),
1483 .init_static_data = jpeg2000_init_static_data,
82f8eb5f 1484 .init = jpeg2000_decode_init,
70f96615
JG
1485 .decode = jpeg2000_decode_frame,
1486 .priv_class = &class,
70f96615 1487 .profiles = NULL_IF_CONFIG_SMALL(profiles)
c81a7063 1488};