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