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
28 #include "libavutil/common.h"
29 #include "libavutil/opt.h"
31 #include "bytestream.h"
36 #define JP2_SIG_TYPE 0x6A502020
37 #define JP2_SIG_VALUE 0x0D0A870A
38 #define JP2_CODESTREAM 0x6A703263
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
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];
60 typedef struct Jpeg2000DecoderContext {
62 AVCodecContext *avctx;
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];
74 int tile_width, tile_height;
75 int numXtiles, numYtiles;
78 Jpeg2000CodingStyle codsty[4];
79 Jpeg2000QuantStyle qntsty[4];
86 /*options parameters*/
88 int16_t reduction_factor;
89 } Jpeg2000DecoderContext;
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)
101 if (s->bit_index == 0) {
102 s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
105 res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
110 static void jpeg2000_flush(Jpeg2000DecoderContext *s)
112 if (bytestream2_get_byte(&s->g) == 0xff)
113 bytestream2_skip(&s->g, 1);
117 /* decode the value stored in node */
118 static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
121 Jpeg2000TgtNode *stack[30];
122 int sp = -1, curval = 0;
124 while (node && !node->vis) {
132 curval = stack[sp]->val;
134 while (curval < threshold && sp >= 0) {
135 if (curval < stack[sp]->val)
136 curval = stack[sp]->val;
137 while (curval < threshold) {
139 if ((ret = get_bits(s, 1)) > 0) {
147 stack[sp]->val = curval;
153 /* marker segments */
154 /* get sizes and offsets of image, tiles; number of components */
155 static int get_siz(Jpeg2000DecoderContext *s)
159 if (bytestream2_get_bytes_left(&s->g) < 36)
160 return AVERROR(EINVAL);
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 s->ncomponents = bytestream2_get_be16u(&s->g); // CSiz
173 if(s->ncomponents <= 0 || s->ncomponents > 4) {
174 av_log(s->avctx, AV_LOG_ERROR, "unsupported/invalid ncomponents: %d\n", s->ncomponents);
175 return AVERROR(EINVAL);
177 if(s->tile_width<=0 || s->tile_height<=0)
178 return AVERROR(EINVAL);
180 if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
181 return AVERROR(EINVAL);
183 for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
184 uint8_t x = bytestream2_get_byteu(&s->g);
185 s->cbps[i] = (x & 0x7f) + 1;
186 s->precision = FFMAX(s->cbps[i], s->precision);
187 s->sgnd[i] = (x & 0x80) == 1;
188 s->cdx[i] = bytestream2_get_byteu(&s->g);
189 s->cdy[i] = bytestream2_get_byteu(&s->g);
192 s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
193 s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
195 if(s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(Jpeg2000Tile))
196 return AVERROR(EINVAL);
198 s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(*s->tile));
200 return AVERROR(ENOMEM);
202 for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
203 Jpeg2000Tile *tile = s->tile + i;
205 tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
207 return AVERROR(ENOMEM);
210 /* compute image size with reduction factor */
211 s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
212 s->reduction_factor);
213 s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
214 s->reduction_factor);
216 switch (s->avctx->profile) {
217 case FF_PROFILE_JPEG2000_DCINEMA_2K:
218 case FF_PROFILE_JPEG2000_DCINEMA_4K:
219 /* XYZ color-space for digital cinema profiles */
220 s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;
223 /* For other profiles selects color-space according number of
224 * components and bit depth precision. */
225 switch (s->ncomponents) {
227 if (s->precision > 8)
228 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
230 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
233 if (s->precision > 8)
234 s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
236 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
239 s->avctx->pix_fmt = AV_PIX_FMT_BGRA;
242 /* pixel format can not be identified */
243 s->avctx->pix_fmt = AV_PIX_FMT_NONE;
251 /* get common part for COD and COC segments */
252 static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
256 if (bytestream2_get_bytes_left(&s->g) < 5)
257 return AVERROR(EINVAL);
258 c->nreslevels = bytestream2_get_byteu(&s->g) + 1; // num of resolution levels - 1
260 /* compute number of resolution levels to decode */
261 if (c->nreslevels < s->reduction_factor)
262 c->nreslevels2decode = 1;
264 c->nreslevels2decode = c->nreslevels - s->reduction_factor;
266 c->log2_cblk_width = bytestream2_get_byteu(&s->g) + 2; // cblk width
267 c->log2_cblk_height = bytestream2_get_byteu(&s->g) + 2; // cblk height
269 c->cblk_style = bytestream2_get_byteu(&s->g);
270 if (c->cblk_style != 0) { // cblk style
271 av_log(s->avctx, AV_LOG_ERROR, "no extra cblk styles supported\n");
274 c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
275 /* set integer 9/7 DWT in case of BITEXACT flag */
276 if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
277 c->transform = FF_DWT97_INT;
279 if (c->csty & JPEG2000_CSTY_PREC) {
281 for (i = 0; i < c->nreslevels; i++) {
282 byte = bytestream2_get_byte(&s->g);
283 c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
284 c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
290 /* get coding parameters for a particular tile or whole image*/
291 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
294 Jpeg2000CodingStyle tmp;
297 if (bytestream2_get_bytes_left(&s->g) < 5)
298 return AVERROR(EINVAL);
300 tmp.log2_prec_width =
301 tmp.log2_prec_height = 15;
303 tmp.csty = bytestream2_get_byteu(&s->g);
305 // get progression order
306 tmp.prog_order = bytestream2_get_byteu(&s->g);
308 tmp.nlayers = bytestream2_get_be16u(&s->g);
309 tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
312 for (compno = 0; compno < s->ncomponents; compno++)
313 if (!(properties[compno] & HAD_COC))
314 memcpy(c + compno, &tmp, sizeof(tmp));
318 /* Get coding parameters for a component in the whole image or a
319 * particular tile. */
320 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
325 if (bytestream2_get_bytes_left(&s->g) < 2)
326 return AVERROR(EINVAL);
328 compno = bytestream2_get_byteu(&s->g);
331 c->csty = bytestream2_get_byteu(&s->g);
334 properties[compno] |= HAD_COC;
338 /* Get common part for QCD and QCC segments. */
339 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
343 if (bytestream2_get_bytes_left(&s->g) < 1)
344 return AVERROR(EINVAL);
346 x = bytestream2_get_byteu(&s->g); // Sqcd
348 q->nguardbits = x >> 5;
349 q->quantsty = x & 0x1f;
351 if (q->quantsty == JPEG2000_QSTY_NONE) {
353 if (bytestream2_get_bytes_left(&s->g) < n || 32*3 < n)
354 return AVERROR(EINVAL);
355 for (i = 0; i < n; i++)
356 q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
357 } else if (q->quantsty == JPEG2000_QSTY_SI) {
358 if (bytestream2_get_bytes_left(&s->g) < 2)
359 return AVERROR(EINVAL);
360 x = bytestream2_get_be16u(&s->g);
361 q->expn[0] = x >> 11;
362 q->mant[0] = x & 0x7ff;
363 for (i = 1; i < 32 * 3; i++) {
364 int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
365 q->expn[i] = curexpn;
366 q->mant[i] = q->mant[0];
370 if (bytestream2_get_bytes_left(&s->g) < 2 * n || 32*3 < n)
371 return AVERROR(EINVAL);
372 for (i = 0; i < n; i++) {
373 x = bytestream2_get_be16u(&s->g);
374 q->expn[i] = x >> 11;
375 q->mant[i] = x & 0x7ff;
381 /* Get quantization parameters for a particular tile or a whole image. */
382 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
385 Jpeg2000QuantStyle tmp;
388 if (get_qcx(s, n, &tmp))
390 for (compno = 0; compno < s->ncomponents; compno++)
391 if (!(properties[compno] & HAD_QCC))
392 memcpy(q + compno, &tmp, sizeof(tmp));
396 /* Get quantization parameters for a component in the whole image
397 * on in a particular tile. */
398 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
403 if (bytestream2_get_bytes_left(&s->g) < 1)
404 return AVERROR(EINVAL);
406 compno = bytestream2_get_byteu(&s->g);
407 properties[compno] |= HAD_QCC;
408 return get_qcx(s, n - 1, q + compno);
411 /* Get start of tile segment. */
412 static int get_sot(Jpeg2000DecoderContext *s, int n)
414 Jpeg2000TilePart *tp;
419 if (bytestream2_get_bytes_left(&s->g) < 8)
420 return AVERROR(EINVAL);
422 s->curtileno = Isot = bytestream2_get_be16u(&s->g); // Isot
423 if((unsigned)s->curtileno >= s->numXtiles * s->numYtiles){
425 return AVERROR(EINVAL);
428 av_log(s->avctx, AV_LOG_ERROR,
429 "Not a DCINEMA JP2K file: more than one tile\n");
432 Psot = bytestream2_get_be32u(&s->g); // Psot
433 TPsot = bytestream2_get_byteu(&s->g); // TPsot
435 /* Read TNSot but not used */
436 bytestream2_get_byteu(&s->g); // TNsot
438 if (TPsot >= FF_ARRAY_ELEMS(s->tile[s->curtileno].tile_part)) {
439 av_log(s->avctx, AV_LOG_ERROR, "TPsot %d too big\n", TPsot);
440 return AVERROR_PATCHWELCOME;
443 tp = s->tile[s->curtileno].tile_part + TPsot;
444 tp->tile_index = Isot;
448 /* Start of bit stream. Pointer to SOD marker
449 * Check SOD marker is present. */
450 if (JPEG2000_SOD == bytestream2_get_be16(&s->g)) {
451 bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_len - n - 4);
452 bytestream2_skip(&s->g, tp->tp_len - n - 4);
454 av_log(s->avctx, AV_LOG_ERROR, "SOD marker not found \n");
458 /* End address of bit stream =
459 * start address + (Psot - size of SOT HEADER(n)
460 * - size of SOT MARKER(2) - size of SOD marker(2) */
465 /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
466 * Used to know the number of tile parts and lengths.
467 * There may be multiple TLMs in the header.
468 * TODO: The function is not used for tile-parts management, nor anywhere else.
469 * It can be useful to allocate memory for tile parts, before managing the SOT
470 * markers. Parsing the TLM header is needed to increment the input header
472 * This marker is mandatory for DCI. */
473 static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
475 uint8_t Stlm, ST, SP, tile_tlm, i;
476 bytestream2_get_byte(&s->g); /* Ztlm: skipped */
477 Stlm = bytestream2_get_byte(&s->g);
479 // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
480 ST = (Stlm >> 4) & 0x03;
481 // TODO: Manage case of ST = 0b11 --> raise error
482 SP = (Stlm >> 6) & 0x01;
483 tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
484 for (i = 0; i < tile_tlm; i++) {
489 bytestream2_get_byte(&s->g);
492 bytestream2_get_be16(&s->g);
495 bytestream2_get_be32(&s->g);
499 bytestream2_get_be16(&s->g);
501 bytestream2_get_be32(&s->g);
507 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
510 int tilex = tileno % s->numXtiles;
511 int tiley = tileno / s->numXtiles;
512 Jpeg2000Tile *tile = s->tile + tileno;
513 Jpeg2000CodingStyle *codsty;
514 Jpeg2000QuantStyle *qntsty;
517 return AVERROR(ENOMEM);
519 /* copy codsty, qnsty to tile. TODO: Is it the best way?
520 * codsty, qnsty is an array of 4 structs Jpeg2000CodingStyle
521 * and Jpeg2000QuantStyle */
522 memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(*codsty));
523 memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(*qntsty));
525 for (compno = 0; compno < s->ncomponents; compno++) {
526 Jpeg2000Component *comp = tile->comp + compno;
527 int ret; // global bandno
528 codsty = tile->codsty + compno;
529 qntsty = tile->qntsty + compno;
531 comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
532 comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
533 comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
534 comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
536 // FIXME: add a dcinema profile check ?
537 // value is guaranteed by profile (orig=0, 1 tile)
538 comp->coord[0][0] = 0;
539 comp->coord[0][1] = s->avctx->width;
540 comp->coord[1][0] = 0;
541 comp->coord[1][1] = s->avctx->height;
543 if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
544 s->cbps[compno], s->cdx[compno],
545 s->cdy[compno], s->avctx))
551 /* Read the number of coding passes. */
552 static int getnpasses(Jpeg2000DecoderContext *s)
559 if ((num = get_bits(s, 2)) != 3)
560 return num < 0 ? num : 3 + num;
561 if ((num = get_bits(s, 5)) != 31)
562 return num < 0 ? num : 6 + num;
563 num = get_bits(s, 7);
564 return num < 0 ? num : 37 + num;
567 static int getlblockinc(Jpeg2000DecoderContext *s)
570 while (ret = get_bits(s, 1)) {
578 static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
579 Jpeg2000CodingStyle *codsty,
580 Jpeg2000ResLevel *rlevel, int precno,
581 int layno, uint8_t *expn, int numgbits)
583 int bandno, cblkno, ret, nb_code_blocks;
585 if (!(ret = get_bits(s, 1))) {
591 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
592 Jpeg2000Band *band = rlevel->band + bandno;
593 Jpeg2000Prec *prec = band->prec + precno;
595 if (band->coord[0][0] == band->coord[0][1] ||
596 band->coord[1][0] == band->coord[1][1])
600 nb_code_blocks = prec->nb_codeblocks_height *
601 prec->nb_codeblocks_width;
602 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
603 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
604 int incl, newpasses, llen;
607 incl = get_bits(s, 1);
609 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
616 cblk->nonzerobits = expn[bandno] + numgbits - 1 -
617 tag_tree_decode(s, prec->zerobits + cblkno,
619 if ((newpasses = getnpasses(s)) < 0)
621 if ((llen = getlblockinc(s)) < 0)
623 cblk->lblock += llen;
624 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
626 cblk->lengthinc = ret;
627 cblk->npasses += newpasses;
632 if (codsty->csty & JPEG2000_CSTY_EPH) {
633 if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
634 bytestream2_skip(&s->g, 2);
636 av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
639 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
640 Jpeg2000Band *band = rlevel->band + bandno;
641 Jpeg2000Prec *prec = band->prec + precno;
643 nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
644 for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
645 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
646 if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
647 || sizeof(cblk->data) < cblk->lengthinc
649 return AVERROR(EINVAL);
650 /* Code-block data can be empty. In that case initialize data
652 if (cblk->lengthinc > 0) {
653 bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
655 cblk->data[0] = 0xFF;
656 cblk->data[1] = 0xFF;
658 cblk->length += cblk->lengthinc;
665 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
667 int layno, reslevelno, compno, precno, ok_reslevel;
668 uint8_t prog_order = tile->codsty[0].prog_order;
673 switch (prog_order) {
674 case JPEG2000_PGOD_LRCP:
675 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
677 for (reslevelno = 0; ok_reslevel; reslevelno++) {
679 for (compno = 0; compno < s->ncomponents; compno++) {
680 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
681 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
682 if (reslevelno < codsty->nreslevels) {
683 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
686 for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
687 if (jpeg2000_decode_packet(s,
690 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
699 case JPEG2000_PGOD_CPRL:
700 for (compno = 0; compno < s->ncomponents; compno++) {
701 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
702 Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
704 /* Set bit stream buffer address according to tile-part.
705 * For DCinema one tile-part per component, so can be
706 * indexed by component. */
707 s->g = tile->tile_part[compno].tpg;
709 /* Position loop (y axis)
710 * TODO: Automate computing of step 256.
711 * Fixed here, but to be computed before entering here. */
712 for (y = 0; y < s->height; y += 256) {
713 /* Position loop (y axis)
714 * TODO: automate computing of step 256.
715 * Fixed here, but to be computed before entering here. */
716 for (x = 0; x < s->width; x += 256) {
717 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
719 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
720 Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
722 if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
723 (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
726 if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
727 (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
730 // check if a precinct exists
731 prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
732 prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
733 precno = prcx + rlevel->num_precincts_x * prcy;
734 for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
735 if (jpeg2000_decode_packet(s, codsty, rlevel,
737 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
751 /* EOC marker reached */
752 bytestream2_skip(&s->g, 2);
757 /* TIER-1 routines */
758 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
759 int bpno, int bandno)
761 int mask = 3 << (bpno - 1), y0, x, y;
763 for (y0 = 0; y0 < height; y0 += 4)
764 for (x = 0; x < width; x++)
765 for (y = y0; y < height && y < y0 + 4; y++)
766 if ((t1->flags[y + 1][x + 1] & JPEG2000_T1_SIG_NB)
767 && !(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
768 if (ff_mqc_decode(&t1->mqc,
770 ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
772 int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
776 (ff_mqc_decode(&t1->mqc,
777 t1->mqc.cx_states + ctxno) ^ xorbit)
780 ff_jpeg2000_set_significance(t1, x, y,
783 t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
787 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
793 phalf = 1 << (bpno - 1);
796 for (y0 = 0; y0 < height; y0 += 4)
797 for (x = 0; x < width; x++)
798 for (y = y0; y < height && y < y0 + 4; y++)
799 if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
800 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
801 int r = ff_mqc_decode(&t1->mqc,
802 t1->mqc.cx_states + ctxno)
804 t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
805 t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
809 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
810 int width, int height, int bpno, int bandno,
813 int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
815 for (y0 = 0; y0 < height; y0 += 4)
816 for (x = 0; x < width; x++) {
817 if (y0 + 3 < height &&
818 !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
819 (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
820 (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
821 (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
822 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
824 runlen = ff_mqc_decode(&t1->mqc,
825 t1->mqc.cx_states + MQC_CX_UNI);
826 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
835 for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
837 if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))
838 dec = ff_mqc_decode(&t1->mqc,
840 ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
845 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
847 t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
848 t1->mqc.cx_states + ctxno) ^
851 ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
854 t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
859 val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
860 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
861 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
862 val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
864 av_log(s->avctx, AV_LOG_ERROR,
865 "Segmentation symbol value incorrect\n");
869 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
870 Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
871 int width, int height, int bandpos)
873 int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
875 for (y = 0; y < height; y++)
876 memset(t1->data[y], 0, width * sizeof(width));
878 /* If code-block contains no compressed data: nothing to do. */
881 for (y = 0; y < height + 2; y++)
882 memset(t1->flags[y], 0, (width + 2) * sizeof(width));
884 ff_mqc_initdec(&t1->mqc, cblk->data);
885 cblk->data[cblk->length] = 0xff;
886 cblk->data[cblk->length + 1] = 0xff;
891 decode_sigpass(t1, width, height, bpno + 1, bandpos);
894 decode_refpass(t1, width, height, bpno + 1);
897 decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
898 codsty->cblk_style & JPEG2000_CBLK_SEGSYM);
911 /* TODO: Verify dequantization for lossless case
912 * comp->data can be float or int
913 * band->stepsize can be float or int
914 * depending on the type of DWT transformation.
915 * see ISO/IEC 15444-1:2002 A.6.1 */
917 /* Float dequantization of a codeblock.*/
918 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
919 Jpeg2000Component *comp,
920 Jpeg2000T1Context *t1, Jpeg2000Band *band)
923 float *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
924 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
925 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
926 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
927 datap[idx] = (float)(t1->data[j][i]) * ((float)band->stepsize);
932 /* Integer dequantization of a codeblock.*/
933 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
934 Jpeg2000Component *comp,
935 Jpeg2000T1Context *t1, Jpeg2000Band *band)
939 (int32_t *) &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
940 for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
941 for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
942 idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
944 ((int32_t)(t1->data[j][i]) * ((int32_t)band->stepsize) + (1 << 15)) >> 16;
949 /* Inverse ICT parameters in float and integer.
950 * int value = (float value) * (1<<16) */
951 static const float f_ict_params[4] = {
957 static const int i_ict_params[4] = {
964 static int mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
968 int32_t *src[3], i0, i1, i2;
969 float *srcf[3], i0f, i1f, i2f;
971 for (i = 0; i < 3; i++)
972 if (tile->codsty[0].transform == FF_DWT97)
973 srcf[i] = tile->comp[i].data;
975 src[i] = (int32_t *)tile->comp[i].data;
977 for (i = 0; i < 2; i++)
978 csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
979 switch (tile->codsty[0].transform) {
981 for (i = 0; i < csize; i++) {
982 i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
983 i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
984 - (f_ict_params[2] * *srcf[2]);
985 i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
992 for (i = 0; i < csize; i++) {
993 i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
994 i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
995 - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
996 i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
1003 for (i = 0; i < csize; i++) {
1004 i1 = *src[0] - (*src[2] + *src[1] >> 2);
1016 static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1019 int compno, reslevelno, bandno;
1023 Jpeg2000T1Context t1;
1024 /* Loop on tile components */
1026 for (compno = 0; compno < s->ncomponents; compno++) {
1027 Jpeg2000Component *comp = tile->comp + compno;
1028 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1029 /* Loop on resolution levels */
1030 for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1031 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1033 for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1034 uint16_t nb_precincts, precno;
1035 Jpeg2000Band *band = rlevel->band + bandno;
1036 int cblkno = 0, bandpos;
1037 bandpos = bandno + (reslevelno > 0);
1039 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1040 /* Loop on precincts */
1041 for (precno = 0; precno < nb_precincts; precno++) {
1042 Jpeg2000Prec *prec = band->prec + precno;
1044 /* Loop on codeblocks */
1045 for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1047 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1048 decode_cblk(s, codsty, &t1, cblk,
1049 cblk->coord[0][1] - cblk->coord[0][0],
1050 cblk->coord[1][1] - cblk->coord[1][0],
1053 /* Manage band offsets */
1054 x = cblk->coord[0][0];
1055 y = cblk->coord[1][0];
1056 if ((reslevelno > 0) && ((bandno + 1) & 1)) {
1057 Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1058 x += pres->coord[0][1] - pres->coord[0][0];
1060 if ((reslevelno > 0) && ((bandno + 1) & 2)) {
1061 Jpeg2000ResLevel *pres = comp->reslevel + (reslevelno - 1);
1062 y += pres->coord[1][1] - pres->coord[1][0];
1065 if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1066 dequantization_int(x, y, cblk, comp, &t1, band);
1068 dequantization_float(x, y, cblk, comp, &t1, band);
1072 } /* end reslevel */
1075 ff_dwt_decode(&comp->dwt, comp->data);
1078 /* inverse MCT transformation */
1079 if (tile->codsty[0].mct)
1080 mct_decode(s, tile);
1082 if (s->avctx->pix_fmt == AV_PIX_FMT_BGRA) // RGBA -> BGRA
1083 FFSWAP(float *, tile->comp[0].data, tile->comp[2].data);
1085 if (s->precision <= 8) {
1086 for (compno = 0; compno < s->ncomponents; compno++) {
1087 Jpeg2000Component *comp = tile->comp + compno;
1088 int32_t *datap = (int32_t *)comp->data;
1089 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1090 line = picture->data[0] + y * picture->linesize[0];
1091 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1094 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1095 dst = line + x * s->ncomponents + compno;
1097 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
1098 *datap += 1 << (s->cbps[compno] - 1);
1101 else if (*datap >= (1 << s->cbps[compno]))
1102 *datap = (1 << s->cbps[compno]) - 1;
1104 dst += s->ncomponents;
1106 line += picture->linesize[0];
1110 for (compno = 0; compno < s->ncomponents; compno++) {
1111 Jpeg2000Component *comp = tile->comp + compno;
1112 float *datap = comp->data;
1113 int32_t *i_datap = (int32_t *) comp->data;
1116 y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1117 linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
1118 for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1120 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1121 dst = linel + (x * s->ncomponents + compno);
1122 for (; x < s->avctx->width; x += s->cdx[compno]) {
1124 /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1125 if (s->avctx->flags & CODEC_FLAG_BITEXACT)
1126 val = *i_datap + (1 << (s->cbps[compno] - 1));
1128 val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
1129 val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
1130 /* align 12 bit values in little-endian mode */
1134 dst += s->ncomponents;
1136 linel += picture->linesize[0] >> 1;
1143 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
1146 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1147 for (compno = 0; compno < s->ncomponents; compno++) {
1148 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1149 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1151 ff_jpeg2000_cleanup(comp, codsty);
1153 av_freep(&s->tile[tileno].comp);
1158 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
1160 Jpeg2000CodingStyle *codsty = s->codsty;
1161 Jpeg2000QuantStyle *qntsty = s->qntsty;
1162 uint8_t *properties = s->properties;
1169 if (bytestream2_get_bytes_left(&s->g) < 2) {
1170 av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1174 marker = bytestream2_get_be16u(&s->g);
1175 oldpos = bytestream2_tell(&s->g);
1177 if (marker == JPEG2000_EOC)
1180 if (bytestream2_get_bytes_left(&s->g) < 2)
1181 return AVERROR(EINVAL);
1182 len = bytestream2_get_be16u(&s->g);
1187 s->numXtiles = s->numYtiles = 0;
1190 ret = get_coc(s, codsty, properties);
1193 ret = get_cod(s, codsty, properties);
1196 ret = get_qcc(s, len, qntsty, properties);
1199 ret = get_qcd(s, len, qntsty, properties);
1202 ret = get_sot(s, len);
1205 // the comment is ignored
1206 bytestream2_skip(&s->g, len - 2);
1209 // Tile-part lengths
1210 ret = get_tlm(s, len);
1213 av_log(s->avctx, AV_LOG_ERROR,
1214 "unsupported marker 0x%.4X at pos 0x%X\n",
1215 marker, bytestream2_tell(&s->g) - 4);
1216 bytestream2_skip(&s->g, len - 2);
1219 if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {
1220 av_log(s->avctx, AV_LOG_ERROR,
1221 "error during processing marker segment %.4x\n", marker);
1222 return ret ? ret : -1;
1228 /* Read bit stream packets --> T2 operation. */
1229 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
1232 Jpeg2000Tile *tile = s->tile + s->curtileno;
1234 if (ret = init_tile(s, s->curtileno))
1236 if (ret = jpeg2000_decode_packets(s, tile))
1242 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
1244 uint32_t atom_size, atom;
1245 int found_codestream = 0, search_range = 10;
1247 while(!found_codestream && search_range && bytestream2_get_bytes_left(&s->g) >= 8) {
1248 atom_size = bytestream2_get_be32u(&s->g);
1249 atom = bytestream2_get_be32u(&s->g);
1250 if (atom == JP2_CODESTREAM) {
1251 found_codestream = 1;
1253 if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
1255 bytestream2_skipu(&s->g, atom_size - 8);
1260 if (found_codestream)
1265 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1266 int *got_frame, AVPacket *avpkt)
1268 Jpeg2000DecoderContext *s = avctx->priv_data;
1269 ThreadFrame frame = { .f = data };
1270 AVFrame *picture = data;
1274 bytestream2_init(&s->g, avpkt->data, avpkt->size);
1275 s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
1277 // reduction factor, i.e number of resolution levels to skip
1278 s->reduction_factor = s->lowres;
1280 if (bytestream2_get_bytes_left(&s->g) < 2)
1281 return AVERROR(EINVAL);
1283 // check if the image is in jp2 format
1284 if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1285 (bytestream2_get_be32u(&s->g) == 12) &&
1286 (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1287 (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
1288 if (!jp2_find_codestream(s)) {
1289 av_log(avctx, AV_LOG_ERROR,
1290 "couldn't find jpeg2k codestream atom\n");
1294 bytestream2_seek(&s->g, 0, SEEK_SET);
1295 if (bytestream2_peek_be16(&s->g) != JPEG2000_SOC /*&& AV_RB32(s->buf + 4) == JP2_CODESTREAM*/)
1296 bytestream2_skip(&s->g, 8);
1299 if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1300 av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1303 if (ret = jpeg2000_read_main_headers(s))
1306 /* get picture buffer */
1307 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
1308 av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
1311 picture->pict_type = AV_PICTURE_TYPE_I;
1312 picture->key_frame = 1;
1314 if (ret = jpeg2000_read_bitstream_packets(s))
1316 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1317 if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
1319 jpeg2000_dec_cleanup(s);
1323 return bytestream2_tell(&s->g);
1325 jpeg2000_dec_cleanup(s);
1329 static void jpeg2000_init_static_data(AVCodec *codec)
1331 ff_jpeg2000_init_tier1_luts();
1334 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1335 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1337 static const AVOption options[] = {
1338 { "lowres", "Lower the decoding resolution by a power of two",
1339 OFFSET(lowres), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1343 static const AVProfile profiles[] = {
1344 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1345 { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1346 { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1347 { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1348 { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1349 { FF_PROFILE_UNKNOWN },
1352 static const AVClass class = {
1353 .class_name = "jpeg2000",
1354 .item_name = av_default_item_name,
1356 .version = LIBAVUTIL_VERSION_INT,
1359 AVCodec ff_jpeg2000_decoder = {
1361 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1362 .type = AVMEDIA_TYPE_VIDEO,
1363 .id = AV_CODEC_ID_JPEG2000,
1364 .capabilities = CODEC_CAP_FRAME_THREADS,
1365 .priv_data_size = sizeof(Jpeg2000DecoderContext),
1366 .init_static_data = jpeg2000_init_static_data,
1367 .decode = jpeg2000_decode_frame,
1368 .priv_class = &class,
1369 .pix_fmts = (enum AVPixelFormat[]) { AV_PIX_FMT_XYZ12,
1372 .profiles = NULL_IF_CONFIG_SMALL(profiles)