jpeg2000: Do not warn about known and skippable markers
[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
735static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
736{
d57c737a
MN
737 int ret = 0;
738 int layno, reslevelno, compno, precno, ok_reslevel;
739 int x, y;
c81a7063
NB
740
741 s->bit_index = 8;
d57c737a 742 switch (tile->codsty[0].prog_order) {
c81a7063
NB
743 case JPEG2000_PGOD_LRCP:
744 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
745 ok_reslevel = 1;
746 for (reslevelno = 0; ok_reslevel; reslevelno++) {
747 ok_reslevel = 0;
748 for (compno = 0; compno < s->ncomponents; compno++) {
749 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
750 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
751 if (reslevelno < codsty->nreslevels) {
752 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
753 reslevelno;
754 ok_reslevel = 1;
755 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
5efadcb8
LB
756 if ((ret = jpeg2000_decode_packet(s,
757 codsty, rlevel,
758 precno, layno,
759 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
760 qntsty->nguardbits)) < 0)
761 return ret;
c81a7063
NB
762 }
763 }
764 }
765 }
766 break;
767
768 case JPEG2000_PGOD_CPRL:
769 for (compno = 0; compno < s->ncomponents; compno++) {
770 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
771 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
772
773 /* Set bit stream buffer address according to tile-part.
774 * For DCinema one tile-part per component, so can be
775 * indexed by component. */
1a3598aa 776 s->g = tile->tile_part[compno].tpg;
c81a7063
NB
777
778 /* Position loop (y axis)
779 * TODO: Automate computing of step 256.
780 * Fixed here, but to be computed before entering here. */
781 for (y = 0; y < s->height; y += 256) {
782 /* Position loop (y axis)
783 * TODO: automate computing of step 256.
784 * Fixed here, but to be computed before entering here. */
785 for (x = 0; x < s->width; x += 256) {
786 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
787 uint16_t prcx, prcy;
788 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
789 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
790
791 if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
792 (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
793 continue;
794
795 if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
796 (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
797 continue;
798
799 // check if a precinct exists
800 prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
801 prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
802 precno = prcx + rlevel->num_precincts_x * prcy;
803 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
5efadcb8
LB
804 if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
805 precno, layno,
806 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
807 qntsty->nguardbits)) < 0)
808 return ret;
c81a7063
NB
809 }
810 }
811 }
812 }
813 }
814 break;
815
d57c737a
MN
816 case JPEG2000_PGOD_RLCP:
817 avpriv_request_sample(s->avctx, "Progression order RLCP");
818 ret = AVERROR_PATCHWELCOME;
819 break;
820
821 case JPEG2000_PGOD_RPCL:
822 avpriv_request_sample(s->avctx, "Progression order RPCL");
823 ret = AVERROR_PATCHWELCOME;
824 break;
825
826 case JPEG2000_PGOD_PCRL:
827 avpriv_request_sample(s->avctx, "Progression order PCRL");
828 ret = AVERROR_PATCHWELCOME;
829 break;
830
c81a7063
NB
831 default:
832 break;
833 }
834
835 /* EOC marker reached */
1a3598aa 836 bytestream2_skip(&s->g, 2);
c81a7063 837
d57c737a 838 return ret;
c81a7063
NB
839}
840
841/* TIER-1 routines */
842static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
64f6570c
MN
843 int bpno, int bandno, int bpass_csty_symbol,
844 int vert_causal_ctx_csty_symbol)
c81a7063
NB
845{
846 int mask = 3 << (bpno - 1), y0, x, y;
847
848 for (y0 = 0; y0 < height; y0 += 4)
849 for (x = 0; x < width; x++)
64f6570c
MN
850 for (y = y0; y < height && y < y0 + 4; y++) {
851 if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
852 && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
853 int flags_mask = -1;
854 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
855 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
856 if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
857 int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
858 if (bpass_csty_symbol)
859 t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
860 else
861 t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
862 -mask : mask;
c81a7063
NB
863
864 ff_jpeg2000_set_significance(t1, x, y,
865 t1->data[y][x] < 0);
866 }
867 t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
868 }
64f6570c 869 }
c81a7063
NB
870}
871
872static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
873 int bpno)
874{
875 int phalf, nhalf;
876 int y0, x, y;
877
878 phalf = 1 << (bpno - 1);
879 nhalf = -phalf;
880
881 for (y0 = 0; y0 < height; y0 += 4)
882 for (x = 0; x < width; x++)
883 for (y = y0; y < height && y < y0 + 4; y++)
884 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
885 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
886 int r = ff_mqc_decode(&t1->mqc,
887 t1->mqc.cx_states + ctxno)
888 ? phalf : nhalf;
889 t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
890 t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
891 }
892}
893
894static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
895 int width, int height, int bpno, int bandno,
64f6570c 896 int seg_symbols, int vert_causal_ctx_csty_symbol)
c81a7063
NB
897{
898 int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
899
64f6570c 900 for (y0 = 0; y0 < height; y0 += 4) {
c81a7063
NB
901 for (x = 0; x < width; x++) {
902 if (y0 + 3 < height &&
903 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
904 (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
905 (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
906 (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
907 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
908 continue;
909 runlen = ff_mqc_decode(&t1->mqc,
910 t1->mqc.cx_states + MQC_CX_UNI);
911 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
912 t1->mqc.cx_states +
913 MQC_CX_UNI);
914 dec = 1;
915 } else {
916 runlen = 0;
917 dec = 0;
918 }
919
920 for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
921 if (!dec) {
64f6570c
MN
922 if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
923 int flags_mask = -1;
924 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
925 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
926 dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
927 bandno));
928 }
c81a7063
NB
929 }
930 if (dec) {
931 int xorbit;
932 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
933 &xorbit);
934 t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
935 t1->mqc.cx_states + ctxno) ^
936 xorbit)
937 ? -mask : mask;
938 ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
939 }
940 dec = 0;
941 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
942 }
943 }
64f6570c 944 }
c81a7063
NB
945 if (seg_symbols) {
946 int val;
947 val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
948 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
949 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
950 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
951 if (val != 0xa)
952 av_log(s->avctx, AV_LOG_ERROR,
953 "Segmentation symbol value incorrect\n");
954 }
955}
956
957static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
958 Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
959 int width, int height, int bandpos)
960{
961 int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
64f6570c
MN
962 int clnpass_cnt = 0;
963 int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
964 int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
c81a7063 965
c81a7063 966 for (y = 0; y < height; y++)
589e5b52
MN
967 memset(t1->data[y], 0, width * sizeof(**t1->data));
968
28816f9d
NB
969 /* If code-block contains no compressed data: nothing to do. */
970 if (!cblk->length)
971 return 0;
972 for (y = 0; y < height + 2; y++)
589e5b52 973 memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
c81a7063
NB
974
975 ff_mqc_initdec(&t1->mqc, cblk->data);
976 cblk->data[cblk->length] = 0xff;
977 cblk->data[cblk->length + 1] = 0xff;
978
979 while (passno--) {
980 switch (pass_t) {
981 case 0:
64f6570c
MN
982 decode_sigpass(t1, width, height, bpno + 1, bandpos,
983 bpass_csty_symbol && (clnpass_cnt >= 4),
984 vert_causal_ctx_csty_symbol);
c81a7063
NB
985 break;
986 case 1:
987 decode_refpass(t1, width, height, bpno + 1);
64f6570c
MN
988 if (bpass_csty_symbol && clnpass_cnt >= 4)
989 ff_mqc_initdec(&t1->mqc, cblk->data);
c81a7063
NB
990 break;
991 case 2:
992 decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
64f6570c
MN
993 codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
994 vert_causal_ctx_csty_symbol);
995 clnpass_cnt = clnpass_cnt + 1;
996 if (bpass_csty_symbol && clnpass_cnt >= 4)
997 ff_mqc_initdec(&t1->mqc, cblk->data);
c81a7063
NB
998 break;
999 }
1000
1001 pass_t++;
1002 if (pass_t == 3) {
1003 bpno--;
1004 pass_t = 0;
1005 }
1006 }
1007 return 0;
1008}
1009
1010/* TODO: Verify dequantization for lossless case
1011 * comp->data can be float or int
1012 * band->stepsize can be float or int
1013 * depending on the type of DWT transformation.
1014 * see ISO/IEC 15444-1:2002 A.6.1 */
1015
1016/* Float dequantization of a codeblock.*/
1017static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1018 Jpeg2000Component *comp,
1019 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1020{
e11099db
MN
1021 int i, j;
1022 int w = cblk->coord[0][1] - cblk->coord[0][0];
1023 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1024 float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1025 int *src = t1->data[j];
1026 for (i = 0; i < w; ++i)
1027 datap[i] = src[i] * band->f_stepsize;
1028 }
c81a7063
NB
1029}
1030
1031/* Integer dequantization of a codeblock.*/
1032static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1033 Jpeg2000Component *comp,
1034 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1035{
e11099db
MN
1036 int i, j;
1037 int w = cblk->coord[0][1] - cblk->coord[0][0];
1038 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1039 int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1040 int *src = t1->data[j];
1041 for (i = 0; i < w; ++i)
1042 datap[i] = (src[i] * band->i_stepsize + (1 << 15)) >> 16;
1043 }
c81a7063
NB
1044}
1045
82f8eb5f 1046static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
c81a7063
NB
1047{
1048 int i, csize = 1;
82f8eb5f 1049 void *src[3];
c81a7063
NB
1050
1051 for (i = 0; i < 3; i++)
1052 if (tile->codsty[0].transform == FF_DWT97)
82f8eb5f 1053 src[i] = tile->comp[i].f_data;
c81a7063 1054 else
82f8eb5f 1055 src[i] = tile->comp[i].i_data;
c81a7063
NB
1056
1057 for (i = 0; i < 2; i++)
1058 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
82f8eb5f
JA
1059
1060 s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
c81a7063
NB
1061}
1062
1063static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1064 AVFrame *picture)
1065{
1066 int compno, reslevelno, bandno;
1067 int x, y;
1068
1069 uint8_t *line;
1070 Jpeg2000T1Context t1;
1071 /* Loop on tile components */
1072
1073 for (compno = 0; compno < s->ncomponents; compno++) {
1074 Jpeg2000Component *comp = tile->comp + compno;
1075 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1076 /* Loop on resolution levels */
1077 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1078 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1079 /* Loop on bands */
1080 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1081 uint16_t nb_precincts, precno;
1082 Jpeg2000Band *band = rlevel->band + bandno;
1083 int cblkno = 0, bandpos;
1084 bandpos = bandno + (reslevelno > 0);
1085
53d5d89c
MN
1086 if (band->coord[0][0] == band->coord[0][1] ||
1087 band->coord[1][0] == band->coord[1][1])
1088 continue;
1089
c81a7063
NB
1090 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1091 /* Loop on precincts */
1092 for (precno = 0; precno < nb_precincts; precno++) {
1093 Jpeg2000Prec *prec = band->prec + precno;
1094
1095 /* Loop on codeblocks */
1096 for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1097 int x, y;
1098 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1099 decode_cblk(s, codsty, &t1, cblk,
1100 cblk->coord[0][1] - cblk->coord[0][0],
1101 cblk->coord[1][1] - cblk->coord[1][0],
1102 bandpos);
1103
c81a7063
NB
1104 x = cblk->coord[0][0];
1105 y = cblk->coord[1][0];
c81a7063 1106
a458b91c 1107 if (codsty->transform == FF_DWT97)
c81a7063 1108 dequantization_float(x, y, cblk, comp, &t1, band);
a458b91c
MN
1109 else
1110 dequantization_int(x, y, cblk, comp, &t1, band);
c81a7063
NB
1111 } /* end cblk */
1112 } /*end prec */
1113 } /* end band */
1114 } /* end reslevel */
1115
1116 /* inverse DWT */
5bf208f6 1117 ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
c81a7063
NB
1118 } /*end comp */
1119
1120 /* inverse MCT transformation */
1121 if (tile->codsty[0].mct)
1122 mct_decode(s, tile);
1123
c81a7063
NB
1124 if (s->precision <= 8) {
1125 for (compno = 0; compno < s->ncomponents; compno++) {
1126 Jpeg2000Component *comp = tile->comp + compno;
95a57d26 1127 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
5bf208f6
MN
1128 float *datap = comp->f_data;
1129 int32_t *i_datap = comp->i_data;
22e18ea3
MN
1130 int cbps = s->cbps[compno];
1131 int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1132
c81a7063
NB
1133 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1134 line = picture->data[0] + y * picture->linesize[0];
1135 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1136 uint8_t *dst;
1137
1138 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1139 dst = line + x * s->ncomponents + compno;
1140
95a57d26 1141 if (codsty->transform == FF_DWT97) {
22e18ea3
MN
1142 for (; x < w; x += s->cdx[compno]) {
1143 int val = lrintf(*datap) + (1 << (cbps - 1));
1144 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1145 val = av_clip(val, 0, (1 << cbps) - 1);
1146 *dst = val << (8 - cbps);
1147 datap++;
1148 dst += s->ncomponents;
1149 }
1150 } else {
1151 for (; x < w; x += s->cdx[compno]) {
1152 int val = *i_datap + (1 << (cbps - 1));
1153 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1154 val = av_clip(val, 0, (1 << cbps) - 1);
1155 *dst = val << (8 - cbps);
1156 i_datap++;
1157 dst += s->ncomponents;
1158 }
c81a7063
NB
1159 }
1160 line += picture->linesize[0];
1161 }
1162 }
1163 } else {
1164 for (compno = 0; compno < s->ncomponents; compno++) {
1165 Jpeg2000Component *comp = tile->comp + compno;
95a57d26 1166 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
5bf208f6
MN
1167 float *datap = comp->f_data;
1168 int32_t *i_datap = comp->i_data;
c81a7063 1169 uint16_t *linel;
22e18ea3
MN
1170 int cbps = s->cbps[compno];
1171 int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
c81a7063
NB
1172
1173 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1174 linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
1175 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1176 uint16_t *dst;
1177 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1178 dst = linel + (x * s->ncomponents + compno);
95a57d26 1179 if (codsty->transform == FF_DWT97) {
22e18ea3
MN
1180 for (; x < w; x += s-> cdx[compno]) {
1181 int val = lrintf(*datap) + (1 << (cbps - 1));
1182 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1183 val = av_clip(val, 0, (1 << cbps) - 1);
1184 /* align 12 bit values in little-endian mode */
1185 *dst = val << (16 - cbps);
1186 datap++;
1187 dst += s->ncomponents;
1188 }
1189 } else {
1190 for (; x < w; x += s-> cdx[compno]) {
1191 int val = *i_datap + (1 << (cbps - 1));
1192 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1193 val = av_clip(val, 0, (1 << cbps) - 1);
1194 /* align 12 bit values in little-endian mode */
1195 *dst = val << (16 - cbps);
1196 i_datap++;
1197 dst += s->ncomponents;
1198 }
c81a7063
NB
1199 }
1200 linel += picture->linesize[0] >> 1;
1201 }
1202 }
1203 }
22e18ea3 1204
c81a7063
NB
1205 return 0;
1206}
1207
1208static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1209{
1210 int tileno, compno;
1211 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1212 for (compno = 0; compno < s->ncomponents; compno++) {
1213 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1214 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1215
1216 ff_jpeg2000_cleanup(comp, codsty);
1217 }
1218 av_freep(&s->tile[tileno].comp);
1219 }
1220 av_freep(&s->tile);
f0552e63 1221 s->numXtiles = s->numYtiles = 0;
c81a7063
NB
1222}
1223
1224static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1225{
1226 Jpeg2000CodingStyle *codsty = s->codsty;
1227 Jpeg2000QuantStyle *qntsty = s->qntsty;
1228 uint8_t *properties = s->properties;
1229
1230 for (;;) {
1231 int len, ret = 0;
1232 uint16_t marker;
1a3598aa 1233 int oldpos;
c81a7063 1234
1a3598aa 1235 if (bytestream2_get_bytes_left(&s->g) < 2) {
c81a7063
NB
1236 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1237 break;
1238 }
1239
1a3598aa
MN
1240 marker = bytestream2_get_be16u(&s->g);
1241 oldpos = bytestream2_tell(&s->g);
c81a7063 1242
b564784a
MN
1243 if (marker == JPEG2000_SOD) {
1244 Jpeg2000Tile *tile;
1245 Jpeg2000TilePart *tp;
1246
1247 if (s->curtileno < 0) {
1248 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
1249 return AVERROR_INVALIDDATA;
1250 }
18a245a2
MS
1251 if (!s->tile) {
1252 av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
1253 return AVERROR_INVALIDDATA;
1254 }
b564784a
MN
1255
1256 tile = s->tile + s->curtileno;
1257 tp = tile->tile_part + tile->tp_idx;
1258 bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
1259 bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
1260
1261 continue;
1262 }
c81a7063
NB
1263 if (marker == JPEG2000_EOC)
1264 break;
1265
1a3598aa 1266 len = bytestream2_get_be16u(&s->g);
fd54dd02
MN
1267 if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
1268 return AVERROR_INVALIDDATA;
1269
c81a7063
NB
1270 switch (marker) {
1271 case JPEG2000_SIZ:
1272 ret = get_siz(s);
1273 break;
1274 case JPEG2000_COC:
1275 ret = get_coc(s, codsty, properties);
1276 break;
1277 case JPEG2000_COD:
1278 ret = get_cod(s, codsty, properties);
1279 break;
1280 case JPEG2000_QCC:
1281 ret = get_qcc(s, len, qntsty, properties);
1282 break;
1283 case JPEG2000_QCD:
1284 ret = get_qcd(s, len, qntsty, properties);
1285 break;
1286 case JPEG2000_SOT:
aa16bbaf
MN
1287 if (!(ret = get_sot(s, len))) {
1288 codsty = s->tile[s->curtileno].codsty;
1289 qntsty = s->tile[s->curtileno].qntsty;
1290 properties = s->tile[s->curtileno].properties;
1291 }
c81a7063 1292 break;
db53a230
LB
1293 case JPEG2000_PLT:
1294 // the PLT marker is ignored
1295 case JPEG2000_PLM:
1296 // the PLM marker is ignored
c81a7063
NB
1297 case JPEG2000_COM:
1298 // the comment is ignored
1a3598aa 1299 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1300 break;
1301 case JPEG2000_TLM:
1302 // Tile-part lengths
1303 ret = get_tlm(s, len);
1304 break;
1305 default:
1306 av_log(s->avctx, AV_LOG_ERROR,
cc8163e1 1307 "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
1a3598aa
MN
1308 marker, bytestream2_tell(&s->g) - 4);
1309 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1310 break;
1311 }
aa16bbaf 1312 if (bytestream2_tell(&s->g) - oldpos != len || ret) {
c81a7063 1313 av_log(s->avctx, AV_LOG_ERROR,
cc8163e1
DB
1314 "error during processing marker segment %.4"PRIx16"\n",
1315 marker);
c81a7063
NB
1316 return ret ? ret : -1;
1317 }
1318 }
1319 return 0;
1320}
1321
1322/* Read bit stream packets --> T2 operation. */
1323static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1324{
1325 int ret = 0;
c1dcbc59 1326 int tileno;
c81a7063 1327
c1dcbc59
MN
1328 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1329 Jpeg2000Tile *tile = s->tile + tileno;
1330
1331 if (ret = init_tile(s, tileno))
1332 return ret;
1333
1334 s->g = tile->tile_part[0].tpg;
1335 if (ret = jpeg2000_decode_packets(s, tile))
1336 return ret;
1337 }
c81a7063
NB
1338
1339 return 0;
1340}
1341
1342static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1343{
1a3598aa 1344 uint32_t atom_size, atom;
c81a7063
NB
1345 int found_codestream = 0, search_range = 10;
1346
1a3598aa
MN
1347 while(!found_codestream && search_range
1348 &&
1349 bytestream2_get_bytes_left(&s->g) >= 8) {
1350 atom_size = bytestream2_get_be32u(&s->g);
1351 atom = bytestream2_get_be32u(&s->g);
1352 if (atom == JP2_CODESTREAM) {
c81a7063 1353 found_codestream = 1;
c81a7063 1354 } else {
1a3598aa
MN
1355 if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1356 return 0;
1357 bytestream2_skipu(&s->g, atom_size - 8);
c81a7063
NB
1358 search_range--;
1359 }
1360 }
1361
1362 if (found_codestream)
1363 return 1;
1364 return 0;
1365}
1366
82f8eb5f
JA
1367static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
1368{
1369 Jpeg2000DecoderContext *s = avctx->priv_data;
1370
1371 ff_jpeg2000dsp_init(&s->dsp);
1372
1373 return 0;
1374}
1375
c81a7063
NB
1376static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1377 int *got_frame, AVPacket *avpkt)
1378{
1379 Jpeg2000DecoderContext *s = avctx->priv_data;
2e2d2466 1380 ThreadFrame frame = { .f = data };
c81a7063
NB
1381 AVFrame *picture = data;
1382 int tileno, ret;
1383
1384 s->avctx = avctx;
1a3598aa 1385 bytestream2_init(&s->g, avpkt->data, avpkt->size);
c81a7063
NB
1386 s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1387
daeb4e30
LB
1388 if (bytestream2_get_bytes_left(&s->g) < 2) {
1389 ret = AVERROR_INVALIDDATA;
1390 goto end;
1391 }
c81a7063
NB
1392
1393 // check if the image is in jp2 format
1a3598aa
MN
1394 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1395 (bytestream2_get_be32u(&s->g) == 12) &&
1396 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1397 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
c81a7063
NB
1398 if (!jp2_find_codestream(s)) {
1399 av_log(avctx, AV_LOG_ERROR,
5efadcb8 1400 "Could not find Jpeg2000 codestream atom.\n");
daeb4e30
LB
1401 ret = AVERROR_INVALIDDATA;
1402 goto end;
c81a7063 1403 }
1a3598aa
MN
1404 } else {
1405 bytestream2_seek(&s->g, 0, SEEK_SET);
c81a7063
NB
1406 }
1407
1a3598aa 1408 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
c81a7063 1409 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
daeb4e30
LB
1410 ret = AVERROR_INVALIDDATA;
1411 goto end;
c81a7063
NB
1412 }
1413 if (ret = jpeg2000_read_main_headers(s))
45a1694f 1414 goto end;
c81a7063
NB
1415
1416 /* get picture buffer */
2e2d2466
NB
1417 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1418 av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
45a1694f 1419 goto end;
c81a7063
NB
1420 }
1421 picture->pict_type = AV_PICTURE_TYPE_I;
1422 picture->key_frame = 1;
1423
1424 if (ret = jpeg2000_read_bitstream_packets(s))
45a1694f 1425 goto end;
c81a7063
NB
1426 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1427 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
45a1694f 1428 goto end;
c81a7063 1429
daeb4e30
LB
1430 jpeg2000_dec_cleanup(s);
1431
c81a7063
NB
1432 *got_frame = 1;
1433
1a3598aa
MN
1434 return bytestream2_tell(&s->g);
1435
45a1694f
JG
1436end:
1437 jpeg2000_dec_cleanup(s);
1a3598aa 1438 return ret;
c81a7063
NB
1439}
1440
fe4d5fe9 1441static av_cold void jpeg2000_init_static_data(AVCodec *codec)
70f96615
JG
1442{
1443 ff_jpeg2000_init_tier1_luts();
f56fe04d 1444 ff_mqc_init_context_tables();
70f96615
JG
1445}
1446
c81a7063
NB
1447#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1448#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1449
1450static const AVOption options[] = {
1451 { "lowres", "Lower the decoding resolution by a power of two",
f9581f14 1452 OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
c81a7063
NB
1453 { NULL },
1454};
1455
1456static const AVProfile profiles[] = {
1457 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1458 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1459 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1460 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1461 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1462 { FF_PROFILE_UNKNOWN },
1463};
1464
1465static const AVClass class = {
1466 .class_name = "jpeg2000",
1467 .item_name = av_default_item_name,
1468 .option = options,
1469 .version = LIBAVUTIL_VERSION_INT,
1470};
1471
1472AVCodec ff_jpeg2000_decoder = {
70f96615
JG
1473 .name = "jpeg2000",
1474 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1475 .type = AVMEDIA_TYPE_VIDEO,
1476 .id = AV_CODEC_ID_JPEG2000,
def97856 1477 .capabilities = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_DR1,
70f96615
JG
1478 .priv_data_size = sizeof(Jpeg2000DecoderContext),
1479 .init_static_data = jpeg2000_init_static_data,
82f8eb5f 1480 .init = jpeg2000_decode_init,
70f96615
JG
1481 .decode = jpeg2000_decode_frame,
1482 .priv_class = &class,
70f96615 1483 .profiles = NULL_IF_CONFIG_SMALL(profiles)
c81a7063 1484};