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