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