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