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