jpeg2000: Check zero bit-plane validity
[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);
201 s->sgnd[i] = (x & 0x80) == 1;
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 }
321 }
322 return 0;
323}
324
325/* get coding parameters for a particular tile or whole image*/
326static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
327 uint8_t *properties)
328{
329 Jpeg2000CodingStyle tmp;
330 int compno;
331
1a3598aa 332 if (bytestream2_get_bytes_left(&s->g) < 5)
5efadcb8 333 return AVERROR_INVALIDDATA;
c81a7063
NB
334
335 tmp.log2_prec_width =
336 tmp.log2_prec_height = 15;
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
NB
364
365 c += compno;
1a3598aa 366 c->csty = bytestream2_get_byteu(&s->g);
c81a7063
NB
367 get_cox(s, c);
368
369 properties[compno] |= HAD_COC;
370 return 0;
371}
372
373/* Get common part for QCD and QCC segments. */
374static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
375{
376 int i, x;
377
1a3598aa 378 if (bytestream2_get_bytes_left(&s->g) < 1)
5efadcb8 379 return AVERROR_INVALIDDATA;
c81a7063 380
1a3598aa 381 x = bytestream2_get_byteu(&s->g); // Sqcd
c81a7063
NB
382
383 q->nguardbits = x >> 5;
384 q->quantsty = x & 0x1f;
385
386 if (q->quantsty == JPEG2000_QSTY_NONE) {
387 n -= 3;
1a3598aa
MN
388 if (bytestream2_get_bytes_left(&s->g) < n ||
389 n > JPEG2000_MAX_DECLEVELS)
5efadcb8 390 return AVERROR_INVALIDDATA;
c81a7063 391 for (i = 0; i < n; i++)
1a3598aa 392 q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
c81a7063 393 } else if (q->quantsty == JPEG2000_QSTY_SI) {
1a3598aa 394 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 395 return AVERROR_INVALIDDATA;
1a3598aa 396 x = bytestream2_get_be16u(&s->g);
c81a7063
NB
397 q->expn[0] = x >> 11;
398 q->mant[0] = x & 0x7ff;
be327100 399 for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
c81a7063
NB
400 int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
401 q->expn[i] = curexpn;
402 q->mant[i] = q->mant[0];
403 }
404 } else {
405 n = (n - 3) >> 1;
1a3598aa
MN
406 if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
407 n > JPEG2000_MAX_DECLEVELS)
5efadcb8 408 return AVERROR_INVALIDDATA;
c81a7063 409 for (i = 0; i < n; i++) {
1a3598aa 410 x = bytestream2_get_be16u(&s->g);
c81a7063
NB
411 q->expn[i] = x >> 11;
412 q->mant[i] = x & 0x7ff;
413 }
414 }
415 return 0;
416}
417
418/* Get quantization parameters for a particular tile or a whole image. */
419static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
420 uint8_t *properties)
421{
422 Jpeg2000QuantStyle tmp;
5efadcb8 423 int compno, ret;
c81a7063 424
5efadcb8
LB
425 if ((ret = get_qcx(s, n, &tmp)) < 0)
426 return ret;
c81a7063
NB
427 for (compno = 0; compno < s->ncomponents; compno++)
428 if (!(properties[compno] & HAD_QCC))
429 memcpy(q + compno, &tmp, sizeof(tmp));
430 return 0;
431}
432
433/* Get quantization parameters for a component in the whole image
434 * on in a particular tile. */
435static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
436 uint8_t *properties)
437{
438 int compno;
439
1a3598aa 440 if (bytestream2_get_bytes_left(&s->g) < 1)
5efadcb8 441 return AVERROR_INVALIDDATA;
c81a7063 442
1a3598aa 443 compno = bytestream2_get_byteu(&s->g);
c81a7063
NB
444 properties[compno] |= HAD_QCC;
445 return get_qcx(s, n - 1, q + compno);
446}
447
448/* Get start of tile segment. */
5efadcb8 449static int get_sot(Jpeg2000DecoderContext *s, int n)
c81a7063
NB
450{
451 Jpeg2000TilePart *tp;
452 uint16_t Isot;
453 uint32_t Psot;
454 uint8_t TPsot;
455
1a3598aa 456 if (bytestream2_get_bytes_left(&s->g) < 8)
5efadcb8 457 return AVERROR_INVALIDDATA;
c81a7063 458
1a3598aa 459 Isot = bytestream2_get_be16u(&s->g); // Isot
d3cb302b
MN
460 if (Isot >= s->numXtiles * s->numYtiles)
461 return AVERROR_INVALIDDATA;
462
c81a7063 463 if (Isot) {
5efadcb8
LB
464 avpriv_request_sample(s->avctx, "Support for more than one tile");
465 return AVERROR_PATCHWELCOME;
c81a7063 466 }
1a3598aa
MN
467 Psot = bytestream2_get_be32u(&s->g); // Psot
468 TPsot = bytestream2_get_byteu(&s->g); // TPsot
c81a7063
NB
469
470 /* Read TNSot but not used */
1a3598aa 471 bytestream2_get_byteu(&s->g); // TNsot
c81a7063 472
d3cb302b
MN
473 if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
474 av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot);
475 return AVERROR_INVALIDDATA;
476 }
477
478 if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
479 avpriv_request_sample(s->avctx, "Support for %d components", TPsot);
480 return AVERROR_PATCHWELCOME;
481 }
482
c81a7063
NB
483 tp = s->tile[s->curtileno].tile_part + TPsot;
484 tp->tile_index = Isot;
485 tp->tp_len = Psot;
486 tp->tp_idx = TPsot;
487
488 /* Start of bit stream. Pointer to SOD marker
489 * Check SOD marker is present. */
1a3598aa
MN
490 if (JPEG2000_SOD == bytestream2_get_be16(&s->g)) {
491 bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_len - n - 4);
492 bytestream2_skip(&s->g, tp->tp_len - n - 4);
493 } else {
c81a7063 494 av_log(s->avctx, AV_LOG_ERROR, "SOD marker not found \n");
5efadcb8 495 return AVERROR_INVALIDDATA;
c81a7063
NB
496 }
497
498 /* End address of bit stream =
499 * start address + (Psot - size of SOT HEADER(n)
500 * - size of SOT MARKER(2) - size of SOD marker(2) */
c81a7063
NB
501
502 return 0;
503}
504
505/* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
506 * Used to know the number of tile parts and lengths.
507 * There may be multiple TLMs in the header.
508 * TODO: The function is not used for tile-parts management, nor anywhere else.
509 * It can be useful to allocate memory for tile parts, before managing the SOT
510 * markers. Parsing the TLM header is needed to increment the input header
511 * buffer.
512 * This marker is mandatory for DCI. */
513static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
514{
515 uint8_t Stlm, ST, SP, tile_tlm, i;
1a3598aa
MN
516 bytestream2_get_byte(&s->g); /* Ztlm: skipped */
517 Stlm = bytestream2_get_byte(&s->g);
c81a7063
NB
518
519 // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
520 ST = (Stlm >> 4) & 0x03;
521 // TODO: Manage case of ST = 0b11 --> raise error
522 SP = (Stlm >> 6) & 0x01;
523 tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
524 for (i = 0; i < tile_tlm; i++) {
525 switch (ST) {
526 case 0:
527 break;
528 case 1:
1a3598aa 529 bytestream2_get_byte(&s->g);
c81a7063
NB
530 break;
531 case 2:
1a3598aa 532 bytestream2_get_be16(&s->g);
c81a7063
NB
533 break;
534 case 3:
1a3598aa 535 bytestream2_get_be32(&s->g);
c81a7063
NB
536 break;
537 }
538 if (SP == 0) {
1a3598aa 539 bytestream2_get_be16(&s->g);
c81a7063 540 } else {
1a3598aa 541 bytestream2_get_be32(&s->g);
c81a7063
NB
542 }
543 }
544 return 0;
545}
546
547static int init_tile(Jpeg2000DecoderContext *s, int tileno)
548{
549 int compno;
550 int tilex = tileno % s->numXtiles;
551 int tiley = tileno / s->numXtiles;
552 Jpeg2000Tile *tile = s->tile + tileno;
553 Jpeg2000CodingStyle *codsty;
554 Jpeg2000QuantStyle *qntsty;
555
556 if (!tile->comp)
557 return AVERROR(ENOMEM);
558
559 /* copy codsty, qnsty to tile. TODO: Is it the best way?
560 * codsty, qnsty is an array of 4 structs Jpeg2000CodingStyle
561 * and Jpeg2000QuantStyle */
562 memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(*codsty));
563 memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(*qntsty));
564
565 for (compno = 0; compno < s->ncomponents; compno++) {
566 Jpeg2000Component *comp = tile->comp + compno;
567 int ret; // global bandno
568 codsty = tile->codsty + compno;
569 qntsty = tile->qntsty + compno;
570
571 comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
572 comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
573 comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
574 comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
575
576 // FIXME: add a dcinema profile check ?
577 // value is guaranteed by profile (orig=0, 1 tile)
578 comp->coord[0][0] = 0;
579 comp->coord[0][1] = s->avctx->width;
580 comp->coord[1][0] = 0;
581 comp->coord[1][1] = s->avctx->height;
582
583 if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
584 s->cbps[compno], s->cdx[compno],
585 s->cdy[compno], s->avctx))
586 return ret;
587 }
588 return 0;
589}
590
591/* Read the number of coding passes. */
592static int getnpasses(Jpeg2000DecoderContext *s)
593{
594 int num;
595 if (!get_bits(s, 1))
596 return 1;
597 if (!get_bits(s, 1))
598 return 2;
599 if ((num = get_bits(s, 2)) != 3)
600 return num < 0 ? num : 3 + num;
601 if ((num = get_bits(s, 5)) != 31)
602 return num < 0 ? num : 6 + num;
603 num = get_bits(s, 7);
604 return num < 0 ? num : 37 + num;
605}
606
607static int getlblockinc(Jpeg2000DecoderContext *s)
608{
609 int res = 0, ret;
610 while (ret = get_bits(s, 1)) {
611 if (ret < 0)
612 return ret;
613 res++;
614 }
615 return res;
616}
617
618static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
619 Jpeg2000CodingStyle *codsty,
620 Jpeg2000ResLevel *rlevel, int precno,
621 int layno, uint8_t *expn, int numgbits)
622{
623 int bandno, cblkno, ret, nb_code_blocks;
624
625 if (!(ret = get_bits(s, 1))) {
626 jpeg2000_flush(s);
627 return 0;
628 } else if (ret < 0)
629 return ret;
630
631 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
632 Jpeg2000Band *band = rlevel->band + bandno;
633 Jpeg2000Prec *prec = band->prec + precno;
634
635 if (band->coord[0][0] == band->coord[0][1] ||
636 band->coord[1][0] == band->coord[1][1])
637 continue;
638 prec->yi0 = 0;
639 prec->xi0 = 0;
640 nb_code_blocks = prec->nb_codeblocks_height *
641 prec->nb_codeblocks_width;
642 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
643 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
644 int incl, newpasses, llen;
645
646 if (cblk->npasses)
647 incl = get_bits(s, 1);
648 else
649 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
650 if (!incl)
651 continue;
652 else if (incl < 0)
653 return incl;
654
17e5d614
MN
655 if (!cblk->npasses) {
656 int v = expn[bandno] + numgbits - 1 -
657 tag_tree_decode(s, prec->zerobits + cblkno, 100);
658 if (v < 0) {
659 av_log(s->avctx, AV_LOG_ERROR,
660 "nonzerobits %d invalid\n", v);
661 return AVERROR_INVALIDDATA;
662 }
663 cblk->nonzerobits = v;
664 }
c81a7063
NB
665 if ((newpasses = getnpasses(s)) < 0)
666 return newpasses;
667 if ((llen = getlblockinc(s)) < 0)
668 return llen;
669 cblk->lblock += llen;
670 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
671 return ret;
7e201d57
LB
672 if (ret > sizeof(cblk->data)) {
673 avpriv_request_sample(s->avctx,
674 "Block with lengthinc greater than %zu",
675 sizeof(cblk->data));
676 return AVERROR_PATCHWELCOME;
677 }
c81a7063
NB
678 cblk->lengthinc = ret;
679 cblk->npasses += newpasses;
680 }
681 }
682 jpeg2000_flush(s);
683
684 if (codsty->csty & JPEG2000_CSTY_EPH) {
1a3598aa
MN
685 if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
686 bytestream2_skip(&s->g, 2);
c81a7063
NB
687 else
688 av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
689 }
690
691 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
692 Jpeg2000Band *band = rlevel->band + bandno;
693 Jpeg2000Prec *prec = band->prec + precno;
694
695 nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
696 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
697 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1a3598aa 698 if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)
5efadcb8 699 return AVERROR_INVALIDDATA;
28816f9d
NB
700 /* Code-block data can be empty. In that case initialize data
701 * with 0xFFFF. */
702 if (cblk->lengthinc > 0) {
1a3598aa 703 bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
28816f9d
NB
704 } else {
705 cblk->data[0] = 0xFF;
706 cblk->data[1] = 0xFF;
707 }
c81a7063
NB
708 cblk->length += cblk->lengthinc;
709 cblk->lengthinc = 0;
710 }
711 }
712 return 0;
713}
714
715static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
716{
5efadcb8 717 int layno, reslevelno, compno, precno, ok_reslevel, ret;
c81a7063
NB
718 uint8_t prog_order = tile->codsty[0].prog_order;
719 uint16_t x;
720 uint16_t y;
721
722 s->bit_index = 8;
723 switch (prog_order) {
724 case JPEG2000_PGOD_LRCP:
725 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
726 ok_reslevel = 1;
727 for (reslevelno = 0; ok_reslevel; reslevelno++) {
728 ok_reslevel = 0;
729 for (compno = 0; compno < s->ncomponents; compno++) {
730 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
731 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
732 if (reslevelno < codsty->nreslevels) {
733 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
734 reslevelno;
735 ok_reslevel = 1;
736 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
5efadcb8
LB
737 if ((ret = jpeg2000_decode_packet(s,
738 codsty, rlevel,
739 precno, layno,
740 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
741 qntsty->nguardbits)) < 0)
742 return ret;
c81a7063
NB
743 }
744 }
745 }
746 }
747 break;
748
749 case JPEG2000_PGOD_CPRL:
750 for (compno = 0; compno < s->ncomponents; compno++) {
751 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
752 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
753
754 /* Set bit stream buffer address according to tile-part.
755 * For DCinema one tile-part per component, so can be
756 * indexed by component. */
1a3598aa 757 s->g = tile->tile_part[compno].tpg;
c81a7063
NB
758
759 /* Position loop (y axis)
760 * TODO: Automate computing of step 256.
761 * Fixed here, but to be computed before entering here. */
762 for (y = 0; y < s->height; y += 256) {
763 /* Position loop (y axis)
764 * TODO: automate computing of step 256.
765 * Fixed here, but to be computed before entering here. */
766 for (x = 0; x < s->width; x += 256) {
767 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
768 uint16_t prcx, prcy;
769 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
770 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
771
772 if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
773 (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
774 continue;
775
776 if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
777 (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
778 continue;
779
780 // check if a precinct exists
781 prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
782 prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
783 precno = prcx + rlevel->num_precincts_x * prcy;
784 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
5efadcb8
LB
785 if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
786 precno, layno,
787 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
788 qntsty->nguardbits)) < 0)
789 return ret;
c81a7063
NB
790 }
791 }
792 }
793 }
794 }
795 break;
796
797 default:
798 break;
799 }
800
801 /* EOC marker reached */
1a3598aa 802 bytestream2_skip(&s->g, 2);
c81a7063
NB
803
804 return 0;
805}
806
807/* TIER-1 routines */
808static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
809 int bpno, int bandno)
810{
811 int mask = 3 << (bpno - 1), y0, x, y;
812
813 for (y0 = 0; y0 < height; y0 += 4)
814 for (x = 0; x < width; x++)
815 for (y = y0; y < height && y < y0 + 4; y++)
816 if ((t1->flags[y + 1][x + 1] & JPEG2000_T1_SIG_NB)
817 && !(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
818 if (ff_mqc_decode(&t1->mqc,
819 t1->mqc.cx_states +
820 ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
821 bandno))) {
822 int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
823 &xorbit);
824
825 t1->data[y][x] =
826 (ff_mqc_decode(&t1->mqc,
827 t1->mqc.cx_states + ctxno) ^ xorbit)
828 ? -mask : mask;
829
830 ff_jpeg2000_set_significance(t1, x, y,
831 t1->data[y][x] < 0);
832 }
833 t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
834 }
835}
836
837static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
838 int bpno)
839{
840 int phalf, nhalf;
841 int y0, x, y;
842
843 phalf = 1 << (bpno - 1);
844 nhalf = -phalf;
845
846 for (y0 = 0; y0 < height; y0 += 4)
847 for (x = 0; x < width; x++)
848 for (y = y0; y < height && y < y0 + 4; y++)
849 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
850 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
851 int r = ff_mqc_decode(&t1->mqc,
852 t1->mqc.cx_states + ctxno)
853 ? phalf : nhalf;
854 t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
855 t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
856 }
857}
858
859static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
860 int width, int height, int bpno, int bandno,
861 int seg_symbols)
862{
863 int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
864
865 for (y0 = 0; y0 < height; y0 += 4)
866 for (x = 0; x < width; x++) {
867 if (y0 + 3 < height &&
868 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
869 (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
870 (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
871 (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
872 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
873 continue;
874 runlen = ff_mqc_decode(&t1->mqc,
875 t1->mqc.cx_states + MQC_CX_UNI);
876 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
877 t1->mqc.cx_states +
878 MQC_CX_UNI);
879 dec = 1;
880 } else {
881 runlen = 0;
882 dec = 0;
883 }
884
885 for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
886 if (!dec) {
887 if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))
888 dec = ff_mqc_decode(&t1->mqc,
889 t1->mqc.cx_states +
890 ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
891 bandno));
892 }
893 if (dec) {
894 int xorbit;
895 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
896 &xorbit);
897 t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
898 t1->mqc.cx_states + ctxno) ^
899 xorbit)
900 ? -mask : mask;
901 ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
902 }
903 dec = 0;
904 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
905 }
906 }
907 if (seg_symbols) {
908 int val;
909 val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
910 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
911 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
912 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
913 if (val != 0xa)
914 av_log(s->avctx, AV_LOG_ERROR,
915 "Segmentation symbol value incorrect\n");
916 }
917}
918
919static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
920 Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
921 int width, int height, int bandpos)
922{
923 int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
924
c81a7063
NB
925 for (y = 0; y < height; y++)
926 memset(t1->data[y], 0, width * sizeof(width));
28816f9d
NB
927 /* If code-block contains no compressed data: nothing to do. */
928 if (!cblk->length)
929 return 0;
930 for (y = 0; y < height + 2; y++)
931 memset(t1->flags[y], 0, (width + 2) * sizeof(width));
c81a7063
NB
932
933 ff_mqc_initdec(&t1->mqc, cblk->data);
934 cblk->data[cblk->length] = 0xff;
935 cblk->data[cblk->length + 1] = 0xff;
936
937 while (passno--) {
938 switch (pass_t) {
939 case 0:
940 decode_sigpass(t1, width, height, bpno + 1, bandpos);
941 break;
942 case 1:
943 decode_refpass(t1, width, height, bpno + 1);
944 break;
945 case 2:
946 decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
947 codsty->cblk_style & JPEG2000_CBLK_SEGSYM);
948 break;
949 }
950
951 pass_t++;
952 if (pass_t == 3) {
953 bpno--;
954 pass_t = 0;
955 }
956 }
957 return 0;
958}
959
960/* TODO: Verify dequantization for lossless case
961 * comp->data can be float or int
962 * band->stepsize can be float or int
963 * depending on the type of DWT transformation.
964 * see ISO/IEC 15444-1:2002 A.6.1 */
965
966/* Float dequantization of a codeblock.*/
967static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
968 Jpeg2000Component *comp,
969 Jpeg2000T1Context *t1, Jpeg2000Band *band)
970{
971 int i, j, idx;
972 float *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
973 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
974 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
975 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
976 datap[idx] = (float)(t1->data[j][i]) * ((float)band->stepsize);
977 }
978 return;
979}
980
981/* Integer dequantization of a codeblock.*/
982static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
983 Jpeg2000Component *comp,
984 Jpeg2000T1Context *t1, Jpeg2000Band *band)
985{
986 int i, j, idx;
987 int32_t *datap =
988 (int32_t *) &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
989 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
990 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
991 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
992 datap[idx] =
993 ((int32_t)(t1->data[j][i]) * ((int32_t)band->stepsize) + (1 << 15)) >> 16;
994 }
995 return;
996}
997
998/* Inverse ICT parameters in float and integer.
999 * int value = (float value) * (1<<16) */
1000static const float f_ict_params[4] = {
1001 1.402f,
1002 0.34413f,
1003 0.71414f,
1004 1.772f
1005};
1006static const int i_ict_params[4] = {
1007 91881,
1008 22553,
1009 46802,
1010 116130
1011};
1012
1013static int mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1014{
1015 int i, csize = 1;
1016 int ret = 0;
1017 int32_t *src[3], i0, i1, i2;
1018 float *srcf[3], i0f, i1f, i2f;
1019
1020 for (i = 0; i < 3; i++)
1021 if (tile->codsty[0].transform == FF_DWT97)
1022 srcf[i] = tile->comp[i].data;
1023 else
1024 src[i] = (int32_t *)tile->comp[i].data;
1025
1026 for (i = 0; i < 2; i++)
1027 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1028 switch (tile->codsty[0].transform) {
1029 case FF_DWT97:
1030 for (i = 0; i < csize; i++) {
1031 i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
1032 i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
1033 - (f_ict_params[2] * *srcf[2]);
1034 i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
1035 *srcf[0]++ = i0f;
1036 *srcf[1]++ = i1f;
1037 *srcf[2]++ = i2f;
1038 }
1039 break;
1040 case FF_DWT97_INT:
1041 for (i = 0; i < csize; i++) {
1042 i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
1043 i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
1044 - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
1045 i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
1046 *src[0]++ = i0;
1047 *src[1]++ = i1;
1048 *src[2]++ = i2;
1049 }
1050 break;
1051 case FF_DWT53:
1052 for (i = 0; i < csize; i++) {
1053 i1 = *src[0] - (*src[2] + *src[1] >> 2);
1054 i0 = i1 + *src[2];
1055 i2 = i1 + *src[1];
1056 *src[0]++ = i0;
1057 *src[1]++ = i1;
1058 *src[2]++ = i2;
1059 }
1060 break;
1061 }
1062 return ret;
1063}
1064
1065static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1066 AVFrame *picture)
1067{
1068 int compno, reslevelno, bandno;
1069 int x, y;
1070
1071 uint8_t *line;
1072 Jpeg2000T1Context t1;
1073 /* Loop on tile components */
1074
1075 for (compno = 0; compno < s->ncomponents; compno++) {
1076 Jpeg2000Component *comp = tile->comp + compno;
1077 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1078 /* Loop on resolution levels */
1079 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1080 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1081 /* Loop on bands */
1082 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1083 uint16_t nb_precincts, precno;
1084 Jpeg2000Band *band = rlevel->band + bandno;
1085 int cblkno = 0, bandpos;
1086 bandpos = bandno + (reslevelno > 0);
1087
1088 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1089 /* Loop on precincts */
1090 for (precno = 0; precno < nb_precincts; precno++) {
1091 Jpeg2000Prec *prec = band->prec + precno;
1092
1093 /* Loop on codeblocks */
1094 for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1095 int x, y;
1096 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1097 decode_cblk(s, codsty, &t1, cblk,
1098 cblk->coord[0][1] - cblk->coord[0][0],
1099 cblk->coord[1][1] - cblk->coord[1][0],
1100 bandpos);
1101
1102 /* Manage band offsets */
1103 x = cblk->coord[0][0];
1104 y = cblk->coord[1][0];
1105 if ((reslevelno > 0) && ((bandno + 1) & 1)) {
1106 Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1107 x += pres->coord[0][1] - pres->coord[0][0];
1108 }
1109 if ((reslevelno > 0) && ((bandno + 1) & 2)) {
1110 Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1111 y += pres->coord[1][1] - pres->coord[1][0];
1112 }
1113
1114 if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1115 dequantization_int(x, y, cblk, comp, &t1, band);
1116 else
1117 dequantization_float(x, y, cblk, comp, &t1, band);
1118 } /* end cblk */
1119 } /*end prec */
1120 } /* end band */
1121 } /* end reslevel */
1122
1123 /* inverse DWT */
1124 ff_dwt_decode(&comp->dwt, comp->data);
1125 } /*end comp */
1126
1127 /* inverse MCT transformation */
1128 if (tile->codsty[0].mct)
1129 mct_decode(s, tile);
1130
7c57a582 1131 if (s->avctx->pix_fmt == AV_PIX_FMT_BGRA) // RGBA -> BGRA
c81a7063
NB
1132 FFSWAP(float *, tile->comp[0].data, tile->comp[2].data);
1133
1134 if (s->precision <= 8) {
1135 for (compno = 0; compno < s->ncomponents; compno++) {
1136 Jpeg2000Component *comp = tile->comp + compno;
1137 int32_t *datap = (int32_t *)comp->data;
1138 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1139 line = picture->data[0] + y * picture->linesize[0];
1140 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1141 uint8_t *dst;
1142
1143 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1144 dst = line + x * s->ncomponents + compno;
1145
1146 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
1147 *datap += 1 << (s->cbps[compno] - 1);
1148 if (*datap < 0)
1149 *datap = 0;
1150 else if (*datap >= (1 << s->cbps[compno]))
1151 *datap = (1 << s->cbps[compno]) - 1;
1152 *dst = *datap++;
1153 dst += s->ncomponents;
1154 }
1155 line += picture->linesize[0];
1156 }
1157 }
1158 } else {
1159 for (compno = 0; compno < s->ncomponents; compno++) {
1160 Jpeg2000Component *comp = tile->comp + compno;
1161 float *datap = comp->data;
1162 int32_t *i_datap = (int32_t *) comp->data;
1163 uint16_t *linel;
1164
1165 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1166 linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
1167 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1168 uint16_t *dst;
1169 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1170 dst = linel + (x * s->ncomponents + compno);
1171 for (; x < s->avctx->width; x += s->cdx[compno]) {
1172 int16_t val;
1173 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1174 if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1175 val = *i_datap + (1 << (s->cbps[compno] - 1));
1176 else
1177 val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
1178 val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
1179 /* align 12 bit values in little-endian mode */
1180 *dst = val << 4;
1181 datap++;
1182 i_datap++;
1183 dst += s->ncomponents;
1184 }
1185 linel += picture->linesize[0] >> 1;
1186 }
1187 }
1188 }
1189 return 0;
1190}
1191
1192static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1193{
1194 int tileno, compno;
1195 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1196 for (compno = 0; compno < s->ncomponents; compno++) {
1197 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1198 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1199
1200 ff_jpeg2000_cleanup(comp, codsty);
1201 }
1202 av_freep(&s->tile[tileno].comp);
1203 }
1204 av_freep(&s->tile);
1205}
1206
1207static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1208{
1209 Jpeg2000CodingStyle *codsty = s->codsty;
1210 Jpeg2000QuantStyle *qntsty = s->qntsty;
1211 uint8_t *properties = s->properties;
1212
1213 for (;;) {
1214 int len, ret = 0;
1215 uint16_t marker;
1a3598aa 1216 int oldpos;
c81a7063 1217
1a3598aa 1218 if (bytestream2_get_bytes_left(&s->g) < 2) {
c81a7063
NB
1219 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1220 break;
1221 }
1222
1a3598aa
MN
1223 marker = bytestream2_get_be16u(&s->g);
1224 oldpos = bytestream2_tell(&s->g);
c81a7063
NB
1225
1226 if (marker == JPEG2000_EOC)
1227 break;
1228
1a3598aa 1229 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 1230 return AVERROR_INVALIDDATA;
1a3598aa 1231 len = bytestream2_get_be16u(&s->g);
c81a7063
NB
1232 switch (marker) {
1233 case JPEG2000_SIZ:
1234 ret = get_siz(s);
1235 break;
1236 case JPEG2000_COC:
1237 ret = get_coc(s, codsty, properties);
1238 break;
1239 case JPEG2000_COD:
1240 ret = get_cod(s, codsty, properties);
1241 break;
1242 case JPEG2000_QCC:
1243 ret = get_qcc(s, len, qntsty, properties);
1244 break;
1245 case JPEG2000_QCD:
1246 ret = get_qcd(s, len, qntsty, properties);
1247 break;
1248 case JPEG2000_SOT:
1249 ret = get_sot(s, len);
1250 break;
1251 case JPEG2000_COM:
1252 // the comment is ignored
1a3598aa 1253 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1254 break;
1255 case JPEG2000_TLM:
1256 // Tile-part lengths
1257 ret = get_tlm(s, len);
1258 break;
1259 default:
1260 av_log(s->avctx, AV_LOG_ERROR,
1a3598aa
MN
1261 "unsupported marker 0x%.4X at pos 0x%X\n",
1262 marker, bytestream2_tell(&s->g) - 4);
1263 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1264 break;
1265 }
1a3598aa 1266 if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {
c81a7063
NB
1267 av_log(s->avctx, AV_LOG_ERROR,
1268 "error during processing marker segment %.4x\n", marker);
1269 return ret ? ret : -1;
1270 }
1271 }
1272 return 0;
1273}
1274
1275/* Read bit stream packets --> T2 operation. */
1276static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1277{
1278 int ret = 0;
1279 Jpeg2000Tile *tile = s->tile + s->curtileno;
1280
1281 if (ret = init_tile(s, s->curtileno))
1282 return ret;
1283 if (ret = jpeg2000_decode_packets(s, tile))
1284 return ret;
1285
1286 return 0;
1287}
1288
1289static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1290{
1a3598aa 1291 uint32_t atom_size, atom;
c81a7063
NB
1292 int found_codestream = 0, search_range = 10;
1293
1a3598aa
MN
1294 while(!found_codestream && search_range
1295 &&
1296 bytestream2_get_bytes_left(&s->g) >= 8) {
1297 atom_size = bytestream2_get_be32u(&s->g);
1298 atom = bytestream2_get_be32u(&s->g);
1299 if (atom == JP2_CODESTREAM) {
c81a7063 1300 found_codestream = 1;
c81a7063 1301 } else {
1a3598aa
MN
1302 if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1303 return 0;
1304 bytestream2_skipu(&s->g, atom_size - 8);
c81a7063
NB
1305 search_range--;
1306 }
1307 }
1308
1309 if (found_codestream)
1310 return 1;
1311 return 0;
1312}
1313
1314static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1315 int *got_frame, AVPacket *avpkt)
1316{
1317 Jpeg2000DecoderContext *s = avctx->priv_data;
2e2d2466 1318 ThreadFrame frame = { .f = data };
c81a7063
NB
1319 AVFrame *picture = data;
1320 int tileno, ret;
1321
1322 s->avctx = avctx;
1a3598aa 1323 bytestream2_init(&s->g, avpkt->data, avpkt->size);
c81a7063
NB
1324 s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1325
1326 // reduction factor, i.e number of resolution levels to skip
1327 s->reduction_factor = s->lowres;
1328
1a3598aa 1329 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 1330 return AVERROR_INVALIDDATA;
c81a7063
NB
1331
1332 // check if the image is in jp2 format
1a3598aa
MN
1333 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1334 (bytestream2_get_be32u(&s->g) == 12) &&
1335 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1336 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
c81a7063
NB
1337 if (!jp2_find_codestream(s)) {
1338 av_log(avctx, AV_LOG_ERROR,
5efadcb8
LB
1339 "Could not find Jpeg2000 codestream atom.\n");
1340 return AVERROR_INVALIDDATA;
c81a7063 1341 }
1a3598aa
MN
1342 } else {
1343 bytestream2_seek(&s->g, 0, SEEK_SET);
1344 if (bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
1345 bytestream2_skip(&s->g, 8);
c81a7063
NB
1346 }
1347
1a3598aa 1348 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
c81a7063 1349 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
5efadcb8 1350 return AVERROR_INVALIDDATA;
c81a7063
NB
1351 }
1352 if (ret = jpeg2000_read_main_headers(s))
45a1694f 1353 goto end;
c81a7063
NB
1354
1355 /* get picture buffer */
2e2d2466
NB
1356 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1357 av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
45a1694f 1358 goto end;
c81a7063
NB
1359 }
1360 picture->pict_type = AV_PICTURE_TYPE_I;
1361 picture->key_frame = 1;
1362
1363 if (ret = jpeg2000_read_bitstream_packets(s))
45a1694f 1364 goto end;
c81a7063
NB
1365 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1366 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
45a1694f 1367 goto end;
c81a7063
NB
1368
1369 *got_frame = 1;
1370
1a3598aa
MN
1371 return bytestream2_tell(&s->g);
1372
45a1694f
JG
1373end:
1374 jpeg2000_dec_cleanup(s);
1a3598aa 1375 return ret;
c81a7063
NB
1376}
1377
70f96615
JG
1378static void jpeg2000_init_static_data(AVCodec *codec)
1379{
1380 ff_jpeg2000_init_tier1_luts();
1381}
1382
c81a7063
NB
1383#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1384#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1385
1386static const AVOption options[] = {
1387 { "lowres", "Lower the decoding resolution by a power of two",
1388 OFFSET(lowres), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1389 { NULL },
1390};
1391
1392static const AVProfile profiles[] = {
1393 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1394 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1395 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1396 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1397 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1398 { FF_PROFILE_UNKNOWN },
1399};
1400
1401static const AVClass class = {
1402 .class_name = "jpeg2000",
1403 .item_name = av_default_item_name,
1404 .option = options,
1405 .version = LIBAVUTIL_VERSION_INT,
1406};
1407
1408AVCodec ff_jpeg2000_decoder = {
70f96615
JG
1409 .name = "jpeg2000",
1410 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1411 .type = AVMEDIA_TYPE_VIDEO,
1412 .id = AV_CODEC_ID_JPEG2000,
1413 .capabilities = CODEC_CAP_FRAME_THREADS,
1414 .priv_data_size = sizeof(Jpeg2000DecoderContext),
1415 .init_static_data = jpeg2000_init_static_data,
1416 .decode = jpeg2000_decode_frame,
1417 .priv_class = &class,
7c57a582
AK
1418 .pix_fmts = (enum AVPixelFormat[]) { AV_PIX_FMT_XYZ12,
1419 AV_PIX_FMT_GRAY8,
1420 -1 },
70f96615 1421 .profiles = NULL_IF_CONFIG_SMALL(profiles)
c81a7063 1422};