jpeg2000: Validate block lengthinc
[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
655 if (!cblk->npasses)
656 cblk->nonzerobits = expn[bandno] + numgbits - 1 -
657 tag_tree_decode(s, prec->zerobits + cblkno,
658 100);
659 if ((newpasses = getnpasses(s)) < 0)
660 return newpasses;
661 if ((llen = getlblockinc(s)) < 0)
662 return llen;
663 cblk->lblock += llen;
664 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
665 return ret;
7e201d57
LB
666 if (ret > sizeof(cblk->data)) {
667 avpriv_request_sample(s->avctx,
668 "Block with lengthinc greater than %zu",
669 sizeof(cblk->data));
670 return AVERROR_PATCHWELCOME;
671 }
c81a7063
NB
672 cblk->lengthinc = ret;
673 cblk->npasses += newpasses;
674 }
675 }
676 jpeg2000_flush(s);
677
678 if (codsty->csty & JPEG2000_CSTY_EPH) {
1a3598aa
MN
679 if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
680 bytestream2_skip(&s->g, 2);
c81a7063
NB
681 else
682 av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
683 }
684
685 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
686 Jpeg2000Band *band = rlevel->band + bandno;
687 Jpeg2000Prec *prec = band->prec + precno;
688
689 nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
690 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
691 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1a3598aa 692 if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)
5efadcb8 693 return AVERROR_INVALIDDATA;
28816f9d
NB
694 /* Code-block data can be empty. In that case initialize data
695 * with 0xFFFF. */
696 if (cblk->lengthinc > 0) {
1a3598aa 697 bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
28816f9d
NB
698 } else {
699 cblk->data[0] = 0xFF;
700 cblk->data[1] = 0xFF;
701 }
c81a7063
NB
702 cblk->length += cblk->lengthinc;
703 cblk->lengthinc = 0;
704 }
705 }
706 return 0;
707}
708
709static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
710{
5efadcb8 711 int layno, reslevelno, compno, precno, ok_reslevel, ret;
c81a7063
NB
712 uint8_t prog_order = tile->codsty[0].prog_order;
713 uint16_t x;
714 uint16_t y;
715
716 s->bit_index = 8;
717 switch (prog_order) {
718 case JPEG2000_PGOD_LRCP:
719 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
720 ok_reslevel = 1;
721 for (reslevelno = 0; ok_reslevel; reslevelno++) {
722 ok_reslevel = 0;
723 for (compno = 0; compno < s->ncomponents; compno++) {
724 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
725 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
726 if (reslevelno < codsty->nreslevels) {
727 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
728 reslevelno;
729 ok_reslevel = 1;
730 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
5efadcb8
LB
731 if ((ret = jpeg2000_decode_packet(s,
732 codsty, rlevel,
733 precno, layno,
734 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
735 qntsty->nguardbits)) < 0)
736 return ret;
c81a7063
NB
737 }
738 }
739 }
740 }
741 break;
742
743 case JPEG2000_PGOD_CPRL:
744 for (compno = 0; compno < s->ncomponents; compno++) {
745 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
746 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
747
748 /* Set bit stream buffer address according to tile-part.
749 * For DCinema one tile-part per component, so can be
750 * indexed by component. */
1a3598aa 751 s->g = tile->tile_part[compno].tpg;
c81a7063
NB
752
753 /* Position loop (y axis)
754 * TODO: Automate computing of step 256.
755 * Fixed here, but to be computed before entering here. */
756 for (y = 0; y < s->height; y += 256) {
757 /* Position loop (y axis)
758 * TODO: automate computing of step 256.
759 * Fixed here, but to be computed before entering here. */
760 for (x = 0; x < s->width; x += 256) {
761 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
762 uint16_t prcx, prcy;
763 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
764 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
765
766 if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
767 (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
768 continue;
769
770 if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
771 (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
772 continue;
773
774 // check if a precinct exists
775 prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
776 prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
777 precno = prcx + rlevel->num_precincts_x * prcy;
778 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
5efadcb8
LB
779 if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
780 precno, layno,
781 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
782 qntsty->nguardbits)) < 0)
783 return ret;
c81a7063
NB
784 }
785 }
786 }
787 }
788 }
789 break;
790
791 default:
792 break;
793 }
794
795 /* EOC marker reached */
1a3598aa 796 bytestream2_skip(&s->g, 2);
c81a7063
NB
797
798 return 0;
799}
800
801/* TIER-1 routines */
802static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
803 int bpno, int bandno)
804{
805 int mask = 3 << (bpno - 1), y0, x, y;
806
807 for (y0 = 0; y0 < height; y0 += 4)
808 for (x = 0; x < width; x++)
809 for (y = y0; y < height && y < y0 + 4; y++)
810 if ((t1->flags[y + 1][x + 1] & JPEG2000_T1_SIG_NB)
811 && !(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
812 if (ff_mqc_decode(&t1->mqc,
813 t1->mqc.cx_states +
814 ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
815 bandno))) {
816 int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
817 &xorbit);
818
819 t1->data[y][x] =
820 (ff_mqc_decode(&t1->mqc,
821 t1->mqc.cx_states + ctxno) ^ xorbit)
822 ? -mask : mask;
823
824 ff_jpeg2000_set_significance(t1, x, y,
825 t1->data[y][x] < 0);
826 }
827 t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
828 }
829}
830
831static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
832 int bpno)
833{
834 int phalf, nhalf;
835 int y0, x, y;
836
837 phalf = 1 << (bpno - 1);
838 nhalf = -phalf;
839
840 for (y0 = 0; y0 < height; y0 += 4)
841 for (x = 0; x < width; x++)
842 for (y = y0; y < height && y < y0 + 4; y++)
843 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
844 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
845 int r = ff_mqc_decode(&t1->mqc,
846 t1->mqc.cx_states + ctxno)
847 ? phalf : nhalf;
848 t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
849 t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
850 }
851}
852
853static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
854 int width, int height, int bpno, int bandno,
855 int seg_symbols)
856{
857 int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
858
859 for (y0 = 0; y0 < height; y0 += 4)
860 for (x = 0; x < width; x++) {
861 if (y0 + 3 < height &&
862 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
863 (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
864 (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
865 (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
866 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
867 continue;
868 runlen = ff_mqc_decode(&t1->mqc,
869 t1->mqc.cx_states + MQC_CX_UNI);
870 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
871 t1->mqc.cx_states +
872 MQC_CX_UNI);
873 dec = 1;
874 } else {
875 runlen = 0;
876 dec = 0;
877 }
878
879 for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
880 if (!dec) {
881 if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))
882 dec = ff_mqc_decode(&t1->mqc,
883 t1->mqc.cx_states +
884 ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
885 bandno));
886 }
887 if (dec) {
888 int xorbit;
889 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
890 &xorbit);
891 t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
892 t1->mqc.cx_states + ctxno) ^
893 xorbit)
894 ? -mask : mask;
895 ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
896 }
897 dec = 0;
898 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
899 }
900 }
901 if (seg_symbols) {
902 int val;
903 val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
904 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
905 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
906 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
907 if (val != 0xa)
908 av_log(s->avctx, AV_LOG_ERROR,
909 "Segmentation symbol value incorrect\n");
910 }
911}
912
913static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
914 Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
915 int width, int height, int bandpos)
916{
917 int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
918
c81a7063
NB
919 for (y = 0; y < height; y++)
920 memset(t1->data[y], 0, width * sizeof(width));
28816f9d
NB
921 /* If code-block contains no compressed data: nothing to do. */
922 if (!cblk->length)
923 return 0;
924 for (y = 0; y < height + 2; y++)
925 memset(t1->flags[y], 0, (width + 2) * sizeof(width));
c81a7063
NB
926
927 ff_mqc_initdec(&t1->mqc, cblk->data);
928 cblk->data[cblk->length] = 0xff;
929 cblk->data[cblk->length + 1] = 0xff;
930
931 while (passno--) {
932 switch (pass_t) {
933 case 0:
934 decode_sigpass(t1, width, height, bpno + 1, bandpos);
935 break;
936 case 1:
937 decode_refpass(t1, width, height, bpno + 1);
938 break;
939 case 2:
940 decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
941 codsty->cblk_style & JPEG2000_CBLK_SEGSYM);
942 break;
943 }
944
945 pass_t++;
946 if (pass_t == 3) {
947 bpno--;
948 pass_t = 0;
949 }
950 }
951 return 0;
952}
953
954/* TODO: Verify dequantization for lossless case
955 * comp->data can be float or int
956 * band->stepsize can be float or int
957 * depending on the type of DWT transformation.
958 * see ISO/IEC 15444-1:2002 A.6.1 */
959
960/* Float dequantization of a codeblock.*/
961static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
962 Jpeg2000Component *comp,
963 Jpeg2000T1Context *t1, Jpeg2000Band *band)
964{
965 int i, j, idx;
966 float *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
967 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
968 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
969 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
970 datap[idx] = (float)(t1->data[j][i]) * ((float)band->stepsize);
971 }
972 return;
973}
974
975/* Integer dequantization of a codeblock.*/
976static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
977 Jpeg2000Component *comp,
978 Jpeg2000T1Context *t1, Jpeg2000Band *band)
979{
980 int i, j, idx;
981 int32_t *datap =
982 (int32_t *) &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
983 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
984 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
985 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
986 datap[idx] =
987 ((int32_t)(t1->data[j][i]) * ((int32_t)band->stepsize) + (1 << 15)) >> 16;
988 }
989 return;
990}
991
992/* Inverse ICT parameters in float and integer.
993 * int value = (float value) * (1<<16) */
994static const float f_ict_params[4] = {
995 1.402f,
996 0.34413f,
997 0.71414f,
998 1.772f
999};
1000static const int i_ict_params[4] = {
1001 91881,
1002 22553,
1003 46802,
1004 116130
1005};
1006
1007static int mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1008{
1009 int i, csize = 1;
1010 int ret = 0;
1011 int32_t *src[3], i0, i1, i2;
1012 float *srcf[3], i0f, i1f, i2f;
1013
1014 for (i = 0; i < 3; i++)
1015 if (tile->codsty[0].transform == FF_DWT97)
1016 srcf[i] = tile->comp[i].data;
1017 else
1018 src[i] = (int32_t *)tile->comp[i].data;
1019
1020 for (i = 0; i < 2; i++)
1021 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1022 switch (tile->codsty[0].transform) {
1023 case FF_DWT97:
1024 for (i = 0; i < csize; i++) {
1025 i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
1026 i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
1027 - (f_ict_params[2] * *srcf[2]);
1028 i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
1029 *srcf[0]++ = i0f;
1030 *srcf[1]++ = i1f;
1031 *srcf[2]++ = i2f;
1032 }
1033 break;
1034 case FF_DWT97_INT:
1035 for (i = 0; i < csize; i++) {
1036 i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
1037 i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
1038 - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
1039 i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
1040 *src[0]++ = i0;
1041 *src[1]++ = i1;
1042 *src[2]++ = i2;
1043 }
1044 break;
1045 case FF_DWT53:
1046 for (i = 0; i < csize; i++) {
1047 i1 = *src[0] - (*src[2] + *src[1] >> 2);
1048 i0 = i1 + *src[2];
1049 i2 = i1 + *src[1];
1050 *src[0]++ = i0;
1051 *src[1]++ = i1;
1052 *src[2]++ = i2;
1053 }
1054 break;
1055 }
1056 return ret;
1057}
1058
1059static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1060 AVFrame *picture)
1061{
1062 int compno, reslevelno, bandno;
1063 int x, y;
1064
1065 uint8_t *line;
1066 Jpeg2000T1Context t1;
1067 /* Loop on tile components */
1068
1069 for (compno = 0; compno < s->ncomponents; compno++) {
1070 Jpeg2000Component *comp = tile->comp + compno;
1071 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1072 /* Loop on resolution levels */
1073 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1074 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1075 /* Loop on bands */
1076 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1077 uint16_t nb_precincts, precno;
1078 Jpeg2000Band *band = rlevel->band + bandno;
1079 int cblkno = 0, bandpos;
1080 bandpos = bandno + (reslevelno > 0);
1081
1082 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1083 /* Loop on precincts */
1084 for (precno = 0; precno < nb_precincts; precno++) {
1085 Jpeg2000Prec *prec = band->prec + precno;
1086
1087 /* Loop on codeblocks */
1088 for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1089 int x, y;
1090 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1091 decode_cblk(s, codsty, &t1, cblk,
1092 cblk->coord[0][1] - cblk->coord[0][0],
1093 cblk->coord[1][1] - cblk->coord[1][0],
1094 bandpos);
1095
1096 /* Manage band offsets */
1097 x = cblk->coord[0][0];
1098 y = cblk->coord[1][0];
1099 if ((reslevelno > 0) && ((bandno + 1) & 1)) {
1100 Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1101 x += pres->coord[0][1] - pres->coord[0][0];
1102 }
1103 if ((reslevelno > 0) && ((bandno + 1) & 2)) {
1104 Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1105 y += pres->coord[1][1] - pres->coord[1][0];
1106 }
1107
1108 if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1109 dequantization_int(x, y, cblk, comp, &t1, band);
1110 else
1111 dequantization_float(x, y, cblk, comp, &t1, band);
1112 } /* end cblk */
1113 } /*end prec */
1114 } /* end band */
1115 } /* end reslevel */
1116
1117 /* inverse DWT */
1118 ff_dwt_decode(&comp->dwt, comp->data);
1119 } /*end comp */
1120
1121 /* inverse MCT transformation */
1122 if (tile->codsty[0].mct)
1123 mct_decode(s, tile);
1124
7c57a582 1125 if (s->avctx->pix_fmt == AV_PIX_FMT_BGRA) // RGBA -> BGRA
c81a7063
NB
1126 FFSWAP(float *, tile->comp[0].data, tile->comp[2].data);
1127
1128 if (s->precision <= 8) {
1129 for (compno = 0; compno < s->ncomponents; compno++) {
1130 Jpeg2000Component *comp = tile->comp + compno;
1131 int32_t *datap = (int32_t *)comp->data;
1132 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1133 line = picture->data[0] + y * picture->linesize[0];
1134 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1135 uint8_t *dst;
1136
1137 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1138 dst = line + x * s->ncomponents + compno;
1139
1140 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
1141 *datap += 1 << (s->cbps[compno] - 1);
1142 if (*datap < 0)
1143 *datap = 0;
1144 else if (*datap >= (1 << s->cbps[compno]))
1145 *datap = (1 << s->cbps[compno]) - 1;
1146 *dst = *datap++;
1147 dst += s->ncomponents;
1148 }
1149 line += picture->linesize[0];
1150 }
1151 }
1152 } else {
1153 for (compno = 0; compno < s->ncomponents; compno++) {
1154 Jpeg2000Component *comp = tile->comp + compno;
1155 float *datap = comp->data;
1156 int32_t *i_datap = (int32_t *) comp->data;
1157 uint16_t *linel;
1158
1159 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1160 linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
1161 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1162 uint16_t *dst;
1163 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1164 dst = linel + (x * s->ncomponents + compno);
1165 for (; x < s->avctx->width; x += s->cdx[compno]) {
1166 int16_t val;
1167 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1168 if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1169 val = *i_datap + (1 << (s->cbps[compno] - 1));
1170 else
1171 val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
1172 val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
1173 /* align 12 bit values in little-endian mode */
1174 *dst = val << 4;
1175 datap++;
1176 i_datap++;
1177 dst += s->ncomponents;
1178 }
1179 linel += picture->linesize[0] >> 1;
1180 }
1181 }
1182 }
1183 return 0;
1184}
1185
1186static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1187{
1188 int tileno, compno;
1189 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1190 for (compno = 0; compno < s->ncomponents; compno++) {
1191 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1192 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1193
1194 ff_jpeg2000_cleanup(comp, codsty);
1195 }
1196 av_freep(&s->tile[tileno].comp);
1197 }
1198 av_freep(&s->tile);
1199}
1200
1201static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1202{
1203 Jpeg2000CodingStyle *codsty = s->codsty;
1204 Jpeg2000QuantStyle *qntsty = s->qntsty;
1205 uint8_t *properties = s->properties;
1206
1207 for (;;) {
1208 int len, ret = 0;
1209 uint16_t marker;
1a3598aa 1210 int oldpos;
c81a7063 1211
1a3598aa 1212 if (bytestream2_get_bytes_left(&s->g) < 2) {
c81a7063
NB
1213 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1214 break;
1215 }
1216
1a3598aa
MN
1217 marker = bytestream2_get_be16u(&s->g);
1218 oldpos = bytestream2_tell(&s->g);
c81a7063
NB
1219
1220 if (marker == JPEG2000_EOC)
1221 break;
1222
1a3598aa 1223 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 1224 return AVERROR_INVALIDDATA;
1a3598aa 1225 len = bytestream2_get_be16u(&s->g);
c81a7063
NB
1226 switch (marker) {
1227 case JPEG2000_SIZ:
1228 ret = get_siz(s);
1229 break;
1230 case JPEG2000_COC:
1231 ret = get_coc(s, codsty, properties);
1232 break;
1233 case JPEG2000_COD:
1234 ret = get_cod(s, codsty, properties);
1235 break;
1236 case JPEG2000_QCC:
1237 ret = get_qcc(s, len, qntsty, properties);
1238 break;
1239 case JPEG2000_QCD:
1240 ret = get_qcd(s, len, qntsty, properties);
1241 break;
1242 case JPEG2000_SOT:
1243 ret = get_sot(s, len);
1244 break;
1245 case JPEG2000_COM:
1246 // the comment is ignored
1a3598aa 1247 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1248 break;
1249 case JPEG2000_TLM:
1250 // Tile-part lengths
1251 ret = get_tlm(s, len);
1252 break;
1253 default:
1254 av_log(s->avctx, AV_LOG_ERROR,
1a3598aa
MN
1255 "unsupported marker 0x%.4X at pos 0x%X\n",
1256 marker, bytestream2_tell(&s->g) - 4);
1257 bytestream2_skip(&s->g, len - 2);
c81a7063
NB
1258 break;
1259 }
1a3598aa 1260 if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {
c81a7063
NB
1261 av_log(s->avctx, AV_LOG_ERROR,
1262 "error during processing marker segment %.4x\n", marker);
1263 return ret ? ret : -1;
1264 }
1265 }
1266 return 0;
1267}
1268
1269/* Read bit stream packets --> T2 operation. */
1270static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1271{
1272 int ret = 0;
1273 Jpeg2000Tile *tile = s->tile + s->curtileno;
1274
1275 if (ret = init_tile(s, s->curtileno))
1276 return ret;
1277 if (ret = jpeg2000_decode_packets(s, tile))
1278 return ret;
1279
1280 return 0;
1281}
1282
1283static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1284{
1a3598aa 1285 uint32_t atom_size, atom;
c81a7063
NB
1286 int found_codestream = 0, search_range = 10;
1287
1a3598aa
MN
1288 while(!found_codestream && search_range
1289 &&
1290 bytestream2_get_bytes_left(&s->g) >= 8) {
1291 atom_size = bytestream2_get_be32u(&s->g);
1292 atom = bytestream2_get_be32u(&s->g);
1293 if (atom == JP2_CODESTREAM) {
c81a7063 1294 found_codestream = 1;
c81a7063 1295 } else {
1a3598aa
MN
1296 if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1297 return 0;
1298 bytestream2_skipu(&s->g, atom_size - 8);
c81a7063
NB
1299 search_range--;
1300 }
1301 }
1302
1303 if (found_codestream)
1304 return 1;
1305 return 0;
1306}
1307
1308static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1309 int *got_frame, AVPacket *avpkt)
1310{
1311 Jpeg2000DecoderContext *s = avctx->priv_data;
2e2d2466 1312 ThreadFrame frame = { .f = data };
c81a7063
NB
1313 AVFrame *picture = data;
1314 int tileno, ret;
1315
1316 s->avctx = avctx;
1a3598aa 1317 bytestream2_init(&s->g, avpkt->data, avpkt->size);
c81a7063
NB
1318 s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1319
1320 // reduction factor, i.e number of resolution levels to skip
1321 s->reduction_factor = s->lowres;
1322
1a3598aa 1323 if (bytestream2_get_bytes_left(&s->g) < 2)
5efadcb8 1324 return AVERROR_INVALIDDATA;
c81a7063
NB
1325
1326 // check if the image is in jp2 format
1a3598aa
MN
1327 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1328 (bytestream2_get_be32u(&s->g) == 12) &&
1329 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1330 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
c81a7063
NB
1331 if (!jp2_find_codestream(s)) {
1332 av_log(avctx, AV_LOG_ERROR,
5efadcb8
LB
1333 "Could not find Jpeg2000 codestream atom.\n");
1334 return AVERROR_INVALIDDATA;
c81a7063 1335 }
1a3598aa
MN
1336 } else {
1337 bytestream2_seek(&s->g, 0, SEEK_SET);
1338 if (bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
1339 bytestream2_skip(&s->g, 8);
c81a7063
NB
1340 }
1341
1a3598aa 1342 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
c81a7063 1343 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
5efadcb8 1344 return AVERROR_INVALIDDATA;
c81a7063
NB
1345 }
1346 if (ret = jpeg2000_read_main_headers(s))
45a1694f 1347 goto end;
c81a7063
NB
1348
1349 /* get picture buffer */
2e2d2466
NB
1350 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1351 av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
45a1694f 1352 goto end;
c81a7063
NB
1353 }
1354 picture->pict_type = AV_PICTURE_TYPE_I;
1355 picture->key_frame = 1;
1356
1357 if (ret = jpeg2000_read_bitstream_packets(s))
45a1694f 1358 goto end;
c81a7063
NB
1359 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1360 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
45a1694f 1361 goto end;
c81a7063
NB
1362
1363 *got_frame = 1;
1364
1a3598aa
MN
1365 return bytestream2_tell(&s->g);
1366
45a1694f
JG
1367end:
1368 jpeg2000_dec_cleanup(s);
1a3598aa 1369 return ret;
c81a7063
NB
1370}
1371
70f96615
JG
1372static void jpeg2000_init_static_data(AVCodec *codec)
1373{
1374 ff_jpeg2000_init_tier1_luts();
1375}
1376
c81a7063
NB
1377#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1378#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1379
1380static const AVOption options[] = {
1381 { "lowres", "Lower the decoding resolution by a power of two",
1382 OFFSET(lowres), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1383 { NULL },
1384};
1385
1386static const AVProfile profiles[] = {
1387 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1388 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1389 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1390 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1391 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1392 { FF_PROFILE_UNKNOWN },
1393};
1394
1395static const AVClass class = {
1396 .class_name = "jpeg2000",
1397 .item_name = av_default_item_name,
1398 .option = options,
1399 .version = LIBAVUTIL_VERSION_INT,
1400};
1401
1402AVCodec ff_jpeg2000_decoder = {
70f96615
JG
1403 .name = "jpeg2000",
1404 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1405 .type = AVMEDIA_TYPE_VIDEO,
1406 .id = AV_CODEC_ID_JPEG2000,
1407 .capabilities = CODEC_CAP_FRAME_THREADS,
1408 .priv_data_size = sizeof(Jpeg2000DecoderContext),
1409 .init_static_data = jpeg2000_init_static_data,
1410 .decode = jpeg2000_decode_frame,
1411 .priv_class = &class,
7c57a582
AK
1412 .pix_fmts = (enum AVPixelFormat[]) { AV_PIX_FMT_XYZ12,
1413 AV_PIX_FMT_GRAY8,
1414 -1 },
70f96615 1415 .profiles = NULL_IF_CONFIG_SMALL(profiles)
c81a7063 1416};