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