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