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