GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/jpeg2000dec.c Lines: 835 1467 56.9 %
Date: 2020-10-23 17:01:47 Branches: 525 1105 47.5 %

Line Branch Exec Source
1
/*
2
 * JPEG 2000 image decoder
3
 * Copyright (c) 2007 Kamil Nowosad
4
 * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
/**
24
 * @file
25
 * JPEG 2000 image decoder
26
 */
27
28
#include <inttypes.h>
29
#include <math.h>
30
31
#include "libavutil/attributes.h"
32
#include "libavutil/avassert.h"
33
#include "libavutil/common.h"
34
#include "libavutil/imgutils.h"
35
#include "libavutil/opt.h"
36
#include "libavutil/pixdesc.h"
37
#include "libavutil/thread.h"
38
#include "avcodec.h"
39
#include "bytestream.h"
40
#include "internal.h"
41
#include "thread.h"
42
#include "jpeg2000.h"
43
#include "jpeg2000dsp.h"
44
#include "profiles.h"
45
46
#define JP2_SIG_TYPE    0x6A502020
47
#define JP2_SIG_VALUE   0x0D0A870A
48
#define JP2_CODESTREAM  0x6A703263
49
#define JP2_HEADER      0x6A703268
50
51
#define HAD_COC 0x01
52
#define HAD_QCC 0x02
53
54
#define MAX_POCS 32
55
56
typedef struct Jpeg2000POCEntry {
57
    uint16_t LYEpoc;
58
    uint16_t CSpoc;
59
    uint16_t CEpoc;
60
    uint8_t RSpoc;
61
    uint8_t REpoc;
62
    uint8_t Ppoc;
63
} Jpeg2000POCEntry;
64
65
typedef struct Jpeg2000POC {
66
    Jpeg2000POCEntry poc[MAX_POCS];
67
    int nb_poc;
68
    int is_default;
69
} Jpeg2000POC;
70
71
typedef struct Jpeg2000TilePart {
72
    uint8_t tile_index;                 // Tile index who refers the tile-part
73
    const uint8_t *tp_end;
74
    GetByteContext header_tpg;          // bit stream of header if PPM header is used
75
    GetByteContext tpg;                 // bit stream in tile-part
76
} Jpeg2000TilePart;
77
78
/* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
79
 * one per component, so tile_part elements have a size of 3 */
80
typedef struct Jpeg2000Tile {
81
    Jpeg2000Component   *comp;
82
    uint8_t             properties[4];
83
    Jpeg2000CodingStyle codsty[4];
84
    Jpeg2000QuantStyle  qntsty[4];
85
    Jpeg2000POC         poc;
86
    Jpeg2000TilePart    tile_part[32];
87
    uint8_t             has_ppt;                // whether this tile has a ppt marker
88
    uint8_t             *packed_headers;        // contains packed headers. Used only along with PPT marker
89
    int                 packed_headers_size;    // size in bytes of the packed headers
90
    GetByteContext      packed_headers_stream;  // byte context corresponding to packed headers
91
    uint16_t tp_idx;                    // Tile-part index
92
    int coord[2][2];                    // border coordinates {{x0, x1}, {y0, y1}}
93
} Jpeg2000Tile;
94
95
typedef struct Jpeg2000DecoderContext {
96
    AVClass         *class;
97
    AVCodecContext  *avctx;
98
    GetByteContext  g;
99
100
    int             width, height;
101
    int             image_offset_x, image_offset_y;
102
    int             tile_offset_x, tile_offset_y;
103
    uint8_t         cbps[4];    // bits per sample in particular components
104
    uint8_t         sgnd[4];    // if a component is signed
105
    uint8_t         properties[4];
106
107
    uint8_t         has_ppm;
108
    uint8_t         *packed_headers; // contains packed headers. Used only along with PPM marker
109
    int             packed_headers_size;
110
    GetByteContext  packed_headers_stream;
111
    uint8_t         in_tile_headers;
112
113
    int             cdx[4], cdy[4];
114
    int             precision;
115
    int             ncomponents;
116
    int             colour_space;
117
    uint32_t        palette[256];
118
    int8_t          pal8;
119
    int             cdef[4];
120
    int             tile_width, tile_height;
121
    unsigned        numXtiles, numYtiles;
122
    int             maxtilelen;
123
    AVRational      sar;
124
125
    Jpeg2000CodingStyle codsty[4];
126
    Jpeg2000QuantStyle  qntsty[4];
127
    Jpeg2000POC         poc;
128
    uint8_t             roi_shift[4];
129
130
    int             bit_index;
131
132
    int             curtileno;
133
134
    Jpeg2000Tile    *tile;
135
    Jpeg2000DSPContext dsp;
136
137
    /*options parameters*/
138
    int             reduction_factor;
139
} Jpeg2000DecoderContext;
140
141
/* get_bits functions for JPEG2000 packet bitstream
142
 * It is a get_bit function with a bit-stuffing routine. If the value of the
143
 * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
144
 * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
145
3836718
static int get_bits(Jpeg2000DecoderContext *s, int n)
146
{
147
3836718
    int res = 0;
148
149
10681032
    while (--n >= 0) {
150
6844314
        res <<= 1;
151
6844314
        if (s->bit_index == 0) {
152
840076
            s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
153
        }
154
6844314
        s->bit_index--;
155
6844314
        res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
156
    }
157
3836718
    return res;
158
}
159
160
28473
static void jpeg2000_flush(Jpeg2000DecoderContext *s)
161
{
162
28473
    if (bytestream2_get_byte(&s->g) == 0xff)
163
        bytestream2_skip(&s->g, 1);
164
28473
    s->bit_index = 8;
165
28473
}
166
167
/* decode the value stored in node */
168
841830
static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
169
                           int threshold)
170
{
171
    Jpeg2000TgtNode *stack[30];
172
841830
    int sp = -1, curval = 0;
173
174
841830
    if (!node) {
175
        av_log(s->avctx, AV_LOG_ERROR, "missing node\n");
176
        return AVERROR_INVALIDDATA;
177
    }
178
179

2028229
    while (node && !node->vis) {
180
1186399
        stack[++sp] = node;
181
1186399
        node        = node->parent;
182
    }
183
184
841830
    if (node)
185
687184
        curval = node->val;
186
    else
187
154646
        curval = stack[sp]->val;
188
189

1995546
    while (curval < threshold && sp >= 0) {
190
1153716
        if (curval < stack[sp]->val)
191
4322
            curval = stack[sp]->val;
192
1574169
        while (curval < threshold) {
193
            int ret;
194
1537279
            if ((ret = get_bits(s, 1)) > 0) {
195
1116826
                stack[sp]->vis++;
196
1116826
                break;
197
420453
            } else if (!ret)
198
420453
                curval++;
199
            else
200
                return ret;
201
        }
202
1153716
        stack[sp]->val = curval;
203
1153716
        sp--;
204
    }
205
841830
    return curval;
206
}
207
208
424
static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
209
                         int bpc, uint32_t log2_chroma_wh, int pal8)
210
{
211
424
    int match = 1;
212
424
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
213
214
    av_assert2(desc);
215
216
424
    if (desc->nb_components != components) {
217
11
        return 0;
218
    }
219
220

413
    switch (components) {
221
2
    case 4:
222
4
        match = match && desc->comp[3].depth >= bpc &&
223

5
                         (log2_chroma_wh >> 14 & 3) == 0 &&
224
1
                         (log2_chroma_wh >> 12 & 3) == 0;
225
413
    case 3:
226
825
        match = match && desc->comp[2].depth >= bpc &&
227

1237
                         (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
228
412
                         (log2_chroma_wh >>  8 & 3) == desc->log2_chroma_h;
229
413
    case 2:
230
825
        match = match && desc->comp[1].depth >= bpc &&
231

1237
                         (log2_chroma_wh >>  6 & 3) == desc->log2_chroma_w &&
232
412
                         (log2_chroma_wh >>  4 & 3) == desc->log2_chroma_h;
233
234
413
    case 1:
235
825
        match = match && desc->comp[0].depth >= bpc &&
236
412
                         (log2_chroma_wh >>  2 & 3) == 0 &&
237

1237
                         (log2_chroma_wh       & 3) == 0 &&
238
412
                         (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
239
    }
240
413
    return match;
241
}
242
243
// pix_fmts with lower bpp have to be listed before
244
// similar pix_fmts with higher bpp.
245
#define RGB_PIXEL_FORMATS   AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
246
#define GRAY_PIXEL_FORMATS  AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16,AV_PIX_FMT_YA16
247
#define YUV_PIXEL_FORMATS   AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
248
                            AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
249
                            AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
250
                            AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
251
                            AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
252
                            AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
253
                            AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
254
                            AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
255
                            AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
256
                            AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
257
                            AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
258
#define XYZ_PIXEL_FORMATS   AV_PIX_FMT_XYZ12
259
260
static const enum AVPixelFormat rgb_pix_fmts[]  = {RGB_PIXEL_FORMATS};
261
static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
262
static const enum AVPixelFormat yuv_pix_fmts[]  = {YUV_PIXEL_FORMATS};
263
static const enum AVPixelFormat xyz_pix_fmts[]  = {XYZ_PIXEL_FORMATS,
264
                                                   YUV_PIXEL_FORMATS};
265
static const enum AVPixelFormat all_pix_fmts[]  = {RGB_PIXEL_FORMATS,
266
                                                   GRAY_PIXEL_FORMATS,
267
                                                   YUV_PIXEL_FORMATS,
268
                                                   XYZ_PIXEL_FORMATS};
269
270
/* marker segments */
271
/* get sizes and offsets of image, tiles; number of components */
272
412
static int get_siz(Jpeg2000DecoderContext *s)
273
{
274
    int i;
275
    int ncomponents;
276
412
    uint32_t log2_chroma_wh = 0;
277
412
    const enum AVPixelFormat *possible_fmts = NULL;
278
412
    int possible_fmts_nb = 0;
279
    int ret;
280
    int o_dimx, o_dimy; //original image dimensions.
281
    int dimx, dimy;
282
283
412
    if (bytestream2_get_bytes_left(&s->g) < 36) {
284
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for SIZ\n");
285
        return AVERROR_INVALIDDATA;
286
    }
287
288
412
    s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
289
412
    s->width          = bytestream2_get_be32u(&s->g); // Width
290
412
    s->height         = bytestream2_get_be32u(&s->g); // Height
291
412
    s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
292
412
    s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
293
412
    s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz
294
412
    s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz
295
412
    s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz
296
412
    s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz
297
412
    ncomponents       = bytestream2_get_be16u(&s->g); // CSiz
298
299
412
    if (av_image_check_size2(s->width, s->height, s->avctx->max_pixels, AV_PIX_FMT_NONE, 0, s->avctx)) {
300
        avpriv_request_sample(s->avctx, "Large Dimensions");
301
        return AVERROR_PATCHWELCOME;
302
    }
303
304
412
    if (ncomponents <= 0) {
305
        av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
306
               s->ncomponents);
307
        return AVERROR_INVALIDDATA;
308
    }
309
310
412
    if (ncomponents > 4) {
311
        avpriv_request_sample(s->avctx, "Support for %d components",
312
                              ncomponents);
313
        return AVERROR_PATCHWELCOME;
314
    }
315
316

412
    if (s->tile_offset_x < 0 || s->tile_offset_y < 0 ||
317
412
        s->image_offset_x < s->tile_offset_x ||
318
412
        s->image_offset_y < s->tile_offset_y ||
319
412
        s->tile_width  + (int64_t)s->tile_offset_x <= s->image_offset_x ||
320
412
        s->tile_height + (int64_t)s->tile_offset_y <= s->image_offset_y
321
    ) {
322
        av_log(s->avctx, AV_LOG_ERROR, "Tile offsets are invalid\n");
323
        return AVERROR_INVALIDDATA;
324
    }
325
326
412
    s->ncomponents = ncomponents;
327
328

412
    if (s->tile_width <= 0 || s->tile_height <= 0) {
329
        av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
330
               s->tile_width, s->tile_height);
331
        return AVERROR_INVALIDDATA;
332
    }
333
334
412
    if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) {
335
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for %d components in SIZ\n", s->ncomponents);
336
        return AVERROR_INVALIDDATA;
337
    }
338
339
1649
    for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
340
1237
        uint8_t x    = bytestream2_get_byteu(&s->g);
341
1237
        s->cbps[i]   = (x & 0x7f) + 1;
342
1237
        s->precision = FFMAX(s->cbps[i], s->precision);
343
1237
        s->sgnd[i]   = !!(x & 0x80);
344
1237
        s->cdx[i]    = bytestream2_get_byteu(&s->g);
345
1237
        s->cdy[i]    = bytestream2_get_byteu(&s->g);
346

1237
        if (   !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
347

1237
            || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
348
            av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
349
            return AVERROR_INVALIDDATA;
350
        }
351
1237
        log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
352
    }
353
354
412
    s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
355
412
    s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
356
357
    // There must be at least a SOT and SOD per tile, their minimum size is 14
358
412
    if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile) ||
359
412
        s->numXtiles * s->numYtiles * 14LL > bytestream2_size(&s->g)
360
    ) {
361
        s->numXtiles = s->numYtiles = 0;
362
        return AVERROR(EINVAL);
363
    }
364
365
412
    s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
366
412
    if (!s->tile) {
367
        s->numXtiles = s->numYtiles = 0;
368
        return AVERROR(ENOMEM);
369
    }
370
371
1743
    for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
372
1331
        Jpeg2000Tile *tile = s->tile + i;
373
374
1331
        tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
375
1331
        if (!tile->comp)
376
            return AVERROR(ENOMEM);
377
    }
378
379
    /* compute image size with reduction factor */
380
412
    o_dimx = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,
381
                                               s->reduction_factor);
382
412
    o_dimy = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
383
                                               s->reduction_factor);
384
412
    dimx = ff_jpeg2000_ceildiv(o_dimx, s->cdx[0]);
385
412
    dimy = ff_jpeg2000_ceildiv(o_dimy, s->cdy[0]);
386
1237
    for (i = 1; i < s->ncomponents; i++) {
387
825
        dimx = FFMAX(dimx, ff_jpeg2000_ceildiv(o_dimx, s->cdx[i]));
388
825
        dimy = FFMAX(dimy, ff_jpeg2000_ceildiv(o_dimy, s->cdy[i]));
389
    }
390
391
412
    ret = ff_set_dimensions(s->avctx, dimx, dimy);
392
412
    if (ret < 0)
393
        return ret;
394
395
412
    if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
396
409
        s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
397
3
        possible_fmts = xyz_pix_fmts;
398
3
        possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
399
    } else {
400

409
        switch (s->colour_space) {
401
409
        case 16:
402
409
            possible_fmts = rgb_pix_fmts;
403
409
            possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
404
409
            break;
405
        case 17:
406
            possible_fmts = gray_pix_fmts;
407
            possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
408
            break;
409
        case 18:
410
            possible_fmts = yuv_pix_fmts;
411
            possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
412
            break;
413
        default:
414
            possible_fmts = all_pix_fmts;
415
            possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
416
            break;
417
        }
418
    }
419
412
    if (   s->avctx->pix_fmt != AV_PIX_FMT_NONE
420
402
        && !pix_fmt_match(s->avctx->pix_fmt, ncomponents, s->precision, log2_chroma_wh, s->pal8))
421
            s->avctx->pix_fmt = AV_PIX_FMT_NONE;
422
412
    if (s->avctx->pix_fmt == AV_PIX_FMT_NONE)
423
22
        for (i = 0; i < possible_fmts_nb; ++i) {
424
22
            if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
425
10
                s->avctx->pix_fmt = possible_fmts[i];
426
10
                break;
427
            }
428
        }
429
430
412
    if (i == possible_fmts_nb) {
431
        if (ncomponents == 4 &&
432
            s->cdy[0] == 1 && s->cdx[0] == 1 &&
433
            s->cdy[1] == 1 && s->cdx[1] == 1 &&
434
            s->cdy[2] == s->cdy[3] && s->cdx[2] == s->cdx[3]) {
435
            if (s->precision == 8 && s->cdy[2] == 2 && s->cdx[2] == 2 && !s->pal8) {
436
                s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
437
                s->cdef[0] = 0;
438
                s->cdef[1] = 1;
439
                s->cdef[2] = 2;
440
                s->cdef[3] = 3;
441
                i = 0;
442
            }
443
        } else if (ncomponents == 3 && s->precision == 8 &&
444
                   s->cdx[0] == s->cdx[1] && s->cdx[0] == s->cdx[2] &&
445
                   s->cdy[0] == s->cdy[1] && s->cdy[0] == s->cdy[2]) {
446
            s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
447
            i = 0;
448
        } else if (ncomponents == 2 && s->precision == 8 &&
449
                   s->cdx[0] == s->cdx[1] && s->cdy[0] == s->cdy[1]) {
450
            s->avctx->pix_fmt = AV_PIX_FMT_YA8;
451
            i = 0;
452
        } else if (ncomponents == 1 && s->precision == 8) {
453
            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
454
            i = 0;
455
        }
456
    }
457
458
459
412
    if (i == possible_fmts_nb) {
460
        av_log(s->avctx, AV_LOG_ERROR,
461
               "Unknown pix_fmt, profile: %d, colour_space: %d, "
462
               "components: %d, precision: %d\n"
463
               "cdx[0]: %d, cdy[0]: %d\n"
464
               "cdx[1]: %d, cdy[1]: %d\n"
465
               "cdx[2]: %d, cdy[2]: %d\n"
466
               "cdx[3]: %d, cdy[3]: %d\n",
467
               s->avctx->profile, s->colour_space, ncomponents, s->precision,
468
               s->cdx[0],
469
               s->cdy[0],
470
               ncomponents > 1 ? s->cdx[1] : 0,
471
               ncomponents > 1 ? s->cdy[1] : 0,
472
               ncomponents > 2 ? s->cdx[2] : 0,
473
               ncomponents > 2 ? s->cdy[2] : 0,
474
               ncomponents > 3 ? s->cdx[3] : 0,
475
               ncomponents > 3 ? s->cdy[3] : 0);
476
        return AVERROR_PATCHWELCOME;
477
    }
478
412
    s->avctx->bits_per_raw_sample = s->precision;
479
412
    return 0;
480
}
481
482
/* get common part for COD and COC segments */
483
418
static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
484
{
485
    uint8_t byte;
486
487
418
    if (bytestream2_get_bytes_left(&s->g) < 5) {
488
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COX\n");
489
        return AVERROR_INVALIDDATA;
490
    }
491
492
    /*  nreslevels = number of resolution levels
493
                   = number of decomposition level +1 */
494
418
    c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
495
418
    if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
496
        av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
497
        return AVERROR_INVALIDDATA;
498
    }
499
500
418
    if (c->nreslevels <= s->reduction_factor) {
501
        /* we are forced to update reduction_factor as its requested value is
502
           not compatible with this bitstream, and as we might have used it
503
           already in setup earlier we have to fail this frame until
504
           reinitialization is implemented */
505
        av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1);
506
        s->reduction_factor = c->nreslevels - 1;
507
        return AVERROR(EINVAL);
508
    }
509
510
    /* compute number of resolution levels to decode */
511
418
    c->nreslevels2decode = c->nreslevels - s->reduction_factor;
512
513
418
    c->log2_cblk_width  = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
514
418
    c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
515
516

418
    if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
517
418
        c->log2_cblk_width + c->log2_cblk_height > 12) {
518
        av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
519
        return AVERROR_INVALIDDATA;
520
    }
521
522
418
    c->cblk_style = bytestream2_get_byteu(&s->g);
523
418
    if (c->cblk_style != 0) { // cblk style
524
        av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
525
        if (c->cblk_style & JPEG2000_CBLK_BYPASS)
526
            av_log(s->avctx, AV_LOG_WARNING, "Selective arithmetic coding bypass\n");
527
    }
528
418
    c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
529
    /* set integer 9/7 DWT in case of BITEXACT flag */
530

418
    if ((s->avctx->flags & AV_CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
531
213
        c->transform = FF_DWT97_INT;
532
205
    else if (c->transform == FF_DWT53) {
533
204
        s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
534
    }
535
536
418
    if (c->csty & JPEG2000_CSTY_PREC) {
537
        int i;
538
63
        for (i = 0; i < c->nreslevels; i++) {
539
54
            byte = bytestream2_get_byte(&s->g);
540
54
            c->log2_prec_widths[i]  =  byte       & 0x0F;    // precinct PPx
541
54
            c->log2_prec_heights[i] = (byte >> 4) & 0x0F;    // precinct PPy
542
54
            if (i)
543

45
                if (c->log2_prec_widths[i] == 0 || c->log2_prec_heights[i] == 0) {
544
                    av_log(s->avctx, AV_LOG_ERROR, "PPx %d PPy %d invalid\n",
545
                           c->log2_prec_widths[i], c->log2_prec_heights[i]);
546
                    c->log2_prec_widths[i] = c->log2_prec_heights[i] = 1;
547
                    return AVERROR_INVALIDDATA;
548
                }
549
        }
550
    } else {
551
409
        memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
552
409
        memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
553
    }
554
418
    return 0;
555
}
556
557
/* get coding parameters for a particular tile or whole image*/
558
412
static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
559
                   uint8_t *properties)
560
{
561
    Jpeg2000CodingStyle tmp;
562
    int compno, ret;
563
564
412
    if (bytestream2_get_bytes_left(&s->g) < 5) {
565
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COD\n");
566
        return AVERROR_INVALIDDATA;
567
    }
568
569
412
    tmp.csty = bytestream2_get_byteu(&s->g);
570
571
    // get progression order
572
412
    tmp.prog_order = bytestream2_get_byteu(&s->g);
573
574
412
    tmp.nlayers    = bytestream2_get_be16u(&s->g);
575
412
    tmp.mct        = bytestream2_get_byteu(&s->g); // multiple component transformation
576
577

412
    if (tmp.mct && s->ncomponents < 3) {
578
        av_log(s->avctx, AV_LOG_ERROR,
579
               "MCT %"PRIu8" with too few components (%d)\n",
580
               tmp.mct, s->ncomponents);
581
        return AVERROR_INVALIDDATA;
582
    }
583
584
412
    if ((ret = get_cox(s, &tmp)) < 0)
585
        return ret;
586
412
    tmp.init = 1;
587
1649
    for (compno = 0; compno < s->ncomponents; compno++)
588
1237
        if (!(properties[compno] & HAD_COC))
589
1237
            memcpy(c + compno, &tmp, sizeof(tmp));
590
412
    return 0;
591
}
592
593
/* Get coding parameters for a component in the whole image or a
594
 * particular tile. */
595
6
static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
596
                   uint8_t *properties)
597
{
598
    int compno, ret;
599
    uint8_t has_eph, has_sop;
600
601
6
    if (bytestream2_get_bytes_left(&s->g) < 2) {
602
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COC\n");
603
        return AVERROR_INVALIDDATA;
604
    }
605
606
6
    compno = bytestream2_get_byteu(&s->g);
607
608
6
    if (compno >= s->ncomponents) {
609
        av_log(s->avctx, AV_LOG_ERROR,
610
               "Invalid compno %d. There are %d components in the image.\n",
611
               compno, s->ncomponents);
612
        return AVERROR_INVALIDDATA;
613
    }
614
615
6
    c      += compno;
616
6
    has_eph = c->csty & JPEG2000_CSTY_EPH;
617
6
    has_sop = c->csty & JPEG2000_CSTY_SOP;
618
6
    c->csty = bytestream2_get_byteu(&s->g);
619
6
    c->csty |= has_eph; //do not override eph present bits from COD
620
6
    c->csty |= has_sop; //do not override sop present bits from COD
621
622
6
    if ((ret = get_cox(s, c)) < 0)
623
        return ret;
624
625
6
    properties[compno] |= HAD_COC;
626
6
    c->init = 1;
627
6
    return 0;
628
}
629
630
static int get_rgn(Jpeg2000DecoderContext *s, int n)
631
{
632
    uint16_t compno;
633
    compno = (s->ncomponents < 257)? bytestream2_get_byte(&s->g):
634
                                     bytestream2_get_be16u(&s->g);
635
    if (bytestream2_get_byte(&s->g)) {
636
        av_log(s->avctx, AV_LOG_ERROR, "Invalid RGN header.\n");
637
        return AVERROR_INVALIDDATA; // SRgn field value is 0
638
    }
639
    // SPrgn field
640
    // Currently compno cannot be greater than 4.
641
    // However, future implementation should support compno up to 65536
642
    if (compno < s->ncomponents) {
643
        int v;
644
        if (s->curtileno == -1) {
645
            v =  bytestream2_get_byte(&s->g);
646
            if (v > 30)
647
                return AVERROR_PATCHWELCOME;
648
            s->roi_shift[compno] = v;
649
        } else {
650
            if (s->tile[s->curtileno].tp_idx != 0)
651
                return AVERROR_INVALIDDATA; // marker occurs only in first tile part of tile
652
            v = bytestream2_get_byte(&s->g);
653
            if (v > 30)
654
                return AVERROR_PATCHWELCOME;
655
            s->tile[s->curtileno].comp[compno].roi_shift = v;
656
        }
657
        return 0;
658
    }
659
    return AVERROR_INVALIDDATA;
660
}
661
662
/* Get common part for QCD and QCC segments. */
663
421
static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
664
{
665
    int i, x;
666
667
421
    if (bytestream2_get_bytes_left(&s->g) < 1)
668
        return AVERROR_INVALIDDATA;
669
670
421
    x = bytestream2_get_byteu(&s->g); // Sqcd
671
672
421
    q->nguardbits = x >> 5;
673
421
    q->quantsty   = x & 0x1f;
674
675
421
    if (q->quantsty == JPEG2000_QSTY_NONE) {
676
204
        n -= 3;
677

204
        if (bytestream2_get_bytes_left(&s->g) < n ||
678
            n > JPEG2000_MAX_DECLEVELS*3)
679
            return AVERROR_INVALIDDATA;
680
4080
        for (i = 0; i < n; i++)
681
3876
            q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
682
217
    } else if (q->quantsty == JPEG2000_QSTY_SI) {
683
        if (bytestream2_get_bytes_left(&s->g) < 2)
684
            return AVERROR_INVALIDDATA;
685
        x          = bytestream2_get_be16u(&s->g);
686
        q->expn[0] = x >> 11;
687
        q->mant[0] = x & 0x7ff;
688
        for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
689
            int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
690
            q->expn[i] = curexpn;
691
            q->mant[i] = q->mant[0];
692
        }
693
    } else {
694
217
        n = (n - 3) >> 1;
695

217
        if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
696
            n > JPEG2000_MAX_DECLEVELS*3)
697
            return AVERROR_INVALIDDATA;
698
4301
        for (i = 0; i < n; i++) {
699
4084
            x          = bytestream2_get_be16u(&s->g);
700
4084
            q->expn[i] = x >> 11;
701
4084
            q->mant[i] = x & 0x7ff;
702
        }
703
    }
704
421
    return 0;
705
}
706
707
/* Get quantization parameters for a particular tile or a whole image. */
708
412
static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
709
                   uint8_t *properties)
710
{
711
    Jpeg2000QuantStyle tmp;
712
    int compno, ret;
713
714
412
    memset(&tmp, 0, sizeof(tmp));
715
716
412
    if ((ret = get_qcx(s, n, &tmp)) < 0)
717
        return ret;
718
1649
    for (compno = 0; compno < s->ncomponents; compno++)
719
1237
        if (!(properties[compno] & HAD_QCC))
720
1237
            memcpy(q + compno, &tmp, sizeof(tmp));
721
412
    return 0;
722
}
723
724
/* Get quantization parameters for a component in the whole image
725
 * on in a particular tile. */
726
9
static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
727
                   uint8_t *properties)
728
{
729
    int compno;
730
731
9
    if (bytestream2_get_bytes_left(&s->g) < 1)
732
        return AVERROR_INVALIDDATA;
733
734
9
    compno = bytestream2_get_byteu(&s->g);
735
736
9
    if (compno >= s->ncomponents) {
737
        av_log(s->avctx, AV_LOG_ERROR,
738
               "Invalid compno %d. There are %d components in the image.\n",
739
               compno, s->ncomponents);
740
        return AVERROR_INVALIDDATA;
741
    }
742
743
9
    properties[compno] |= HAD_QCC;
744
9
    return get_qcx(s, n - 1, q + compno);
745
}
746
747
static int get_poc(Jpeg2000DecoderContext *s, int size, Jpeg2000POC *p)
748
{
749
    int i;
750
    int elem_size = s->ncomponents <= 257 ? 7 : 9;
751
    Jpeg2000POC tmp = {{{0}}};
752
753
    if (bytestream2_get_bytes_left(&s->g) < 5 || size < 2 + elem_size) {
754
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for POC\n");
755
        return AVERROR_INVALIDDATA;
756
    }
757
758
    if (elem_size > 7) {
759
        avpriv_request_sample(s->avctx, "Fat POC not supported");
760
        return AVERROR_PATCHWELCOME;
761
    }
762
763
    tmp.nb_poc = (size - 2) / elem_size;
764
    if (tmp.nb_poc > MAX_POCS) {
765
        avpriv_request_sample(s->avctx, "Too many POCs (%d)", tmp.nb_poc);
766
        return AVERROR_PATCHWELCOME;
767
    }
768
769
    for (i = 0; i<tmp.nb_poc; i++) {
770
        Jpeg2000POCEntry *e = &tmp.poc[i];
771
        e->RSpoc  = bytestream2_get_byteu(&s->g);
772
        e->CSpoc  = bytestream2_get_byteu(&s->g);
773
        e->LYEpoc = bytestream2_get_be16u(&s->g);
774
        e->REpoc  = bytestream2_get_byteu(&s->g);
775
        e->CEpoc  = bytestream2_get_byteu(&s->g);
776
        e->Ppoc   = bytestream2_get_byteu(&s->g);
777
        if (!e->CEpoc)
778
            e->CEpoc = 256;
779
        if (e->CEpoc > s->ncomponents)
780
            e->CEpoc = s->ncomponents;
781
        if (   e->RSpoc >= e->REpoc || e->REpoc > 33
782
            || e->CSpoc >= e->CEpoc || e->CEpoc > s->ncomponents
783
            || !e->LYEpoc) {
784
            av_log(s->avctx, AV_LOG_ERROR, "POC Entry %d is invalid (%d, %d, %d, %d, %d, %d)\n", i,
785
                e->RSpoc, e->CSpoc, e->LYEpoc, e->REpoc, e->CEpoc, e->Ppoc
786
            );
787
            return AVERROR_INVALIDDATA;
788
        }
789
    }
790
791
    if (!p->nb_poc || p->is_default) {
792
        *p = tmp;
793
    } else {
794
        if (p->nb_poc + tmp.nb_poc > MAX_POCS) {
795
            av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for POC\n");
796
            return AVERROR_INVALIDDATA;
797
        }
798
        memcpy(p->poc + p->nb_poc, tmp.poc, tmp.nb_poc * sizeof(tmp.poc[0]));
799
        p->nb_poc += tmp.nb_poc;
800
    }
801
802
    p->is_default = 0;
803
804
    return 0;
805
}
806
807
808
/* Get start of tile segment. */
809
1343
static int get_sot(Jpeg2000DecoderContext *s, int n)
810
{
811
    Jpeg2000TilePart *tp;
812
    uint16_t Isot;
813
    uint32_t Psot;
814
    unsigned TPsot;
815
816
1343
    if (bytestream2_get_bytes_left(&s->g) < 8)
817
        return AVERROR_INVALIDDATA;
818
819
1343
    s->curtileno = 0;
820
1343
    Isot = bytestream2_get_be16u(&s->g);        // Isot
821
1343
    if (Isot >= s->numXtiles * s->numYtiles)
822
        return AVERROR_INVALIDDATA;
823
824
1343
    s->curtileno = Isot;
825
1343
    Psot  = bytestream2_get_be32u(&s->g);       // Psot
826
1343
    TPsot = bytestream2_get_byteu(&s->g);       // TPsot
827
828
    /* Read TNSot but not used */
829
1343
    bytestream2_get_byteu(&s->g);               // TNsot
830
831
1343
    if (!Psot)
832
        Psot = bytestream2_get_bytes_left(&s->g) - 2 + n + 2;
833
834
1343
    if (Psot > bytestream2_get_bytes_left(&s->g) - 2 + n + 2) {
835
        av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);
836
        return AVERROR_INVALIDDATA;
837
    }
838
839
1343
    if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
840
        avpriv_request_sample(s->avctx, "Too many tile parts");
841
        return AVERROR_PATCHWELCOME;
842
    }
843
844
1343
    s->tile[Isot].tp_idx = TPsot;
845
1343
    tp             = s->tile[Isot].tile_part + TPsot;
846
1343
    tp->tile_index = Isot;
847
1343
    tp->tp_end     = s->g.buffer + Psot - n - 2;
848
849
1343
    if (!TPsot) {
850
1331
        Jpeg2000Tile *tile = s->tile + s->curtileno;
851
852
        /* copy defaults */
853
1331
        memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
854
1331
        memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
855
1331
        memcpy(&tile->poc  , &s->poc  , sizeof(tile->poc));
856
1331
        tile->poc.is_default = 1;
857
    }
858
859
1343
    return 0;
860
}
861
862
static int read_crg(Jpeg2000DecoderContext *s, int n)
863
{
864
    if (s->ncomponents*4 != n - 2) {
865
        av_log(s->avctx, AV_LOG_ERROR, "Invalid CRG marker.\n");
866
        return AVERROR_INVALIDDATA;
867
    }
868
    bytestream2_skip(&s->g, n - 2);
869
    return 0;
870
}
871
/* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
872
 * Used to know the number of tile parts and lengths.
873
 * There may be multiple TLMs in the header.
874
 * TODO: The function is not used for tile-parts management, nor anywhere else.
875
 * It can be useful to allocate memory for tile parts, before managing the SOT
876
 * markers. Parsing the TLM header is needed to increment the input header
877
 * buffer.
878
 * This marker is mandatory for DCI. */
879
4
static int get_tlm(Jpeg2000DecoderContext *s, int n)
880
{
881
    uint8_t Stlm, ST, SP, tile_tlm, i;
882
4
    bytestream2_get_byte(&s->g);               /* Ztlm: skipped */
883
4
    Stlm = bytestream2_get_byte(&s->g);
884
885
    // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
886
4
    ST = (Stlm >> 4) & 0x03;
887
4
    if (ST == 0x03) {
888
        av_log(s->avctx, AV_LOG_ERROR, "TLM marker contains invalid ST value.\n");
889
        return AVERROR_INVALIDDATA;
890
    }
891
892
4
    SP       = (Stlm >> 6) & 0x01;
893
4
    tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
894
21
    for (i = 0; i < tile_tlm; i++) {
895

17
        switch (ST) {
896
        case 0:
897
            break;
898
17
        case 1:
899
17
            bytestream2_get_byte(&s->g);
900
17
            break;
901
        case 2:
902
            bytestream2_get_be16(&s->g);
903
            break;
904
        case 3:
905
            bytestream2_get_be32(&s->g);
906
            break;
907
        }
908
17
        if (SP == 0) {
909
            bytestream2_get_be16(&s->g);
910
        } else {
911
17
            bytestream2_get_be32(&s->g);
912
        }
913
    }
914
4
    return 0;
915
}
916
917
static int get_plt(Jpeg2000DecoderContext *s, int n)
918
{
919
    int i;
920
    int v;
921
922
    av_log(s->avctx, AV_LOG_DEBUG,
923
            "PLT marker at pos 0x%X\n", bytestream2_tell(&s->g) - 4);
924
925
    if (n < 4)
926
        return AVERROR_INVALIDDATA;
927
928
    /*Zplt =*/ bytestream2_get_byte(&s->g);
929
930
    for (i = 0; i < n - 3; i++) {
931
        v = bytestream2_get_byte(&s->g);
932
    }
933
    if (v & 0x80)
934
        return AVERROR_INVALIDDATA;
935
936
    return 0;
937
}
938
939
static int get_ppm(Jpeg2000DecoderContext *s, int n)
940
{
941
    void *new;
942
943
    if (n < 3) {
944
        av_log(s->avctx, AV_LOG_ERROR, "Invalid length for PPM data.\n");
945
        return AVERROR_INVALIDDATA;
946
    }
947
    bytestream2_get_byte(&s->g); //Zppm is skipped and not used
948
    new = av_realloc(s->packed_headers,
949
                     s->packed_headers_size + n - 3);
950
    if (new) {
951
        s->packed_headers = new;
952
    } else
953
        return AVERROR(ENOMEM);
954
    s->has_ppm = 1;
955
    memset(&s->packed_headers_stream, 0, sizeof(s->packed_headers_stream));
956
    bytestream_get_buffer(&s->g.buffer, s->packed_headers + s->packed_headers_size,
957
                          n - 3);
958
    s->packed_headers_size += n - 3;
959
960
    return 0;
961
}
962
963
static int get_ppt(Jpeg2000DecoderContext *s, int n)
964
{
965
    Jpeg2000Tile *tile;
966
    void *new;
967
968
    if (n < 3) {
969
        av_log(s->avctx, AV_LOG_ERROR, "Invalid length for PPT data.\n");
970
        return AVERROR_INVALIDDATA;
971
    }
972
    if (s->curtileno < 0)
973
        return AVERROR_INVALIDDATA;
974
975
    tile = &s->tile[s->curtileno];
976
    if (tile->tp_idx != 0) {
977
        av_log(s->avctx, AV_LOG_ERROR,
978
               "PPT marker can occur only on first tile part of a tile.\n");
979
        return AVERROR_INVALIDDATA;
980
    }
981
982
    tile->has_ppt = 1;  // this tile has a ppt marker
983
    bytestream2_get_byte(&s->g); // Zppt is skipped and not used
984
    new = av_realloc(tile->packed_headers,
985
                     tile->packed_headers_size + n - 3);
986
    if (new) {
987
        tile->packed_headers = new;
988
    } else
989
        return AVERROR(ENOMEM);
990
    memset(&tile->packed_headers_stream, 0, sizeof(tile->packed_headers_stream));
991
    memcpy(tile->packed_headers + tile->packed_headers_size,
992
           s->g.buffer, n - 3);
993
    tile->packed_headers_size += n - 3;
994
    bytestream2_skip(&s->g, n - 3);
995
996
    return 0;
997
}
998
999
1331
static int init_tile(Jpeg2000DecoderContext *s, int tileno)
1000
{
1001
    int compno;
1002
1331
    int tilex = tileno % s->numXtiles;
1003
1331
    int tiley = tileno / s->numXtiles;
1004
1331
    Jpeg2000Tile *tile = s->tile + tileno;
1005
1006
1331
    if (!tile->comp)
1007
        return AVERROR(ENOMEM);
1008
1009
1331
    tile->coord[0][0] = av_clip(tilex       * (int64_t)s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);
1010
1331
    tile->coord[0][1] = av_clip((tilex + 1) * (int64_t)s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);
1011
1331
    tile->coord[1][0] = av_clip(tiley       * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
1012
1331
    tile->coord[1][1] = av_clip((tiley + 1) * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
1013
1014
5326
    for (compno = 0; compno < s->ncomponents; compno++) {
1015
3995
        Jpeg2000Component *comp = tile->comp + compno;
1016
3995
        Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1017
3995
        Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
1018
        int ret; // global bandno
1019
1020
3995
        comp->coord_o[0][0] = tile->coord[0][0];
1021
3995
        comp->coord_o[0][1] = tile->coord[0][1];
1022
3995
        comp->coord_o[1][0] = tile->coord[1][0];
1023
3995
        comp->coord_o[1][1] = tile->coord[1][1];
1024
1025
3995
        comp->coord_o[0][0] = ff_jpeg2000_ceildiv(comp->coord_o[0][0], s->cdx[compno]);
1026
3995
        comp->coord_o[0][1] = ff_jpeg2000_ceildiv(comp->coord_o[0][1], s->cdx[compno]);
1027
3995
        comp->coord_o[1][0] = ff_jpeg2000_ceildiv(comp->coord_o[1][0], s->cdy[compno]);
1028
3995
        comp->coord_o[1][1] = ff_jpeg2000_ceildiv(comp->coord_o[1][1], s->cdy[compno]);
1029
1030
3995
        comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
1031
3995
        comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
1032
3995
        comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
1033
3995
        comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
1034
1035
3995
        if (!comp->roi_shift)
1036
3995
            comp->roi_shift = s->roi_shift[compno];
1037
3995
        if (!codsty->init)
1038
            return AVERROR_INVALIDDATA;
1039
3995
        if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
1040
3995
                                             s->cbps[compno], s->cdx[compno],
1041
                                             s->cdy[compno], s->avctx))
1042
            return ret;
1043
    }
1044
1331
    return 0;
1045
}
1046
1047
/* Read the number of coding passes. */
1048
400195
static int getnpasses(Jpeg2000DecoderContext *s)
1049
{
1050
    int num;
1051
400195
    if (!get_bits(s, 1))
1052
47412
        return 1;
1053
352783
    if (!get_bits(s, 1))
1054
14156
        return 2;
1055
338627
    if ((num = get_bits(s, 2)) != 3)
1056
118629
        return num < 0 ? num : 3 + num;
1057
219998
    if ((num = get_bits(s, 5)) != 31)
1058
219995
        return num < 0 ? num : 6 + num;
1059
3
    num = get_bits(s, 7);
1060
3
    return num < 0 ? num : 37 + num;
1061
}
1062
1063
400195
static int getlblockinc(Jpeg2000DecoderContext *s)
1064
{
1065
400195
    int res = 0, ret;
1066
557109
    while (ret = get_bits(s, 1)) {
1067
156914
        if (ret < 0)
1068
            return ret;
1069
156914
        res++;
1070
    }
1071
400195
    return res;
1072
}
1073
1074
static inline void select_header(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1075
                                 int *tp_index)
1076
{
1077
    s->g = tile->tile_part[*tp_index].header_tpg;
1078
    if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {
1079
        if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {
1080
            s->g = tile->tile_part[++(*tp_index)].tpg;
1081
        }
1082
    }
1083
}
1084
1085
28473
static inline void select_stream(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1086
                                 int *tp_index, Jpeg2000CodingStyle *codsty)
1087
{
1088
28473
    s->g = tile->tile_part[*tp_index].tpg;
1089

28473
    if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {
1090
12
        if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {
1091
12
            s->g = tile->tile_part[++(*tp_index)].tpg;
1092
        }
1093
    }
1094
28473
    if (codsty->csty & JPEG2000_CSTY_SOP) {
1095
        if (bytestream2_peek_be32(&s->g) == JPEG2000_SOP_FIXED_BYTES)
1096
            bytestream2_skip(&s->g, JPEG2000_SOP_BYTE_LENGTH);
1097
        else
1098
            av_log(s->avctx, AV_LOG_ERROR, "SOP marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1099
    }
1100
28473
}
1101
1102
28473
static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index,
1103
                                  Jpeg2000CodingStyle *codsty,
1104
                                  Jpeg2000ResLevel *rlevel, int precno,
1105
                                  int layno, uint8_t *expn, int numgbits)
1106
{
1107
    int bandno, cblkno, ret, nb_code_blocks;
1108
    int cwsno;
1109
1110
28473
    if (layno < rlevel->band[0].prec[precno].decoded_layers)
1111
        return 0;
1112
28473
    rlevel->band[0].prec[precno].decoded_layers = layno + 1;
1113
    // Select stream to read from
1114
28473
    if (s->has_ppm)
1115
        select_header(s, tile, tp_index);
1116
28473
    else if (tile->has_ppt)
1117
        s->g = tile->packed_headers_stream;
1118
    else
1119
28473
        select_stream(s, tile, tp_index, codsty);
1120
1121
28473
    if (!(ret = get_bits(s, 1))) {
1122
        jpeg2000_flush(s);
1123
        goto skip_data;
1124
28473
    } else if (ret < 0)
1125
        return ret;
1126
1127
105886
    for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1128
77413
        Jpeg2000Band *band = rlevel->band + bandno;
1129
77413
        Jpeg2000Prec *prec = band->prec + precno;
1130
1131
77413
        if (band->coord[0][0] == band->coord[0][1] ||
1132
77413
            band->coord[1][0] == band->coord[1][1])
1133
3672
            continue;
1134
73741
        nb_code_blocks =  prec->nb_codeblocks_height *
1135
73741
                          prec->nb_codeblocks_width;
1136
519268
        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
1137
445527
            Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1138
            int incl, newpasses, llen;
1139
            void *tmp;
1140
1141
445527
            if (cblk->npasses)
1142
2056
                incl = get_bits(s, 1);
1143
            else
1144
443471
                incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
1145
445527
            if (!incl)
1146
45332
                continue;
1147
400195
            else if (incl < 0)
1148
                return incl;
1149
1150
400195
            if (!cblk->npasses) {
1151
796718
                int v = expn[bandno] + numgbits - 1 -
1152
398359
                        tag_tree_decode(s, prec->zerobits + cblkno, 100);
1153

398359
                if (v < 0 || v > 30) {
1154
                    av_log(s->avctx, AV_LOG_ERROR,
1155
                           "nonzerobits %d invalid or unsupported\n", v);
1156
                    return AVERROR_INVALIDDATA;
1157
                }
1158
398359
                cblk->nonzerobits = v;
1159
            }
1160
400195
            if ((newpasses = getnpasses(s)) < 0)
1161
                return newpasses;
1162
            av_assert2(newpasses > 0);
1163
400195
            if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) {
1164
                avpriv_request_sample(s->avctx, "Too many passes");
1165
                return AVERROR_PATCHWELCOME;
1166
            }
1167
400195
            if ((llen = getlblockinc(s)) < 0)
1168
                return llen;
1169
400195
            if (cblk->lblock + llen + av_log2(newpasses) > 16) {
1170
                avpriv_request_sample(s->avctx,
1171
                                      "Block with length beyond 16 bits");
1172
                return AVERROR_PATCHWELCOME;
1173
            }
1174
1175
400195
            cblk->lblock += llen;
1176
1177
400195
            cblk->nb_lengthinc = 0;
1178
400195
            cblk->nb_terminationsinc = 0;
1179
400195
            av_free(cblk->lengthinc);
1180
400195
            cblk->lengthinc  = av_mallocz_array(newpasses    , sizeof(*cblk->lengthinc));
1181
400195
            if (!cblk->lengthinc)
1182
                return AVERROR(ENOMEM);
1183
400195
            tmp = av_realloc_array(cblk->data_start, cblk->nb_terminations + newpasses + 1, sizeof(*cblk->data_start));
1184
400195
            if (!tmp)
1185
                return AVERROR(ENOMEM);
1186
400195
            cblk->data_start = tmp;
1187
            do {
1188
400195
                int newpasses1 = 0;
1189
1190
3195609
                while (newpasses1 < newpasses) {
1191
2795414
                    newpasses1 ++;
1192
2795414
                    if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) {
1193
                        cblk->nb_terminationsinc ++;
1194
                        break;
1195
                    }
1196
                }
1197
1198
400195
                if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0)
1199
                    return ret;
1200
400195
                if (ret > cblk->data_allocated) {
1201
398691
                    size_t new_size = FFMAX(2*cblk->data_allocated, ret);
1202
398691
                    void *new = av_realloc(cblk->data, new_size);
1203
398691
                    if (new) {
1204
398691
                        cblk->data = new;
1205
398691
                        cblk->data_allocated = new_size;
1206
                    }
1207
                }
1208
400195
                if (ret > cblk->data_allocated) {
1209
                    avpriv_request_sample(s->avctx,
1210
                                        "Block with lengthinc greater than %"SIZE_SPECIFIER"",
1211
                                        cblk->data_allocated);
1212
                    return AVERROR_PATCHWELCOME;
1213
                }
1214
400195
                cblk->lengthinc[cblk->nb_lengthinc++] = ret;
1215
400195
                cblk->npasses  += newpasses1;
1216
400195
                newpasses -= newpasses1;
1217
400195
            } while(newpasses);
1218
        }
1219
    }
1220
28473
    jpeg2000_flush(s);
1221
1222
28473
    if (codsty->csty & JPEG2000_CSTY_EPH) {
1223
        if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
1224
            bytestream2_skip(&s->g, 2);
1225
        else
1226
            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1227
    }
1228
1229
    // Save state of stream
1230
28473
    if (s->has_ppm) {
1231
        tile->tile_part[*tp_index].header_tpg = s->g;
1232
        select_stream(s, tile, tp_index, codsty);
1233
28473
    } else if (tile->has_ppt) {
1234
        tile->packed_headers_stream = s->g;
1235
        select_stream(s, tile, tp_index, codsty);
1236
    }
1237
105886
    for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1238
77413
        Jpeg2000Band *band = rlevel->band + bandno;
1239
77413
        Jpeg2000Prec *prec = band->prec + precno;
1240
1241
77413
        nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
1242
526612
        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
1243
449199
            Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1244

449199
            if (!cblk->nb_terminationsinc && !cblk->lengthinc)
1245
49004
                continue;
1246
800390
            for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) {
1247
400195
                if (cblk->data_allocated < cblk->length + cblk->lengthinc[cwsno] + 4) {
1248
399903
                    size_t new_size = FFMAX(2*cblk->data_allocated, cblk->length + cblk->lengthinc[cwsno] + 4);
1249
399903
                    void *new = av_realloc(cblk->data, new_size);
1250
399903
                    if (new) {
1251
399903
                        cblk->data = new;
1252
399903
                        cblk->data_allocated = new_size;
1253
                    }
1254
                }
1255
400195
                if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno]
1256
400195
                    || cblk->data_allocated < cblk->length + cblk->lengthinc[cwsno] + 4
1257
                ) {
1258
                    av_log(s->avctx, AV_LOG_ERROR,
1259
                        "Block length %"PRIu16" or lengthinc %d is too large, left %d\n",
1260
                        cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g));
1261
                    return AVERROR_INVALIDDATA;
1262
                }
1263
1264
400195
                bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]);
1265
400195
                cblk->length   += cblk->lengthinc[cwsno];
1266
400195
                cblk->lengthinc[cwsno] = 0;
1267
400195
                if (cblk->nb_terminationsinc) {
1268
                    cblk->nb_terminationsinc--;
1269
                    cblk->nb_terminations++;
1270
                    cblk->data[cblk->length++] = 0xFF;
1271
                    cblk->data[cblk->length++] = 0xFF;
1272
                    cblk->data_start[cblk->nb_terminations] = cblk->length;
1273
                }
1274
            }
1275
400195
            av_freep(&cblk->lengthinc);
1276
        }
1277
    }
1278
    // Save state of stream
1279
28473
    tile->tile_part[*tp_index].tpg = s->g;
1280
28473
    return 0;
1281
1282
skip_data:
1283
    if (codsty->csty & JPEG2000_CSTY_EPH) {
1284
        if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
1285
            bytestream2_skip(&s->g, 2);
1286
        else
1287
            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1288
    }
1289
    if (s->has_ppm) {
1290
        tile->tile_part[*tp_index].header_tpg = s->g;
1291
        select_stream(s, tile, tp_index, codsty);
1292
    } else if (tile->has_ppt) {
1293
        tile->packed_headers_stream = s->g;
1294
        select_stream(s, tile, tp_index, codsty);
1295
    }
1296
    tile->tile_part[*tp_index].tpg = s->g;
1297
    return 0;
1298
}
1299
1300
1331
static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1301
                                             int RSpoc, int CSpoc,
1302
                                             int LYEpoc, int REpoc, int CEpoc,
1303
                                             int Ppoc, int *tp_index)
1304
{
1305
1331
    int ret = 0;
1306
    int layno, reslevelno, compno, precno, ok_reslevel;
1307
    int x, y;
1308
    int step_x, step_y;
1309
1310

1331
    switch (Ppoc) {
1311
    case JPEG2000_PGOD_RLCP:
1312
        av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");
1313
        ok_reslevel = 1;
1314
        for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1315
            ok_reslevel = 0;
1316
            for (layno = 0; layno < LYEpoc; layno++) {
1317
                for (compno = CSpoc; compno < CEpoc; compno++) {
1318
                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1319
                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1320
                    if (reslevelno < codsty->nreslevels) {
1321
                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
1322
                                                reslevelno;
1323
                        ok_reslevel = 1;
1324
                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
1325
                            if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1326
                                                              codsty, rlevel,
1327
                                                              precno, layno,
1328
                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1329
                                                              qntsty->nguardbits)) < 0)
1330
                                return ret;
1331
                    }
1332
                }
1333
            }
1334
        }
1335
        break;
1336
1337
1326
    case JPEG2000_PGOD_LRCP:
1338
1326
        av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");
1339
2652
        for (layno = 0; layno < LYEpoc; layno++) {
1340
1326
            ok_reslevel = 1;
1341

11934
            for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1342
10608
                ok_reslevel = 0;
1343
42432
                for (compno = CSpoc; compno < CEpoc; compno++) {
1344
31824
                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1345
31824
                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1346
31824
                    if (reslevelno < codsty->nreslevels) {
1347
27846
                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
1348
                                                reslevelno;
1349
27846
                        ok_reslevel = 1;
1350
55692
                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
1351
27846
                            if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1352
                                                              codsty, rlevel,
1353
                                                              precno, layno,
1354
27846
                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1355
27846
                                                              qntsty->nguardbits)) < 0)
1356
                                return ret;
1357
                    }
1358
                }
1359
            }
1360
        }
1361
1326
        break;
1362
1363
5
    case JPEG2000_PGOD_CPRL:
1364
5
        av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");
1365
22
        for (compno = CSpoc; compno < CEpoc; compno++) {
1366
17
            Jpeg2000Component *comp     = tile->comp + compno;
1367
17
            Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1368
17
            Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1369
17
            step_x = 32;
1370
17
            step_y = 32;
1371
1372
17
            if (RSpoc >= FFMIN(codsty->nreslevels, REpoc))
1373
                continue;
1374
1375
119
            for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1376
102
                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1377
102
                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1378
102
                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1379
102
                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1380
            }
1381

17
            if (step_x >= 31 || step_y >= 31){
1382
                avpriv_request_sample(s->avctx, "CPRL with large step");
1383
                return AVERROR_PATCHWELCOME;
1384
            }
1385
17
            step_x = 1<<step_x;
1386
17
            step_y = 1<<step_y;
1387
1388
70
            for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1389
421
                for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1390
2576
                    for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1391
                        unsigned prcx, prcy;
1392
2208
                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1393
2208
                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1394
2208
                        int xc = x / s->cdx[compno];
1395
2208
                        int yc = y / s->cdy[compno];
1396
1397

2208
                        if (yc % (1LL << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
1398
1224
                            continue;
1399
1400

984
                        if (xc % (1LL << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
1401
405
                            continue;
1402
1403
                        // check if a precinct exists
1404
579
                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
1405
579
                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
1406
579
                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1407
579
                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1408
1409
579
                        precno = prcx + rlevel->num_precincts_x * prcy;
1410
1411

579
                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1412
                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1413
                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1414
                            continue;
1415
                        }
1416
1417
1206
                        for (layno = 0; layno < LYEpoc; layno++) {
1418
627
                            if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
1419
                                                              precno, layno,
1420
627
                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1421
627
                                                              qntsty->nguardbits)) < 0)
1422
                                return ret;
1423
                        }
1424
                    }
1425
                }
1426
            }
1427
        }
1428
5
        break;
1429
1430
    case JPEG2000_PGOD_RPCL:
1431
        av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");
1432
        ok_reslevel = 1;
1433
        for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1434
            ok_reslevel = 0;
1435
            step_x = 30;
1436
            step_y = 30;
1437
            for (compno = CSpoc; compno < CEpoc; compno++) {
1438
                Jpeg2000Component *comp     = tile->comp + compno;
1439
                Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1440
1441
                if (reslevelno < codsty->nreslevels) {
1442
                    uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1443
                    Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1444
                    step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1445
                    step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1446
                }
1447
            }
1448
            step_x = 1<<step_x;
1449
            step_y = 1<<step_y;
1450
1451
            for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1452
                for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1453
                    for (compno = CSpoc; compno < CEpoc; compno++) {
1454
                        Jpeg2000Component *comp     = tile->comp + compno;
1455
                        Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1456
                        Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1457
                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1458
                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1459
                        unsigned prcx, prcy;
1460
                        int trx0, try0;
1461
1462
                        if (!s->cdx[compno] || !s->cdy[compno])
1463
                            return AVERROR_INVALIDDATA;
1464
1465
                        if (reslevelno >= codsty->nreslevels)
1466
                            continue;
1467
1468
                        trx0 = ff_jpeg2000_ceildiv(tile->coord[0][0], (int64_t)s->cdx[compno] << reducedresno);
1469
                        try0 = ff_jpeg2000_ceildiv(tile->coord[1][0], (int64_t)s->cdy[compno] << reducedresno);
1470
1471
                        if (!(y % ((uint64_t)s->cdy[compno] << (rlevel->log2_prec_height + reducedresno)) == 0 ||
1472
                             (y == tile->coord[1][0] && ((int64_t)try0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_height)))))
1473
                            continue;
1474
1475
                        if (!(x % ((uint64_t)s->cdx[compno] << (rlevel->log2_prec_width + reducedresno)) == 0 ||
1476
                             (x == tile->coord[0][0] && ((int64_t)trx0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_width)))))
1477
                            continue;
1478
1479
                        // check if a precinct exists
1480
                        prcx   = ff_jpeg2000_ceildiv(x, (int64_t)s->cdx[compno] << reducedresno) >> rlevel->log2_prec_width;
1481
                        prcy   = ff_jpeg2000_ceildiv(y, (int64_t)s->cdy[compno] << reducedresno) >> rlevel->log2_prec_height;
1482
                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1483
                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1484
1485
                        precno = prcx + rlevel->num_precincts_x * prcy;
1486
1487
                        ok_reslevel = 1;
1488
                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1489
                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1490
                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1491
                            continue;
1492
                        }
1493
1494
                        for (layno = 0; layno < LYEpoc; layno++) {
1495
                            if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1496
                                                              codsty, rlevel,
1497
                                                              precno, layno,
1498
                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1499
                                                              qntsty->nguardbits)) < 0)
1500
                                return ret;
1501
                        }
1502
                    }
1503
                }
1504
            }
1505
        }
1506
        break;
1507
1508
    case JPEG2000_PGOD_PCRL:
1509
        av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL\n");
1510
        step_x = 32;
1511
        step_y = 32;
1512
        for (compno = CSpoc; compno < CEpoc; compno++) {
1513
            Jpeg2000Component *comp     = tile->comp + compno;
1514
            Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1515
1516
            for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1517
                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1518
                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1519
                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1520
                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1521
            }
1522
        }
1523
        if (step_x >= 31 || step_y >= 31){
1524
            avpriv_request_sample(s->avctx, "PCRL with large step");
1525
            return AVERROR_PATCHWELCOME;
1526
        }
1527
        step_x = 1<<step_x;
1528
        step_y = 1<<step_y;
1529
1530
        for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1531
            for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1532
                for (compno = CSpoc; compno < CEpoc; compno++) {
1533
                    Jpeg2000Component *comp     = tile->comp + compno;
1534
                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1535
                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1536
1537
                    if (!s->cdx[compno] || !s->cdy[compno])
1538
                        return AVERROR_INVALIDDATA;
1539
1540
                    for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1541
                        unsigned prcx, prcy;
1542
                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1543
                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1544
                        int trx0, try0;
1545
1546
                        trx0 = ff_jpeg2000_ceildiv(tile->coord[0][0], (int64_t)s->cdx[compno] << reducedresno);
1547
                        try0 = ff_jpeg2000_ceildiv(tile->coord[1][0], (int64_t)s->cdy[compno] << reducedresno);
1548
1549
                        if (!(y % ((uint64_t)s->cdy[compno] << (rlevel->log2_prec_height + reducedresno)) == 0 ||
1550
                             (y == tile->coord[1][0] && ((int64_t)try0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_height)))))
1551
                             continue;
1552
1553
                        if (!(x % ((uint64_t)s->cdx[compno] << (rlevel->log2_prec_width + reducedresno)) == 0 ||
1554
                             (x == tile->coord[0][0] && ((int64_t)trx0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_width)))))
1555
                             continue;
1556
1557
                        // check if a precinct exists
1558
                        prcx   = ff_jpeg2000_ceildiv(x, (int64_t)s->cdx[compno] << reducedresno) >> rlevel->log2_prec_width;
1559
                        prcy   = ff_jpeg2000_ceildiv(y, (int64_t)s->cdy[compno] << reducedresno) >> rlevel->log2_prec_height;
1560
                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1561
                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1562
1563
                        precno = prcx + rlevel->num_precincts_x * prcy;
1564
1565
                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1566
                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1567
                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1568
                            continue;
1569
                        }
1570
1571
                        for (layno = 0; layno < LYEpoc; layno++) {
1572
                            if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
1573
                                                              precno, layno,
1574
                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1575
                                                              qntsty->nguardbits)) < 0)
1576
                                return ret;
1577
                        }
1578
                    }
1579
                }
1580
            }
1581
        }
1582
        break;
1583
1584
    default:
1585
        break;
1586
    }
1587
1588
1331
    return ret;
1589
}
1590
1591
1331
static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1592
{
1593
1331
    int ret = AVERROR_BUG;
1594
    int i;
1595
1331
    int tp_index = 0;
1596
1597
1331
    s->bit_index = 8;
1598
1331
    if (tile->poc.nb_poc) {
1599
        for (i=0; i<tile->poc.nb_poc; i++) {
1600
            Jpeg2000POCEntry *e = &tile->poc.poc[i];
1601
            ret = jpeg2000_decode_packets_po_iteration(s, tile,
1602
                e->RSpoc, e->CSpoc,
1603
                FFMIN(e->LYEpoc, tile->codsty[0].nlayers),
1604
                e->REpoc,
1605
                FFMIN(e->CEpoc, s->ncomponents),
1606
                e->Ppoc, &tp_index
1607
                );
1608
            if (ret < 0)
1609
                return ret;
1610
        }
1611
    } else {
1612
1331
        ret = jpeg2000_decode_packets_po_iteration(s, tile,
1613
            0, 0,
1614
1331
            tile->codsty[0].nlayers,
1615
            33,
1616
            s->ncomponents,
1617
1331
            tile->codsty[0].prog_order,
1618
            &tp_index
1619
        );
1620
    }
1621
    /* EOC marker reached */
1622
1331
    bytestream2_skip(&s->g, 2);
1623
1624
1331
    return ret;
1625
}
1626
1627
/* TIER-1 routines */
1628
891445
static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
1629
                           int bpno, int bandno,
1630
                           int vert_causal_ctx_csty_symbol)
1631
{
1632
891445
    int mask = 3 << (bpno - 1), y0, x, y;
1633
1634
3833146
    for (y0 = 0; y0 < height; y0 += 4)
1635
51311550
        for (x = 0; x < width; x++)
1636

240203673
            for (y = y0; y < height && y < y0 + 4; y++) {
1637
191833824
                int flags_mask = -1;
1638

191833824
                if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1639
                    flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1640
191833824
                if ((t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB & flags_mask)
1641
73995008
                && !(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1642
51383726
                    if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, bandno))) {
1643
14828611
                        int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, &xorbit);
1644
14828611
                        if (t1->mqc.raw)
1645
                             t1->data[(y) * t1->stride + x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
1646
                        else
1647
29657222
                             t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
1648
14828611
                                               -mask : mask;
1649
1650
14828611
                        ff_jpeg2000_set_significance(t1, x, y,
1651
14828611
                                                     t1->data[(y) * t1->stride + x] < 0);
1652
                    }
1653
51383726
                    t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_VIS;
1654
                }
1655
            }
1656
891445
}
1657
1658
789700
static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
1659
                           int bpno, int vert_causal_ctx_csty_symbol)
1660
{
1661
    int phalf, nhalf;
1662
    int y0, x, y;
1663
1664
789700
    phalf = 1 << (bpno - 1);
1665
789700
    nhalf = -phalf;
1666
1667
3385702
    for (y0 = 0; y0 < height; y0 += 4)
1668
45520600
        for (x = 0; x < width; x++)
1669

213183605
            for (y = y0; y < height && y < y0 + 4; y++)
1670
170259007
                if ((t1->flags[(y + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
1671
                    int flags_mask = (vert_causal_ctx_csty_symbol && y == y0 + 3) ?
1672
17850258
                        ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S) : -1;
1673
17850258
                    int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask);
1674
35700516
                    int r     = ff_mqc_decode(&t1->mqc,
1675
17850258
                                              t1->mqc.cx_states + ctxno)
1676
17850258
                                ? phalf : nhalf;
1677
17850258
                    t1->data[(y) * t1->stride + x]          += t1->data[(y) * t1->stride + x] < 0 ? -r : r;
1678
17850258
                    t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_REF;
1679
                }
1680
789700
}
1681
1682
1114218
static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
1683
                           int width, int height, int bpno, int bandno,
1684
                           int seg_symbols, int vert_causal_ctx_csty_symbol)
1685
{
1686
1114218
    int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
1687
1688
4894215
    for (y0 = 0; y0 < height; y0 += 4) {
1689
67083363
        for (x = 0; x < width; x++) {
1690
63303366
            int flags_mask = -1;
1691
63303366
            if (vert_causal_ctx_csty_symbol)
1692
                flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1693
63303366
            if (y0 + 3 < height &&
1694
62575999
                !((t1->flags[(y0 + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1695
42536723
                  (t1->flags[(y0 + 2) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1696
40189029
                  (t1->flags[(y0 + 3) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1697
38090697
                  (t1->flags[(y0 + 4) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {
1698
37301242
                if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
1699
34674845
                    continue;
1700
2626397
                runlen = ff_mqc_decode(&t1->mqc,
1701
2626397
                                       t1->mqc.cx_states + MQC_CX_UNI);
1702
5252794
                runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
1703
2626397
                                                       t1->mqc.cx_states +
1704
                                                       MQC_CX_UNI);
1705
2626397
                dec = 1;
1706
            } else {
1707
26002124
                runlen = 0;
1708
26002124
                dec    = 0;
1709
            }
1710
1711

137142084
            for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
1712
108513563
                int flags_mask = -1;
1713

108513563
                if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1714
                    flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1715
108513563
                if (!dec) {
1716
105887166
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1717
50412995
                        dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask,
1718
                                                                                             bandno));
1719
                    }
1720
                }
1721
108513563
                if (dec) {
1722
                    int xorbit;
1723
8745308
                    int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask,
1724
                                                        &xorbit);
1725
17490616
                    t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc,
1726
8745308
                                                    t1->mqc.cx_states + ctxno) ^
1727
                                      xorbit)
1728
8745308
                                     ? -mask : mask;
1729
8745308
                    ff_jpeg2000_set_significance(t1, x, y, t1->data[(y) * t1->stride + x] < 0);
1730
                }
1731
108513563
                dec = 0;
1732
108513563
                t1->flags[(y + 1) * t1->stride + x + 1] &= ~JPEG2000_T1_VIS;
1733
            }
1734
        }
1735
    }
1736
1114218
    if (seg_symbols) {
1737
        int val;
1738
        val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1739
        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1740
        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1741
        val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1742
        if (val != 0xa)
1743
            av_log(s->avctx, AV_LOG_ERROR,
1744
                   "Segmentation symbol value incorrect\n");
1745
    }
1746
1114218
}
1747
1748
443079
static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
1749
                       Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
1750
                       int width, int height, int bandpos, uint8_t roi_shift)
1751
{
1752
443079
    int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1 + roi_shift;
1753
443079
    int pass_cnt = 0;
1754
443079
    int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
1755
443079
    int term_cnt = 0;
1756
    int coder_type;
1757
1758

443079
    av_assert0(width <= 1024U && height <= 1024U);
1759
443079
    av_assert0(width*height <= 4096);
1760
1761
443079
    memset(t1->data, 0, t1->stride * height * sizeof(*t1->data));
1762
1763
    /* If code-block contains no compressed data: nothing to do. */
1764
443079
    if (!cblk->length)
1765
44720
        return 0;
1766
1767
398359
    memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
1768
1769
398359
    cblk->data[cblk->length] = 0xff;
1770
398359
    cblk->data[cblk->length+1] = 0xff;
1771
398359
    ff_mqc_initdec(&t1->mqc, cblk->data, 0, 1);
1772
1773
3193722
    while (passno--) {
1774

2795414
        if (bpno < 0 || bpno > 29) {
1775
51
            av_log(s->avctx, AV_LOG_ERROR, "bpno became invalid\n");
1776
51
            return AVERROR_INVALIDDATA;
1777
        }
1778

2795363
        switch(pass_t) {
1779
891445
        case 0:
1780
891445
            decode_sigpass(t1, width, height, bpno + 1, bandpos,
1781
                           vert_causal_ctx_csty_symbol);
1782
891445
            break;
1783
789700
        case 1:
1784
789700
            decode_refpass(t1, width, height, bpno + 1, vert_causal_ctx_csty_symbol);
1785
789700
            break;
1786
1114218
        case 2:
1787
            av_assert2(!t1->mqc.raw);
1788
1114218
            decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
1789
1114218
                           codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1790
                           vert_causal_ctx_csty_symbol);
1791
1114218
            break;
1792
        }
1793
2795363
        if (codsty->cblk_style & JPEG2000_CBLK_RESET) // XXX no testcase for just this
1794
            ff_mqc_init_contexts(&t1->mqc);
1795
1796

2795363
        if (passno && (coder_type = needs_termination(codsty->cblk_style, pass_cnt))) {
1797
            if (term_cnt >= cblk->nb_terminations) {
1798
                av_log(s->avctx, AV_LOG_ERROR, "Missing needed termination \n");
1799
                return AVERROR_INVALIDDATA;
1800
            }
1801
            if (FFABS(cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp) > 0) {
1802
                av_log(s->avctx, AV_LOG_WARNING, "Mid mismatch %"PTRDIFF_SPECIFIER" in pass %d of %d\n",
1803
                    cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp,
1804
                    pass_cnt, cblk->npasses);
1805
            }
1806
1807
            ff_mqc_initdec(&t1->mqc, cblk->data + cblk->data_start[++term_cnt], coder_type == 2, 0);
1808
        }
1809
1810
2795363
        pass_t++;
1811
2795363
        if (pass_t == 3) {
1812
1114218
            bpno--;
1813
1114218
            pass_t = 0;
1814
        }
1815
2795363
        pass_cnt ++;
1816
    }
1817
1818
398308
    if (cblk->data + cblk->length - 2 > t1->mqc.bp) {
1819
        av_log(s->avctx, AV_LOG_WARNING, "End mismatch %"PTRDIFF_SPECIFIER"\n",
1820
               cblk->data + cblk->length - 2 - t1->mqc.bp);
1821
    }
1822
1823
398308
    if (cblk->data + cblk->length < t1->mqc.bp) {
1824
        av_log(s->avctx, AV_LOG_WARNING, "Synthetic End of Stream Marker Read.\n");
1825
    }
1826
1827
398308
    return 1;
1828
}
1829
1830
static inline int roi_shift_param(Jpeg2000Component *comp,
1831
                                   int quan_parameter)
1832
{
1833
    uint8_t roi_shift;
1834
    int val;
1835
    roi_shift = comp->roi_shift;
1836
    val = (quan_parameter < 0)?-quan_parameter:quan_parameter;
1837
1838
    if (val > (1 << roi_shift))
1839
        return (quan_parameter < 0)?-(val >> roi_shift):(val >> roi_shift);
1840
    return quan_parameter;
1841
}
1842
1843
/* TODO: Verify dequantization for lossless case
1844
 * comp->data can be float or int
1845
 * band->stepsize can be float or int
1846
 * depending on the type of DWT transformation.
1847
 * see ISO/IEC 15444-1:2002 A.6.1 */
1848
1849
/* Float dequantization of a codeblock.*/
1850
2415
static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1851
                                 Jpeg2000Component *comp,
1852
                                 Jpeg2000T1Context *t1, Jpeg2000Band *band)
1853
{
1854
    int i, j;
1855
2415
    int w = cblk->coord[0][1] - cblk->coord[0][0];
1856
75375
    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1857
72960
        float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1858
72960
        int *src = t1->data + j*t1->stride;
1859
9374976
        for (i = 0; i < w; ++i)
1860
9302016
            datap[i] = src[i] * band->f_stepsize;
1861
    }
1862
2415
}
1863
1864
/* Integer dequantization of a codeblock.*/
1865
187065
static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1866
                               Jpeg2000Component *comp,
1867
                               Jpeg2000T1Context *t1, Jpeg2000Band *band)
1868
{
1869
    int i, j;
1870
187065
    int w = cblk->coord[0][1] - cblk->coord[0][0];
1871
2847118
    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1872
2660053
        int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1873
2660053
        int *src = t1->data + j*t1->stride;
1874
2660053
        if (band->i_stepsize == 32768) {
1875
43309513
            for (i = 0; i < w; ++i)
1876
40649460
                datap[i] = src[i] / 2;
1877
        } else {
1878
            // This should be VERY uncommon
1879
            for (i = 0; i < w; ++i)
1880
                datap[i] = (src[i] * (int64_t)band->i_stepsize) / 65536;
1881
        }
1882
    }
1883
187065
}
1884
1885
208879
static void dequantization_int_97(int x, int y, Jpeg2000Cblk *cblk,
1886
                               Jpeg2000Component *comp,
1887
                               Jpeg2000T1Context *t1, Jpeg2000Band *band)
1888
{
1889
    int i, j;
1890
208879
    int w = cblk->coord[0][1] - cblk->coord[0][0];
1891
3333716
    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1892
3124837
        int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1893
3124837
        int *src = t1->data + j*t1->stride;
1894
55058528
        for (i = 0; i < w; ++i)
1895
51933691
            datap[i] = (src[i] * (int64_t)band->i_stepsize + (1<<15)) >> 16;
1896
    }
1897
208879
}
1898
1899
3
static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1900
{
1901
3
    int i, csize = 1;
1902
    void *src[3];
1903
1904
9
    for (i = 1; i < 3; i++) {
1905
6
        if (tile->codsty[0].transform != tile->codsty[i].transform) {
1906
            av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
1907
            return;
1908
        }
1909
6
        if (memcmp(tile->comp[0].coord, tile->comp[i].coord, sizeof(tile->comp[0].coord))) {
1910
            av_log(s->avctx, AV_LOG_ERROR, "Coords mismatch, MCT not supported\n");
1911
            return;
1912
        }
1913
    }
1914
1915
12
    for (i = 0; i < 3; i++)
1916
9
        if (tile->codsty[0].transform == FF_DWT97)
1917
            src[i] = tile->comp[i].f_data;
1918
        else
1919
9
            src[i] = tile->comp[i].i_data;
1920
1921
9
    for (i = 0; i < 2; i++)
1922
6
        csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1923
1924
3
    s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
1925
}
1926
1927
static inline void roi_scale_cblk(Jpeg2000Cblk *cblk,
1928
                                  Jpeg2000Component *comp,
1929
                                  Jpeg2000T1Context *t1)
1930
{
1931
    int i, j;
1932
    int w = cblk->coord[0][1] - cblk->coord[0][0];
1933
    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1934
        int *src = t1->data + j*t1->stride;
1935
        for (i = 0; i < w; ++i)
1936
            src[i] = roi_shift_param(comp, src[i]);
1937
    }
1938
}
1939
1940
1331
static inline void tile_codeblocks(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1941
{
1942
    Jpeg2000T1Context t1;
1943
1944
    int compno, reslevelno, bandno;
1945
1946
    /* Loop on tile components */
1947
5326
    for (compno = 0; compno < s->ncomponents; compno++) {
1948
3995
        Jpeg2000Component *comp     = tile->comp + compno;
1949
3995
        Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1950
3995
        int coded = 0;
1951
1952
3995
        t1.stride = (1<<codsty->log2_cblk_width) + 2;
1953
1954
        /* Loop on resolution levels */
1955
31943
        for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1956
27948
            Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1957
            /* Loop on bands */
1958
103802
            for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1959
                int nb_precincts, precno;
1960
75854
                Jpeg2000Band *band = rlevel->band + bandno;
1961
75854
                int cblkno = 0, bandpos;
1962
1963
75854
                bandpos = bandno + (reslevelno > 0);
1964
1965
75854
                if (band->coord[0][0] == band->coord[0][1] ||
1966
75854
                    band->coord[1][0] == band->coord[1][1])
1967
3672
                    continue;
1968
1969
72182
                nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1970
                /* Loop on precincts */
1971
145795
                for (precno = 0; precno < nb_precincts; precno++) {
1972
73613
                    Jpeg2000Prec *prec = band->prec + precno;
1973
1974
                    /* Loop on codeblocks */
1975
73613
                    for (cblkno = 0;
1976
516692
                         cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height;
1977
443079
                         cblkno++) {
1978
                        int x, y;
1979
443079
                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1980
443079
                        int ret = decode_cblk(s, codsty, &t1, cblk,
1981
443079
                                    cblk->coord[0][1] - cblk->coord[0][0],
1982
443079
                                    cblk->coord[1][1] - cblk->coord[1][0],
1983
443079
                                    bandpos, comp->roi_shift);
1984
443079
                        if (ret)
1985
398359
                            coded = 1;
1986
                        else
1987
44720
                            continue;
1988
398359
                        x = cblk->coord[0][0] - band->coord[0][0];
1989
398359
                        y = cblk->coord[1][0] - band->coord[1][0];
1990
1991
398359
                        if (comp->roi_shift)
1992
                            roi_scale_cblk(cblk, comp, &t1);
1993
398359
                        if (codsty->transform == FF_DWT97)
1994
2415
                            dequantization_float(x, y, cblk, comp, &t1, band);
1995
395944
                        else if (codsty->transform == FF_DWT97_INT)
1996
208879
                            dequantization_int_97(x, y, cblk, comp, &t1, band);
1997
                        else
1998
187065
                            dequantization_int(x, y, cblk, comp, &t1, band);
1999
                   } /* end cblk */
2000
                } /*end prec */
2001
            } /* end band */
2002
        } /* end reslevel */
2003
2004
        /* inverse DWT */
2005
3995
        if (coded)
2006
3995
            ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
2007
2008
    } /*end comp */
2009
1331
}
2010
2011
#define WRITE_FRAME(D, PIXEL)                                                                     \
2012
    static inline void write_frame_ ## D(Jpeg2000DecoderContext * s, Jpeg2000Tile * tile,         \
2013
                                         AVFrame * picture, int precision)                        \
2014
    {                                                                                             \
2015
        const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(s->avctx->pix_fmt);               \
2016
        int planar    = !!(pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR);                              \
2017
        int pixelsize = planar ? 1 : pixdesc->nb_components;                                      \
2018
                                                                                                  \
2019
        int compno;                                                                               \
2020
        int x, y;                                                                                 \
2021
                                                                                                  \
2022
        for (compno = 0; compno < s->ncomponents; compno++) {                                     \
2023
            Jpeg2000Component *comp     = tile->comp + compno;                                    \
2024
            Jpeg2000CodingStyle *codsty = tile->codsty + compno;                                  \
2025
            PIXEL *line;                                                                          \
2026
            float *datap     = comp->f_data;                                                      \
2027
            int32_t *i_datap = comp->i_data;                                                      \
2028
            int cbps         = s->cbps[compno];                                                   \
2029
            int w            = tile->comp[compno].coord[0][1] -                                   \
2030
                               ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[compno]);            \
2031
            int h            = tile->comp[compno].coord[1][1] -                                   \
2032
                               ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[compno]);            \
2033
            int plane        = 0;                                                                 \
2034
                                                                                                  \
2035
            if (planar)                                                                           \
2036
                plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);                 \
2037
                                                                                                  \
2038
            y    = tile->comp[compno].coord[1][0] -                                               \
2039
                   ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[compno]);                        \
2040
            line = (PIXEL *)picture->data[plane] + y * (picture->linesize[plane] / sizeof(PIXEL));\
2041
            for (; y < h; y++) {                                                                  \
2042
                PIXEL *dst;                                                                       \
2043
                                                                                                  \
2044
                x   = tile->comp[compno].coord[0][0] -                                            \
2045
                      ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[compno]);                     \
2046
                dst = line + x * pixelsize + compno*!planar;                                      \
2047
                                                                                                  \
2048
                if (codsty->transform == FF_DWT97) {                                              \
2049
                    for (; x < w; x++) {                                                          \
2050
                        int val = lrintf(*datap) + (1 << (cbps - 1));                             \
2051
                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */                  \
2052
                        val  = av_clip(val, 0, (1 << cbps) - 1);                                  \
2053
                        *dst = val << (precision - cbps);                                         \
2054
                        datap++;                                                                  \
2055
                        dst += pixelsize;                                                         \
2056
                    }                                                                             \
2057
                } else {                                                                          \
2058
                    for (; x < w; x++) {                                                          \
2059
                        int val = *i_datap + (1 << (cbps - 1));                                   \
2060
                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */                  \
2061
                        val  = av_clip(val, 0, (1 << cbps) - 1);                                  \
2062
                        *dst = val << (precision - cbps);                                         \
2063
                        i_datap++;                                                                \
2064
                        dst += pixelsize;                                                         \
2065
                    }                                                                             \
2066
                }                                                                                 \
2067
                line += picture->linesize[plane] / sizeof(PIXEL);                                 \
2068
            }                                                                                     \
2069
        }                                                                                         \
2070
                                                                                                  \
2071
    }
2072
2073




93961380
WRITE_FRAME(8, uint8_t)
2074




28113934
WRITE_FRAME(16, uint16_t)
2075
2076
#undef WRITE_FRAME
2077
2078
1331
static int jpeg2000_decode_tile(AVCodecContext *avctx, void *td,
2079
                                int jobnr, int threadnr)
2080
{
2081
1331
    Jpeg2000DecoderContext *s = avctx->priv_data;
2082
1331
    AVFrame *picture = td;
2083
1331
    Jpeg2000Tile *tile = s->tile + jobnr;
2084
    int x;
2085
2086
1331
    tile_codeblocks(s, tile);
2087
2088
    /* inverse MCT transformation */
2089
1331
    if (tile->codsty[0].mct)
2090
3
        mct_decode(s, tile);
2091
2092
4089
    for (x = 0; x < s->ncomponents; x++) {
2093
3170
        if (s->cdef[x] < 0) {
2094
1649
            for (x = 0; x < s->ncomponents; x++) {
2095
1237
                s->cdef[x] = x + 1;
2096
            }
2097
412
            if ((s->ncomponents & 1) == 0)
2098
1
                s->cdef[s->ncomponents-1] = 0;
2099
412
            break;
2100
        }
2101
    }
2102
2103
1331
    if (s->precision <= 8) {
2104
1326
        write_frame_8(s, tile, picture, 8);
2105
    } else {
2106
12
        int precision = picture->format == AV_PIX_FMT_XYZ12 ||
2107
2
                        picture->format == AV_PIX_FMT_RGB48 ||
2108
2
                        picture->format == AV_PIX_FMT_RGBA64 ||
2109

7
                        picture->format == AV_PIX_FMT_GRAY16 ? 16 : s->precision;
2110
2111
5
        write_frame_16(s, tile, picture, precision);
2112
    }
2113
2114
1331
    return 0;
2115
}
2116
2117
412
static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
2118
{
2119
    int tileno, compno;
2120
1743
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
2121
1331
        if (s->tile[tileno].comp) {
2122
5326
            for (compno = 0; compno < s->ncomponents; compno++) {
2123
3995
                Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
2124
3995
                Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
2125
2126
3995
                ff_jpeg2000_cleanup(comp, codsty);
2127
            }
2128
1331
            av_freep(&s->tile[tileno].comp);
2129
1331
            av_freep(&s->tile[tileno].packed_headers);
2130
1331
            s->tile[tileno].packed_headers_size = 0;
2131
        }
2132
    }
2133
412
    av_freep(&s->packed_headers);
2134
412
    s->packed_headers_size = 0;
2135
412
    memset(&s->packed_headers_stream, 0, sizeof(s->packed_headers_stream));
2136
412
    av_freep(&s->tile);
2137
412
    memset(s->codsty, 0, sizeof(s->codsty));
2138
412
    memset(s->qntsty, 0, sizeof(s->qntsty));
2139
412
    memset(s->properties, 0, sizeof(s->properties));
2140
412
    memset(&s->poc  , 0, sizeof(s->poc));
2141
412
    s->numXtiles = s->numYtiles = 0;
2142
412
    s->ncomponents = 0;
2143
412
}
2144
2145
412
static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
2146
{
2147
412
    Jpeg2000CodingStyle *codsty = s->codsty;
2148
412
    Jpeg2000QuantStyle *qntsty  = s->qntsty;
2149
412
    Jpeg2000POC         *poc    = &s->poc;
2150
412
    uint8_t *properties         = s->properties;
2151
2152
3951
    for (;;) {
2153
4363
        int len, ret = 0;
2154
        uint16_t marker;
2155
        int oldpos;
2156
2157
4363
        if (bytestream2_get_bytes_left(&s->g) < 2) {
2158
            av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
2159
            break;
2160
        }
2161
2162
4363
        marker = bytestream2_get_be16u(&s->g);
2163
4363
        oldpos = bytestream2_tell(&s->g);
2164

4363
        if (marker >= 0xFF30 && marker <= 0xFF3F)
2165
            continue;
2166
4363
        if (marker == JPEG2000_SOD) {
2167
            Jpeg2000Tile *tile;
2168
            Jpeg2000TilePart *tp;
2169
2170
1343
            if (!s->tile) {
2171
                av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
2172
                return AVERROR_INVALIDDATA;
2173
            }
2174
1343
            if (s->curtileno < 0) {
2175
                av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
2176
                return AVERROR_INVALIDDATA;
2177
            }
2178
2179
1343
            tile = s->tile + s->curtileno;
2180
1343
            tp = tile->tile_part + tile->tp_idx;
2181
1343
            if (tp->tp_end < s->g.buffer) {
2182
                av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
2183
                return AVERROR_INVALIDDATA;
2184
            }
2185
2186
1343
            if (s->has_ppm) {
2187
                uint32_t tp_header_size = bytestream2_get_be32(&s->packed_headers_stream);
2188
                if (bytestream2_get_bytes_left(&s->packed_headers_stream) < tp_header_size)
2189
                    return AVERROR_INVALIDDATA;
2190
                bytestream2_init(&tp->header_tpg, s->packed_headers_stream.buffer, tp_header_size);
2191
                bytestream2_skip(&s->packed_headers_stream, tp_header_size);
2192
            }
2193

1343
            if (tile->has_ppt && tile->tp_idx == 0) {
2194
                bytestream2_init(&tile->packed_headers_stream, tile->packed_headers, tile->packed_headers_size);
2195
            }
2196
2197
1343
            bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
2198
1343
            bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
2199
2200
1343
            continue;
2201
        }
2202
3020
        if (marker == JPEG2000_EOC)
2203
412
            break;
2204
2205
2608
        len = bytestream2_get_be16(&s->g);
2206

2608
        if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) {
2207
            if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
2208
                av_log(s->avctx, AV_LOG_ERROR, "Invalid len %d left=%d\n", len, bytestream2_get_bytes_left(&s->g));
2209
                return AVERROR_INVALIDDATA;
2210
            }
2211
            av_log(s->avctx, AV_LOG_WARNING, "Missing EOC Marker.\n");
2212
            break;
2213
        }
2214
2215



2608
        switch (marker) {
2216
412
        case JPEG2000_SIZ:
2217
412
            if (s->ncomponents) {
2218
                av_log(s->avctx, AV_LOG_ERROR, "Duplicate SIZ\n");
2219
                return AVERROR_INVALIDDATA;
2220
            }
2221
412
            ret = get_siz(s);
2222
412
            if (!s->tile)
2223
                s->numXtiles = s->numYtiles = 0;
2224
412
            break;
2225
6
        case JPEG2000_COC:
2226
6
            ret = get_coc(s, codsty, properties);
2227
6
            break;
2228
412
        case JPEG2000_COD:
2229
412
            ret = get_cod(s, codsty, properties);
2230
412
            break;
2231
        case JPEG2000_RGN:
2232
            ret = get_rgn(s, len);
2233
            break;
2234
9
        case JPEG2000_QCC:
2235
9
            ret = get_qcc(s, len, qntsty, properties);
2236
9
            break;
2237
412
        case JPEG2000_QCD:
2238
412
            ret = get_qcd(s, len, qntsty, properties);
2239
412
            break;
2240
        case JPEG2000_POC:
2241
            ret = get_poc(s, len, poc);
2242
            break;
2243
1343
        case JPEG2000_SOT:
2244
1343
            if (!s->in_tile_headers) {
2245
19
                s->in_tile_headers = 1;
2246
19
                if (s->has_ppm) {
2247
                    bytestream2_init(&s->packed_headers_stream, s->packed_headers, s->packed_headers_size);
2248
                }
2249
            }
2250
1343
            if (!(ret = get_sot(s, len))) {
2251
                av_assert1(s->curtileno >= 0);
2252
1343
                codsty = s->tile[s->curtileno].codsty;
2253
1343
                qntsty = s->tile[s->curtileno].qntsty;
2254
1343
                poc    = &s->tile[s->curtileno].poc;
2255
1343
                properties = s->tile[s->curtileno].properties;
2256
            }
2257
1343
            break;
2258
10
        case JPEG2000_PLM:
2259
            // the PLM marker is ignored
2260
        case JPEG2000_COM:
2261
            // the comment is ignored
2262
10
            bytestream2_skip(&s->g, len - 2);
2263
10
            break;
2264
        case JPEG2000_CRG:
2265
            ret = read_crg(s, len);
2266
            break;
2267
4
        case JPEG2000_TLM:
2268
            // Tile-part lengths
2269
4
            ret = get_tlm(s, len);
2270
4
            break;
2271
        case JPEG2000_PLT:
2272
            // Packet length, tile-part header
2273
            ret = get_plt(s, len);
2274
            break;
2275
        case JPEG2000_PPM:
2276
            // Packed headers, main header
2277
            if (s->in_tile_headers) {
2278
                av_log(s->avctx, AV_LOG_ERROR, "PPM Marker can only be in Main header\n");
2279
                return AVERROR_INVALIDDATA;
2280
            }
2281
            ret = get_ppm(s, len);
2282
            break;
2283
        case JPEG2000_PPT:
2284
            // Packed headers, tile-part header
2285
            if (s->has_ppm) {
2286
                av_log(s->avctx, AV_LOG_ERROR,
2287
                       "Cannot have both PPT and PPM marker.\n");
2288
                return AVERROR_INVALIDDATA;
2289
            }
2290
2291
            ret = get_ppt(s, len);
2292
            break;
2293
        default:
2294
            av_log(s->avctx, AV_LOG_ERROR,
2295
                   "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
2296
                   marker, bytestream2_tell(&s->g) - 4);
2297
            bytestream2_skip(&s->g, len - 2);
2298
            break;
2299
        }
2300

2608
        if (bytestream2_tell(&s->g) - oldpos != len || ret) {
2301
            av_log(s->avctx, AV_LOG_ERROR,
2302
                   "error during processing marker segment %.4"PRIx16"\n",
2303
                   marker);
2304
            return ret ? ret : -1;
2305
        }
2306
    }
2307
412
    return 0;
2308
}
2309
2310
/* Read bit stream packets --> T2 operation. */
2311
412
static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
2312
{
2313
412
    int ret = 0;
2314
    int tileno;
2315
2316
1743
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
2317
1331
        Jpeg2000Tile *tile = s->tile + tileno;
2318
2319
1331
        if ((ret = init_tile(s, tileno)) < 0)
2320
            return ret;
2321
2322
1331
        if ((ret = jpeg2000_decode_packets(s, tile)) < 0)
2323
            return ret;
2324
    }
2325
2326
412
    return 0;
2327
}
2328
2329
409
static int jp2_find_codestream(Jpeg2000DecoderContext *s)
2330
{
2331
    uint32_t atom_size, atom, atom_end;
2332
409
    int search_range = 10;
2333
2334
1228
    while (search_range
2335
1228
           &&
2336
1228
           bytestream2_get_bytes_left(&s->g) >= 8) {
2337
1228
        atom_size = bytestream2_get_be32u(&s->g);
2338
1228
        atom      = bytestream2_get_be32u(&s->g);
2339
1228
        if (atom_size == 1) {
2340
            if (bytestream2_get_be32u(&s->g)) {
2341
                avpriv_request_sample(s->avctx, "Huge atom");
2342
                return 0;
2343
            }
2344
            atom_size = bytestream2_get_be32u(&s->g);
2345
            atom_end  = bytestream2_tell(&s->g) + atom_size - 16;
2346
        } else {
2347
1228
            atom_end  = bytestream2_tell(&s->g) + atom_size -  8;
2348
        }
2349
2350
1228
        if (atom == JP2_CODESTREAM)
2351
409
            return 1;
2352
2353

819
        if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
2354
            return 0;
2355
2356

819
        if (atom == JP2_HEADER &&
2357
409
                   atom_size >= 16) {
2358
            uint32_t atom2_size, atom2, atom2_end;
2359
            do {
2360
818
                atom2_size = bytestream2_get_be32u(&s->g);
2361
818
                atom2      = bytestream2_get_be32u(&s->g);
2362
818
                atom2_end  = bytestream2_tell(&s->g) + atom2_size - 8;
2363

818
                if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
2364
                    break;
2365
818
                atom2_size -= 8;
2366
818
                if (atom2 == JP2_CODESTREAM) {
2367
                    return 1;
2368

1227
                } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
2369
409
                    int method = bytestream2_get_byteu(&s->g);
2370
409
                    bytestream2_skipu(&s->g, 2);
2371
409
                    if (method == 1) {
2372
409
                        s->colour_space = bytestream2_get_be32u(&s->g);
2373
                    }
2374

409
                } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
2375
                    int i, size, colour_count, colour_channels, colour_depth[3];
2376
                    colour_count = bytestream2_get_be16u(&s->g);
2377
                    colour_channels = bytestream2_get_byteu(&s->g);
2378
                    // FIXME: Do not ignore channel_sign
2379
                    colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2380
                    colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2381
                    colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2382
                    size = (colour_depth[0] + 7 >> 3) * colour_count +
2383
                           (colour_depth[1] + 7 >> 3) * colour_count +
2384
                           (colour_depth[2] + 7 >> 3) * colour_count;
2385
                    if (colour_count > AVPALETTE_COUNT ||
2386
                        colour_channels != 3 ||
2387
                        colour_depth[0] > 16 ||
2388
                        colour_depth[1] > 16 ||
2389
                        colour_depth[2] > 16 ||
2390
                        atom2_size < size) {
2391
                        avpriv_request_sample(s->avctx, "Unknown palette");
2392
                        bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2393
                        continue;
2394
                    }
2395
                    s->pal8 = 1;
2396
                    for (i = 0; i < colour_count; i++) {
2397
                        uint32_t r, g, b;
2398
                        if (colour_depth[0] <= 8) {
2399
                            r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
2400
                            r |= r >> colour_depth[0];
2401
                        } else {
2402
                            r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
2403
                        }
2404
                        if (colour_depth[1] <= 8) {
2405
                            g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
2406
                            g |= g >> colour_depth[1];
2407
                        } else {
2408
                            g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
2409
                        }
2410
                        if (colour_depth[2] <= 8) {
2411
                            b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
2412
                            b |= b >> colour_depth[2];
2413
                        } else {
2414
                            b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
2415
                        }
2416
                        s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
2417
                    }
2418

409
                } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
2419
                    int n = bytestream2_get_be16u(&s->g);
2420
                    for (; n>0; n--) {
2421
                        int cn   = bytestream2_get_be16(&s->g);
2422
                        int av_unused typ  = bytestream2_get_be16(&s->g);
2423
                        int asoc = bytestream2_get_be16(&s->g);
2424
                        if (cn < 4 && asoc < 4)
2425
                            s->cdef[cn] = asoc;
2426
                    }
2427

409
                } else if (atom2 == MKBETAG('r','e','s',' ') && atom2_size >= 18) {
2428
                    int64_t vnum, vden, hnum, hden, vexp, hexp;
2429
                    uint32_t resx;
2430
                    bytestream2_skip(&s->g, 4);
2431
                    resx = bytestream2_get_be32u(&s->g);
2432
                    if (resx != MKBETAG('r','e','s','c') && resx != MKBETAG('r','e','s','d')) {
2433
                        bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2434
                        continue;
2435
                    }
2436
                    vnum = bytestream2_get_be16u(&s->g);
2437
                    vden = bytestream2_get_be16u(&s->g);
2438
                    hnum = bytestream2_get_be16u(&s->g);
2439
                    hden = bytestream2_get_be16u(&s->g);
2440
                    vexp = bytestream2_get_byteu(&s->g);
2441
                    hexp = bytestream2_get_byteu(&s->g);
2442
                    if (!vnum || !vden || !hnum || !hden) {
2443
                        bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2444
                        av_log(s->avctx, AV_LOG_WARNING, "RES box invalid\n");
2445
                        continue;
2446
                    }
2447
                    if (vexp > hexp) {
2448
                        vexp -= hexp;
2449
                        hexp = 0;
2450
                    } else {
2451
                        hexp -= vexp;
2452
                        vexp = 0;
2453
                    }
2454
                    if (   INT64_MAX / (hnum * vden) > pow(10, hexp)
2455
                        && INT64_MAX / (vnum * hden) > pow(10, vexp))
2456
                        av_reduce(&s->sar.den, &s->sar.num,
2457
                                  hnum * vden * pow(10, hexp),
2458
                                  vnum * hden * pow(10, vexp),
2459
                                  INT32_MAX);
2460
                }
2461
818
                bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2462
818
            } while (atom_end - atom2_end >= 8);
2463
        } else {
2464
410
            search_range--;
2465
        }
2466
819
        bytestream2_seek(&s->g, atom_end, SEEK_SET);
2467
    }
2468
2469
    return 0;
2470
}
2471
2472
10
static av_cold void jpeg2000_init_static_data(void)
2473
{
2474
10
    ff_jpeg2000_init_tier1_luts();
2475
10
    ff_mqc_init_context_tables();
2476
10
}
2477
2478
19
static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
2479
{
2480
    static AVOnce init_static_once = AV_ONCE_INIT;
2481
19
    Jpeg2000DecoderContext *s = avctx->priv_data;
2482
2483
19
    ff_thread_once(&init_static_once, jpeg2000_init_static_data);
2484
19
    ff_jpeg2000dsp_init(&s->dsp);
2485
2486
19
    return 0;
2487
}
2488
2489
412
static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
2490
                                 int *got_frame, AVPacket *avpkt)
2491
{
2492
412
    Jpeg2000DecoderContext *s = avctx->priv_data;
2493
412
    ThreadFrame frame = { .f = data };
2494
412
    AVFrame *picture = data;
2495
    int ret;
2496
2497
412
    s->avctx     = avctx;
2498
412
    bytestream2_init(&s->g, avpkt->data, avpkt->size);
2499
412
    s->curtileno = -1;
2500
412
    memset(s->cdef, -1, sizeof(s->cdef));
2501
2502
412
    if (bytestream2_get_bytes_left(&s->g) < 2) {
2503
        ret = AVERROR_INVALIDDATA;
2504
        goto end;
2505
    }
2506
2507
    // check if the image is in jp2 format
2508

824
    if (bytestream2_get_bytes_left(&s->g) >= 12 &&
2509
821
       (bytestream2_get_be32u(&s->g) == 12) &&
2510
818
       (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
2511
409
       (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
2512
409
        if (!jp2_find_codestream(s)) {
2513
            av_log(avctx, AV_LOG_ERROR,
2514
                   "Could not find Jpeg2000 codestream atom.\n");
2515
            ret = AVERROR_INVALIDDATA;
2516
            goto end;
2517
        }
2518
    } else {
2519
3
        bytestream2_seek(&s->g, 0, SEEK_SET);
2520
    }
2521
2522

412
    while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
2523
        bytestream2_skip(&s->g, 1);
2524
2525
412
    if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
2526
        av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
2527
        ret = AVERROR_INVALIDDATA;
2528
        goto end;
2529
    }
2530
412
    if (ret = jpeg2000_read_main_headers(s))
2531
        goto end;
2532
2533
    /* get picture buffer */
2534
412
    if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
2535
        goto end;
2536
412
    picture->pict_type = AV_PICTURE_TYPE_I;
2537
412
    picture->key_frame = 1;
2538
2539
412
    if (ret = jpeg2000_read_bitstream_packets(s))
2540
        goto end;
2541
2542
412
    avctx->execute2(avctx, jpeg2000_decode_tile, picture, NULL, s->numXtiles * s->numYtiles);
2543
2544
412
    jpeg2000_dec_cleanup(s);
2545
2546
412
    *got_frame = 1;
2547
2548
412
    if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
2549
        memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
2550

412
    if (s->sar.num && s->sar.den)
2551
        avctx->sample_aspect_ratio = s->sar;
2552
412
    s->sar.num = s->sar.den = 0;
2553
2554
412
    return bytestream2_tell(&s->g);
2555
2556
end:
2557
    jpeg2000_dec_cleanup(s);
2558
    return ret;
2559
}
2560
2561
#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
2562
#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2563
2564
static const AVOption options[] = {
2565
    { "lowres",  "Lower the decoding resolution by a power of two",
2566
        OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
2567
    { NULL },
2568
};
2569
2570
static const AVClass jpeg2000_class = {
2571
    .class_name = "jpeg2000",
2572
    .item_name  = av_default_item_name,
2573
    .option     = options,
2574
    .version    = LIBAVUTIL_VERSION_INT,
2575
};
2576
2577
AVCodec ff_jpeg2000_decoder = {
2578
    .name             = "jpeg2000",
2579
    .long_name        = NULL_IF_CONFIG_SMALL("JPEG 2000"),
2580
    .type             = AVMEDIA_TYPE_VIDEO,
2581
    .id               = AV_CODEC_ID_JPEG2000,
2582
    .capabilities     = AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_DR1,
2583
    .priv_data_size   = sizeof(Jpeg2000DecoderContext),
2584
    .init             = jpeg2000_decode_init,
2585
    .decode           = jpeg2000_decode_frame,
2586
    .priv_class       = &jpeg2000_class,
2587
    .max_lowres       = 5,
2588
    .profiles         = NULL_IF_CONFIG_SMALL(ff_jpeg2000_profiles)
2589
};