LCOV - code coverage report
Current view: top level - libavcodec - jpeg2000dec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 792 1261 62.8 %
Date: 2018-05-20 11:54:08 Functions: 38 40 95.0 %

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

Generated by: LCOV version 1.13