07ccbe5c8e4d2fd82341fcfd4f8b529b243847bd
[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->f_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]) * band->f_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 = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
1008 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
1009 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
1010 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
1011 datap[idx] =
1012 ((int32_t)(t1->data[j][i]) * band->i_stepsize + (1 << 15)) >> 16;
1013 }
1014 }
1015
1016 /* Inverse ICT parameters in float and integer.
1017 * int value = (float value) * (1<<16) */
1018 static const float f_ict_params[4] = {
1019 1.402f,
1020 0.34413f,
1021 0.71414f,
1022 1.772f
1023 };
1024 static const int i_ict_params[4] = {
1025 91881,
1026 22553,
1027 46802,
1028 116130
1029 };
1030
1031 static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1032 {
1033 int i, csize = 1;
1034 int32_t *src[3], i0, i1, i2;
1035 float *srcf[3], i0f, i1f, i2f;
1036
1037 for (i = 0; i < 3; i++)
1038 if (tile->codsty[0].transform == FF_DWT97)
1039 srcf[i] = tile->comp[i].f_data;
1040 else
1041 src [i] = tile->comp[i].i_data;
1042
1043 for (i = 0; i < 2; i++)
1044 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1045 switch (tile->codsty[0].transform) {
1046 case FF_DWT97:
1047 for (i = 0; i < csize; i++) {
1048 i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
1049 i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
1050 - (f_ict_params[2] * *srcf[2]);
1051 i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
1052 *srcf[0]++ = i0f;
1053 *srcf[1]++ = i1f;
1054 *srcf[2]++ = i2f;
1055 }
1056 break;
1057 case FF_DWT97_INT:
1058 for (i = 0; i < csize; i++) {
1059 i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
1060 i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
1061 - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
1062 i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
1063 *src[0]++ = i0;
1064 *src[1]++ = i1;
1065 *src[2]++ = i2;
1066 }
1067 break;
1068 case FF_DWT53:
1069 for (i = 0; i < csize; i++) {
1070 i1 = *src[0] - (*src[2] + *src[1] >> 2);
1071 i0 = i1 + *src[2];
1072 i2 = i1 + *src[1];
1073 *src[0]++ = i0;
1074 *src[1]++ = i1;
1075 *src[2]++ = i2;
1076 }
1077 break;
1078 }
1079 }
1080
1081 static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1082 AVFrame *picture)
1083 {
1084 int compno, reslevelno, bandno;
1085 int x, y;
1086
1087 uint8_t *line;
1088 Jpeg2000T1Context t1;
1089 /* Loop on tile components */
1090
1091 for (compno = 0; compno < s->ncomponents; compno++) {
1092 Jpeg2000Component *comp = tile->comp + compno;
1093 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1094 /* Loop on resolution levels */
1095 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1096 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1097 /* Loop on bands */
1098 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1099 uint16_t nb_precincts, precno;
1100 Jpeg2000Band *band = rlevel->band + bandno;
1101 int cblkno = 0, bandpos;
1102 bandpos = bandno + (reslevelno > 0);
1103
1104 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1105 /* Loop on precincts */
1106 for (precno = 0; precno < nb_precincts; precno++) {
1107 Jpeg2000Prec *prec = band->prec + precno;
1108
1109 /* Loop on codeblocks */
1110 for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1111 int x, y;
1112 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1113 decode_cblk(s, codsty, &t1, cblk,
1114 cblk->coord[0][1] - cblk->coord[0][0],
1115 cblk->coord[1][1] - cblk->coord[1][0],
1116 bandpos);
1117
1118 x = cblk->coord[0][0];
1119 y = cblk->coord[1][0];
1120
1121 if (codsty->transform == FF_DWT97)
1122 dequantization_float(x, y, cblk, comp, &t1, band);
1123 else
1124 dequantization_int(x, y, cblk, comp, &t1, band);
1125 } /* end cblk */
1126 } /*end prec */
1127 } /* end band */
1128 } /* end reslevel */
1129
1130 /* inverse DWT */
1131 ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
1132 } /*end comp */
1133
1134 /* inverse MCT transformation */
1135 if (tile->codsty[0].mct)
1136 mct_decode(s, tile);
1137
1138 if (s->avctx->pix_fmt == AV_PIX_FMT_BGRA) { // RGBA -> BGRA
1139 FFSWAP(float *, tile->comp[0].f_data, tile->comp[2].f_data);
1140 FFSWAP(int *, tile->comp[0].i_data, tile->comp[2].i_data);
1141 }
1142
1143 if (s->precision <= 8) {
1144 for (compno = 0; compno < s->ncomponents; compno++) {
1145 Jpeg2000Component *comp = tile->comp + compno;
1146 float *datap = comp->f_data;
1147 int32_t *i_datap = comp->i_data;
1148 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1149 line = picture->data[0] + y * picture->linesize[0];
1150 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1151 uint8_t *dst;
1152
1153 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1154 dst = line + x * s->ncomponents + compno;
1155
1156 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
1157 int val;
1158 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1159 if (tile->codsty->transform == FF_DWT97)
1160 val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
1161 else
1162 val = *i_datap + (1 << (s->cbps[compno] - 1));
1163 val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
1164 *dst = val << (8 - s->cbps[compno]);
1165 datap++;
1166 i_datap++;
1167 dst += s->ncomponents;
1168 }
1169 line += picture->linesize[0];
1170 }
1171 }
1172 } else {
1173 for (compno = 0; compno < s->ncomponents; compno++) {
1174 Jpeg2000Component *comp = tile->comp + compno;
1175 float *datap = comp->f_data;
1176 int32_t *i_datap = comp->i_data;
1177 uint16_t *linel;
1178
1179 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1180 linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
1181 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1182 uint16_t *dst;
1183 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1184 dst = linel + (x * s->ncomponents + compno);
1185 for (; x < s->avctx->width; x += s->cdx[compno]) {
1186 int val;
1187 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1188 if (tile->codsty->transform == FF_DWT97)
1189 val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
1190 else
1191 val = *i_datap + (1 << (s->cbps[compno] - 1));
1192 val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
1193 /* align 12 bit values in little-endian mode */
1194 *dst = val << (16 - s->cbps[compno]);
1195 datap++;
1196 i_datap++;
1197 dst += s->ncomponents;
1198 }
1199 linel += picture->linesize[0] >> 1;
1200 }
1201 }
1202 }
1203 return 0;
1204 }
1205
1206 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1207 {
1208 int tileno, compno;
1209 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1210 for (compno = 0; compno < s->ncomponents; compno++) {
1211 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1212 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1213
1214 ff_jpeg2000_cleanup(comp, codsty);
1215 }
1216 av_freep(&s->tile[tileno].comp);
1217 }
1218 av_freep(&s->tile);
1219 }
1220
1221 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1222 {
1223 Jpeg2000CodingStyle *codsty = s->codsty;
1224 Jpeg2000QuantStyle *qntsty = s->qntsty;
1225 uint8_t *properties = s->properties;
1226
1227 for (;;) {
1228 int len, ret = 0;
1229 uint16_t marker;
1230 int oldpos;
1231
1232 if (bytestream2_get_bytes_left(&s->g) < 2) {
1233 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1234 break;
1235 }
1236
1237 marker = bytestream2_get_be16u(&s->g);
1238 oldpos = bytestream2_tell(&s->g);
1239
1240 if (marker == JPEG2000_SOD) {
1241 Jpeg2000Tile *tile;
1242 Jpeg2000TilePart *tp;
1243
1244 if (s->curtileno < 0) {
1245 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
1246 return AVERROR_INVALIDDATA;
1247 }
1248
1249 tile = s->tile + s->curtileno;
1250 tp = tile->tile_part + tile->tp_idx;
1251 bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
1252 bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
1253
1254 continue;
1255 }
1256 if (marker == JPEG2000_EOC)
1257 break;
1258
1259 len = bytestream2_get_be16u(&s->g);
1260 if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
1261 return AVERROR_INVALIDDATA;
1262
1263 switch (marker) {
1264 case JPEG2000_SIZ:
1265 ret = get_siz(s);
1266 break;
1267 case JPEG2000_COC:
1268 ret = get_coc(s, codsty, properties);
1269 break;
1270 case JPEG2000_COD:
1271 ret = get_cod(s, codsty, properties);
1272 break;
1273 case JPEG2000_QCC:
1274 ret = get_qcc(s, len, qntsty, properties);
1275 break;
1276 case JPEG2000_QCD:
1277 ret = get_qcd(s, len, qntsty, properties);
1278 break;
1279 case JPEG2000_SOT:
1280 ret = get_sot(s, len);
1281 break;
1282 case JPEG2000_COM:
1283 // the comment is ignored
1284 bytestream2_skip(&s->g, len - 2);
1285 break;
1286 case JPEG2000_TLM:
1287 // Tile-part lengths
1288 ret = get_tlm(s, len);
1289 break;
1290 default:
1291 av_log(s->avctx, AV_LOG_ERROR,
1292 "unsupported marker 0x%.4X at pos 0x%X\n",
1293 marker, bytestream2_tell(&s->g) - 4);
1294 bytestream2_skip(&s->g, len - 2);
1295 break;
1296 }
1297 if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {
1298 av_log(s->avctx, AV_LOG_ERROR,
1299 "error during processing marker segment %.4x\n", marker);
1300 return ret ? ret : -1;
1301 }
1302 }
1303 return 0;
1304 }
1305
1306 /* Read bit stream packets --> T2 operation. */
1307 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1308 {
1309 int ret = 0;
1310 Jpeg2000Tile *tile = s->tile + s->curtileno;
1311
1312 if (ret = init_tile(s, s->curtileno))
1313 return ret;
1314 if (ret = jpeg2000_decode_packets(s, tile))
1315 return ret;
1316
1317 return 0;
1318 }
1319
1320 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1321 {
1322 uint32_t atom_size, atom;
1323 int found_codestream = 0, search_range = 10;
1324
1325 while(!found_codestream && search_range
1326 &&
1327 bytestream2_get_bytes_left(&s->g) >= 8) {
1328 atom_size = bytestream2_get_be32u(&s->g);
1329 atom = bytestream2_get_be32u(&s->g);
1330 if (atom == JP2_CODESTREAM) {
1331 found_codestream = 1;
1332 } else {
1333 if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1334 return 0;
1335 bytestream2_skipu(&s->g, atom_size - 8);
1336 search_range--;
1337 }
1338 }
1339
1340 if (found_codestream)
1341 return 1;
1342 return 0;
1343 }
1344
1345 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1346 int *got_frame, AVPacket *avpkt)
1347 {
1348 Jpeg2000DecoderContext *s = avctx->priv_data;
1349 ThreadFrame frame = { .f = data };
1350 AVFrame *picture = data;
1351 int tileno, ret;
1352
1353 s->avctx = avctx;
1354 bytestream2_init(&s->g, avpkt->data, avpkt->size);
1355 s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1356
1357 if (bytestream2_get_bytes_left(&s->g) < 2)
1358 return AVERROR_INVALIDDATA;
1359
1360 // check if the image is in jp2 format
1361 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1362 (bytestream2_get_be32u(&s->g) == 12) &&
1363 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1364 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
1365 if (!jp2_find_codestream(s)) {
1366 av_log(avctx, AV_LOG_ERROR,
1367 "Could not find Jpeg2000 codestream atom.\n");
1368 return AVERROR_INVALIDDATA;
1369 }
1370 } else {
1371 bytestream2_seek(&s->g, 0, SEEK_SET);
1372 if (bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
1373 bytestream2_skip(&s->g, 8);
1374 }
1375
1376 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1377 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1378 return AVERROR_INVALIDDATA;
1379 }
1380 if (ret = jpeg2000_read_main_headers(s))
1381 goto end;
1382
1383 /* get picture buffer */
1384 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1385 av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
1386 goto end;
1387 }
1388 picture->pict_type = AV_PICTURE_TYPE_I;
1389 picture->key_frame = 1;
1390
1391 if (ret = jpeg2000_read_bitstream_packets(s))
1392 goto end;
1393 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1394 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
1395 goto end;
1396
1397 *got_frame = 1;
1398
1399 return bytestream2_tell(&s->g);
1400
1401 end:
1402 jpeg2000_dec_cleanup(s);
1403 return ret;
1404 }
1405
1406 static void jpeg2000_init_static_data(AVCodec *codec)
1407 {
1408 ff_jpeg2000_init_tier1_luts();
1409 }
1410
1411 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1412 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1413
1414 static const AVOption options[] = {
1415 { "lowres", "Lower the decoding resolution by a power of two",
1416 OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1417 { NULL },
1418 };
1419
1420 static const AVProfile profiles[] = {
1421 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1422 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1423 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1424 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1425 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1426 { FF_PROFILE_UNKNOWN },
1427 };
1428
1429 static const AVClass class = {
1430 .class_name = "jpeg2000",
1431 .item_name = av_default_item_name,
1432 .option = options,
1433 .version = LIBAVUTIL_VERSION_INT,
1434 };
1435
1436 AVCodec ff_jpeg2000_decoder = {
1437 .name = "jpeg2000",
1438 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1439 .type = AVMEDIA_TYPE_VIDEO,
1440 .id = AV_CODEC_ID_JPEG2000,
1441 .capabilities = CODEC_CAP_FRAME_THREADS,
1442 .priv_data_size = sizeof(Jpeg2000DecoderContext),
1443 .init_static_data = jpeg2000_init_static_data,
1444 .decode = jpeg2000_decode_frame,
1445 .priv_class = &class,
1446 .pix_fmts = (enum AVPixelFormat[]) { AV_PIX_FMT_XYZ12,
1447 AV_PIX_FMT_GRAY8,
1448 -1 },
1449 .profiles = NULL_IF_CONFIG_SMALL(profiles)
1450 };