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