Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * JPEG 2000 image decoder
  3.  * Copyright (c) 2007 Kamil Nowosad
  4.  * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
  5.  *
  6.  * This file is part of FFmpeg.
  7.  *
  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.
  12.  *
  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.
  17.  *
  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
  21.  */
  22.  
  23. /**
  24.  * @file
  25.  * JPEG 2000 image decoder
  26.  */
  27.  
  28. #include <inttypes.h>
  29.  
  30. #include "libavutil/attributes.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/common.h"
  33. #include "libavutil/imgutils.h"
  34. #include "libavutil/opt.h"
  35. #include "libavutil/pixdesc.h"
  36. #include "avcodec.h"
  37. #include "bytestream.h"
  38. #include "internal.h"
  39. #include "thread.h"
  40. #include "jpeg2000.h"
  41. #include "jpeg2000dsp.h"
  42.  
  43. #define JP2_SIG_TYPE    0x6A502020
  44. #define JP2_SIG_VALUE   0x0D0A870A
  45. #define JP2_CODESTREAM  0x6A703263
  46. #define JP2_HEADER      0x6A703268
  47.  
  48. #define HAD_COC 0x01
  49. #define HAD_QCC 0x02
  50.  
  51. #define MAX_POCS 32
  52.  
  53. typedef struct Jpeg2000POCEntry {
  54.     uint16_t LYEpoc;
  55.     uint16_t CSpoc;
  56.     uint16_t CEpoc;
  57.     uint8_t RSpoc;
  58.     uint8_t REpoc;
  59.     uint8_t Ppoc;
  60. } Jpeg2000POCEntry;
  61.  
  62. typedef struct Jpeg2000POC {
  63.     Jpeg2000POCEntry poc[MAX_POCS];
  64.     int nb_poc;
  65.     int is_default;
  66. } Jpeg2000POC;
  67.  
  68. typedef struct Jpeg2000TilePart {
  69.     uint8_t tile_index;                 // Tile index who refers the tile-part
  70.     const uint8_t *tp_end;
  71.     GetByteContext tpg;                 // bit stream in tile-part
  72. } Jpeg2000TilePart;
  73.  
  74. /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
  75.  * one per component, so tile_part elements have a size of 3 */
  76. typedef struct Jpeg2000Tile {
  77.     Jpeg2000Component   *comp;
  78.     uint8_t             properties[4];
  79.     Jpeg2000CodingStyle codsty[4];
  80.     Jpeg2000QuantStyle  qntsty[4];
  81.     Jpeg2000POC         poc;
  82.     Jpeg2000TilePart    tile_part[256];
  83.     uint16_t tp_idx;                    // Tile-part index
  84.     int coord[2][2];                    // border coordinates {{x0, x1}, {y0, y1}}
  85. } Jpeg2000Tile;
  86.  
  87. typedef struct Jpeg2000DecoderContext {
  88.     AVClass         *class;
  89.     AVCodecContext  *avctx;
  90.     GetByteContext  g;
  91.  
  92.     int             width, height;
  93.     int             image_offset_x, image_offset_y;
  94.     int             tile_offset_x, tile_offset_y;
  95.     uint8_t         cbps[4];    // bits per sample in particular components
  96.     uint8_t         sgnd[4];    // if a component is signed
  97.     uint8_t         properties[4];
  98.     int             cdx[4], cdy[4];
  99.     int             precision;
  100.     int             ncomponents;
  101.     int             colour_space;
  102.     uint32_t        palette[256];
  103.     int8_t          pal8;
  104.     int             cdef[4];
  105.     int             tile_width, tile_height;
  106.     unsigned        numXtiles, numYtiles;
  107.     int             maxtilelen;
  108.  
  109.     Jpeg2000CodingStyle codsty[4];
  110.     Jpeg2000QuantStyle  qntsty[4];
  111.     Jpeg2000POC         poc;
  112.  
  113.     int             bit_index;
  114.  
  115.     int             curtileno;
  116.  
  117.     Jpeg2000Tile    *tile;
  118.     Jpeg2000DSPContext dsp;
  119.  
  120.     /*options parameters*/
  121.     int             reduction_factor;
  122. } Jpeg2000DecoderContext;
  123.  
  124. /* get_bits functions for JPEG2000 packet bitstream
  125.  * It is a get_bit function with a bit-stuffing routine. If the value of the
  126.  * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
  127.  * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
  128. static int get_bits(Jpeg2000DecoderContext *s, int n)
  129. {
  130.     int res = 0;
  131.  
  132.     while (--n >= 0) {
  133.         res <<= 1;
  134.         if (s->bit_index == 0) {
  135.             s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
  136.         }
  137.         s->bit_index--;
  138.         res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
  139.     }
  140.     return res;
  141. }
  142.  
  143. static void jpeg2000_flush(Jpeg2000DecoderContext *s)
  144. {
  145.     if (bytestream2_get_byte(&s->g) == 0xff)
  146.         bytestream2_skip(&s->g, 1);
  147.     s->bit_index = 8;
  148. }
  149.  
  150. /* decode the value stored in node */
  151. static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
  152.                            int threshold)
  153. {
  154.     Jpeg2000TgtNode *stack[30];
  155.     int sp = -1, curval = 0;
  156.  
  157.     if (!node) {
  158.         av_log(s->avctx, AV_LOG_ERROR, "missing node\n");
  159.         return AVERROR_INVALIDDATA;
  160.     }
  161.  
  162.     while (node && !node->vis) {
  163.         stack[++sp] = node;
  164.         node        = node->parent;
  165.     }
  166.  
  167.     if (node)
  168.         curval = node->val;
  169.     else
  170.         curval = stack[sp]->val;
  171.  
  172.     while (curval < threshold && sp >= 0) {
  173.         if (curval < stack[sp]->val)
  174.             curval = stack[sp]->val;
  175.         while (curval < threshold) {
  176.             int ret;
  177.             if ((ret = get_bits(s, 1)) > 0) {
  178.                 stack[sp]->vis++;
  179.                 break;
  180.             } else if (!ret)
  181.                 curval++;
  182.             else
  183.                 return ret;
  184.         }
  185.         stack[sp]->val = curval;
  186.         sp--;
  187.     }
  188.     return curval;
  189. }
  190.  
  191. static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
  192.                          int bpc, uint32_t log2_chroma_wh, int pal8)
  193. {
  194.     int match = 1;
  195.     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
  196.  
  197.     av_assert2(desc);
  198.  
  199.     if (desc->nb_components != components) {
  200.         return 0;
  201.     }
  202.  
  203.     switch (components) {
  204.     case 4:
  205.         match = match && desc->comp[3].depth_minus1 + 1 >= bpc &&
  206.                          (log2_chroma_wh >> 14 & 3) == 0 &&
  207.                          (log2_chroma_wh >> 12 & 3) == 0;
  208.     case 3:
  209.         match = match && desc->comp[2].depth_minus1 + 1 >= bpc &&
  210.                          (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
  211.                          (log2_chroma_wh >>  8 & 3) == desc->log2_chroma_h;
  212.     case 2:
  213.         match = match && desc->comp[1].depth_minus1 + 1 >= bpc &&
  214.                          (log2_chroma_wh >>  6 & 3) == desc->log2_chroma_w &&
  215.                          (log2_chroma_wh >>  4 & 3) == desc->log2_chroma_h;
  216.  
  217.     case 1:
  218.         match = match && desc->comp[0].depth_minus1 + 1 >= bpc &&
  219.                          (log2_chroma_wh >>  2 & 3) == 0 &&
  220.                          (log2_chroma_wh       & 3) == 0 &&
  221.                          (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
  222.     }
  223.     return match;
  224. }
  225.  
  226. // pix_fmts with lower bpp have to be listed before
  227. // similar pix_fmts with higher bpp.
  228. #define RGB_PIXEL_FORMATS   AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
  229. #define GRAY_PIXEL_FORMATS  AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16,AV_PIX_FMT_YA16
  230. #define YUV_PIXEL_FORMATS   AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
  231.                             AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
  232.                             AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
  233.                             AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
  234.                             AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
  235.                             AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
  236.                             AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
  237.                             AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
  238.                             AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
  239.                             AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
  240.                             AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
  241. #define XYZ_PIXEL_FORMATS   AV_PIX_FMT_XYZ12
  242.  
  243. static const enum AVPixelFormat rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
  244. static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
  245. static const enum AVPixelFormat yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
  246. static const enum AVPixelFormat xyz_pix_fmts[]  = {XYZ_PIXEL_FORMATS,
  247.                                                    YUV_PIXEL_FORMATS};
  248. static const enum AVPixelFormat all_pix_fmts[]  = {RGB_PIXEL_FORMATS,
  249.                                                    GRAY_PIXEL_FORMATS,
  250.                                                    YUV_PIXEL_FORMATS,
  251.                                                    XYZ_PIXEL_FORMATS};
  252.  
  253. /* marker segments */
  254. /* get sizes and offsets of image, tiles; number of components */
  255. static int get_siz(Jpeg2000DecoderContext *s)
  256. {
  257.     int i;
  258.     int ncomponents;
  259.     uint32_t log2_chroma_wh = 0;
  260.     const enum AVPixelFormat *possible_fmts = NULL;
  261.     int possible_fmts_nb = 0;
  262.  
  263.     if (bytestream2_get_bytes_left(&s->g) < 36) {
  264.         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for SIZ\n");
  265.         return AVERROR_INVALIDDATA;
  266.     }
  267.  
  268.     s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
  269.     s->width          = bytestream2_get_be32u(&s->g); // Width
  270.     s->height         = bytestream2_get_be32u(&s->g); // Height
  271.     s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
  272.     s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
  273.     s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz
  274.     s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz
  275.     s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz
  276.     s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz
  277.     ncomponents       = bytestream2_get_be16u(&s->g); // CSiz
  278.  
  279.     if (s->image_offset_x || s->image_offset_y) {
  280.         avpriv_request_sample(s->avctx, "Support for image offsets");
  281.         return AVERROR_PATCHWELCOME;
  282.     }
  283.     if (av_image_check_size(s->width, s->height, 0, s->avctx)) {
  284.         avpriv_request_sample(s->avctx, "Large Dimensions");
  285.         return AVERROR_PATCHWELCOME;
  286.     }
  287.  
  288.     if (ncomponents <= 0) {
  289.         av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
  290.                s->ncomponents);
  291.         return AVERROR_INVALIDDATA;
  292.     }
  293.  
  294.     if (ncomponents > 4) {
  295.         avpriv_request_sample(s->avctx, "Support for %d components",
  296.                               ncomponents);
  297.         return AVERROR_PATCHWELCOME;
  298.     }
  299.  
  300.     s->ncomponents = ncomponents;
  301.  
  302.     if (s->tile_width <= 0 || s->tile_height <= 0) {
  303.         av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
  304.                s->tile_width, s->tile_height);
  305.         return AVERROR_INVALIDDATA;
  306.     }
  307.  
  308.     if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) {
  309.         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for %d components in SIZ\n", s->ncomponents);
  310.         return AVERROR_INVALIDDATA;
  311.     }
  312.  
  313.     for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
  314.         uint8_t x    = bytestream2_get_byteu(&s->g);
  315.         s->cbps[i]   = (x & 0x7f) + 1;
  316.         s->precision = FFMAX(s->cbps[i], s->precision);
  317.         s->sgnd[i]   = !!(x & 0x80);
  318.         s->cdx[i]    = bytestream2_get_byteu(&s->g);
  319.         s->cdy[i]    = bytestream2_get_byteu(&s->g);
  320.         if (   !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
  321.             || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
  322.             av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
  323.             return AVERROR_INVALIDDATA;
  324.         }
  325.         log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
  326.     }
  327.  
  328.     s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
  329.     s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
  330.  
  331.     if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
  332.         s->numXtiles = s->numYtiles = 0;
  333.         return AVERROR(EINVAL);
  334.     }
  335.  
  336.     s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
  337.     if (!s->tile) {
  338.         s->numXtiles = s->numYtiles = 0;
  339.         return AVERROR(ENOMEM);
  340.     }
  341.  
  342.     for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
  343.         Jpeg2000Tile *tile = s->tile + i;
  344.  
  345.         tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
  346.         if (!tile->comp)
  347.             return AVERROR(ENOMEM);
  348.     }
  349.  
  350.     /* compute image size with reduction factor */
  351.     s->avctx->width  = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,
  352.                                                s->reduction_factor);
  353.     s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
  354.                                                s->reduction_factor);
  355.  
  356.     if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
  357.         s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
  358.         possible_fmts = xyz_pix_fmts;
  359.         possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
  360.     } else {
  361.         switch (s->colour_space) {
  362.         case 16:
  363.             possible_fmts = rgb_pix_fmts;
  364.             possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
  365.             break;
  366.         case 17:
  367.             possible_fmts = gray_pix_fmts;
  368.             possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
  369.             break;
  370.         case 18:
  371.             possible_fmts = yuv_pix_fmts;
  372.             possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
  373.             break;
  374.         default:
  375.             possible_fmts = all_pix_fmts;
  376.             possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
  377.             break;
  378.         }
  379.     }
  380.     for (i = 0; i < possible_fmts_nb; ++i) {
  381.         if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
  382.             s->avctx->pix_fmt = possible_fmts[i];
  383.             break;
  384.         }
  385.     }
  386.  
  387.     if (i == possible_fmts_nb) {
  388.         if (ncomponents == 4 &&
  389.             s->cdy[0] == 1 && s->cdx[0] == 1 &&
  390.             s->cdy[1] == 1 && s->cdx[1] == 1 &&
  391.             s->cdy[2] == s->cdy[3] && s->cdx[2] == s->cdx[3]) {
  392.             if (s->precision == 8 && s->cdy[2] == 2 && s->cdx[2] == 2 && !s->pal8) {
  393.                 s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
  394.                 s->cdef[0] = 0;
  395.                 s->cdef[1] = 1;
  396.                 s->cdef[2] = 2;
  397.                 s->cdef[3] = 3;
  398.                 i = 0;
  399.             }
  400.         }
  401.     }
  402.  
  403.  
  404.     if (i == possible_fmts_nb) {
  405.         av_log(s->avctx, AV_LOG_ERROR,
  406.                "Unknown pix_fmt, profile: %d, colour_space: %d, "
  407.                "components: %d, precision: %d\n"
  408.                "cdx[0]: %d, cdy[0]: %d\n"
  409.                "cdx[1]: %d, cdy[1]: %d\n"
  410.                "cdx[2]: %d, cdy[2]: %d\n"
  411.                "cdx[3]: %d, cdy[3]: %d\n",
  412.                s->avctx->profile, s->colour_space, ncomponents, s->precision,
  413.                s->cdx[0],
  414.                s->cdy[0],
  415.                ncomponents > 1 ? s->cdx[1] : 0,
  416.                ncomponents > 1 ? s->cdy[1] : 0,
  417.                ncomponents > 2 ? s->cdx[2] : 0,
  418.                ncomponents > 2 ? s->cdy[2] : 0,
  419.                ncomponents > 3 ? s->cdx[3] : 0,
  420.                ncomponents > 3 ? s->cdy[3] : 0);
  421.         return AVERROR_PATCHWELCOME;
  422.     }
  423.     s->avctx->bits_per_raw_sample = s->precision;
  424.     return 0;
  425. }
  426.  
  427. /* get common part for COD and COC segments */
  428. static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
  429. {
  430.     uint8_t byte;
  431.  
  432.     if (bytestream2_get_bytes_left(&s->g) < 5) {
  433.         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COX\n");
  434.         return AVERROR_INVALIDDATA;
  435.     }
  436.  
  437.     /*  nreslevels = number of resolution levels
  438.                    = number of decomposition level +1 */
  439.     c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
  440.     if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
  441.         av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
  442.         return AVERROR_INVALIDDATA;
  443.     }
  444.  
  445.     if (c->nreslevels <= s->reduction_factor) {
  446.         /* we are forced to update reduction_factor as its requested value is
  447.            not compatible with this bitstream, and as we might have used it
  448.            already in setup earlier we have to fail this frame until
  449.            reinitialization is implemented */
  450.         av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1);
  451.         s->reduction_factor = c->nreslevels - 1;
  452.         return AVERROR(EINVAL);
  453.     }
  454.  
  455.     /* compute number of resolution levels to decode */
  456.     c->nreslevels2decode = c->nreslevels - s->reduction_factor;
  457.  
  458.     c->log2_cblk_width  = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
  459.     c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
  460.  
  461.     if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
  462.         c->log2_cblk_width + c->log2_cblk_height > 12) {
  463.         av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
  464.         return AVERROR_INVALIDDATA;
  465.     }
  466.  
  467.     c->cblk_style = bytestream2_get_byteu(&s->g);
  468.     if (c->cblk_style != 0) { // cblk style
  469.         av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
  470.         if (c->cblk_style & JPEG2000_CBLK_BYPASS)
  471.             av_log(s->avctx, AV_LOG_WARNING, "Selective arithmetic coding bypass\n");
  472.     }
  473.     c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
  474.     /* set integer 9/7 DWT in case of BITEXACT flag */
  475.     if ((s->avctx->flags & AV_CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
  476.         c->transform = FF_DWT97_INT;
  477.     else if (c->transform == FF_DWT53) {
  478.         s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
  479.     }
  480.  
  481.     if (c->csty & JPEG2000_CSTY_PREC) {
  482.         int i;
  483.         for (i = 0; i < c->nreslevels; i++) {
  484.             byte = bytestream2_get_byte(&s->g);
  485.             c->log2_prec_widths[i]  =  byte       & 0x0F;    // precinct PPx
  486.             c->log2_prec_heights[i] = (byte >> 4) & 0x0F;    // precinct PPy
  487.             if (i)
  488.                 if (c->log2_prec_widths[i] == 0 || c->log2_prec_heights[i] == 0) {
  489.                     av_log(s->avctx, AV_LOG_ERROR, "PPx %d PPy %d invalid\n",
  490.                            c->log2_prec_widths[i], c->log2_prec_heights[i]);
  491.                     c->log2_prec_widths[i] = c->log2_prec_heights[i] = 1;
  492.                     return AVERROR_INVALIDDATA;
  493.                 }
  494.         }
  495.     } else {
  496.         memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
  497.         memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
  498.     }
  499.     return 0;
  500. }
  501.  
  502. /* get coding parameters for a particular tile or whole image*/
  503. static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  504.                    uint8_t *properties)
  505. {
  506.     Jpeg2000CodingStyle tmp;
  507.     int compno, ret;
  508.  
  509.     if (bytestream2_get_bytes_left(&s->g) < 5) {
  510.         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COD\n");
  511.         return AVERROR_INVALIDDATA;
  512.     }
  513.  
  514.     tmp.csty = bytestream2_get_byteu(&s->g);
  515.  
  516.     // get progression order
  517.     tmp.prog_order = bytestream2_get_byteu(&s->g);
  518.  
  519.     tmp.nlayers    = bytestream2_get_be16u(&s->g);
  520.     tmp.mct        = bytestream2_get_byteu(&s->g); // multiple component transformation
  521.  
  522.     if (tmp.mct && s->ncomponents < 3) {
  523.         av_log(s->avctx, AV_LOG_ERROR,
  524.                "MCT %"PRIu8" with too few components (%d)\n",
  525.                tmp.mct, s->ncomponents);
  526.         return AVERROR_INVALIDDATA;
  527.     }
  528.  
  529.     if ((ret = get_cox(s, &tmp)) < 0)
  530.         return ret;
  531.  
  532.     for (compno = 0; compno < s->ncomponents; compno++)
  533.         if (!(properties[compno] & HAD_COC))
  534.             memcpy(c + compno, &tmp, sizeof(tmp));
  535.     return 0;
  536. }
  537.  
  538. /* Get coding parameters for a component in the whole image or a
  539.  * particular tile. */
  540. static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  541.                    uint8_t *properties)
  542. {
  543.     int compno, ret;
  544.  
  545.     if (bytestream2_get_bytes_left(&s->g) < 2) {
  546.         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COC\n");
  547.         return AVERROR_INVALIDDATA;
  548.     }
  549.  
  550.     compno = bytestream2_get_byteu(&s->g);
  551.  
  552.     if (compno >= s->ncomponents) {
  553.         av_log(s->avctx, AV_LOG_ERROR,
  554.                "Invalid compno %d. There are %d components in the image.\n",
  555.                compno, s->ncomponents);
  556.         return AVERROR_INVALIDDATA;
  557.     }
  558.  
  559.     c      += compno;
  560.     c->csty = bytestream2_get_byteu(&s->g);
  561.  
  562.     if ((ret = get_cox(s, c)) < 0)
  563.         return ret;
  564.  
  565.     properties[compno] |= HAD_COC;
  566.     return 0;
  567. }
  568.  
  569. /* Get common part for QCD and QCC segments. */
  570. static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
  571. {
  572.     int i, x;
  573.  
  574.     if (bytestream2_get_bytes_left(&s->g) < 1)
  575.         return AVERROR_INVALIDDATA;
  576.  
  577.     x = bytestream2_get_byteu(&s->g); // Sqcd
  578.  
  579.     q->nguardbits = x >> 5;
  580.     q->quantsty   = x & 0x1f;
  581.  
  582.     if (q->quantsty == JPEG2000_QSTY_NONE) {
  583.         n -= 3;
  584.         if (bytestream2_get_bytes_left(&s->g) < n ||
  585.             n > JPEG2000_MAX_DECLEVELS*3)
  586.             return AVERROR_INVALIDDATA;
  587.         for (i = 0; i < n; i++)
  588.             q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
  589.     } else if (q->quantsty == JPEG2000_QSTY_SI) {
  590.         if (bytestream2_get_bytes_left(&s->g) < 2)
  591.             return AVERROR_INVALIDDATA;
  592.         x          = bytestream2_get_be16u(&s->g);
  593.         q->expn[0] = x >> 11;
  594.         q->mant[0] = x & 0x7ff;
  595.         for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
  596.             int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
  597.             q->expn[i] = curexpn;
  598.             q->mant[i] = q->mant[0];
  599.         }
  600.     } else {
  601.         n = (n - 3) >> 1;
  602.         if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
  603.             n > JPEG2000_MAX_DECLEVELS*3)
  604.             return AVERROR_INVALIDDATA;
  605.         for (i = 0; i < n; i++) {
  606.             x          = bytestream2_get_be16u(&s->g);
  607.             q->expn[i] = x >> 11;
  608.             q->mant[i] = x & 0x7ff;
  609.         }
  610.     }
  611.     return 0;
  612. }
  613.  
  614. /* Get quantization parameters for a particular tile or a whole image. */
  615. static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  616.                    uint8_t *properties)
  617. {
  618.     Jpeg2000QuantStyle tmp;
  619.     int compno, ret;
  620.  
  621.     memset(&tmp, 0, sizeof(tmp));
  622.  
  623.     if ((ret = get_qcx(s, n, &tmp)) < 0)
  624.         return ret;
  625.     for (compno = 0; compno < s->ncomponents; compno++)
  626.         if (!(properties[compno] & HAD_QCC))
  627.             memcpy(q + compno, &tmp, sizeof(tmp));
  628.     return 0;
  629. }
  630.  
  631. /* Get quantization parameters for a component in the whole image
  632.  * on in a particular tile. */
  633. static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  634.                    uint8_t *properties)
  635. {
  636.     int compno;
  637.  
  638.     if (bytestream2_get_bytes_left(&s->g) < 1)
  639.         return AVERROR_INVALIDDATA;
  640.  
  641.     compno = bytestream2_get_byteu(&s->g);
  642.  
  643.     if (compno >= s->ncomponents) {
  644.         av_log(s->avctx, AV_LOG_ERROR,
  645.                "Invalid compno %d. There are %d components in the image.\n",
  646.                compno, s->ncomponents);
  647.         return AVERROR_INVALIDDATA;
  648.     }
  649.  
  650.     properties[compno] |= HAD_QCC;
  651.     return get_qcx(s, n - 1, q + compno);
  652. }
  653.  
  654. static int get_poc(Jpeg2000DecoderContext *s, int size, Jpeg2000POC *p)
  655. {
  656.     int i;
  657.     int elem_size = s->ncomponents <= 257 ? 7 : 9;
  658.     Jpeg2000POC tmp = {{{0}}};
  659.  
  660.     if (bytestream2_get_bytes_left(&s->g) < 5 || size < 2 + elem_size) {
  661.         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for POC\n");
  662.         return AVERROR_INVALIDDATA;
  663.     }
  664.  
  665.     if (elem_size > 7) {
  666.         avpriv_request_sample(s->avctx, "Fat POC not supported");
  667.         return AVERROR_PATCHWELCOME;
  668.     }
  669.  
  670.     tmp.nb_poc = (size - 2) / elem_size;
  671.     if (tmp.nb_poc > MAX_POCS) {
  672.         avpriv_request_sample(s->avctx, "Too many POCs (%d)", tmp.nb_poc);
  673.         return AVERROR_PATCHWELCOME;
  674.     }
  675.  
  676.     for (i = 0; i<tmp.nb_poc; i++) {
  677.         Jpeg2000POCEntry *e = &tmp.poc[i];
  678.         e->RSpoc  = bytestream2_get_byteu(&s->g);
  679.         e->CSpoc  = bytestream2_get_byteu(&s->g);
  680.         e->LYEpoc = bytestream2_get_be16u(&s->g);
  681.         e->REpoc  = bytestream2_get_byteu(&s->g);
  682.         e->CEpoc  = bytestream2_get_byteu(&s->g);
  683.         e->Ppoc   = bytestream2_get_byteu(&s->g);
  684.         if (!e->CEpoc)
  685.             e->CEpoc = 256;
  686.         if (e->CEpoc > s->ncomponents)
  687.             e->CEpoc = s->ncomponents;
  688.         if (   e->RSpoc >= e->REpoc || e->REpoc > 33
  689.             || e->CSpoc >= e->CEpoc || e->CEpoc > s->ncomponents
  690.             || !e->LYEpoc) {
  691.             av_log(s->avctx, AV_LOG_ERROR, "POC Entry %d is invalid (%d, %d, %d, %d, %d, %d)\n", i,
  692.                 e->RSpoc, e->CSpoc, e->LYEpoc, e->REpoc, e->CEpoc, e->Ppoc
  693.             );
  694.             return AVERROR_INVALIDDATA;
  695.         }
  696.     }
  697.  
  698.     if (!p->nb_poc || p->is_default) {
  699.         *p = tmp;
  700.     } else {
  701.         if (p->nb_poc + tmp.nb_poc > MAX_POCS) {
  702.             av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for POC\n");
  703.             return AVERROR_INVALIDDATA;
  704.         }
  705.         memcpy(p->poc + p->nb_poc, tmp.poc, tmp.nb_poc * sizeof(tmp.poc[0]));
  706.         p->nb_poc += tmp.nb_poc;
  707.     }
  708.  
  709.     p->is_default = 0;
  710.  
  711.     return 0;
  712. }
  713.  
  714.  
  715. /* Get start of tile segment. */
  716. static int get_sot(Jpeg2000DecoderContext *s, int n)
  717. {
  718.     Jpeg2000TilePart *tp;
  719.     uint16_t Isot;
  720.     uint32_t Psot;
  721.     unsigned TPsot;
  722.  
  723.     if (bytestream2_get_bytes_left(&s->g) < 8)
  724.         return AVERROR_INVALIDDATA;
  725.  
  726.     s->curtileno = 0;
  727.     Isot = bytestream2_get_be16u(&s->g);        // Isot
  728.     if (Isot >= s->numXtiles * s->numYtiles)
  729.         return AVERROR_INVALIDDATA;
  730.  
  731.     s->curtileno = Isot;
  732.     Psot  = bytestream2_get_be32u(&s->g);       // Psot
  733.     TPsot = bytestream2_get_byteu(&s->g);       // TPsot
  734.  
  735.     /* Read TNSot but not used */
  736.     bytestream2_get_byteu(&s->g);               // TNsot
  737.  
  738.     if (!Psot)
  739.         Psot = bytestream2_get_bytes_left(&s->g) + n + 2;
  740.  
  741.     if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
  742.         av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);
  743.         return AVERROR_INVALIDDATA;
  744.     }
  745.  
  746.     av_assert0(TPsot < FF_ARRAY_ELEMS(s->tile[Isot].tile_part));
  747.  
  748.     s->tile[Isot].tp_idx = TPsot;
  749.     tp             = s->tile[Isot].tile_part + TPsot;
  750.     tp->tile_index = Isot;
  751.     tp->tp_end     = s->g.buffer + Psot - n - 2;
  752.  
  753.     if (!TPsot) {
  754.         Jpeg2000Tile *tile = s->tile + s->curtileno;
  755.  
  756.         /* copy defaults */
  757.         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
  758.         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
  759.         memcpy(&tile->poc  , &s->poc  , sizeof(tile->poc));
  760.         tile->poc.is_default = 1;
  761.     }
  762.  
  763.     return 0;
  764. }
  765.  
  766. /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
  767.  * Used to know the number of tile parts and lengths.
  768.  * There may be multiple TLMs in the header.
  769.  * TODO: The function is not used for tile-parts management, nor anywhere else.
  770.  * It can be useful to allocate memory for tile parts, before managing the SOT
  771.  * markers. Parsing the TLM header is needed to increment the input header
  772.  * buffer.
  773.  * This marker is mandatory for DCI. */
  774. static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
  775. {
  776.     uint8_t Stlm, ST, SP, tile_tlm, i;
  777.     bytestream2_get_byte(&s->g);               /* Ztlm: skipped */
  778.     Stlm = bytestream2_get_byte(&s->g);
  779.  
  780.     // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
  781.     ST = (Stlm >> 4) & 0x03;
  782.     // TODO: Manage case of ST = 0b11 --> raise error
  783.     SP       = (Stlm >> 6) & 0x01;
  784.     tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
  785.     for (i = 0; i < tile_tlm; i++) {
  786.         switch (ST) {
  787.         case 0:
  788.             break;
  789.         case 1:
  790.             bytestream2_get_byte(&s->g);
  791.             break;
  792.         case 2:
  793.             bytestream2_get_be16(&s->g);
  794.             break;
  795.         case 3:
  796.             bytestream2_get_be32(&s->g);
  797.             break;
  798.         }
  799.         if (SP == 0) {
  800.             bytestream2_get_be16(&s->g);
  801.         } else {
  802.             bytestream2_get_be32(&s->g);
  803.         }
  804.     }
  805.     return 0;
  806. }
  807.  
  808. static uint8_t get_plt(Jpeg2000DecoderContext *s, int n)
  809. {
  810.     int i;
  811.  
  812.     av_log(s->avctx, AV_LOG_DEBUG,
  813.             "PLT marker at pos 0x%X\n", bytestream2_tell(&s->g) - 4);
  814.  
  815.     /*Zplt =*/ bytestream2_get_byte(&s->g);
  816.  
  817.     for (i = 0; i < n - 3; i++) {
  818.         bytestream2_get_byte(&s->g);
  819.     }
  820.  
  821.     return 0;
  822. }
  823.  
  824. static int init_tile(Jpeg2000DecoderContext *s, int tileno)
  825. {
  826.     int compno;
  827.     int tilex = tileno % s->numXtiles;
  828.     int tiley = tileno / s->numXtiles;
  829.     Jpeg2000Tile *tile = s->tile + tileno;
  830.  
  831.     if (!tile->comp)
  832.         return AVERROR(ENOMEM);
  833.  
  834.     tile->coord[0][0] = av_clip(tilex       * (int64_t)s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);
  835.     tile->coord[0][1] = av_clip((tilex + 1) * (int64_t)s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);
  836.     tile->coord[1][0] = av_clip(tiley       * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
  837.     tile->coord[1][1] = av_clip((tiley + 1) * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
  838.  
  839.     for (compno = 0; compno < s->ncomponents; compno++) {
  840.         Jpeg2000Component *comp = tile->comp + compno;
  841.         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  842.         Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
  843.         int ret; // global bandno
  844.  
  845.         comp->coord_o[0][0] = tile->coord[0][0];
  846.         comp->coord_o[0][1] = tile->coord[0][1];
  847.         comp->coord_o[1][0] = tile->coord[1][0];
  848.         comp->coord_o[1][1] = tile->coord[1][1];
  849.         if (compno) {
  850.             comp->coord_o[0][0] /= s->cdx[compno];
  851.             comp->coord_o[0][1] /= s->cdx[compno];
  852.             comp->coord_o[1][0] /= s->cdy[compno];
  853.             comp->coord_o[1][1] /= s->cdy[compno];
  854.         }
  855.  
  856.         comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
  857.         comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
  858.         comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
  859.         comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
  860.  
  861.         if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
  862.                                              s->cbps[compno], s->cdx[compno],
  863.                                              s->cdy[compno], s->avctx))
  864.             return ret;
  865.     }
  866.     return 0;
  867. }
  868.  
  869. /* Read the number of coding passes. */
  870. static int getnpasses(Jpeg2000DecoderContext *s)
  871. {
  872.     int num;
  873.     if (!get_bits(s, 1))
  874.         return 1;
  875.     if (!get_bits(s, 1))
  876.         return 2;
  877.     if ((num = get_bits(s, 2)) != 3)
  878.         return num < 0 ? num : 3 + num;
  879.     if ((num = get_bits(s, 5)) != 31)
  880.         return num < 0 ? num : 6 + num;
  881.     num = get_bits(s, 7);
  882.     return num < 0 ? num : 37 + num;
  883. }
  884.  
  885. static int getlblockinc(Jpeg2000DecoderContext *s)
  886. {
  887.     int res = 0, ret;
  888.     while (ret = get_bits(s, 1)) {
  889.         if (ret < 0)
  890.             return ret;
  891.         res++;
  892.     }
  893.     return res;
  894. }
  895.  
  896. static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index,
  897.                                   Jpeg2000CodingStyle *codsty,
  898.                                   Jpeg2000ResLevel *rlevel, int precno,
  899.                                   int layno, uint8_t *expn, int numgbits)
  900. {
  901.     int bandno, cblkno, ret, nb_code_blocks;
  902.     int cwsno;
  903.  
  904.     if (layno < rlevel->band[0].prec[precno].decoded_layers)
  905.         return 0;
  906.     rlevel->band[0].prec[precno].decoded_layers = layno + 1;
  907.  
  908.     if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {
  909.         if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {
  910.             s->g = tile->tile_part[++(*tp_index)].tpg;
  911.         }
  912.     }
  913.  
  914.     if (bytestream2_peek_be32(&s->g) == JPEG2000_SOP_FIXED_BYTES)
  915.         bytestream2_skip(&s->g, JPEG2000_SOP_BYTE_LENGTH);
  916.  
  917.     if (!(ret = get_bits(s, 1))) {
  918.         jpeg2000_flush(s);
  919.         return 0;
  920.     } else if (ret < 0)
  921.         return ret;
  922.  
  923.     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  924.         Jpeg2000Band *band = rlevel->band + bandno;
  925.         Jpeg2000Prec *prec = band->prec + precno;
  926.  
  927.         if (band->coord[0][0] == band->coord[0][1] ||
  928.             band->coord[1][0] == band->coord[1][1])
  929.             continue;
  930.         nb_code_blocks =  prec->nb_codeblocks_height *
  931.                           prec->nb_codeblocks_width;
  932.         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  933.             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  934.             int incl, newpasses, llen;
  935.  
  936.             if (cblk->npasses)
  937.                 incl = get_bits(s, 1);
  938.             else
  939.                 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
  940.             if (!incl)
  941.                 continue;
  942.             else if (incl < 0)
  943.                 return incl;
  944.  
  945.             if (!cblk->npasses) {
  946.                 int v = expn[bandno] + numgbits - 1 -
  947.                         tag_tree_decode(s, prec->zerobits + cblkno, 100);
  948.                 if (v < 0) {
  949.                     av_log(s->avctx, AV_LOG_ERROR,
  950.                            "nonzerobits %d invalid\n", v);
  951.                     return AVERROR_INVALIDDATA;
  952.                 }
  953.                 cblk->nonzerobits = v;
  954.             }
  955.             if ((newpasses = getnpasses(s)) < 0)
  956.                 return newpasses;
  957.             av_assert2(newpasses > 0);
  958.             if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) {
  959.                 avpriv_request_sample(s->avctx, "Too many passes");
  960.                 return AVERROR_PATCHWELCOME;
  961.             }
  962.             if ((llen = getlblockinc(s)) < 0)
  963.                 return llen;
  964.             if (cblk->lblock + llen + av_log2(newpasses) > 16) {
  965.                 avpriv_request_sample(s->avctx,
  966.                                       "Block with length beyond 16 bits");
  967.                 return AVERROR_PATCHWELCOME;
  968.             }
  969.  
  970.             cblk->lblock += llen;
  971.  
  972.             cblk->nb_lengthinc = 0;
  973.             cblk->nb_terminationsinc = 0;
  974.             do {
  975.                 int newpasses1 = 0;
  976.  
  977.                 while (newpasses1 < newpasses) {
  978.                     newpasses1 ++;
  979.                     if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) {
  980.                         cblk->nb_terminationsinc ++;
  981.                         break;
  982.                     }
  983.                 }
  984.  
  985.                 if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0)
  986.                     return ret;
  987.                 if (ret > sizeof(cblk->data)) {
  988.                     avpriv_request_sample(s->avctx,
  989.                                         "Block with lengthinc greater than %"SIZE_SPECIFIER"",
  990.                                         sizeof(cblk->data));
  991.                     return AVERROR_PATCHWELCOME;
  992.                 }
  993.                 cblk->lengthinc[cblk->nb_lengthinc++] = ret;
  994.                 cblk->npasses  += newpasses1;
  995.                 newpasses -= newpasses1;
  996.             } while(newpasses);
  997.         }
  998.     }
  999.     jpeg2000_flush(s);
  1000.  
  1001.     if (codsty->csty & JPEG2000_CSTY_EPH) {
  1002.         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
  1003.             bytestream2_skip(&s->g, 2);
  1004.         else
  1005.             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
  1006.     }
  1007.  
  1008.     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  1009.         Jpeg2000Band *band = rlevel->band + bandno;
  1010.         Jpeg2000Prec *prec = band->prec + precno;
  1011.  
  1012.         nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
  1013.         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  1014.             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  1015.             for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) {
  1016.                 if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno]
  1017.                     || sizeof(cblk->data) < cblk->length + cblk->lengthinc[cwsno] + 4
  1018.                 ) {
  1019.                     av_log(s->avctx, AV_LOG_ERROR,
  1020.                         "Block length %"PRIu16" or lengthinc %d is too large, left %d\n",
  1021.                         cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g));
  1022.                     return AVERROR_INVALIDDATA;
  1023.                 }
  1024.  
  1025.                 bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]);
  1026.                 cblk->length   += cblk->lengthinc[cwsno];
  1027.                 cblk->lengthinc[cwsno] = 0;
  1028.                 if (cblk->nb_terminationsinc) {
  1029.                     cblk->nb_terminationsinc--;
  1030.                     cblk->nb_terminations++;
  1031.                     cblk->data[cblk->length++] = 0xFF;
  1032.                     cblk->data[cblk->length++] = 0xFF;
  1033.                     cblk->data_start[cblk->nb_terminations] = cblk->length;
  1034.                 }
  1035.             }
  1036.         }
  1037.     }
  1038.     return 0;
  1039. }
  1040.  
  1041. static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
  1042.                                              int RSpoc, int CSpoc,
  1043.                                              int LYEpoc, int REpoc, int CEpoc,
  1044.                                              int Ppoc, int *tp_index)
  1045. {
  1046.     int ret = 0;
  1047.     int layno, reslevelno, compno, precno, ok_reslevel;
  1048.     int x, y;
  1049.     int step_x, step_y;
  1050.  
  1051.     switch (Ppoc) {
  1052.     case JPEG2000_PGOD_RLCP:
  1053.         av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");
  1054.         ok_reslevel = 1;
  1055.         for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
  1056.             ok_reslevel = 0;
  1057.             for (layno = 0; layno < LYEpoc; layno++) {
  1058.                 for (compno = CSpoc; compno < CEpoc; compno++) {
  1059.                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1060.                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
  1061.                     if (reslevelno < codsty->nreslevels) {
  1062.                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
  1063.                                                 reslevelno;
  1064.                         ok_reslevel = 1;
  1065.                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
  1066.                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
  1067.                                                               codsty, rlevel,
  1068.                                                               precno, layno,
  1069.                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  1070.                                                               qntsty->nguardbits)) < 0)
  1071.                                 return ret;
  1072.                     }
  1073.                 }
  1074.             }
  1075.         }
  1076.         break;
  1077.  
  1078.     case JPEG2000_PGOD_LRCP:
  1079.         av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");
  1080.         for (layno = 0; layno < LYEpoc; layno++) {
  1081.             ok_reslevel = 1;
  1082.             for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
  1083.                 ok_reslevel = 0;
  1084.                 for (compno = CSpoc; compno < CEpoc; compno++) {
  1085.                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1086.                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
  1087.                     if (reslevelno < codsty->nreslevels) {
  1088.                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
  1089.                                                 reslevelno;
  1090.                         ok_reslevel = 1;
  1091.                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
  1092.                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
  1093.                                                               codsty, rlevel,
  1094.                                                               precno, layno,
  1095.                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  1096.                                                               qntsty->nguardbits)) < 0)
  1097.                                 return ret;
  1098.                     }
  1099.                 }
  1100.             }
  1101.         }
  1102.         break;
  1103.  
  1104.     case JPEG2000_PGOD_CPRL:
  1105.         av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");
  1106.         for (compno = CSpoc; compno < CEpoc; compno++) {
  1107.             Jpeg2000Component *comp     = tile->comp + compno;
  1108.             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1109.             Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
  1110.             step_x = 32;
  1111.             step_y = 32;
  1112.  
  1113.             for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
  1114.                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
  1115.                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1116.                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
  1117.                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
  1118.             }
  1119.             av_assert0(step_x < 32 && step_y < 32);
  1120.             step_x = 1<<step_x;
  1121.             step_y = 1<<step_y;
  1122.  
  1123.             for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
  1124.                 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
  1125.                     for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
  1126.                         unsigned prcx, prcy;
  1127.                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
  1128.                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1129.                         int xc = x / s->cdx[compno];
  1130.                         int yc = y / s->cdy[compno];
  1131.  
  1132.                         if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
  1133.                             continue;
  1134.  
  1135.                         if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
  1136.                             continue;
  1137.  
  1138.                         // check if a precinct exists
  1139.                         prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
  1140.                         prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
  1141.                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
  1142.                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
  1143.  
  1144.                         precno = prcx + rlevel->num_precincts_x * prcy;
  1145.  
  1146.                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
  1147.                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
  1148.                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
  1149.                             continue;
  1150.                         }
  1151.  
  1152.                         for (layno = 0; layno < LYEpoc; layno++) {
  1153.                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
  1154.                                                               precno, layno,
  1155.                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  1156.                                                               qntsty->nguardbits)) < 0)
  1157.                                 return ret;
  1158.                         }
  1159.                     }
  1160.                 }
  1161.             }
  1162.         }
  1163.         break;
  1164.  
  1165.     case JPEG2000_PGOD_RPCL:
  1166.         av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");
  1167.         ok_reslevel = 1;
  1168.         for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
  1169.             ok_reslevel = 0;
  1170.             step_x = 30;
  1171.             step_y = 30;
  1172.             for (compno = CSpoc; compno < CEpoc; compno++) {
  1173.                 Jpeg2000Component *comp     = tile->comp + compno;
  1174.                 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1175.  
  1176.                 if (reslevelno < codsty->nreslevels) {
  1177.                     uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
  1178.                     Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1179.                     step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
  1180.                     step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
  1181.                 }
  1182.             }
  1183.             step_x = 1<<step_x;
  1184.             step_y = 1<<step_y;
  1185.  
  1186.             for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
  1187.                 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
  1188.                     for (compno = CSpoc; compno < CEpoc; compno++) {
  1189.                         Jpeg2000Component *comp     = tile->comp + compno;
  1190.                         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1191.                         Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
  1192.                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
  1193.                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1194.                         unsigned prcx, prcy;
  1195.  
  1196.                         int xc = x / s->cdx[compno];
  1197.                         int yc = y / s->cdy[compno];
  1198.  
  1199.                         if (reslevelno >= codsty->nreslevels)
  1200.                             continue;
  1201.  
  1202.                         if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
  1203.                             continue;
  1204.  
  1205.                         if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
  1206.                             continue;
  1207.  
  1208.                         // check if a precinct exists
  1209.                         prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
  1210.                         prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
  1211.                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
  1212.                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
  1213.  
  1214.                         precno = prcx + rlevel->num_precincts_x * prcy;
  1215.  
  1216.                         ok_reslevel = 1;
  1217.                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
  1218.                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
  1219.                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
  1220.                             continue;
  1221.                         }
  1222.  
  1223.                             for (layno = 0; layno < LYEpoc; layno++) {
  1224.                                 if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
  1225.                                                                 codsty, rlevel,
  1226.                                                                 precno, layno,
  1227.                                                                 qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  1228.                                                                 qntsty->nguardbits)) < 0)
  1229.                                     return ret;
  1230.                             }
  1231.                     }
  1232.                 }
  1233.             }
  1234.         }
  1235.         break;
  1236.  
  1237.     case JPEG2000_PGOD_PCRL:
  1238.         av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL\n");
  1239.         step_x = 32;
  1240.         step_y = 32;
  1241.         for (compno = CSpoc; compno < CEpoc; compno++) {
  1242.             Jpeg2000Component *comp     = tile->comp + compno;
  1243.             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1244.  
  1245.             for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
  1246.                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
  1247.                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1248.                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
  1249.                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
  1250.             }
  1251.         }
  1252.         step_x = 1<<step_x;
  1253.         step_y = 1<<step_y;
  1254.  
  1255.         for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
  1256.             for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
  1257.                 for (compno = CSpoc; compno < CEpoc; compno++) {
  1258.                     Jpeg2000Component *comp     = tile->comp + compno;
  1259.                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1260.                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
  1261.                     int xc = x / s->cdx[compno];
  1262.                     int yc = y / s->cdy[compno];
  1263.  
  1264.                     for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
  1265.                         unsigned prcx, prcy;
  1266.                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
  1267.                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1268.  
  1269.                         if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
  1270.                             continue;
  1271.  
  1272.                         if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
  1273.                             continue;
  1274.  
  1275.                         // check if a precinct exists
  1276.                         prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
  1277.                         prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
  1278.                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
  1279.                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
  1280.  
  1281.                         precno = prcx + rlevel->num_precincts_x * prcy;
  1282.  
  1283.                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
  1284.                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
  1285.                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
  1286.                             continue;
  1287.                         }
  1288.  
  1289.                         for (layno = 0; layno < LYEpoc; layno++) {
  1290.                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
  1291.                                                               precno, layno,
  1292.                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  1293.                                                               qntsty->nguardbits)) < 0)
  1294.                                 return ret;
  1295.                         }
  1296.                     }
  1297.                 }
  1298.             }
  1299.         }
  1300.         break;
  1301.  
  1302.     default:
  1303.         break;
  1304.     }
  1305.  
  1306.     return ret;
  1307. }
  1308.  
  1309. static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  1310. {
  1311.     int ret = AVERROR_BUG;
  1312.     int i;
  1313.     int tp_index = 0;
  1314.  
  1315.     s->bit_index = 8;
  1316.     if (tile->poc.nb_poc) {
  1317.         for (i=0; i<tile->poc.nb_poc; i++) {
  1318.             Jpeg2000POCEntry *e = &tile->poc.poc[i];
  1319.             ret = jpeg2000_decode_packets_po_iteration(s, tile,
  1320.                 e->RSpoc, e->CSpoc,
  1321.                 FFMIN(e->LYEpoc, tile->codsty[0].nlayers),
  1322.                 e->REpoc,
  1323.                 FFMIN(e->CEpoc, s->ncomponents),
  1324.                 e->Ppoc, &tp_index
  1325.                 );
  1326.             if (ret < 0)
  1327.                 return ret;
  1328.         }
  1329.     } else {
  1330.         ret = jpeg2000_decode_packets_po_iteration(s, tile,
  1331.             0, 0,
  1332.             tile->codsty[0].nlayers,
  1333.             33,
  1334.             s->ncomponents,
  1335.             tile->codsty[0].prog_order,
  1336.             &tp_index
  1337.         );
  1338.     }
  1339.     /* EOC marker reached */
  1340.     bytestream2_skip(&s->g, 2);
  1341.  
  1342.     return ret;
  1343. }
  1344.  
  1345. /* TIER-1 routines */
  1346. static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
  1347.                            int bpno, int bandno,
  1348.                            int vert_causal_ctx_csty_symbol)
  1349. {
  1350.     int mask = 3 << (bpno - 1), y0, x, y;
  1351.  
  1352.     for (y0 = 0; y0 < height; y0 += 4)
  1353.         for (x = 0; x < width; x++)
  1354.             for (y = y0; y < height && y < y0 + 4; y++) {
  1355.                 int flags_mask = -1;
  1356.                 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
  1357.                     flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
  1358.                 if ((t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB & flags_mask)
  1359.                 && !(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  1360.                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, bandno))) {
  1361.                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, &xorbit);
  1362.                         if (t1->mqc.raw)
  1363.                              t1->data[(y) * t1->stride + x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
  1364.                         else
  1365.                              t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
  1366.                                                -mask : mask;
  1367.  
  1368.                         ff_jpeg2000_set_significance(t1, x, y,
  1369.                                                      t1->data[(y) * t1->stride + x] < 0);
  1370.                     }
  1371.                     t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_VIS;
  1372.                 }
  1373.             }
  1374. }
  1375.  
  1376. static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
  1377.                            int bpno, int vert_causal_ctx_csty_symbol)
  1378. {
  1379.     int phalf, nhalf;
  1380.     int y0, x, y;
  1381.  
  1382.     phalf = 1 << (bpno - 1);
  1383.     nhalf = -phalf;
  1384.  
  1385.     for (y0 = 0; y0 < height; y0 += 4)
  1386.         for (x = 0; x < width; x++)
  1387.             for (y = y0; y < height && y < y0 + 4; y++)
  1388.                 if ((t1->flags[(y + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
  1389.                     int flags_mask = (vert_causal_ctx_csty_symbol && y == y0 + 3) ?
  1390.                         ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S) : -1;
  1391.                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask);
  1392.                     int r     = ff_mqc_decode(&t1->mqc,
  1393.                                               t1->mqc.cx_states + ctxno)
  1394.                                 ? phalf : nhalf;
  1395.                     t1->data[(y) * t1->stride + x]          += t1->data[(y) * t1->stride + x] < 0 ? -r : r;
  1396.                     t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_REF;
  1397.                 }
  1398. }
  1399.  
  1400. static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
  1401.                            int width, int height, int bpno, int bandno,
  1402.                            int seg_symbols, int vert_causal_ctx_csty_symbol)
  1403. {
  1404.     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
  1405.  
  1406.     for (y0 = 0; y0 < height; y0 += 4) {
  1407.         for (x = 0; x < width; x++) {
  1408.             int flags_mask = -1;
  1409.             if (vert_causal_ctx_csty_symbol)
  1410.                 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
  1411.             if (y0 + 3 < height &&
  1412.                 !((t1->flags[(y0 + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  1413.                   (t1->flags[(y0 + 2) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  1414.                   (t1->flags[(y0 + 3) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  1415.                   (t1->flags[(y0 + 4) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {
  1416.                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
  1417.                     continue;
  1418.                 runlen = ff_mqc_decode(&t1->mqc,
  1419.                                        t1->mqc.cx_states + MQC_CX_UNI);
  1420.                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
  1421.                                                        t1->mqc.cx_states +
  1422.                                                        MQC_CX_UNI);
  1423.                 dec = 1;
  1424.             } else {
  1425.                 runlen = 0;
  1426.                 dec    = 0;
  1427.             }
  1428.  
  1429.             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
  1430.                 int flags_mask = -1;
  1431.                 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
  1432.                     flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
  1433.                 if (!dec) {
  1434.                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  1435.                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask,
  1436.                                                                                              bandno));
  1437.                     }
  1438.                 }
  1439.                 if (dec) {
  1440.                     int xorbit;
  1441.                     int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask,
  1442.                                                         &xorbit);
  1443.                     t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc,
  1444.                                                     t1->mqc.cx_states + ctxno) ^
  1445.                                       xorbit)
  1446.                                      ? -mask : mask;
  1447.                     ff_jpeg2000_set_significance(t1, x, y, t1->data[(y) * t1->stride + x] < 0);
  1448.                 }
  1449.                 dec = 0;
  1450.                 t1->flags[(y + 1) * t1->stride + x + 1] &= ~JPEG2000_T1_VIS;
  1451.             }
  1452.         }
  1453.     }
  1454.     if (seg_symbols) {
  1455.         int val;
  1456.         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  1457.         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  1458.         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  1459.         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  1460.         if (val != 0xa)
  1461.             av_log(s->avctx, AV_LOG_ERROR,
  1462.                    "Segmentation symbol value incorrect\n");
  1463.     }
  1464. }
  1465.  
  1466. static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
  1467.                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
  1468.                        int width, int height, int bandpos)
  1469. {
  1470.     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1;
  1471.     int pass_cnt = 0;
  1472.     int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
  1473.     int term_cnt = 0;
  1474.     int coder_type;
  1475.  
  1476.     av_assert0(width <= 1024U && height <= 1024U);
  1477.     av_assert0(width*height <= 4096);
  1478.  
  1479.     memset(t1->data, 0, t1->stride * height * sizeof(*t1->data));
  1480.  
  1481.     /* If code-block contains no compressed data: nothing to do. */
  1482.     if (!cblk->length)
  1483.         return 0;
  1484.  
  1485.     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
  1486.  
  1487.     cblk->data[cblk->length] = 0xff;
  1488.     cblk->data[cblk->length+1] = 0xff;
  1489.     ff_mqc_initdec(&t1->mqc, cblk->data, 0, 1);
  1490.  
  1491.     while (passno--) {
  1492.         if (bpno < 0) {
  1493.             av_log(s->avctx, AV_LOG_ERROR, "bpno became negative\n");
  1494.             return AVERROR_INVALIDDATA;
  1495.         }
  1496.         switch(pass_t) {
  1497.         case 0:
  1498.             decode_sigpass(t1, width, height, bpno + 1, bandpos,
  1499.                            vert_causal_ctx_csty_symbol);
  1500.             break;
  1501.         case 1:
  1502.             decode_refpass(t1, width, height, bpno + 1, vert_causal_ctx_csty_symbol);
  1503.             break;
  1504.         case 2:
  1505.             av_assert2(!t1->mqc.raw);
  1506.             decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
  1507.                            codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
  1508.                            vert_causal_ctx_csty_symbol);
  1509.             break;
  1510.         }
  1511.         if (codsty->cblk_style & JPEG2000_CBLK_RESET) // XXX no testcase for just this
  1512.             ff_mqc_init_contexts(&t1->mqc);
  1513.  
  1514.         if (passno && (coder_type = needs_termination(codsty->cblk_style, pass_cnt))) {
  1515.             if (term_cnt >= cblk->nb_terminations) {
  1516.                 av_log(s->avctx, AV_LOG_ERROR, "Missing needed termination \n");
  1517.                 return AVERROR_INVALIDDATA;
  1518.             }
  1519.             if (FFABS(cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp) > 0) {
  1520.                 av_log(s->avctx, AV_LOG_WARNING, "Mid mismatch %"PTRDIFF_SPECIFIER" in pass %d of %d\n",
  1521.                     cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp,
  1522.                     pass_cnt, cblk->npasses);
  1523.             }
  1524.  
  1525.             ff_mqc_initdec(&t1->mqc, cblk->data + cblk->data_start[++term_cnt], coder_type == 2, 0);
  1526.         }
  1527.  
  1528.         pass_t++;
  1529.         if (pass_t == 3) {
  1530.             bpno--;
  1531.             pass_t = 0;
  1532.         }
  1533.         pass_cnt ++;
  1534.     }
  1535.  
  1536.     if (cblk->data + cblk->length - 2*(term_cnt < cblk->nb_terminations) != t1->mqc.bp) {
  1537.         av_log(s->avctx, AV_LOG_WARNING, "End mismatch %"PTRDIFF_SPECIFIER"\n",
  1538.                cblk->data + cblk->length - 2*(term_cnt < cblk->nb_terminations) - t1->mqc.bp);
  1539.     }
  1540.  
  1541.     return 0;
  1542. }
  1543.  
  1544. /* TODO: Verify dequantization for lossless case
  1545.  * comp->data can be float or int
  1546.  * band->stepsize can be float or int
  1547.  * depending on the type of DWT transformation.
  1548.  * see ISO/IEC 15444-1:2002 A.6.1 */
  1549.  
  1550. /* Float dequantization of a codeblock.*/
  1551. static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
  1552.                                  Jpeg2000Component *comp,
  1553.                                  Jpeg2000T1Context *t1, Jpeg2000Band *band)
  1554. {
  1555.     int i, j;
  1556.     int w = cblk->coord[0][1] - cblk->coord[0][0];
  1557.     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  1558.         float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
  1559.         int *src = t1->data + j*t1->stride;
  1560.         for (i = 0; i < w; ++i)
  1561.             datap[i] = src[i] * band->f_stepsize;
  1562.     }
  1563. }
  1564.  
  1565. /* Integer dequantization of a codeblock.*/
  1566. static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
  1567.                                Jpeg2000Component *comp,
  1568.                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
  1569. {
  1570.     int i, j;
  1571.     int w = cblk->coord[0][1] - cblk->coord[0][0];
  1572.     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  1573.         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
  1574.         int *src = t1->data + j*t1->stride;
  1575.         if (band->i_stepsize == 32768) {
  1576.             for (i = 0; i < w; ++i)
  1577.                 datap[i] = src[i] / 2;
  1578.         } else {
  1579.             // This should be VERY uncommon
  1580.             for (i = 0; i < w; ++i)
  1581.                 datap[i] = (src[i] * (int64_t)band->i_stepsize) / 65536;
  1582.         }
  1583.     }
  1584. }
  1585.  
  1586. static void dequantization_int_97(int x, int y, Jpeg2000Cblk *cblk,
  1587.                                Jpeg2000Component *comp,
  1588.                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
  1589. {
  1590.     int i, j;
  1591.     int w = cblk->coord[0][1] - cblk->coord[0][0];
  1592.     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  1593.         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
  1594.         int *src = t1->data + j*t1->stride;
  1595.         for (i = 0; i < w; ++i)
  1596.             datap[i] = (src[i] * (int64_t)band->i_stepsize + (1<<15)) >> 16;
  1597.     }
  1598. }
  1599.  
  1600. static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  1601. {
  1602.     int i, csize = 1;
  1603.     void *src[3];
  1604.  
  1605.     for (i = 1; i < 3; i++) {
  1606.         if (tile->codsty[0].transform != tile->codsty[i].transform) {
  1607.             av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
  1608.             return;
  1609.         }
  1610.         if (memcmp(tile->comp[0].coord, tile->comp[i].coord, sizeof(tile->comp[0].coord))) {
  1611.             av_log(s->avctx, AV_LOG_ERROR, "Coords mismatch, MCT not supported\n");
  1612.             return;
  1613.         }
  1614.     }
  1615.  
  1616.     for (i = 0; i < 3; i++)
  1617.         if (tile->codsty[0].transform == FF_DWT97)
  1618.             src[i] = tile->comp[i].f_data;
  1619.         else
  1620.             src[i] = tile->comp[i].i_data;
  1621.  
  1622.     for (i = 0; i < 2; i++)
  1623.         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
  1624.  
  1625.     s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
  1626. }
  1627.  
  1628. static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
  1629.                                 AVFrame *picture)
  1630. {
  1631.     const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
  1632.     int compno, reslevelno, bandno;
  1633.     int x, y;
  1634.     int planar    = !!(pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR);
  1635.     int pixelsize = planar ? 1 : pixdesc->nb_components;
  1636.  
  1637.     uint8_t *line;
  1638.     Jpeg2000T1Context t1;
  1639.  
  1640.     /* Loop on tile components */
  1641.     for (compno = 0; compno < s->ncomponents; compno++) {
  1642.         Jpeg2000Component *comp     = tile->comp + compno;
  1643.         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1644.  
  1645.         t1.stride = (1<<codsty->log2_cblk_width) + 2;
  1646.  
  1647.         /* Loop on resolution levels */
  1648.         for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
  1649.             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  1650.             /* Loop on bands */
  1651.             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  1652.                 int nb_precincts, precno;
  1653.                 Jpeg2000Band *band = rlevel->band + bandno;
  1654.                 int cblkno = 0, bandpos;
  1655.  
  1656.                 bandpos = bandno + (reslevelno > 0);
  1657.  
  1658.                 if (band->coord[0][0] == band->coord[0][1] ||
  1659.                     band->coord[1][0] == band->coord[1][1])
  1660.                     continue;
  1661.  
  1662.                 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
  1663.                 /* Loop on precincts */
  1664.                 for (precno = 0; precno < nb_precincts; precno++) {
  1665.                     Jpeg2000Prec *prec = band->prec + precno;
  1666.  
  1667.                     /* Loop on codeblocks */
  1668.                     for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
  1669.                         int x, y;
  1670.                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  1671.                         decode_cblk(s, codsty, &t1, cblk,
  1672.                                     cblk->coord[0][1] - cblk->coord[0][0],
  1673.                                     cblk->coord[1][1] - cblk->coord[1][0],
  1674.                                     bandpos);
  1675.  
  1676.                         x = cblk->coord[0][0] - band->coord[0][0];
  1677.                         y = cblk->coord[1][0] - band->coord[1][0];
  1678.  
  1679.                         if (codsty->transform == FF_DWT97)
  1680.                             dequantization_float(x, y, cblk, comp, &t1, band);
  1681.                         else if (codsty->transform == FF_DWT97_INT)
  1682.                             dequantization_int_97(x, y, cblk, comp, &t1, band);
  1683.                         else
  1684.                             dequantization_int(x, y, cblk, comp, &t1, band);
  1685.                    } /* end cblk */
  1686.                 } /*end prec */
  1687.             } /* end band */
  1688.         } /* end reslevel */
  1689.  
  1690.         /* inverse DWT */
  1691.         ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
  1692.     } /*end comp */
  1693.  
  1694.     /* inverse MCT transformation */
  1695.     if (tile->codsty[0].mct)
  1696.         mct_decode(s, tile);
  1697.  
  1698.     if (s->cdef[0] < 0) {
  1699.         for (x = 0; x < s->ncomponents; x++)
  1700.             s->cdef[x] = x + 1;
  1701.         if ((s->ncomponents & 1) == 0)
  1702.             s->cdef[s->ncomponents-1] = 0;
  1703.     }
  1704.  
  1705.     if (s->precision <= 8) {
  1706.         for (compno = 0; compno < s->ncomponents; compno++) {
  1707.             Jpeg2000Component *comp = tile->comp + compno;
  1708.             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1709.             float *datap = comp->f_data;
  1710.             int32_t *i_datap = comp->i_data;
  1711.             int cbps = s->cbps[compno];
  1712.             int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
  1713.             int plane = 0;
  1714.  
  1715.             if (planar)
  1716.                 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
  1717.  
  1718.  
  1719.             y    = tile->comp[compno].coord[1][0] - s->image_offset_y / s->cdy[compno];
  1720.             line = picture->data[plane] + y * picture->linesize[plane];
  1721.             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y ++) {
  1722.                 uint8_t *dst;
  1723.  
  1724.                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x / s->cdx[compno];
  1725.                 dst = line + x * pixelsize + compno*!planar;
  1726.  
  1727.                 if (codsty->transform == FF_DWT97) {
  1728.                     for (; x < w; x ++) {
  1729.                         int val = lrintf(*datap) + (1 << (cbps - 1));
  1730.                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1731.                         val = av_clip(val, 0, (1 << cbps) - 1);
  1732.                         *dst = val << (8 - cbps);
  1733.                         datap++;
  1734.                         dst += pixelsize;
  1735.                     }
  1736.                 } else {
  1737.                     for (; x < w; x ++) {
  1738.                         int val = *i_datap + (1 << (cbps - 1));
  1739.                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1740.                         val = av_clip(val, 0, (1 << cbps) - 1);
  1741.                         *dst = val << (8 - cbps);
  1742.                         i_datap++;
  1743.                         dst += pixelsize;
  1744.                     }
  1745.                 }
  1746.                 line += picture->linesize[plane];
  1747.             }
  1748.         }
  1749.     } else {
  1750.         int precision = picture->format == AV_PIX_FMT_XYZ12 ||
  1751.                         picture->format == AV_PIX_FMT_RGB48 ||
  1752.                         picture->format == AV_PIX_FMT_RGBA64 ||
  1753.                         picture->format == AV_PIX_FMT_GRAY16 ? 16 : s->precision;
  1754.  
  1755.         for (compno = 0; compno < s->ncomponents; compno++) {
  1756.             Jpeg2000Component *comp = tile->comp + compno;
  1757.             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1758.             float *datap = comp->f_data;
  1759.             int32_t *i_datap = comp->i_data;
  1760.             uint16_t *linel;
  1761.             int cbps = s->cbps[compno];
  1762.             int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
  1763.             int plane = 0;
  1764.  
  1765.             if (planar)
  1766.                 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
  1767.  
  1768.             y     = tile->comp[compno].coord[1][0] - s->image_offset_y / s->cdy[compno];
  1769.             linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1);
  1770.             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y ++) {
  1771.                 uint16_t *dst;
  1772.  
  1773.                 x   = tile->comp[compno].coord[0][0] - s->image_offset_x / s->cdx[compno];
  1774.                 dst = linel + (x * pixelsize + compno*!planar);
  1775.                 if (codsty->transform == FF_DWT97) {
  1776.                     for (; x < w; x ++) {
  1777.                         int  val = lrintf(*datap) + (1 << (cbps - 1));
  1778.                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1779.                         val = av_clip(val, 0, (1 << cbps) - 1);
  1780.                         /* align 12 bit values in little-endian mode */
  1781.                         *dst = val << (precision - cbps);
  1782.                         datap++;
  1783.                         dst += pixelsize;
  1784.                     }
  1785.                 } else {
  1786.                     for (; x < w; x ++) {
  1787.                         int val = *i_datap + (1 << (cbps - 1));
  1788.                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1789.                         val = av_clip(val, 0, (1 << cbps) - 1);
  1790.                         /* align 12 bit values in little-endian mode */
  1791.                         *dst = val << (precision - cbps);
  1792.                         i_datap++;
  1793.                         dst += pixelsize;
  1794.                     }
  1795.                 }
  1796.                 linel += picture->linesize[plane] >> 1;
  1797.             }
  1798.         }
  1799.     }
  1800.  
  1801.     return 0;
  1802. }
  1803.  
  1804. static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
  1805. {
  1806.     int tileno, compno;
  1807.     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  1808.         if (s->tile[tileno].comp) {
  1809.             for (compno = 0; compno < s->ncomponents; compno++) {
  1810.                 Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
  1811.                 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
  1812.  
  1813.                 ff_jpeg2000_cleanup(comp, codsty);
  1814.             }
  1815.             av_freep(&s->tile[tileno].comp);
  1816.         }
  1817.     }
  1818.     av_freep(&s->tile);
  1819.     memset(s->codsty, 0, sizeof(s->codsty));
  1820.     memset(s->qntsty, 0, sizeof(s->qntsty));
  1821.     memset(s->properties, 0, sizeof(s->properties));
  1822.     memset(&s->poc  , 0, sizeof(s->poc));
  1823.     s->numXtiles = s->numYtiles = 0;
  1824.     s->ncomponents = 0;
  1825. }
  1826.  
  1827. static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
  1828. {
  1829.     Jpeg2000CodingStyle *codsty = s->codsty;
  1830.     Jpeg2000QuantStyle *qntsty  = s->qntsty;
  1831.     Jpeg2000POC         *poc    = &s->poc;
  1832.     uint8_t *properties         = s->properties;
  1833.  
  1834.     for (;;) {
  1835.         int len, ret = 0;
  1836.         uint16_t marker;
  1837.         int oldpos;
  1838.  
  1839.         if (bytestream2_get_bytes_left(&s->g) < 2) {
  1840.             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
  1841.             break;
  1842.         }
  1843.  
  1844.         marker = bytestream2_get_be16u(&s->g);
  1845.         oldpos = bytestream2_tell(&s->g);
  1846.  
  1847.         if (marker == JPEG2000_SOD) {
  1848.             Jpeg2000Tile *tile;
  1849.             Jpeg2000TilePart *tp;
  1850.  
  1851.             if (!s->tile) {
  1852.                 av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
  1853.                 return AVERROR_INVALIDDATA;
  1854.             }
  1855.             if (s->curtileno < 0) {
  1856.                 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
  1857.                 return AVERROR_INVALIDDATA;
  1858.             }
  1859.  
  1860.             tile = s->tile + s->curtileno;
  1861.             tp = tile->tile_part + tile->tp_idx;
  1862.             if (tp->tp_end < s->g.buffer) {
  1863.                 av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
  1864.                 return AVERROR_INVALIDDATA;
  1865.             }
  1866.             bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
  1867.             bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
  1868.  
  1869.             continue;
  1870.         }
  1871.         if (marker == JPEG2000_EOC)
  1872.             break;
  1873.  
  1874.         len = bytestream2_get_be16(&s->g);
  1875.         if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) {
  1876.             av_log(s->avctx, AV_LOG_ERROR, "Invalid len %d left=%d\n", len, bytestream2_get_bytes_left(&s->g));
  1877.             return AVERROR_INVALIDDATA;
  1878.         }
  1879.  
  1880.         switch (marker) {
  1881.         case JPEG2000_SIZ:
  1882.             if (s->ncomponents) {
  1883.                 av_log(s->avctx, AV_LOG_ERROR, "Duplicate SIZ\n");
  1884.                 return AVERROR_INVALIDDATA;
  1885.             }
  1886.             ret = get_siz(s);
  1887.             if (!s->tile)
  1888.                 s->numXtiles = s->numYtiles = 0;
  1889.             break;
  1890.         case JPEG2000_COC:
  1891.             ret = get_coc(s, codsty, properties);
  1892.             break;
  1893.         case JPEG2000_COD:
  1894.             ret = get_cod(s, codsty, properties);
  1895.             break;
  1896.         case JPEG2000_QCC:
  1897.             ret = get_qcc(s, len, qntsty, properties);
  1898.             break;
  1899.         case JPEG2000_QCD:
  1900.             ret = get_qcd(s, len, qntsty, properties);
  1901.             break;
  1902.         case JPEG2000_POC:
  1903.             ret = get_poc(s, len, poc);
  1904.             break;
  1905.         case JPEG2000_SOT:
  1906.             if (!(ret = get_sot(s, len))) {
  1907.                 av_assert1(s->curtileno >= 0);
  1908.                 codsty = s->tile[s->curtileno].codsty;
  1909.                 qntsty = s->tile[s->curtileno].qntsty;
  1910.                 poc    = &s->tile[s->curtileno].poc;
  1911.                 properties = s->tile[s->curtileno].properties;
  1912.             }
  1913.             break;
  1914.         case JPEG2000_COM:
  1915.             // the comment is ignored
  1916.             bytestream2_skip(&s->g, len - 2);
  1917.             break;
  1918.         case JPEG2000_TLM:
  1919.             // Tile-part lengths
  1920.             ret = get_tlm(s, len);
  1921.             break;
  1922.         case JPEG2000_PLT:
  1923.             // Packet length, tile-part header
  1924.             ret = get_plt(s, len);
  1925.             break;
  1926.         default:
  1927.             av_log(s->avctx, AV_LOG_ERROR,
  1928.                    "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
  1929.                    marker, bytestream2_tell(&s->g) - 4);
  1930.             bytestream2_skip(&s->g, len - 2);
  1931.             break;
  1932.         }
  1933.         if (bytestream2_tell(&s->g) - oldpos != len || ret) {
  1934.             av_log(s->avctx, AV_LOG_ERROR,
  1935.                    "error during processing marker segment %.4"PRIx16"\n",
  1936.                    marker);
  1937.             return ret ? ret : -1;
  1938.         }
  1939.     }
  1940.     return 0;
  1941. }
  1942.  
  1943. /* Read bit stream packets --> T2 operation. */
  1944. static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
  1945. {
  1946.     int ret = 0;
  1947.     int tileno;
  1948.  
  1949.     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  1950.         Jpeg2000Tile *tile = s->tile + tileno;
  1951.  
  1952.         if ((ret = init_tile(s, tileno)) < 0)
  1953.             return ret;
  1954.  
  1955.         s->g = tile->tile_part[0].tpg;
  1956.         if ((ret = jpeg2000_decode_packets(s, tile)) < 0)
  1957.             return ret;
  1958.     }
  1959.  
  1960.     return 0;
  1961. }
  1962.  
  1963. static int jp2_find_codestream(Jpeg2000DecoderContext *s)
  1964. {
  1965.     uint32_t atom_size, atom, atom_end;
  1966.     int search_range = 10;
  1967.  
  1968.     while (search_range
  1969.            &&
  1970.            bytestream2_get_bytes_left(&s->g) >= 8) {
  1971.         atom_size = bytestream2_get_be32u(&s->g);
  1972.         atom      = bytestream2_get_be32u(&s->g);
  1973.         atom_end  = bytestream2_tell(&s->g) + atom_size - 8;
  1974.  
  1975.         if (atom == JP2_CODESTREAM)
  1976.             return 1;
  1977.  
  1978.         if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
  1979.             return 0;
  1980.  
  1981.         if (atom == JP2_HEADER &&
  1982.                    atom_size >= 16) {
  1983.             uint32_t atom2_size, atom2, atom2_end;
  1984.             do {
  1985.                 atom2_size = bytestream2_get_be32u(&s->g);
  1986.                 atom2      = bytestream2_get_be32u(&s->g);
  1987.                 atom2_end  = bytestream2_tell(&s->g) + atom2_size - 8;
  1988.                 if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
  1989.                     break;
  1990.                 if (atom2 == JP2_CODESTREAM) {
  1991.                     return 1;
  1992.                 } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
  1993.                     int method = bytestream2_get_byteu(&s->g);
  1994.                     bytestream2_skipu(&s->g, 2);
  1995.                     if (method == 1) {
  1996.                         s->colour_space = bytestream2_get_be32u(&s->g);
  1997.                     }
  1998.                 } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
  1999.                     int i, size, colour_count, colour_channels, colour_depth[3];
  2000.                     uint32_t r, g, b;
  2001.                     colour_count = bytestream2_get_be16u(&s->g);
  2002.                     colour_channels = bytestream2_get_byteu(&s->g);
  2003.                     // FIXME: Do not ignore channel_sign
  2004.                     colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
  2005.                     colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
  2006.                     colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
  2007.                     size = (colour_depth[0] + 7 >> 3) * colour_count +
  2008.                            (colour_depth[1] + 7 >> 3) * colour_count +
  2009.                            (colour_depth[2] + 7 >> 3) * colour_count;
  2010.                     if (colour_count > 256   ||
  2011.                         colour_channels != 3 ||
  2012.                         colour_depth[0] > 16 ||
  2013.                         colour_depth[1] > 16 ||
  2014.                         colour_depth[2] > 16 ||
  2015.                         atom2_size < size) {
  2016.                         avpriv_request_sample(s->avctx, "Unknown palette");
  2017.                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
  2018.                         continue;
  2019.                     }
  2020.                     s->pal8 = 1;
  2021.                     for (i = 0; i < colour_count; i++) {
  2022.                         if (colour_depth[0] <= 8) {
  2023.                             r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
  2024.                             r |= r >> colour_depth[0];
  2025.                         } else {
  2026.                             r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
  2027.                         }
  2028.                         if (colour_depth[1] <= 8) {
  2029.                             g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
  2030.                             r |= r >> colour_depth[1];
  2031.                         } else {
  2032.                             g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
  2033.                         }
  2034.                         if (colour_depth[2] <= 8) {
  2035.                             b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
  2036.                             r |= r >> colour_depth[2];
  2037.                         } else {
  2038.                             b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
  2039.                         }
  2040.                         s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
  2041.                     }
  2042.                 } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
  2043.                     int n = bytestream2_get_be16u(&s->g);
  2044.                     for (; n>0; n--) {
  2045.                         int cn   = bytestream2_get_be16(&s->g);
  2046.                         int av_unused typ  = bytestream2_get_be16(&s->g);
  2047.                         int asoc = bytestream2_get_be16(&s->g);
  2048.                         if (cn < 4 && asoc < 4)
  2049.                             s->cdef[cn] = asoc;
  2050.                     }
  2051.                 }
  2052.                 bytestream2_seek(&s->g, atom2_end, SEEK_SET);
  2053.             } while (atom_end - atom2_end >= 8);
  2054.         } else {
  2055.             search_range--;
  2056.         }
  2057.         bytestream2_seek(&s->g, atom_end, SEEK_SET);
  2058.     }
  2059.  
  2060.     return 0;
  2061. }
  2062.  
  2063. static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
  2064. {
  2065.     Jpeg2000DecoderContext *s = avctx->priv_data;
  2066.  
  2067.     ff_jpeg2000dsp_init(&s->dsp);
  2068.  
  2069.     return 0;
  2070. }
  2071.  
  2072. static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
  2073.                                  int *got_frame, AVPacket *avpkt)
  2074. {
  2075.     Jpeg2000DecoderContext *s = avctx->priv_data;
  2076.     ThreadFrame frame = { .f = data };
  2077.     AVFrame *picture = data;
  2078.     int tileno, ret;
  2079.  
  2080.     s->avctx     = avctx;
  2081.     bytestream2_init(&s->g, avpkt->data, avpkt->size);
  2082.     s->curtileno = -1;
  2083.     memset(s->cdef, -1, sizeof(s->cdef));
  2084.  
  2085.     if (bytestream2_get_bytes_left(&s->g) < 2) {
  2086.         ret = AVERROR_INVALIDDATA;
  2087.         goto end;
  2088.     }
  2089.  
  2090.     // check if the image is in jp2 format
  2091.     if (bytestream2_get_bytes_left(&s->g) >= 12 &&
  2092.        (bytestream2_get_be32u(&s->g) == 12) &&
  2093.        (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
  2094.        (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
  2095.         if (!jp2_find_codestream(s)) {
  2096.             av_log(avctx, AV_LOG_ERROR,
  2097.                    "Could not find Jpeg2000 codestream atom.\n");
  2098.             ret = AVERROR_INVALIDDATA;
  2099.             goto end;
  2100.         }
  2101.     } else {
  2102.         bytestream2_seek(&s->g, 0, SEEK_SET);
  2103.     }
  2104.  
  2105.     while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
  2106.         bytestream2_skip(&s->g, 1);
  2107.  
  2108.     if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
  2109.         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
  2110.         ret = AVERROR_INVALIDDATA;
  2111.         goto end;
  2112.     }
  2113.     if (ret = jpeg2000_read_main_headers(s))
  2114.         goto end;
  2115.  
  2116.     /* get picture buffer */
  2117.     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
  2118.         goto end;
  2119.     picture->pict_type = AV_PICTURE_TYPE_I;
  2120.     picture->key_frame = 1;
  2121.  
  2122.     if (ret = jpeg2000_read_bitstream_packets(s))
  2123.         goto end;
  2124.  
  2125.     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
  2126.         if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
  2127.             goto end;
  2128.  
  2129.     jpeg2000_dec_cleanup(s);
  2130.  
  2131.     *got_frame = 1;
  2132.  
  2133.     if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
  2134.         memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
  2135.  
  2136.     return bytestream2_tell(&s->g);
  2137.  
  2138. end:
  2139.     jpeg2000_dec_cleanup(s);
  2140.     return ret;
  2141. }
  2142.  
  2143. static av_cold void jpeg2000_init_static_data(AVCodec *codec)
  2144. {
  2145.     ff_jpeg2000_init_tier1_luts();
  2146.     ff_mqc_init_context_tables();
  2147. }
  2148.  
  2149. #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
  2150. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  2151.  
  2152. static const AVOption options[] = {
  2153.     { "lowres",  "Lower the decoding resolution by a power of two",
  2154.         OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
  2155.     { NULL },
  2156. };
  2157.  
  2158. static const AVProfile profiles[] = {
  2159.     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0,  "JPEG 2000 codestream restriction 0"   },
  2160.     { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1,  "JPEG 2000 codestream restriction 1"   },
  2161.     { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
  2162.     { FF_PROFILE_JPEG2000_DCINEMA_2K,             "JPEG 2000 digital cinema 2K"          },
  2163.     { FF_PROFILE_JPEG2000_DCINEMA_4K,             "JPEG 2000 digital cinema 4K"          },
  2164.     { FF_PROFILE_UNKNOWN },
  2165. };
  2166.  
  2167. static const AVClass jpeg2000_class = {
  2168.     .class_name = "jpeg2000",
  2169.     .item_name  = av_default_item_name,
  2170.     .option     = options,
  2171.     .version    = LIBAVUTIL_VERSION_INT,
  2172. };
  2173.  
  2174. AVCodec ff_jpeg2000_decoder = {
  2175.     .name             = "jpeg2000",
  2176.     .long_name        = NULL_IF_CONFIG_SMALL("JPEG 2000"),
  2177.     .type             = AVMEDIA_TYPE_VIDEO,
  2178.     .id               = AV_CODEC_ID_JPEG2000,
  2179.     .capabilities     = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_DR1,
  2180.     .priv_data_size   = sizeof(Jpeg2000DecoderContext),
  2181.     .init_static_data = jpeg2000_init_static_data,
  2182.     .init             = jpeg2000_decode_init,
  2183.     .decode           = jpeg2000_decode_frame,
  2184.     .priv_class       = &jpeg2000_class,
  2185.     .max_lowres       = 5,
  2186.     .profiles         = NULL_IF_CONFIG_SMALL(profiles)
  2187. };
  2188.