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

Generated by: LCOV version 1.13