2 * JPEG 2000 image decoder
3 * Copyright (c) 2007 Kamil Nowosad
4 * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
6 * This file is part of FFmpeg.
8 * FFmpeg 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.
13 * FFmpeg 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.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * JPEG 2000 image decoder
30 #include "libavutil/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/common.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
36 #include "bytestream.h"
40 #include "jpeg2000dsp.h"
42 #define JP2_SIG_TYPE 0x6A502020
43 #define JP2_SIG_VALUE 0x0D0A870A
44 #define JP2_CODESTREAM 0x6A703263
45 #define JP2_HEADER 0x6A703268
50 typedef struct Jpeg2000TilePart {
51 uint8_t tile_index; // Tile index who refers the tile-part
52 const uint8_t *tp_end;
53 GetByteContext tpg; // bit stream in tile-part
56 /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
57 * one per component, so tile_part elements have a size of 3 */
58 typedef struct Jpeg2000Tile {
59 Jpeg2000Component *comp;
60 uint8_t properties[4];
61 Jpeg2000CodingStyle codsty[4];
62 Jpeg2000QuantStyle qntsty[4];
63 Jpeg2000TilePart tile_part[256];
64 uint16_t tp_idx; // Tile-part index
65 int coord[2][2]; // border coordinates {{x0, x1}, {y0, y1}}
68 typedef struct Jpeg2000DecoderContext {
70 AVCodecContext *avctx;
74 int image_offset_x, image_offset_y;
75 int tile_offset_x, tile_offset_y;
76 uint8_t cbps[4]; // bits per sample in particular components
77 uint8_t sgnd[4]; // if a component is signed
78 uint8_t properties[4];
83 uint32_t palette[256];
86 int tile_width, tile_height;
87 unsigned numXtiles, numYtiles;
90 Jpeg2000CodingStyle codsty[4];
91 Jpeg2000QuantStyle qntsty[4];
98 Jpeg2000DSPContext dsp;
100 /*options parameters*/
101 int reduction_factor;
102 } Jpeg2000DecoderContext;
104 /* get_bits functions for JPEG2000 packet bitstream
105 * It is a get_bit function with a bit-stuffing routine. If the value of the
106 * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
107 * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
108 static int get_bits(Jpeg2000DecoderContext *s, int n)
114 if (s->bit_index == 0) {
115 s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
118 res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
123 static void jpeg2000_flush(Jpeg2000DecoderContext *s)
125 if (bytestream2_get_byte(&s->g) == 0xff)
126 bytestream2_skip(&s->g, 1);
130 /* decode the value stored in node */
131 static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
134 Jpeg2000TgtNode *stack[30];
135 int sp = -1, curval = 0;
138 av_log(s->avctx, AV_LOG_ERROR, "missing node\n");
139 return AVERROR_INVALIDDATA;
142 while (node && !node->vis) {
150 curval = stack[sp]->val;
152 while (curval < threshold && sp >= 0) {
153 if (curval < stack[sp]->val)
154 curval = stack[sp]->val;
155 while (curval < threshold) {
157 if ((ret = get_bits(s, 1)) > 0) {
165 stack[sp]->val = curval;
171 static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
172 int bpc, uint32_t log2_chroma_wh, int pal8)
175 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
179 if (desc->nb_components != components) {
183 switch (components) {
185 match = match && desc->comp[3].depth_minus1 + 1 >= bpc &&
186 (log2_chroma_wh >> 14 & 3) == 0 &&
187 (log2_chroma_wh >> 12 & 3) == 0;
189 match = match && desc->comp[2].depth_minus1 + 1 >= bpc &&
190 (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
191 (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h;
193 match = match && desc->comp[1].depth_minus1 + 1 >= bpc &&
194 (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w &&
195 (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h;
198 match = match && desc->comp[0].depth_minus1 + 1 >= bpc &&
199 (log2_chroma_wh >> 2 & 3) == 0 &&
200 (log2_chroma_wh & 3) == 0 &&
201 (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
206 // pix_fmts with lower bpp have to be listed before
207 // similar pix_fmts with higher bpp.
208 #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
209 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16,AV_PIX_FMT_YA16
210 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
211 AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
212 AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
213 AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
214 AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
215 AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
216 AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
217 AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
218 AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
219 AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
220 AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
221 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12
223 static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS};
224 static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
225 static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS};
226 static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS,
228 static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS,
233 /* marker segments */
234 /* get sizes and offsets of image, tiles; number of components */
235 static int get_siz(Jpeg2000DecoderContext *s)
239 uint32_t log2_chroma_wh = 0;
240 const enum AVPixelFormat *possible_fmts = NULL;
241 int possible_fmts_nb = 0;
243 if (bytestream2_get_bytes_left(&s->g) < 36) {
244 av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for SIZ\n");
245 return AVERROR_INVALIDDATA;
248 s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
249 s->width = bytestream2_get_be32u(&s->g); // Width
250 s->height = bytestream2_get_be32u(&s->g); // Height
251 s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
252 s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
253 s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
254 s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
255 s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
256 s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
257 ncomponents = bytestream2_get_be16u(&s->g); // CSiz
259 if (s->image_offset_x || s->image_offset_y) {
260 avpriv_request_sample(s->avctx, "Support for image offsets");
261 return AVERROR_PATCHWELCOME;
264 if (ncomponents <= 0) {
265 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
267 return AVERROR_INVALIDDATA;
270 if (ncomponents > 4) {
271 avpriv_request_sample(s->avctx, "Support for %d components",
273 return AVERROR_PATCHWELCOME;
276 s->ncomponents = ncomponents;
278 if (s->tile_width <= 0 || s->tile_height <= 0) {
279 av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
280 s->tile_width, s->tile_height);
281 return AVERROR_INVALIDDATA;
284 if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) {
285 av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for %d components in SIZ\n", s->ncomponents);
286 return AVERROR_INVALIDDATA;
289 for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
290 uint8_t x = bytestream2_get_byteu(&s->g);
291 s->cbps[i] = (x & 0x7f) + 1;
292 s->precision = FFMAX(s->cbps[i], s->precision);
293 s->sgnd[i] = !!(x & 0x80);
294 s->cdx[i] = bytestream2_get_byteu(&s->g);
295 s->cdy[i] = bytestream2_get_byteu(&s->g);
296 if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
297 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
298 av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
299 return AVERROR_INVALIDDATA;
301 log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
304 s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
305 s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
307 if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
308 s->numXtiles = s->numYtiles = 0;
309 return AVERROR(EINVAL);
312 s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
314 s->numXtiles = s->numYtiles = 0;
315 return AVERROR(ENOMEM);
318 for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
319 Jpeg2000Tile *tile = s->tile + i;
321 tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
323 return AVERROR(ENOMEM);
326 /* compute image size with reduction factor */
327 s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
328 s->reduction_factor);
329 s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
330 s->reduction_factor);
332 if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
333 s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
334 possible_fmts = xyz_pix_fmts;
335 possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
337 switch (s->colour_space) {
339 possible_fmts = rgb_pix_fmts;
340 possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
343 possible_fmts = gray_pix_fmts;
344 possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
347 possible_fmts = yuv_pix_fmts;
348 possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
351 possible_fmts = all_pix_fmts;
352 possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
356 for (i = 0; i < possible_fmts_nb; ++i) {
357 if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
358 s->avctx->pix_fmt = possible_fmts[i];
363 if (i == possible_fmts_nb) {
364 if (ncomponents == 4 &&
365 s->cdy[0] == 1 && s->cdx[0] == 1 &&
366 s->cdy[1] == 1 && s->cdx[1] == 1 &&
367 s->cdy[2] == s->cdy[3] && s->cdx[2] == s->cdx[3]) {
368 if (s->precision == 8 && s->cdy[2] == 2 && s->cdx[2] == 2 && !s->pal8) {
369 s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
380 if (i == possible_fmts_nb) {
381 av_log(s->avctx, AV_LOG_ERROR,
382 "Unknown pix_fmt, profile: %d, colour_space: %d, "
383 "components: %d, precision: %d\n"
384 "cdx[0]: %d, cdy[0]: %d\n"
385 "cdx[1]: %d, cdy[1]: %d\n"
386 "cdx[2]: %d, cdy[2]: %d\n"
387 "cdx[3]: %d, cdy[3]: %d\n",
388 s->avctx->profile, s->colour_space, ncomponents, s->precision,
391 ncomponents > 1 ? s->cdx[1] : 0,
392 ncomponents > 1 ? s->cdy[1] : 0,
393 ncomponents > 2 ? s->cdx[2] : 0,
394 ncomponents > 2 ? s->cdy[2] : 0,
395 ncomponents > 3 ? s->cdx[3] : 0,
396 ncomponents > 3 ? s->cdy[3] : 0);
397 return AVERROR_PATCHWELCOME;
399 s->avctx->bits_per_raw_sample = s->precision;
403 /* get common part for COD and COC segments */
404 static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
408 if (bytestream2_get_bytes_left(&s->g) < 5) {
409 av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COX\n");
410 return AVERROR_INVALIDDATA;
413 /* nreslevels = number of resolution levels
414 = number of decomposition level +1 */
415 c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
416 if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
417 av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
418 return AVERROR_INVALIDDATA;
421 if (c->nreslevels <= s->reduction_factor) {
422 /* we are forced to update reduction_factor as its requested value is
423 not compatible with this bitstream, and as we might have used it
424 already in setup earlier we have to fail this frame until
425 reinitialization is implemented */
426 av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1);
427 s->reduction_factor = c->nreslevels - 1;
428 return AVERROR(EINVAL);
431 /* compute number of resolution levels to decode */
432 c->nreslevels2decode = c->nreslevels - s->reduction_factor;
434 c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
435 c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
437 if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
438 c->log2_cblk_width + c->log2_cblk_height > 12) {
439 av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
440 return AVERROR_INVALIDDATA;
443 c->cblk_style = bytestream2_get_byteu(&s->g);
444 if (c->cblk_style != 0) { // cblk style
445 av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
446 if (c->cblk_style & JPEG2000_CBLK_BYPASS)
447 av_log(s->avctx, AV_LOG_WARNING, "Selective arithmetic coding bypass\n");
449 c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
450 /* set integer 9/7 DWT in case of BITEXACT flag */
451 if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
452 c->transform = FF_DWT97_INT;
454 if (c->csty & JPEG2000_CSTY_PREC) {
456 for (i = 0; i < c->nreslevels; i++) {
457 byte = bytestream2_get_byte(&s->g);
458 c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
459 c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
461 if (c->log2_prec_widths[i] == 0 || c->log2_prec_heights[i] == 0) {
462 av_log(s->avctx, AV_LOG_ERROR, "PPx %d PPy %d invalid\n",
463 c->log2_prec_widths[i], c->log2_prec_heights[i]);
464 c->log2_prec_widths[i] = c->log2_prec_heights[i] = 1;
465 return AVERROR_INVALIDDATA;
469 memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
470 memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
475 /* get coding parameters for a particular tile or whole image*/
476 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
479 Jpeg2000CodingStyle tmp;
482 if (bytestream2_get_bytes_left(&s->g) < 5) {
483 av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COD\n");
484 return AVERROR_INVALIDDATA;
487 tmp.csty = bytestream2_get_byteu(&s->g);
489 // get progression order
490 tmp.prog_order = bytestream2_get_byteu(&s->g);
492 tmp.nlayers = bytestream2_get_be16u(&s->g);
493 tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
495 if (tmp.mct && s->ncomponents < 3) {
496 av_log(s->avctx, AV_LOG_ERROR,
497 "MCT %"PRIu8" with too few components (%d)\n",
498 tmp.mct, s->ncomponents);
499 return AVERROR_INVALIDDATA;
502 if ((ret = get_cox(s, &tmp)) < 0)
505 for (compno = 0; compno < s->ncomponents; compno++)
506 if (!(properties[compno] & HAD_COC))
507 memcpy(c + compno, &tmp, sizeof(tmp));
511 /* Get coding parameters for a component in the whole image or a
512 * particular tile. */
513 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
518 if (bytestream2_get_bytes_left(&s->g) < 2) {
519 av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COC\n");
520 return AVERROR_INVALIDDATA;
523 compno = bytestream2_get_byteu(&s->g);
525 if (compno >= s->ncomponents) {
526 av_log(s->avctx, AV_LOG_ERROR,
527 "Invalid compno %d. There are %d components in the image.\n",
528 compno, s->ncomponents);
529 return AVERROR_INVALIDDATA;
533 c->csty = bytestream2_get_byteu(&s->g);
535 if ((ret = get_cox(s, c)) < 0)
538 properties[compno] |= HAD_COC;
542 /* Get common part for QCD and QCC segments. */
543 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
547 if (bytestream2_get_bytes_left(&s->g) < 1)
548 return AVERROR_INVALIDDATA;
550 x = bytestream2_get_byteu(&s->g); // Sqcd
552 q->nguardbits = x >> 5;
553 q->quantsty = x & 0x1f;
555 if (q->quantsty == JPEG2000_QSTY_NONE) {
557 if (bytestream2_get_bytes_left(&s->g) < n ||
558 n > JPEG2000_MAX_DECLEVELS*3)
559 return AVERROR_INVALIDDATA;
560 for (i = 0; i < n; i++)
561 q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
562 } else if (q->quantsty == JPEG2000_QSTY_SI) {
563 if (bytestream2_get_bytes_left(&s->g) < 2)
564 return AVERROR_INVALIDDATA;
565 x = bytestream2_get_be16u(&s->g);
566 q->expn[0] = x >> 11;
567 q->mant[0] = x & 0x7ff;
568 for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
569 int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
570 q->expn[i] = curexpn;
571 q->mant[i] = q->mant[0];
575 if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
576 n > JPEG2000_MAX_DECLEVELS*3)
577 return AVERROR_INVALIDDATA;
578 for (i = 0; i < n; i++) {
579 x = bytestream2_get_be16u(&s->g);
580 q->expn[i] = x >> 11;
581 q->mant[i] = x & 0x7ff;
587 /* Get quantization parameters for a particular tile or a whole image. */
588 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
591 Jpeg2000QuantStyle tmp;
594 memset(&tmp, 0, sizeof(tmp));
596 if ((ret = get_qcx(s, n, &tmp)) < 0)
598 for (compno = 0; compno < s->ncomponents; compno++)
599 if (!(properties[compno] & HAD_QCC))
600 memcpy(q + compno, &tmp, sizeof(tmp));
604 /* Get quantization parameters for a component in the whole image
605 * on in a particular tile. */
606 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
611 if (bytestream2_get_bytes_left(&s->g) < 1)
612 return AVERROR_INVALIDDATA;
614 compno = bytestream2_get_byteu(&s->g);
616 if (compno >= s->ncomponents) {
617 av_log(s->avctx, AV_LOG_ERROR,
618 "Invalid compno %d. There are %d components in the image.\n",
619 compno, s->ncomponents);
620 return AVERROR_INVALIDDATA;
623 properties[compno] |= HAD_QCC;
624 return get_qcx(s, n - 1, q + compno);
627 /* Get start of tile segment. */
628 static int get_sot(Jpeg2000DecoderContext *s, int n)
630 Jpeg2000TilePart *tp;
635 if (bytestream2_get_bytes_left(&s->g) < 8)
636 return AVERROR_INVALIDDATA;
639 Isot = bytestream2_get_be16u(&s->g); // Isot
640 if (Isot >= s->numXtiles * s->numYtiles)
641 return AVERROR_INVALIDDATA;
644 Psot = bytestream2_get_be32u(&s->g); // Psot
645 TPsot = bytestream2_get_byteu(&s->g); // TPsot
647 /* Read TNSot but not used */
648 bytestream2_get_byteu(&s->g); // TNsot
651 Psot = bytestream2_get_bytes_left(&s->g) + n + 2;
653 if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
654 av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);
655 return AVERROR_INVALIDDATA;
658 av_assert0(TPsot < FF_ARRAY_ELEMS(s->tile[Isot].tile_part));
660 s->tile[Isot].tp_idx = TPsot;
661 tp = s->tile[Isot].tile_part + TPsot;
662 tp->tile_index = Isot;
663 tp->tp_end = s->g.buffer + Psot - n - 2;
666 Jpeg2000Tile *tile = s->tile + s->curtileno;
669 memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
670 memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
676 /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
677 * Used to know the number of tile parts and lengths.
678 * There may be multiple TLMs in the header.
679 * TODO: The function is not used for tile-parts management, nor anywhere else.
680 * It can be useful to allocate memory for tile parts, before managing the SOT
681 * markers. Parsing the TLM header is needed to increment the input header
683 * This marker is mandatory for DCI. */
684 static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
686 uint8_t Stlm, ST, SP, tile_tlm, i;
687 bytestream2_get_byte(&s->g); /* Ztlm: skipped */
688 Stlm = bytestream2_get_byte(&s->g);
690 // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
691 ST = (Stlm >> 4) & 0x03;
692 // TODO: Manage case of ST = 0b11 --> raise error
693 SP = (Stlm >> 6) & 0x01;
694 tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
695 for (i = 0; i < tile_tlm; i++) {
700 bytestream2_get_byte(&s->g);
703 bytestream2_get_be16(&s->g);
706 bytestream2_get_be32(&s->g);
710 bytestream2_get_be16(&s->g);
712 bytestream2_get_be32(&s->g);
718 static uint8_t get_plt(Jpeg2000DecoderContext *s, int n)
722 av_log(s->avctx, AV_LOG_DEBUG,
723 "PLT marker at pos 0x%X\n", bytestream2_tell(&s->g) - 4);
725 /*Zplt =*/ bytestream2_get_byte(&s->g);
727 for (i = 0; i < n - 3; i++) {
728 bytestream2_get_byte(&s->g);
734 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
737 int tilex = tileno % s->numXtiles;
738 int tiley = tileno / s->numXtiles;
739 Jpeg2000Tile *tile = s->tile + tileno;
742 return AVERROR(ENOMEM);
744 tile->coord[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
745 tile->coord[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
746 tile->coord[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
747 tile->coord[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
749 for (compno = 0; compno < s->ncomponents; compno++) {
750 Jpeg2000Component *comp = tile->comp + compno;
751 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
752 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
753 int ret; // global bandno
755 comp->coord_o[0][0] = tile->coord[0][0];
756 comp->coord_o[0][1] = tile->coord[0][1];
757 comp->coord_o[1][0] = tile->coord[1][0];
758 comp->coord_o[1][1] = tile->coord[1][1];
760 comp->coord_o[0][0] /= s->cdx[compno];
761 comp->coord_o[0][1] /= s->cdx[compno];
762 comp->coord_o[1][0] /= s->cdy[compno];
763 comp->coord_o[1][1] /= s->cdy[compno];
766 comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
767 comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
768 comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
769 comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
771 if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
772 s->cbps[compno], s->cdx[compno],
773 s->cdy[compno], s->avctx))
779 /* Read the number of coding passes. */
780 static int getnpasses(Jpeg2000DecoderContext *s)
787 if ((num = get_bits(s, 2)) != 3)
788 return num < 0 ? num : 3 + num;
789 if ((num = get_bits(s, 5)) != 31)
790 return num < 0 ? num : 6 + num;
791 num = get_bits(s, 7);
792 return num < 0 ? num : 37 + num;
795 static int getlblockinc(Jpeg2000DecoderContext *s)
798 while (ret = get_bits(s, 1)) {
806 static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index,
807 Jpeg2000CodingStyle *codsty,
808 Jpeg2000ResLevel *rlevel, int precno,
809 int layno, uint8_t *expn, int numgbits)
811 int bandno, cblkno, ret, nb_code_blocks;
814 if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {
815 if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {
816 s->g = tile->tile_part[++(*tp_index)].tpg;
820 if (bytestream2_peek_be32(&s->g) == JPEG2000_SOP_FIXED_BYTES)
821 bytestream2_skip(&s->g, JPEG2000_SOP_BYTE_LENGTH);
823 if (!(ret = get_bits(s, 1))) {
829 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
830 Jpeg2000Band *band = rlevel->band + bandno;
831 Jpeg2000Prec *prec = band->prec + precno;
833 if (band->coord[0][0] == band->coord[0][1] ||
834 band->coord[1][0] == band->coord[1][1])
836 nb_code_blocks = prec->nb_codeblocks_height *
837 prec->nb_codeblocks_width;
838 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
839 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
840 int incl, newpasses, llen;
843 incl = get_bits(s, 1);
845 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
851 if (!cblk->npasses) {
852 int v = expn[bandno] + numgbits - 1 -
853 tag_tree_decode(s, prec->zerobits + cblkno, 100);
855 av_log(s->avctx, AV_LOG_ERROR,
856 "nonzerobits %d invalid\n", v);
857 return AVERROR_INVALIDDATA;
859 cblk->nonzerobits = v;
861 if ((newpasses = getnpasses(s)) < 0)
863 av_assert2(newpasses > 0);
864 if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) {
865 avpriv_request_sample(s->avctx, "Too many passes\n");
866 return AVERROR_PATCHWELCOME;
868 if ((llen = getlblockinc(s)) < 0)
870 if (cblk->lblock + llen + av_log2(newpasses) > 16) {
871 avpriv_request_sample(s->avctx,
872 "Block with length beyond 16 bits\n");
873 return AVERROR_PATCHWELCOME;
876 cblk->lblock += llen;
878 cblk->nb_lengthinc = 0;
879 cblk->nb_terminationsinc = 0;
883 while (newpasses1 < newpasses) {
885 if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) {
886 cblk->nb_terminationsinc ++;
891 if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0)
893 if (ret > sizeof(cblk->data)) {
894 avpriv_request_sample(s->avctx,
895 "Block with lengthinc greater than %"SIZE_SPECIFIER"",
897 return AVERROR_PATCHWELCOME;
899 cblk->lengthinc[cblk->nb_lengthinc++] = ret;
900 cblk->npasses += newpasses1;
901 newpasses -= newpasses1;
907 if (codsty->csty & JPEG2000_CSTY_EPH) {
908 if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
909 bytestream2_skip(&s->g, 2);
911 av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
914 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
915 Jpeg2000Band *band = rlevel->band + bandno;
916 Jpeg2000Prec *prec = band->prec + precno;
918 nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
919 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
920 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
921 for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) {
922 if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno]
923 || sizeof(cblk->data) < cblk->length + cblk->lengthinc[cwsno] + 4
925 av_log(s->avctx, AV_LOG_ERROR,
926 "Block length %"PRIu16" or lengthinc %d is too large, left %d\n",
927 cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g));
928 return AVERROR_INVALIDDATA;
931 bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]);
932 cblk->length += cblk->lengthinc[cwsno];
933 cblk->lengthinc[cwsno] = 0;
934 if (cblk->nb_terminationsinc) {
935 cblk->nb_terminationsinc--;
936 cblk->nb_terminations++;
937 cblk->data[cblk->length++] = 0xFF;
938 cblk->data[cblk->length++] = 0xFF;
939 cblk->data_start[cblk->nb_terminations] = cblk->length;
947 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
950 int layno, reslevelno, compno, precno, ok_reslevel;
956 switch (tile->codsty[0].prog_order) {
957 case JPEG2000_PGOD_RLCP:
958 av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");
960 for (reslevelno = 0; ok_reslevel; reslevelno++) {
962 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
963 for (compno = 0; compno < s->ncomponents; compno++) {
964 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
965 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
966 if (reslevelno < codsty->nreslevels) {
967 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
970 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
971 if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,
974 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
975 qntsty->nguardbits)) < 0)
983 case JPEG2000_PGOD_LRCP:
984 av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");
985 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
987 for (reslevelno = 0; ok_reslevel; reslevelno++) {
989 for (compno = 0; compno < s->ncomponents; compno++) {
990 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
991 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
992 if (reslevelno < codsty->nreslevels) {
993 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
996 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
997 if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,
1000 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1001 qntsty->nguardbits)) < 0)
1009 case JPEG2000_PGOD_CPRL:
1010 av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");
1011 for (compno = 0; compno < s->ncomponents; compno++) {
1012 Jpeg2000Component *comp = tile->comp + compno;
1013 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1014 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
1015 int maxlogstep_x = 0;
1016 int maxlogstep_y = 0;
1017 int start_x, start_y;
1021 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1022 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1023 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1024 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
1025 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1026 maxlogstep_x = FFMAX(maxlogstep_x, rlevel->log2_prec_width + reducedresno);
1027 maxlogstep_y = FFMAX(maxlogstep_y, rlevel->log2_prec_height + reducedresno);
1032 start_y = comp->coord_o[1][0] >> maxlogstep_y << maxlogstep_y;
1033 start_x = comp->coord_o[0][0] >> maxlogstep_x << maxlogstep_x;
1034 for (y = start_y; y < comp->coord_o[1][1]; y += step_y) {
1035 for (x = start_x; x < comp->coord_o[0][1]; x += step_x) {
1036 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1037 unsigned prcx, prcy;
1038 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1039 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1041 if (y % (1 << (rlevel->log2_prec_height + reducedresno)))
1044 if (x % (1 << (rlevel->log2_prec_width + reducedresno)))
1047 // check if a precinct exists
1048 prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
1049 prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
1050 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1051 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1053 precno = prcx + rlevel->num_precincts_x * prcy;
1055 if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1056 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1057 prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1061 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
1062 if ((ret = jpeg2000_decode_packet(s, tile, &tp_index, codsty, rlevel,
1064 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1065 qntsty->nguardbits)) < 0)
1074 case JPEG2000_PGOD_RPCL:
1075 av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");
1077 for (reslevelno = 0; ok_reslevel; reslevelno++) {
1081 for (compno = 0; compno < s->ncomponents; compno++) {
1082 Jpeg2000Component *comp = tile->comp + compno;
1083 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1085 if (reslevelno < codsty->nreslevels) {
1086 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1087 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1088 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
1089 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1095 //FIXME we could iterate over less than the whole image
1096 for (y = 0; y < s->height; y += step_y) {
1097 for (x = 0; x < s->width; x += step_x) {
1098 for (compno = 0; compno < s->ncomponents; compno++) {
1099 Jpeg2000Component *comp = tile->comp + compno;
1100 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1101 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
1102 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1103 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1104 unsigned prcx, prcy;
1106 int xc = x / s->cdx[compno];
1107 int yc = y / s->cdy[compno];
1109 if (reslevelno >= codsty->nreslevels)
1112 if (yc % (1 << (rlevel->log2_prec_height + reducedresno)))
1115 if (xc % (1 << (rlevel->log2_prec_width + reducedresno)))
1118 // check if a precinct exists
1119 prcx = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
1120 prcy = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
1121 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1122 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1124 precno = prcx + rlevel->num_precincts_x * prcy;
1127 if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1128 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1129 prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1133 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
1134 if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,
1137 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1138 qntsty->nguardbits)) < 0)
1147 case JPEG2000_PGOD_PCRL:
1148 av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL");
1151 for (compno = 0; compno < s->ncomponents; compno++) {
1152 Jpeg2000Component *comp = tile->comp + compno;
1153 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1154 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
1156 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1157 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1158 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1159 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
1160 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1166 for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1167 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1168 for (compno = 0; compno < s->ncomponents; compno++) {
1169 Jpeg2000Component *comp = tile->comp + compno;
1170 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1171 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
1172 int xc = x / s->cdx[compno];
1173 int yc = y / s->cdy[compno];
1175 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1176 unsigned prcx, prcy;
1177 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1178 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1180 if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
1183 if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
1186 // check if a precinct exists
1187 prcx = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
1188 prcy = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
1189 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1190 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1192 precno = prcx + rlevel->num_precincts_x * prcy;
1194 if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1195 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1196 prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1200 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
1201 if ((ret = jpeg2000_decode_packet(s, tile, &tp_index, codsty, rlevel,
1203 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1204 qntsty->nguardbits)) < 0)
1217 /* EOC marker reached */
1218 bytestream2_skip(&s->g, 2);
1223 /* TIER-1 routines */
1224 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
1225 int bpno, int bandno,
1226 int vert_causal_ctx_csty_symbol)
1228 int mask = 3 << (bpno - 1), y0, x, y;
1230 for (y0 = 0; y0 < height; y0 += 4)
1231 for (x = 0; x < width; x++)
1232 for (y = y0; y < height && y < y0 + 4; y++) {
1233 int flags_mask = -1;
1234 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1235 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1236 if ((t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB & flags_mask)
1237 && !(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1238 if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, bandno))) {
1239 int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, &xorbit);
1241 t1->data[(y) * t1->stride + x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
1243 t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
1246 ff_jpeg2000_set_significance(t1, x, y,
1247 t1->data[(y) * t1->stride + x] < 0);
1249 t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_VIS;
1254 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
1255 int bpno, int vert_causal_ctx_csty_symbol)
1260 phalf = 1 << (bpno - 1);
1263 for (y0 = 0; y0 < height; y0 += 4)
1264 for (x = 0; x < width; x++)
1265 for (y = y0; y < height && y < y0 + 4; y++)
1266 if ((t1->flags[(y + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
1267 int flags_mask = (vert_causal_ctx_csty_symbol && y == y0 + 3) ?
1268 ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S) : -1;
1269 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask);
1270 int r = ff_mqc_decode(&t1->mqc,
1271 t1->mqc.cx_states + ctxno)
1273 t1->data[(y) * t1->stride + x] += t1->data[(y) * t1->stride + x] < 0 ? -r : r;
1274 t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_REF;
1278 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
1279 int width, int height, int bpno, int bandno,
1280 int seg_symbols, int vert_causal_ctx_csty_symbol)
1282 int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
1284 for (y0 = 0; y0 < height; y0 += 4) {
1285 for (x = 0; x < width; x++) {
1286 int flags_mask = -1;
1287 if (vert_causal_ctx_csty_symbol)
1288 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1289 if (y0 + 3 < height &&
1290 !((t1->flags[(y0 + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1291 (t1->flags[(y0 + 2) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1292 (t1->flags[(y0 + 3) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1293 (t1->flags[(y0 + 4) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {
1294 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
1296 runlen = ff_mqc_decode(&t1->mqc,
1297 t1->mqc.cx_states + MQC_CX_UNI);
1298 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
1307 for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
1308 int flags_mask = -1;
1309 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1310 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1312 if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1313 dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask,
1319 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask,
1321 t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc,
1322 t1->mqc.cx_states + ctxno) ^
1325 ff_jpeg2000_set_significance(t1, x, y, t1->data[(y) * t1->stride + x] < 0);
1328 t1->flags[(y + 1) * t1->stride + x + 1] &= ~JPEG2000_T1_VIS;
1334 val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1335 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1336 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1337 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1339 av_log(s->avctx, AV_LOG_ERROR,
1340 "Segmentation symbol value incorrect\n");
1344 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
1345 Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
1346 int width, int height, int bandpos)
1348 int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
1350 int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
1354 av_assert0(width <= 1024U && height <= 1024U);
1355 av_assert0(width*height <= 4096);
1357 memset(t1->data, 0, t1->stride * height * sizeof(*t1->data));
1359 /* If code-block contains no compressed data: nothing to do. */
1363 memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
1365 cblk->data[cblk->length] = 0xff;
1366 cblk->data[cblk->length+1] = 0xff;
1367 ff_mqc_initdec(&t1->mqc, cblk->data, 0, 1);
1372 decode_sigpass(t1, width, height, bpno + 1, bandpos,
1373 vert_causal_ctx_csty_symbol);
1376 decode_refpass(t1, width, height, bpno + 1, vert_causal_ctx_csty_symbol);
1379 av_assert2(!t1->mqc.raw);
1380 decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
1381 codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1382 vert_causal_ctx_csty_symbol);
1385 if (codsty->cblk_style & JPEG2000_CBLK_RESET) // XXX no testcase for just this
1386 ff_mqc_init_contexts(&t1->mqc);
1388 if (passno && (coder_type = needs_termination(codsty->cblk_style, pass_cnt))) {
1389 if (term_cnt >= cblk->nb_terminations) {
1390 av_log(s->avctx, AV_LOG_ERROR, "Missing needed termination \n");
1391 return AVERROR_INVALIDDATA;
1393 ff_mqc_initdec(&t1->mqc, cblk->data + cblk->data_start[++term_cnt], coder_type == 2, 0);
1404 if (cblk->data + cblk->length - 2*(term_cnt < cblk->nb_terminations) != t1->mqc.bp) {
1405 av_log(s->avctx, AV_LOG_WARNING, "End mismatch %"PTRDIFF_SPECIFIER"\n",
1406 cblk->data + cblk->length - 2*(term_cnt < cblk->nb_terminations) - t1->mqc.bp);
1412 /* TODO: Verify dequantization for lossless case
1413 * comp->data can be float or int
1414 * band->stepsize can be float or int
1415 * depending on the type of DWT transformation.
1416 * see ISO/IEC 15444-1:2002 A.6.1 */
1418 /* Float dequantization of a codeblock.*/
1419 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1420 Jpeg2000Component *comp,
1421 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1424 int w = cblk->coord[0][1] - cblk->coord[0][0];
1425 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1426 float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1427 int *src = t1->data + j*t1->stride;
1428 for (i = 0; i < w; ++i)
1429 datap[i] = src[i] * band->f_stepsize;
1433 /* Integer dequantization of a codeblock.*/
1434 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1435 Jpeg2000Component *comp,
1436 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1439 int w = cblk->coord[0][1] - cblk->coord[0][0];
1440 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1441 int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1442 int *src = t1->data + j*t1->stride;
1443 if (band->i_stepsize == 16384) {
1444 for (i = 0; i < w; ++i)
1445 datap[i] = src[i] / 2;
1447 // This should be VERY uncommon
1448 for (i = 0; i < w; ++i)
1449 datap[i] = (src[i] * (int64_t)band->i_stepsize) / 32768;
1454 static void dequantization_int_97(int x, int y, Jpeg2000Cblk *cblk,
1455 Jpeg2000Component *comp,
1456 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1459 int w = cblk->coord[0][1] - cblk->coord[0][0];
1460 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1461 int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1462 int *src = t1->data + j*t1->stride;
1463 for (i = 0; i < w; ++i)
1464 datap[i] = (src[i] * (int64_t)band->i_stepsize + (1<<14)) >> 15;
1468 static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1473 for (i = 1; i < 3; i++) {
1474 if (tile->codsty[0].transform != tile->codsty[i].transform) {
1475 av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
1478 if (memcmp(tile->comp[0].coord, tile->comp[i].coord, sizeof(tile->comp[0].coord))) {
1479 av_log(s->avctx, AV_LOG_ERROR, "Coords mismatch, MCT not supported\n");
1484 for (i = 0; i < 3; i++)
1485 if (tile->codsty[0].transform == FF_DWT97)
1486 src[i] = tile->comp[i].f_data;
1488 src[i] = tile->comp[i].i_data;
1490 for (i = 0; i < 2; i++)
1491 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1493 s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
1496 static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1499 const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
1500 int compno, reslevelno, bandno;
1502 int planar = !!(pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR);
1503 int pixelsize = planar ? 1 : pixdesc->nb_components;
1506 Jpeg2000T1Context t1;
1508 /* Loop on tile components */
1509 for (compno = 0; compno < s->ncomponents; compno++) {
1510 Jpeg2000Component *comp = tile->comp + compno;
1511 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1513 t1.stride = (1<<codsty->log2_cblk_width) + 2;
1515 /* Loop on resolution levels */
1516 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1517 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1519 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1520 int nb_precincts, precno;
1521 Jpeg2000Band *band = rlevel->band + bandno;
1522 int cblkno = 0, bandpos;
1524 bandpos = bandno + (reslevelno > 0);
1526 if (band->coord[0][0] == band->coord[0][1] ||
1527 band->coord[1][0] == band->coord[1][1])
1530 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1531 /* Loop on precincts */
1532 for (precno = 0; precno < nb_precincts; precno++) {
1533 Jpeg2000Prec *prec = band->prec + precno;
1535 /* Loop on codeblocks */
1536 for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1538 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1539 decode_cblk(s, codsty, &t1, cblk,
1540 cblk->coord[0][1] - cblk->coord[0][0],
1541 cblk->coord[1][1] - cblk->coord[1][0],
1544 x = cblk->coord[0][0] - band->coord[0][0];
1545 y = cblk->coord[1][0] - band->coord[1][0];
1547 if (codsty->transform == FF_DWT97)
1548 dequantization_float(x, y, cblk, comp, &t1, band);
1549 else if (codsty->transform == FF_DWT97_INT)
1550 dequantization_int_97(x, y, cblk, comp, &t1, band);
1552 dequantization_int(x, y, cblk, comp, &t1, band);
1556 } /* end reslevel */
1559 ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
1562 /* inverse MCT transformation */
1563 if (tile->codsty[0].mct)
1564 mct_decode(s, tile);
1566 if (s->cdef[0] < 0) {
1567 for (x = 0; x < s->ncomponents; x++)
1569 if ((s->ncomponents & 1) == 0)
1570 s->cdef[s->ncomponents-1] = 0;
1573 if (s->precision <= 8) {
1574 for (compno = 0; compno < s->ncomponents; compno++) {
1575 Jpeg2000Component *comp = tile->comp + compno;
1576 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1577 float *datap = comp->f_data;
1578 int32_t *i_datap = comp->i_data;
1579 int cbps = s->cbps[compno];
1580 int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1584 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
1587 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1588 line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane];
1589 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y ++) {
1592 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1593 dst = line + x / s->cdx[compno] * pixelsize + compno*!planar;
1595 if (codsty->transform == FF_DWT97) {
1596 for (; x < w; x ++) {
1597 int val = lrintf(*datap) + (1 << (cbps - 1));
1598 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1599 val = av_clip(val, 0, (1 << cbps) - 1);
1600 *dst = val << (8 - cbps);
1605 for (; x < w; x ++) {
1606 int val = *i_datap + (1 << (cbps - 1));
1607 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1608 val = av_clip(val, 0, (1 << cbps) - 1);
1609 *dst = val << (8 - cbps);
1614 line += picture->linesize[plane];
1618 int precision = picture->format == AV_PIX_FMT_XYZ12 ||
1619 picture->format == AV_PIX_FMT_RGB48 ||
1620 picture->format == AV_PIX_FMT_RGBA64 ||
1621 picture->format == AV_PIX_FMT_GRAY16 ? 16 : s->precision;
1623 for (compno = 0; compno < s->ncomponents; compno++) {
1624 Jpeg2000Component *comp = tile->comp + compno;
1625 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1626 float *datap = comp->f_data;
1627 int32_t *i_datap = comp->i_data;
1629 int cbps = s->cbps[compno];
1630 int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1634 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
1636 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1637 linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1);
1638 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y ++) {
1641 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1642 dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar);
1643 if (codsty->transform == FF_DWT97) {
1644 for (; x < w; x ++) {
1645 int val = lrintf(*datap) + (1 << (cbps - 1));
1646 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1647 val = av_clip(val, 0, (1 << cbps) - 1);
1648 /* align 12 bit values in little-endian mode */
1649 *dst = val << (precision - cbps);
1654 for (; x < w; x ++) {
1655 int val = *i_datap + (1 << (cbps - 1));
1656 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1657 val = av_clip(val, 0, (1 << cbps) - 1);
1658 /* align 12 bit values in little-endian mode */
1659 *dst = val << (precision - cbps);
1664 linel += picture->linesize[plane] >> 1;
1672 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1675 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1676 if (s->tile[tileno].comp) {
1677 for (compno = 0; compno < s->ncomponents; compno++) {
1678 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1679 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1681 ff_jpeg2000_cleanup(comp, codsty);
1683 av_freep(&s->tile[tileno].comp);
1687 memset(s->codsty, 0, sizeof(s->codsty));
1688 memset(s->qntsty, 0, sizeof(s->qntsty));
1689 s->numXtiles = s->numYtiles = 0;
1692 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1694 Jpeg2000CodingStyle *codsty = s->codsty;
1695 Jpeg2000QuantStyle *qntsty = s->qntsty;
1696 uint8_t *properties = s->properties;
1703 if (bytestream2_get_bytes_left(&s->g) < 2) {
1704 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1708 marker = bytestream2_get_be16u(&s->g);
1709 oldpos = bytestream2_tell(&s->g);
1711 if (marker == JPEG2000_SOD) {
1713 Jpeg2000TilePart *tp;
1716 av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
1717 return AVERROR_INVALIDDATA;
1719 if (s->curtileno < 0) {
1720 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
1721 return AVERROR_INVALIDDATA;
1724 tile = s->tile + s->curtileno;
1725 tp = tile->tile_part + tile->tp_idx;
1726 if (tp->tp_end < s->g.buffer) {
1727 av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
1728 return AVERROR_INVALIDDATA;
1730 bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
1731 bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
1735 if (marker == JPEG2000_EOC)
1738 len = bytestream2_get_be16(&s->g);
1739 if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) {
1740 av_log(s->avctx, AV_LOG_ERROR, "Invalid len %d left=%d\n", len, bytestream2_get_bytes_left(&s->g));
1741 return AVERROR_INVALIDDATA;
1748 s->numXtiles = s->numYtiles = 0;
1751 ret = get_coc(s, codsty, properties);
1754 ret = get_cod(s, codsty, properties);
1757 ret = get_qcc(s, len, qntsty, properties);
1760 ret = get_qcd(s, len, qntsty, properties);
1763 if (!(ret = get_sot(s, len))) {
1764 av_assert1(s->curtileno >= 0);
1765 codsty = s->tile[s->curtileno].codsty;
1766 qntsty = s->tile[s->curtileno].qntsty;
1767 properties = s->tile[s->curtileno].properties;
1771 // the comment is ignored
1772 bytestream2_skip(&s->g, len - 2);
1775 // Tile-part lengths
1776 ret = get_tlm(s, len);
1779 // Packet length, tile-part header
1780 ret = get_plt(s, len);
1783 av_log(s->avctx, AV_LOG_ERROR,
1784 "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
1785 marker, bytestream2_tell(&s->g) - 4);
1786 bytestream2_skip(&s->g, len - 2);
1789 if (bytestream2_tell(&s->g) - oldpos != len || ret) {
1790 av_log(s->avctx, AV_LOG_ERROR,
1791 "error during processing marker segment %.4"PRIx16"\n",
1793 return ret ? ret : -1;
1799 /* Read bit stream packets --> T2 operation. */
1800 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1805 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1806 Jpeg2000Tile *tile = s->tile + tileno;
1808 if ((ret = init_tile(s, tileno)) < 0)
1811 s->g = tile->tile_part[0].tpg;
1812 if ((ret = jpeg2000_decode_packets(s, tile)) < 0)
1819 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1821 uint32_t atom_size, atom, atom_end;
1822 int search_range = 10;
1826 bytestream2_get_bytes_left(&s->g) >= 8) {
1827 atom_size = bytestream2_get_be32u(&s->g);
1828 atom = bytestream2_get_be32u(&s->g);
1829 atom_end = bytestream2_tell(&s->g) + atom_size - 8;
1831 if (atom == JP2_CODESTREAM)
1834 if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
1837 if (atom == JP2_HEADER &&
1839 uint32_t atom2_size, atom2, atom2_end;
1841 atom2_size = bytestream2_get_be32u(&s->g);
1842 atom2 = bytestream2_get_be32u(&s->g);
1843 atom2_end = bytestream2_tell(&s->g) + atom2_size - 8;
1844 if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
1846 if (atom2 == JP2_CODESTREAM) {
1848 } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
1849 int method = bytestream2_get_byteu(&s->g);
1850 bytestream2_skipu(&s->g, 2);
1852 s->colour_space = bytestream2_get_be32u(&s->g);
1854 } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
1855 int i, size, colour_count, colour_channels, colour_depth[3];
1857 colour_count = bytestream2_get_be16u(&s->g);
1858 colour_channels = bytestream2_get_byteu(&s->g);
1859 // FIXME: Do not ignore channel_sign
1860 colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1861 colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1862 colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1863 size = (colour_depth[0] + 7 >> 3) * colour_count +
1864 (colour_depth[1] + 7 >> 3) * colour_count +
1865 (colour_depth[2] + 7 >> 3) * colour_count;
1866 if (colour_count > 256 ||
1867 colour_channels != 3 ||
1868 colour_depth[0] > 16 ||
1869 colour_depth[1] > 16 ||
1870 colour_depth[2] > 16 ||
1871 atom2_size < size) {
1872 avpriv_request_sample(s->avctx, "Unknown palette");
1873 bytestream2_seek(&s->g, atom2_end, SEEK_SET);
1877 for (i = 0; i < colour_count; i++) {
1878 if (colour_depth[0] <= 8) {
1879 r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
1880 r |= r >> colour_depth[0];
1882 r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
1884 if (colour_depth[1] <= 8) {
1885 g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
1886 r |= r >> colour_depth[1];
1888 g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
1890 if (colour_depth[2] <= 8) {
1891 b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
1892 r |= r >> colour_depth[2];
1894 b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
1896 s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
1898 } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
1899 int n = bytestream2_get_be16u(&s->g);
1901 int cn = bytestream2_get_be16(&s->g);
1902 int av_unused typ = bytestream2_get_be16(&s->g);
1903 int asoc = bytestream2_get_be16(&s->g);
1904 if (cn < 4 && asoc < 4)
1908 bytestream2_seek(&s->g, atom2_end, SEEK_SET);
1909 } while (atom_end - atom2_end >= 8);
1913 bytestream2_seek(&s->g, atom_end, SEEK_SET);
1919 static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
1921 Jpeg2000DecoderContext *s = avctx->priv_data;
1923 ff_jpeg2000dsp_init(&s->dsp);
1928 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1929 int *got_frame, AVPacket *avpkt)
1931 Jpeg2000DecoderContext *s = avctx->priv_data;
1932 ThreadFrame frame = { .f = data };
1933 AVFrame *picture = data;
1937 bytestream2_init(&s->g, avpkt->data, avpkt->size);
1939 memset(s->cdef, -1, sizeof(s->cdef));
1941 if (bytestream2_get_bytes_left(&s->g) < 2) {
1942 ret = AVERROR_INVALIDDATA;
1946 // check if the image is in jp2 format
1947 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1948 (bytestream2_get_be32u(&s->g) == 12) &&
1949 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1950 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
1951 if (!jp2_find_codestream(s)) {
1952 av_log(avctx, AV_LOG_ERROR,
1953 "Could not find Jpeg2000 codestream atom.\n");
1954 ret = AVERROR_INVALIDDATA;
1958 bytestream2_seek(&s->g, 0, SEEK_SET);
1961 while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
1962 bytestream2_skip(&s->g, 1);
1964 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1965 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1966 ret = AVERROR_INVALIDDATA;
1969 if (ret = jpeg2000_read_main_headers(s))
1972 /* get picture buffer */
1973 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1975 picture->pict_type = AV_PICTURE_TYPE_I;
1976 picture->key_frame = 1;
1978 if (ret = jpeg2000_read_bitstream_packets(s))
1981 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1982 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
1985 jpeg2000_dec_cleanup(s);
1989 if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
1990 memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
1992 return bytestream2_tell(&s->g);
1995 jpeg2000_dec_cleanup(s);
1999 static av_cold void jpeg2000_init_static_data(AVCodec *codec)
2001 ff_jpeg2000_init_tier1_luts();
2002 ff_mqc_init_context_tables();
2005 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
2006 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2008 static const AVOption options[] = {
2009 { "lowres", "Lower the decoding resolution by a power of two",
2010 OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
2014 static const AVProfile profiles[] = {
2015 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
2016 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
2017 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
2018 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
2019 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
2020 { FF_PROFILE_UNKNOWN },
2023 static const AVClass jpeg2000_class = {
2024 .class_name = "jpeg2000",
2025 .item_name = av_default_item_name,
2027 .version = LIBAVUTIL_VERSION_INT,
2030 AVCodec ff_jpeg2000_decoder = {
2032 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
2033 .type = AVMEDIA_TYPE_VIDEO,
2034 .id = AV_CODEC_ID_JPEG2000,
2035 .capabilities = CODEC_CAP_FRAME_THREADS,
2036 .priv_data_size = sizeof(Jpeg2000DecoderContext),
2037 .init_static_data = jpeg2000_init_static_data,
2038 .init = jpeg2000_decode_init,
2039 .decode = jpeg2000_decode_frame,
2040 .priv_class = &jpeg2000_class,
2042 .profiles = NULL_IF_CONFIG_SMALL(profiles)