• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * JPEG 2000 image decoder
3  * Copyright (c) 2007 Kamil Nowosad
4  * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 /**
24  * @file
25  * JPEG 2000 image decoder
26  */
27 
28 #include <inttypes.h>
29 #include <math.h>
30 
31 #include "libavutil/attributes.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/common.h"
34 #include "libavutil/imgutils.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "avcodec.h"
38 #include "bytestream.h"
39 #include "codec_internal.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 */
get_bits(Jpeg2000DecoderContext * s,int n)145 static int get_bits(Jpeg2000DecoderContext *s, int n)
146 {
147     int res = 0;
148 
149     while (--n >= 0) {
150         res <<= 1;
151         if (s->bit_index == 0) {
152             s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
153         }
154         s->bit_index--;
155         res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
156     }
157     return res;
158 }
159 
jpeg2000_flush(Jpeg2000DecoderContext * s)160 static void jpeg2000_flush(Jpeg2000DecoderContext *s)
161 {
162     if (bytestream2_get_byte(&s->g) == 0xff)
163         bytestream2_skip(&s->g, 1);
164     s->bit_index = 8;
165 }
166 
167 /* decode the value stored in node */
tag_tree_decode(Jpeg2000DecoderContext * s,Jpeg2000TgtNode * node,int threshold)168 static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
169                            int threshold)
170 {
171     Jpeg2000TgtNode *stack[30];
172     int sp = -1, curval = 0;
173 
174     if (!node) {
175         av_log(s->avctx, AV_LOG_ERROR, "missing node\n");
176         return AVERROR_INVALIDDATA;
177     }
178 
179     while (node && !node->vis) {
180         stack[++sp] = node;
181         node        = node->parent;
182     }
183 
184     if (node)
185         curval = node->val;
186     else
187         curval = stack[sp]->val;
188 
189     while (curval < threshold && sp >= 0) {
190         if (curval < stack[sp]->val)
191             curval = stack[sp]->val;
192         while (curval < threshold) {
193             int ret;
194             if ((ret = get_bits(s, 1)) > 0) {
195                 stack[sp]->vis++;
196                 break;
197             } else if (!ret)
198                 curval++;
199             else
200                 return ret;
201         }
202         stack[sp]->val = curval;
203         sp--;
204     }
205     return curval;
206 }
207 
pix_fmt_match(enum AVPixelFormat pix_fmt,int components,int bpc,uint32_t log2_chroma_wh,int pal8)208 static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
209                          int bpc, uint32_t log2_chroma_wh, int pal8)
210 {
211     int match = 1;
212     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
213 
214     av_assert2(desc);
215 
216     if (desc->nb_components != components) {
217         return 0;
218     }
219 
220     switch (components) {
221     case 4:
222         match = match && desc->comp[3].depth >= bpc &&
223                          (log2_chroma_wh >> 14 & 3) == 0 &&
224                          (log2_chroma_wh >> 12 & 3) == 0;
225     case 3:
226         match = match && desc->comp[2].depth >= bpc &&
227                          (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
228                          (log2_chroma_wh >>  8 & 3) == desc->log2_chroma_h;
229     case 2:
230         match = match && desc->comp[1].depth >= bpc &&
231                          (log2_chroma_wh >>  6 & 3) == desc->log2_chroma_w &&
232                          (log2_chroma_wh >>  4 & 3) == desc->log2_chroma_h;
233 
234     case 1:
235         match = match && desc->comp[0].depth >= bpc &&
236                          (log2_chroma_wh >>  2 & 3) == 0 &&
237                          (log2_chroma_wh       & 3) == 0 &&
238                          (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
239     }
240     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 */
get_siz(Jpeg2000DecoderContext * s)272 static int get_siz(Jpeg2000DecoderContext *s)
273 {
274     int i;
275     int ncomponents;
276     uint32_t log2_chroma_wh = 0;
277     const enum AVPixelFormat *possible_fmts = NULL;
278     int possible_fmts_nb = 0;
279     int ret;
280     int o_dimx, o_dimy; //original image dimensions.
281     int dimx, dimy;
282 
283     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     s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
289     s->width          = bytestream2_get_be32u(&s->g); // Width
290     s->height         = bytestream2_get_be32u(&s->g); // Height
291     s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
292     s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
293     s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz
294     s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz
295     s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz
296     s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz
297     ncomponents       = bytestream2_get_be16u(&s->g); // CSiz
298 
299     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     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     if (ncomponents > 4) {
311         avpriv_request_sample(s->avctx, "Support for %d components",
312                               ncomponents);
313         return AVERROR_PATCHWELCOME;
314     }
315 
316     if (s->tile_offset_x < 0 || s->tile_offset_y < 0 ||
317         s->image_offset_x < s->tile_offset_x ||
318         s->image_offset_y < s->tile_offset_y ||
319         s->tile_width  + (int64_t)s->tile_offset_x <= s->image_offset_x ||
320         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     if (s->image_offset_x >= s->width || s->image_offset_y >= s->height) {
327         av_log(s->avctx, AV_LOG_ERROR, "image offsets outside image");
328         return AVERROR_INVALIDDATA;
329     }
330 
331     if (s->reduction_factor && (s->image_offset_x || s->image_offset_y) ){
332         av_log(s->avctx, AV_LOG_ERROR, "reduction factor with image offsets is not fully implemented");
333         return AVERROR_PATCHWELCOME;
334     }
335 
336     s->ncomponents = ncomponents;
337 
338     if (s->tile_width <= 0 || s->tile_height <= 0) {
339         av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
340                s->tile_width, s->tile_height);
341         return AVERROR_INVALIDDATA;
342     }
343 
344     if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) {
345         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for %d components in SIZ\n", s->ncomponents);
346         return AVERROR_INVALIDDATA;
347     }
348 
349     for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
350         uint8_t x    = bytestream2_get_byteu(&s->g);
351         s->cbps[i]   = (x & 0x7f) + 1;
352         s->precision = FFMAX(s->cbps[i], s->precision);
353         s->sgnd[i]   = !!(x & 0x80);
354         s->cdx[i]    = bytestream2_get_byteu(&s->g);
355         s->cdy[i]    = bytestream2_get_byteu(&s->g);
356         if (   !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
357             || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
358             av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
359             return AVERROR_INVALIDDATA;
360         }
361         log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
362     }
363 
364     s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
365     s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
366 
367     // There must be at least a SOT and SOD per tile, their minimum size is 14
368     if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile) ||
369         s->numXtiles * s->numYtiles * 14LL > bytestream2_size(&s->g)
370     ) {
371         s->numXtiles = s->numYtiles = 0;
372         return AVERROR(EINVAL);
373     }
374 
375     s->tile = av_calloc(s->numXtiles * s->numYtiles, sizeof(*s->tile));
376     if (!s->tile) {
377         s->numXtiles = s->numYtiles = 0;
378         return AVERROR(ENOMEM);
379     }
380 
381     for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
382         Jpeg2000Tile *tile = s->tile + i;
383 
384         tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
385         if (!tile->comp)
386             return AVERROR(ENOMEM);
387     }
388 
389     /* compute image size with reduction factor */
390     o_dimx = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,
391                                                s->reduction_factor);
392     o_dimy = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
393                                                s->reduction_factor);
394     dimx = ff_jpeg2000_ceildiv(o_dimx, s->cdx[0]);
395     dimy = ff_jpeg2000_ceildiv(o_dimy, s->cdy[0]);
396     for (i = 1; i < s->ncomponents; i++) {
397         dimx = FFMAX(dimx, ff_jpeg2000_ceildiv(o_dimx, s->cdx[i]));
398         dimy = FFMAX(dimy, ff_jpeg2000_ceildiv(o_dimy, s->cdy[i]));
399     }
400 
401     ret = ff_set_dimensions(s->avctx, dimx << s->avctx->lowres, dimy << s->avctx->lowres);
402     if (ret < 0)
403         return ret;
404 
405     if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
406         s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
407         possible_fmts = xyz_pix_fmts;
408         possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
409     } else {
410         switch (s->colour_space) {
411         case 16:
412             possible_fmts = rgb_pix_fmts;
413             possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
414             break;
415         case 17:
416             possible_fmts = gray_pix_fmts;
417             possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
418             break;
419         case 18:
420             possible_fmts = yuv_pix_fmts;
421             possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
422             break;
423         default:
424             possible_fmts = all_pix_fmts;
425             possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
426             break;
427         }
428     }
429     if (   s->avctx->pix_fmt != AV_PIX_FMT_NONE
430         && !pix_fmt_match(s->avctx->pix_fmt, ncomponents, s->precision, log2_chroma_wh, s->pal8))
431             s->avctx->pix_fmt = AV_PIX_FMT_NONE;
432     if (s->avctx->pix_fmt == AV_PIX_FMT_NONE)
433         for (i = 0; i < possible_fmts_nb; ++i) {
434             if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
435                 s->avctx->pix_fmt = possible_fmts[i];
436                 break;
437             }
438         }
439 
440     if (i == possible_fmts_nb) {
441         if (ncomponents == 4 &&
442             s->cdy[0] == 1 && s->cdx[0] == 1 &&
443             s->cdy[1] == 1 && s->cdx[1] == 1 &&
444             s->cdy[2] == s->cdy[3] && s->cdx[2] == s->cdx[3]) {
445             if (s->precision == 8 && s->cdy[2] == 2 && s->cdx[2] == 2 && !s->pal8) {
446                 s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
447                 s->cdef[0] = 0;
448                 s->cdef[1] = 1;
449                 s->cdef[2] = 2;
450                 s->cdef[3] = 3;
451                 i = 0;
452             }
453         } else if (ncomponents == 3 && s->precision == 8 &&
454                    s->cdx[0] == s->cdx[1] && s->cdx[0] == s->cdx[2] &&
455                    s->cdy[0] == s->cdy[1] && s->cdy[0] == s->cdy[2]) {
456             s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
457             i = 0;
458         } else if (ncomponents == 2 && s->precision == 8 &&
459                    s->cdx[0] == s->cdx[1] && s->cdy[0] == s->cdy[1]) {
460             s->avctx->pix_fmt = AV_PIX_FMT_YA8;
461             i = 0;
462         } else if (ncomponents == 1 && s->precision == 8) {
463             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
464             i = 0;
465         }
466     }
467 
468 
469     if (i == possible_fmts_nb) {
470         av_log(s->avctx, AV_LOG_ERROR,
471                "Unknown pix_fmt, profile: %d, colour_space: %d, "
472                "components: %d, precision: %d\n"
473                "cdx[0]: %d, cdy[0]: %d\n"
474                "cdx[1]: %d, cdy[1]: %d\n"
475                "cdx[2]: %d, cdy[2]: %d\n"
476                "cdx[3]: %d, cdy[3]: %d\n",
477                s->avctx->profile, s->colour_space, ncomponents, s->precision,
478                s->cdx[0],
479                s->cdy[0],
480                ncomponents > 1 ? s->cdx[1] : 0,
481                ncomponents > 1 ? s->cdy[1] : 0,
482                ncomponents > 2 ? s->cdx[2] : 0,
483                ncomponents > 2 ? s->cdy[2] : 0,
484                ncomponents > 3 ? s->cdx[3] : 0,
485                ncomponents > 3 ? s->cdy[3] : 0);
486         return AVERROR_PATCHWELCOME;
487     }
488     s->avctx->bits_per_raw_sample = s->precision;
489     return 0;
490 }
491 
492 /* get common part for COD and COC segments */
get_cox(Jpeg2000DecoderContext * s,Jpeg2000CodingStyle * c)493 static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
494 {
495     uint8_t byte;
496 
497     if (bytestream2_get_bytes_left(&s->g) < 5) {
498         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COX\n");
499         return AVERROR_INVALIDDATA;
500     }
501 
502     /*  nreslevels = number of resolution levels
503                    = number of decomposition level +1 */
504     c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
505     if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
506         av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
507         return AVERROR_INVALIDDATA;
508     }
509 
510     if (c->nreslevels <= s->reduction_factor) {
511         /* we are forced to update reduction_factor as its requested value is
512            not compatible with this bitstream, and as we might have used it
513            already in setup earlier we have to fail this frame until
514            reinitialization is implemented */
515         av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1);
516         s->reduction_factor = c->nreslevels - 1;
517         return AVERROR(EINVAL);
518     }
519 
520     /* compute number of resolution levels to decode */
521     c->nreslevels2decode = c->nreslevels - s->reduction_factor;
522 
523     c->log2_cblk_width  = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
524     c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
525 
526     if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
527         c->log2_cblk_width + c->log2_cblk_height > 12) {
528         av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
529         return AVERROR_INVALIDDATA;
530     }
531 
532     c->cblk_style = bytestream2_get_byteu(&s->g);
533     if (c->cblk_style != 0) { // cblk style
534         av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
535         if (c->cblk_style & JPEG2000_CBLK_BYPASS)
536             av_log(s->avctx, AV_LOG_WARNING, "Selective arithmetic coding bypass\n");
537     }
538     c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
539     /* set integer 9/7 DWT in case of BITEXACT flag */
540     if ((s->avctx->flags & AV_CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
541         c->transform = FF_DWT97_INT;
542     else if (c->transform == FF_DWT53) {
543         s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
544     }
545 
546     if (c->csty & JPEG2000_CSTY_PREC) {
547         int i;
548         for (i = 0; i < c->nreslevels; i++) {
549             byte = bytestream2_get_byte(&s->g);
550             c->log2_prec_widths[i]  =  byte       & 0x0F;    // precinct PPx
551             c->log2_prec_heights[i] = (byte >> 4) & 0x0F;    // precinct PPy
552             if (i)
553                 if (c->log2_prec_widths[i] == 0 || c->log2_prec_heights[i] == 0) {
554                     av_log(s->avctx, AV_LOG_ERROR, "PPx %d PPy %d invalid\n",
555                            c->log2_prec_widths[i], c->log2_prec_heights[i]);
556                     c->log2_prec_widths[i] = c->log2_prec_heights[i] = 1;
557                     return AVERROR_INVALIDDATA;
558                 }
559         }
560     } else {
561         memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
562         memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
563     }
564     return 0;
565 }
566 
567 /* get coding parameters for a particular tile or whole image*/
get_cod(Jpeg2000DecoderContext * s,Jpeg2000CodingStyle * c,uint8_t * properties)568 static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
569                    uint8_t *properties)
570 {
571     Jpeg2000CodingStyle tmp;
572     int compno, ret;
573 
574     if (bytestream2_get_bytes_left(&s->g) < 5) {
575         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COD\n");
576         return AVERROR_INVALIDDATA;
577     }
578 
579     tmp.csty = bytestream2_get_byteu(&s->g);
580 
581     // get progression order
582     tmp.prog_order = bytestream2_get_byteu(&s->g);
583 
584     tmp.nlayers    = bytestream2_get_be16u(&s->g);
585     tmp.mct        = bytestream2_get_byteu(&s->g); // multiple component transformation
586 
587     if (tmp.mct && s->ncomponents < 3) {
588         av_log(s->avctx, AV_LOG_ERROR,
589                "MCT %"PRIu8" with too few components (%d)\n",
590                tmp.mct, s->ncomponents);
591         return AVERROR_INVALIDDATA;
592     }
593 
594     if ((ret = get_cox(s, &tmp)) < 0)
595         return ret;
596     tmp.init = 1;
597     for (compno = 0; compno < s->ncomponents; compno++)
598         if (!(properties[compno] & HAD_COC))
599             memcpy(c + compno, &tmp, sizeof(tmp));
600     return 0;
601 }
602 
603 /* Get coding parameters for a component in the whole image or a
604  * particular tile. */
get_coc(Jpeg2000DecoderContext * s,Jpeg2000CodingStyle * c,uint8_t * properties)605 static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
606                    uint8_t *properties)
607 {
608     int compno, ret;
609     uint8_t has_eph, has_sop;
610 
611     if (bytestream2_get_bytes_left(&s->g) < 2) {
612         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for COC\n");
613         return AVERROR_INVALIDDATA;
614     }
615 
616     compno = bytestream2_get_byteu(&s->g);
617 
618     if (compno >= s->ncomponents) {
619         av_log(s->avctx, AV_LOG_ERROR,
620                "Invalid compno %d. There are %d components in the image.\n",
621                compno, s->ncomponents);
622         return AVERROR_INVALIDDATA;
623     }
624 
625     c      += compno;
626     has_eph = c->csty & JPEG2000_CSTY_EPH;
627     has_sop = c->csty & JPEG2000_CSTY_SOP;
628     c->csty = bytestream2_get_byteu(&s->g);
629     c->csty |= has_eph; //do not override eph present bits from COD
630     c->csty |= has_sop; //do not override sop present bits from COD
631 
632     if ((ret = get_cox(s, c)) < 0)
633         return ret;
634 
635     properties[compno] |= HAD_COC;
636     c->init = 1;
637     return 0;
638 }
639 
get_rgn(Jpeg2000DecoderContext * s,int n)640 static int get_rgn(Jpeg2000DecoderContext *s, int n)
641 {
642     uint16_t compno;
643     compno = (s->ncomponents < 257)? bytestream2_get_byte(&s->g):
644                                      bytestream2_get_be16u(&s->g);
645     if (bytestream2_get_byte(&s->g)) {
646         av_log(s->avctx, AV_LOG_ERROR, "Invalid RGN header.\n");
647         return AVERROR_INVALIDDATA; // SRgn field value is 0
648     }
649     // SPrgn field
650     // Currently compno cannot be greater than 4.
651     // However, future implementation should support compno up to 65536
652     if (compno < s->ncomponents) {
653         int v;
654         if (s->curtileno == -1) {
655             v =  bytestream2_get_byte(&s->g);
656             if (v > 30)
657                 return AVERROR_PATCHWELCOME;
658             s->roi_shift[compno] = v;
659         } else {
660             if (s->tile[s->curtileno].tp_idx != 0)
661                 return AVERROR_INVALIDDATA; // marker occurs only in first tile part of tile
662             v = bytestream2_get_byte(&s->g);
663             if (v > 30)
664                 return AVERROR_PATCHWELCOME;
665             s->tile[s->curtileno].comp[compno].roi_shift = v;
666         }
667         return 0;
668     }
669     return AVERROR_INVALIDDATA;
670 }
671 
672 /* Get common part for QCD and QCC segments. */
get_qcx(Jpeg2000DecoderContext * s,int n,Jpeg2000QuantStyle * q)673 static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
674 {
675     int i, x;
676 
677     if (bytestream2_get_bytes_left(&s->g) < 1)
678         return AVERROR_INVALIDDATA;
679 
680     x = bytestream2_get_byteu(&s->g); // Sqcd
681 
682     q->nguardbits = x >> 5;
683     q->quantsty   = x & 0x1f;
684 
685     if (q->quantsty == JPEG2000_QSTY_NONE) {
686         n -= 3;
687         if (bytestream2_get_bytes_left(&s->g) < n ||
688             n > JPEG2000_MAX_DECLEVELS*3)
689             return AVERROR_INVALIDDATA;
690         for (i = 0; i < n; i++)
691             q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
692     } else if (q->quantsty == JPEG2000_QSTY_SI) {
693         if (bytestream2_get_bytes_left(&s->g) < 2)
694             return AVERROR_INVALIDDATA;
695         x          = bytestream2_get_be16u(&s->g);
696         q->expn[0] = x >> 11;
697         q->mant[0] = x & 0x7ff;
698         for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
699             int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
700             q->expn[i] = curexpn;
701             q->mant[i] = q->mant[0];
702         }
703     } else {
704         n = (n - 3) >> 1;
705         if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
706             n > JPEG2000_MAX_DECLEVELS*3)
707             return AVERROR_INVALIDDATA;
708         for (i = 0; i < n; i++) {
709             x          = bytestream2_get_be16u(&s->g);
710             q->expn[i] = x >> 11;
711             q->mant[i] = x & 0x7ff;
712         }
713     }
714     return 0;
715 }
716 
717 /* Get quantization parameters for a particular tile or a whole image. */
get_qcd(Jpeg2000DecoderContext * s,int n,Jpeg2000QuantStyle * q,uint8_t * properties)718 static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
719                    uint8_t *properties)
720 {
721     Jpeg2000QuantStyle tmp;
722     int compno, ret;
723 
724     memset(&tmp, 0, sizeof(tmp));
725 
726     if ((ret = get_qcx(s, n, &tmp)) < 0)
727         return ret;
728     for (compno = 0; compno < s->ncomponents; compno++)
729         if (!(properties[compno] & HAD_QCC))
730             memcpy(q + compno, &tmp, sizeof(tmp));
731     return 0;
732 }
733 
734 /* Get quantization parameters for a component in the whole image
735  * on in a particular tile. */
get_qcc(Jpeg2000DecoderContext * s,int n,Jpeg2000QuantStyle * q,uint8_t * properties)736 static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
737                    uint8_t *properties)
738 {
739     int compno;
740 
741     if (bytestream2_get_bytes_left(&s->g) < 1)
742         return AVERROR_INVALIDDATA;
743 
744     compno = bytestream2_get_byteu(&s->g);
745 
746     if (compno >= s->ncomponents) {
747         av_log(s->avctx, AV_LOG_ERROR,
748                "Invalid compno %d. There are %d components in the image.\n",
749                compno, s->ncomponents);
750         return AVERROR_INVALIDDATA;
751     }
752 
753     properties[compno] |= HAD_QCC;
754     return get_qcx(s, n - 1, q + compno);
755 }
756 
get_poc(Jpeg2000DecoderContext * s,int size,Jpeg2000POC * p)757 static int get_poc(Jpeg2000DecoderContext *s, int size, Jpeg2000POC *p)
758 {
759     int i;
760     int elem_size = s->ncomponents <= 257 ? 7 : 9;
761     Jpeg2000POC tmp = {{{0}}};
762 
763     if (bytestream2_get_bytes_left(&s->g) < 5 || size < 2 + elem_size) {
764         av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for POC\n");
765         return AVERROR_INVALIDDATA;
766     }
767 
768     if (elem_size > 7) {
769         avpriv_request_sample(s->avctx, "Fat POC not supported");
770         return AVERROR_PATCHWELCOME;
771     }
772 
773     tmp.nb_poc = (size - 2) / elem_size;
774     if (tmp.nb_poc > MAX_POCS) {
775         avpriv_request_sample(s->avctx, "Too many POCs (%d)", tmp.nb_poc);
776         return AVERROR_PATCHWELCOME;
777     }
778 
779     for (i = 0; i<tmp.nb_poc; i++) {
780         Jpeg2000POCEntry *e = &tmp.poc[i];
781         e->RSpoc  = bytestream2_get_byteu(&s->g);
782         e->CSpoc  = bytestream2_get_byteu(&s->g);
783         e->LYEpoc = bytestream2_get_be16u(&s->g);
784         e->REpoc  = bytestream2_get_byteu(&s->g);
785         e->CEpoc  = bytestream2_get_byteu(&s->g);
786         e->Ppoc   = bytestream2_get_byteu(&s->g);
787         if (!e->CEpoc)
788             e->CEpoc = 256;
789         if (e->CEpoc > s->ncomponents)
790             e->CEpoc = s->ncomponents;
791         if (   e->RSpoc >= e->REpoc || e->REpoc > 33
792             || e->CSpoc >= e->CEpoc || e->CEpoc > s->ncomponents
793             || !e->LYEpoc) {
794             av_log(s->avctx, AV_LOG_ERROR, "POC Entry %d is invalid (%d, %d, %d, %d, %d, %d)\n", i,
795                 e->RSpoc, e->CSpoc, e->LYEpoc, e->REpoc, e->CEpoc, e->Ppoc
796             );
797             return AVERROR_INVALIDDATA;
798         }
799     }
800 
801     if (!p->nb_poc || p->is_default) {
802         *p = tmp;
803     } else {
804         if (p->nb_poc + tmp.nb_poc > MAX_POCS) {
805             av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for POC\n");
806             return AVERROR_INVALIDDATA;
807         }
808         memcpy(p->poc + p->nb_poc, tmp.poc, tmp.nb_poc * sizeof(tmp.poc[0]));
809         p->nb_poc += tmp.nb_poc;
810     }
811 
812     p->is_default = 0;
813 
814     return 0;
815 }
816 
817 
818 /* Get start of tile segment. */
get_sot(Jpeg2000DecoderContext * s,int n)819 static int get_sot(Jpeg2000DecoderContext *s, int n)
820 {
821     Jpeg2000TilePart *tp;
822     uint16_t Isot;
823     uint32_t Psot;
824     unsigned TPsot;
825 
826     if (bytestream2_get_bytes_left(&s->g) < 8)
827         return AVERROR_INVALIDDATA;
828 
829     s->curtileno = 0;
830     Isot = bytestream2_get_be16u(&s->g);        // Isot
831     if (Isot >= s->numXtiles * s->numYtiles)
832         return AVERROR_INVALIDDATA;
833 
834     s->curtileno = Isot;
835     Psot  = bytestream2_get_be32u(&s->g);       // Psot
836     TPsot = bytestream2_get_byteu(&s->g);       // TPsot
837 
838     /* Read TNSot but not used */
839     bytestream2_get_byteu(&s->g);               // TNsot
840 
841     if (!Psot)
842         Psot = bytestream2_get_bytes_left(&s->g) - 2 + n + 2;
843 
844     if (Psot > bytestream2_get_bytes_left(&s->g) - 2 + n + 2) {
845         av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);
846         return AVERROR_INVALIDDATA;
847     }
848 
849     if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
850         avpriv_request_sample(s->avctx, "Too many tile parts");
851         return AVERROR_PATCHWELCOME;
852     }
853 
854     s->tile[Isot].tp_idx = TPsot;
855     tp             = s->tile[Isot].tile_part + TPsot;
856     tp->tile_index = Isot;
857     tp->tp_end     = s->g.buffer + Psot - n - 2;
858 
859     if (!TPsot) {
860         Jpeg2000Tile *tile = s->tile + s->curtileno;
861 
862         /* copy defaults */
863         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
864         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
865         memcpy(&tile->poc  , &s->poc  , sizeof(tile->poc));
866         tile->poc.is_default = 1;
867     }
868 
869     return 0;
870 }
871 
read_crg(Jpeg2000DecoderContext * s,int n)872 static int read_crg(Jpeg2000DecoderContext *s, int n)
873 {
874     if (s->ncomponents*4 != n - 2) {
875         av_log(s->avctx, AV_LOG_ERROR, "Invalid CRG marker.\n");
876         return AVERROR_INVALIDDATA;
877     }
878     bytestream2_skip(&s->g, n - 2);
879     return 0;
880 }
881 /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
882  * Used to know the number of tile parts and lengths.
883  * There may be multiple TLMs in the header.
884  * TODO: The function is not used for tile-parts management, nor anywhere else.
885  * It can be useful to allocate memory for tile parts, before managing the SOT
886  * markers. Parsing the TLM header is needed to increment the input header
887  * buffer.
888  * This marker is mandatory for DCI. */
get_tlm(Jpeg2000DecoderContext * s,int n)889 static int get_tlm(Jpeg2000DecoderContext *s, int n)
890 {
891     uint8_t Stlm, ST, SP, tile_tlm, i;
892     bytestream2_get_byte(&s->g);               /* Ztlm: skipped */
893     Stlm = bytestream2_get_byte(&s->g);
894 
895     // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
896     ST = (Stlm >> 4) & 0x03;
897     if (ST == 0x03) {
898         av_log(s->avctx, AV_LOG_ERROR, "TLM marker contains invalid ST value.\n");
899         return AVERROR_INVALIDDATA;
900     }
901 
902     SP       = (Stlm >> 6) & 0x01;
903     tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
904     for (i = 0; i < tile_tlm; i++) {
905         switch (ST) {
906         case 0:
907             break;
908         case 1:
909             bytestream2_get_byte(&s->g);
910             break;
911         case 2:
912             bytestream2_get_be16(&s->g);
913             break;
914         case 3:
915             bytestream2_get_be32(&s->g);
916             break;
917         }
918         if (SP == 0) {
919             bytestream2_get_be16(&s->g);
920         } else {
921             bytestream2_get_be32(&s->g);
922         }
923     }
924     return 0;
925 }
926 
get_plt(Jpeg2000DecoderContext * s,int n)927 static int get_plt(Jpeg2000DecoderContext *s, int n)
928 {
929     int i;
930     int v;
931 
932     av_log(s->avctx, AV_LOG_DEBUG,
933             "PLT marker at pos 0x%X\n", bytestream2_tell(&s->g) - 4);
934 
935     if (n < 4)
936         return AVERROR_INVALIDDATA;
937 
938     /*Zplt =*/ bytestream2_get_byte(&s->g);
939 
940     for (i = 0; i < n - 3; i++) {
941         v = bytestream2_get_byte(&s->g);
942     }
943     if (v & 0x80)
944         return AVERROR_INVALIDDATA;
945 
946     return 0;
947 }
948 
get_ppm(Jpeg2000DecoderContext * s,int n)949 static int get_ppm(Jpeg2000DecoderContext *s, int n)
950 {
951     void *new;
952 
953     if (n < 3) {
954         av_log(s->avctx, AV_LOG_ERROR, "Invalid length for PPM data.\n");
955         return AVERROR_INVALIDDATA;
956     }
957     bytestream2_get_byte(&s->g); //Zppm is skipped and not used
958     new = av_realloc(s->packed_headers,
959                      s->packed_headers_size + n - 3);
960     if (new) {
961         s->packed_headers = new;
962     } else
963         return AVERROR(ENOMEM);
964     s->has_ppm = 1;
965     memset(&s->packed_headers_stream, 0, sizeof(s->packed_headers_stream));
966     bytestream_get_buffer(&s->g.buffer, s->packed_headers + s->packed_headers_size,
967                           n - 3);
968     s->packed_headers_size += n - 3;
969 
970     return 0;
971 }
972 
get_ppt(Jpeg2000DecoderContext * s,int n)973 static int get_ppt(Jpeg2000DecoderContext *s, int n)
974 {
975     Jpeg2000Tile *tile;
976     void *new;
977 
978     if (n < 3) {
979         av_log(s->avctx, AV_LOG_ERROR, "Invalid length for PPT data.\n");
980         return AVERROR_INVALIDDATA;
981     }
982     if (s->curtileno < 0)
983         return AVERROR_INVALIDDATA;
984 
985     tile = &s->tile[s->curtileno];
986     if (tile->tp_idx != 0) {
987         av_log(s->avctx, AV_LOG_ERROR,
988                "PPT marker can occur only on first tile part of a tile.\n");
989         return AVERROR_INVALIDDATA;
990     }
991 
992     tile->has_ppt = 1;  // this tile has a ppt marker
993     bytestream2_get_byte(&s->g); // Zppt is skipped and not used
994     new = av_realloc(tile->packed_headers,
995                      tile->packed_headers_size + n - 3);
996     if (new) {
997         tile->packed_headers = new;
998     } else
999         return AVERROR(ENOMEM);
1000     memset(&tile->packed_headers_stream, 0, sizeof(tile->packed_headers_stream));
1001     memcpy(tile->packed_headers + tile->packed_headers_size,
1002            s->g.buffer, n - 3);
1003     tile->packed_headers_size += n - 3;
1004     bytestream2_skip(&s->g, n - 3);
1005 
1006     return 0;
1007 }
1008 
init_tile(Jpeg2000DecoderContext * s,int tileno)1009 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
1010 {
1011     int compno;
1012     int tilex = tileno % s->numXtiles;
1013     int tiley = tileno / s->numXtiles;
1014     Jpeg2000Tile *tile = s->tile + tileno;
1015 
1016     if (!tile->comp)
1017         return AVERROR(ENOMEM);
1018 
1019     tile->coord[0][0] = av_clip(tilex       * (int64_t)s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);
1020     tile->coord[0][1] = av_clip((tilex + 1) * (int64_t)s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);
1021     tile->coord[1][0] = av_clip(tiley       * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
1022     tile->coord[1][1] = av_clip((tiley + 1) * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
1023 
1024     for (compno = 0; compno < s->ncomponents; compno++) {
1025         Jpeg2000Component *comp = tile->comp + compno;
1026         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1027         Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;
1028         int ret; // global bandno
1029 
1030         comp->coord_o[0][0] = tile->coord[0][0];
1031         comp->coord_o[0][1] = tile->coord[0][1];
1032         comp->coord_o[1][0] = tile->coord[1][0];
1033         comp->coord_o[1][1] = tile->coord[1][1];
1034 
1035         comp->coord_o[0][0] = ff_jpeg2000_ceildiv(comp->coord_o[0][0], s->cdx[compno]);
1036         comp->coord_o[0][1] = ff_jpeg2000_ceildiv(comp->coord_o[0][1], s->cdx[compno]);
1037         comp->coord_o[1][0] = ff_jpeg2000_ceildiv(comp->coord_o[1][0], s->cdy[compno]);
1038         comp->coord_o[1][1] = ff_jpeg2000_ceildiv(comp->coord_o[1][1], s->cdy[compno]);
1039 
1040         comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
1041         comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
1042         comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
1043         comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
1044 
1045         if (!comp->roi_shift)
1046             comp->roi_shift = s->roi_shift[compno];
1047         if (!codsty->init)
1048             return AVERROR_INVALIDDATA;
1049         if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
1050                                              s->cbps[compno], s->cdx[compno],
1051                                              s->cdy[compno], s->avctx))
1052             return ret;
1053     }
1054     return 0;
1055 }
1056 
1057 /* Read the number of coding passes. */
getnpasses(Jpeg2000DecoderContext * s)1058 static int getnpasses(Jpeg2000DecoderContext *s)
1059 {
1060     int num;
1061     if (!get_bits(s, 1))
1062         return 1;
1063     if (!get_bits(s, 1))
1064         return 2;
1065     if ((num = get_bits(s, 2)) != 3)
1066         return num < 0 ? num : 3 + num;
1067     if ((num = get_bits(s, 5)) != 31)
1068         return num < 0 ? num : 6 + num;
1069     num = get_bits(s, 7);
1070     return num < 0 ? num : 37 + num;
1071 }
1072 
getlblockinc(Jpeg2000DecoderContext * s)1073 static int getlblockinc(Jpeg2000DecoderContext *s)
1074 {
1075     int res = 0, ret;
1076     while (ret = get_bits(s, 1)) {
1077         if (ret < 0)
1078             return ret;
1079         res++;
1080     }
1081     return res;
1082 }
1083 
select_header(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile,int * tp_index)1084 static inline void select_header(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1085                                  int *tp_index)
1086 {
1087     s->g = tile->tile_part[*tp_index].header_tpg;
1088     if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {
1089         if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {
1090             s->g = tile->tile_part[++(*tp_index)].tpg;
1091         }
1092     }
1093 }
1094 
select_stream(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile,int * tp_index,Jpeg2000CodingStyle * codsty)1095 static inline void select_stream(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1096                                  int *tp_index, Jpeg2000CodingStyle *codsty)
1097 {
1098     s->g = tile->tile_part[*tp_index].tpg;
1099     if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {
1100         if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {
1101             s->g = tile->tile_part[++(*tp_index)].tpg;
1102         }
1103     }
1104     if (codsty->csty & JPEG2000_CSTY_SOP) {
1105         if (bytestream2_peek_be32(&s->g) == JPEG2000_SOP_FIXED_BYTES)
1106             bytestream2_skip(&s->g, JPEG2000_SOP_BYTE_LENGTH);
1107         else
1108             av_log(s->avctx, AV_LOG_ERROR, "SOP marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1109     }
1110 }
1111 
jpeg2000_decode_packet(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile,int * tp_index,Jpeg2000CodingStyle * codsty,Jpeg2000ResLevel * rlevel,int precno,int layno,uint8_t * expn,int numgbits)1112 static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index,
1113                                   Jpeg2000CodingStyle *codsty,
1114                                   Jpeg2000ResLevel *rlevel, int precno,
1115                                   int layno, uint8_t *expn, int numgbits)
1116 {
1117     int bandno, cblkno, ret, nb_code_blocks;
1118     int cwsno;
1119 
1120     if (layno < rlevel->band[0].prec[precno].decoded_layers)
1121         return 0;
1122     rlevel->band[0].prec[precno].decoded_layers = layno + 1;
1123     // Select stream to read from
1124     if (s->has_ppm)
1125         select_header(s, tile, tp_index);
1126     else if (tile->has_ppt)
1127         s->g = tile->packed_headers_stream;
1128     else
1129         select_stream(s, tile, tp_index, codsty);
1130 
1131     if (!(ret = get_bits(s, 1))) {
1132         jpeg2000_flush(s);
1133         goto skip_data;
1134     } else if (ret < 0)
1135         return ret;
1136 
1137     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1138         Jpeg2000Band *band = rlevel->band + bandno;
1139         Jpeg2000Prec *prec = band->prec + precno;
1140 
1141         if (band->coord[0][0] == band->coord[0][1] ||
1142             band->coord[1][0] == band->coord[1][1])
1143             continue;
1144         nb_code_blocks =  prec->nb_codeblocks_height *
1145                           prec->nb_codeblocks_width;
1146         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
1147             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1148             int incl, newpasses, llen;
1149             void *tmp;
1150 
1151             if (cblk->npasses)
1152                 incl = get_bits(s, 1);
1153             else
1154                 incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
1155             if (!incl)
1156                 continue;
1157             else if (incl < 0)
1158                 return incl;
1159 
1160             if (!cblk->npasses) {
1161                 int v = expn[bandno] + numgbits - 1 -
1162                         tag_tree_decode(s, prec->zerobits + cblkno, 100);
1163                 if (v < 0 || v > 30) {
1164                     av_log(s->avctx, AV_LOG_ERROR,
1165                            "nonzerobits %d invalid or unsupported\n", v);
1166                     return AVERROR_INVALIDDATA;
1167                 }
1168                 cblk->nonzerobits = v;
1169             }
1170             if ((newpasses = getnpasses(s)) < 0)
1171                 return newpasses;
1172             av_assert2(newpasses > 0);
1173             if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) {
1174                 avpriv_request_sample(s->avctx, "Too many passes");
1175                 return AVERROR_PATCHWELCOME;
1176             }
1177             if ((llen = getlblockinc(s)) < 0)
1178                 return llen;
1179             if (cblk->lblock + llen + av_log2(newpasses) > 16) {
1180                 avpriv_request_sample(s->avctx,
1181                                       "Block with length beyond 16 bits");
1182                 return AVERROR_PATCHWELCOME;
1183             }
1184 
1185             cblk->lblock += llen;
1186 
1187             cblk->nb_lengthinc = 0;
1188             cblk->nb_terminationsinc = 0;
1189             av_free(cblk->lengthinc);
1190             cblk->lengthinc = av_calloc(newpasses, sizeof(*cblk->lengthinc));
1191             if (!cblk->lengthinc)
1192                 return AVERROR(ENOMEM);
1193             tmp = av_realloc_array(cblk->data_start, cblk->nb_terminations + newpasses + 1, sizeof(*cblk->data_start));
1194             if (!tmp)
1195                 return AVERROR(ENOMEM);
1196             cblk->data_start = tmp;
1197             do {
1198                 int newpasses1 = 0;
1199 
1200                 while (newpasses1 < newpasses) {
1201                     newpasses1 ++;
1202                     if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) {
1203                         cblk->nb_terminationsinc ++;
1204                         break;
1205                     }
1206                 }
1207 
1208                 if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0)
1209                     return ret;
1210                 if (ret > cblk->data_allocated) {
1211                     size_t new_size = FFMAX(2*cblk->data_allocated, ret);
1212                     void *new = av_realloc(cblk->data, new_size);
1213                     if (new) {
1214                         cblk->data = new;
1215                         cblk->data_allocated = new_size;
1216                     }
1217                 }
1218                 if (ret > cblk->data_allocated) {
1219                     avpriv_request_sample(s->avctx,
1220                                         "Block with lengthinc greater than %"SIZE_SPECIFIER"",
1221                                         cblk->data_allocated);
1222                     return AVERROR_PATCHWELCOME;
1223                 }
1224                 cblk->lengthinc[cblk->nb_lengthinc++] = ret;
1225                 cblk->npasses  += newpasses1;
1226                 newpasses -= newpasses1;
1227             } while(newpasses);
1228         }
1229     }
1230     jpeg2000_flush(s);
1231 
1232     if (codsty->csty & JPEG2000_CSTY_EPH) {
1233         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
1234             bytestream2_skip(&s->g, 2);
1235         else
1236             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1237     }
1238 
1239     // Save state of stream
1240     if (s->has_ppm) {
1241         tile->tile_part[*tp_index].header_tpg = s->g;
1242         select_stream(s, tile, tp_index, codsty);
1243     } else if (tile->has_ppt) {
1244         tile->packed_headers_stream = s->g;
1245         select_stream(s, tile, tp_index, codsty);
1246     }
1247     for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1248         Jpeg2000Band *band = rlevel->band + bandno;
1249         Jpeg2000Prec *prec = band->prec + precno;
1250 
1251         nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
1252         for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
1253             Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1254             if (!cblk->nb_terminationsinc && !cblk->lengthinc)
1255                 continue;
1256             for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) {
1257                 if (cblk->data_allocated < cblk->length + cblk->lengthinc[cwsno] + 4) {
1258                     size_t new_size = FFMAX(2*cblk->data_allocated, cblk->length + cblk->lengthinc[cwsno] + 4);
1259                     void *new = av_realloc(cblk->data, new_size);
1260                     if (new) {
1261                         cblk->data = new;
1262                         cblk->data_allocated = new_size;
1263                     }
1264                 }
1265                 if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno]
1266                     || cblk->data_allocated < cblk->length + cblk->lengthinc[cwsno] + 4
1267                 ) {
1268                     av_log(s->avctx, AV_LOG_ERROR,
1269                         "Block length %"PRIu16" or lengthinc %d is too large, left %d\n",
1270                         cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g));
1271                     return AVERROR_INVALIDDATA;
1272                 }
1273 
1274                 bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]);
1275                 cblk->length   += cblk->lengthinc[cwsno];
1276                 cblk->lengthinc[cwsno] = 0;
1277                 if (cblk->nb_terminationsinc) {
1278                     cblk->nb_terminationsinc--;
1279                     cblk->nb_terminations++;
1280                     cblk->data[cblk->length++] = 0xFF;
1281                     cblk->data[cblk->length++] = 0xFF;
1282                     cblk->data_start[cblk->nb_terminations] = cblk->length;
1283                 }
1284             }
1285             av_freep(&cblk->lengthinc);
1286         }
1287     }
1288     // Save state of stream
1289     tile->tile_part[*tp_index].tpg = s->g;
1290     return 0;
1291 
1292 skip_data:
1293     if (codsty->csty & JPEG2000_CSTY_EPH) {
1294         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
1295             bytestream2_skip(&s->g, 2);
1296         else
1297             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1298     }
1299     if (s->has_ppm) {
1300         tile->tile_part[*tp_index].header_tpg = s->g;
1301         select_stream(s, tile, tp_index, codsty);
1302     } else if (tile->has_ppt) {
1303         tile->packed_headers_stream = s->g;
1304         select_stream(s, tile, tp_index, codsty);
1305     }
1306     tile->tile_part[*tp_index].tpg = s->g;
1307     return 0;
1308 }
1309 
jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile,int RSpoc,int CSpoc,int LYEpoc,int REpoc,int CEpoc,int Ppoc,int * tp_index)1310 static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1311                                              int RSpoc, int CSpoc,
1312                                              int LYEpoc, int REpoc, int CEpoc,
1313                                              int Ppoc, int *tp_index)
1314 {
1315     int ret = 0;
1316     int layno, reslevelno, compno, precno, ok_reslevel;
1317     int x, y;
1318     int step_x, step_y;
1319 
1320     switch (Ppoc) {
1321     case JPEG2000_PGOD_RLCP:
1322         av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");
1323         ok_reslevel = 1;
1324         for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1325             ok_reslevel = 0;
1326             for (layno = 0; layno < LYEpoc; layno++) {
1327                 for (compno = CSpoc; compno < CEpoc; compno++) {
1328                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1329                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1330                     if (reslevelno < codsty->nreslevels) {
1331                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
1332                                                 reslevelno;
1333                         ok_reslevel = 1;
1334                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
1335                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1336                                                               codsty, rlevel,
1337                                                               precno, layno,
1338                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1339                                                               qntsty->nguardbits)) < 0)
1340                                 return ret;
1341                     }
1342                 }
1343             }
1344         }
1345         break;
1346 
1347     case JPEG2000_PGOD_LRCP:
1348         av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");
1349         for (layno = 0; layno < LYEpoc; layno++) {
1350             ok_reslevel = 1;
1351             for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1352                 ok_reslevel = 0;
1353                 for (compno = CSpoc; compno < CEpoc; compno++) {
1354                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1355                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1356                     if (reslevelno < codsty->nreslevels) {
1357                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
1358                                                 reslevelno;
1359                         ok_reslevel = 1;
1360                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
1361                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1362                                                               codsty, rlevel,
1363                                                               precno, layno,
1364                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1365                                                               qntsty->nguardbits)) < 0)
1366                                 return ret;
1367                     }
1368                 }
1369             }
1370         }
1371         break;
1372 
1373     case JPEG2000_PGOD_CPRL:
1374         av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");
1375         for (compno = CSpoc; compno < CEpoc; compno++) {
1376             Jpeg2000Component *comp     = tile->comp + compno;
1377             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1378             Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1379             step_x = 32;
1380             step_y = 32;
1381 
1382             if (RSpoc >= FFMIN(codsty->nreslevels, REpoc))
1383                 continue;
1384 
1385             for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1386                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1387                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1388                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1389                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1390             }
1391             if (step_x >= 31 || step_y >= 31){
1392                 avpriv_request_sample(s->avctx, "CPRL with large step");
1393                 return AVERROR_PATCHWELCOME;
1394             }
1395             step_x = 1<<step_x;
1396             step_y = 1<<step_y;
1397 
1398             for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1399                 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1400                     for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1401                         unsigned prcx, prcy;
1402                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1403                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1404                         int xc = x / s->cdx[compno];
1405                         int yc = y / s->cdy[compno];
1406 
1407                         if (yc % (1LL << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
1408                             continue;
1409 
1410                         if (xc % (1LL << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
1411                             continue;
1412 
1413                         // check if a precinct exists
1414                         prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
1415                         prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
1416                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1417                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1418 
1419                         precno = prcx + rlevel->num_precincts_x * prcy;
1420 
1421                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1422                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1423                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1424                             continue;
1425                         }
1426 
1427                         for (layno = 0; layno < LYEpoc; layno++) {
1428                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
1429                                                               precno, layno,
1430                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1431                                                               qntsty->nguardbits)) < 0)
1432                                 return ret;
1433                         }
1434                     }
1435                 }
1436             }
1437         }
1438         break;
1439 
1440     case JPEG2000_PGOD_RPCL:
1441         av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");
1442         ok_reslevel = 1;
1443         for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1444             ok_reslevel = 0;
1445             step_x = 30;
1446             step_y = 30;
1447             for (compno = CSpoc; compno < CEpoc; compno++) {
1448                 Jpeg2000Component *comp     = tile->comp + compno;
1449                 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1450 
1451                 if (reslevelno < codsty->nreslevels) {
1452                     uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1453                     Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1454                     step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1455                     step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1456                 }
1457             }
1458             step_x = 1<<step_x;
1459             step_y = 1<<step_y;
1460 
1461             for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1462                 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1463                     for (compno = CSpoc; compno < CEpoc; compno++) {
1464                         Jpeg2000Component *comp     = tile->comp + compno;
1465                         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1466                         Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1467                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1468                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1469                         unsigned prcx, prcy;
1470                         int trx0, try0;
1471 
1472                         if (!s->cdx[compno] || !s->cdy[compno])
1473                             return AVERROR_INVALIDDATA;
1474 
1475                         if (reslevelno >= codsty->nreslevels)
1476                             continue;
1477 
1478                         trx0 = ff_jpeg2000_ceildiv(tile->coord[0][0], (int64_t)s->cdx[compno] << reducedresno);
1479                         try0 = ff_jpeg2000_ceildiv(tile->coord[1][0], (int64_t)s->cdy[compno] << reducedresno);
1480 
1481                         if (!(y % ((uint64_t)s->cdy[compno] << (rlevel->log2_prec_height + reducedresno)) == 0 ||
1482                              (y == tile->coord[1][0] && ((int64_t)try0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_height)))))
1483                             continue;
1484 
1485                         if (!(x % ((uint64_t)s->cdx[compno] << (rlevel->log2_prec_width + reducedresno)) == 0 ||
1486                              (x == tile->coord[0][0] && ((int64_t)trx0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_width)))))
1487                             continue;
1488 
1489                         // check if a precinct exists
1490                         prcx   = ff_jpeg2000_ceildiv(x, (int64_t)s->cdx[compno] << reducedresno) >> rlevel->log2_prec_width;
1491                         prcy   = ff_jpeg2000_ceildiv(y, (int64_t)s->cdy[compno] << reducedresno) >> rlevel->log2_prec_height;
1492                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1493                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1494 
1495                         precno = prcx + rlevel->num_precincts_x * prcy;
1496 
1497                         ok_reslevel = 1;
1498                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1499                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1500                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1501                             continue;
1502                         }
1503 
1504                         for (layno = 0; layno < LYEpoc; layno++) {
1505                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1506                                                               codsty, rlevel,
1507                                                               precno, layno,
1508                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1509                                                               qntsty->nguardbits)) < 0)
1510                                 return ret;
1511                         }
1512                     }
1513                 }
1514             }
1515         }
1516         break;
1517 
1518     case JPEG2000_PGOD_PCRL:
1519         av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL\n");
1520         step_x = 32;
1521         step_y = 32;
1522         for (compno = CSpoc; compno < CEpoc; compno++) {
1523             Jpeg2000Component *comp     = tile->comp + compno;
1524             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1525 
1526             for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1527                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1528                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1529                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1530                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1531             }
1532         }
1533         if (step_x >= 31 || step_y >= 31){
1534             avpriv_request_sample(s->avctx, "PCRL with large step");
1535             return AVERROR_PATCHWELCOME;
1536         }
1537         step_x = 1<<step_x;
1538         step_y = 1<<step_y;
1539 
1540         for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1541             for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1542                 for (compno = CSpoc; compno < CEpoc; compno++) {
1543                     Jpeg2000Component *comp     = tile->comp + compno;
1544                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1545                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1546 
1547                     if (!s->cdx[compno] || !s->cdy[compno])
1548                         return AVERROR_INVALIDDATA;
1549 
1550                     for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1551                         unsigned prcx, prcy;
1552                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1553                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1554                         int trx0, try0;
1555 
1556                         trx0 = ff_jpeg2000_ceildiv(tile->coord[0][0], (int64_t)s->cdx[compno] << reducedresno);
1557                         try0 = ff_jpeg2000_ceildiv(tile->coord[1][0], (int64_t)s->cdy[compno] << reducedresno);
1558 
1559                         if (!(y % ((uint64_t)s->cdy[compno] << (rlevel->log2_prec_height + reducedresno)) == 0 ||
1560                              (y == tile->coord[1][0] && ((int64_t)try0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_height)))))
1561                              continue;
1562 
1563                         if (!(x % ((uint64_t)s->cdx[compno] << (rlevel->log2_prec_width + reducedresno)) == 0 ||
1564                              (x == tile->coord[0][0] && ((int64_t)trx0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_width)))))
1565                              continue;
1566 
1567                         // check if a precinct exists
1568                         prcx   = ff_jpeg2000_ceildiv(x, (int64_t)s->cdx[compno] << reducedresno) >> rlevel->log2_prec_width;
1569                         prcy   = ff_jpeg2000_ceildiv(y, (int64_t)s->cdy[compno] << reducedresno) >> rlevel->log2_prec_height;
1570                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1571                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1572 
1573                         precno = prcx + rlevel->num_precincts_x * prcy;
1574 
1575                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1576                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1577                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1578                             continue;
1579                         }
1580 
1581                         for (layno = 0; layno < LYEpoc; layno++) {
1582                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
1583                                                               precno, layno,
1584                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1585                                                               qntsty->nguardbits)) < 0)
1586                                 return ret;
1587                         }
1588                     }
1589                 }
1590             }
1591         }
1592         break;
1593 
1594     default:
1595         break;
1596     }
1597 
1598     return ret;
1599 }
1600 
jpeg2000_decode_packets(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile)1601 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1602 {
1603     int ret = AVERROR_BUG;
1604     int i;
1605     int tp_index = 0;
1606 
1607     s->bit_index = 8;
1608     if (tile->poc.nb_poc) {
1609         for (i=0; i<tile->poc.nb_poc; i++) {
1610             Jpeg2000POCEntry *e = &tile->poc.poc[i];
1611             ret = jpeg2000_decode_packets_po_iteration(s, tile,
1612                 e->RSpoc, e->CSpoc,
1613                 FFMIN(e->LYEpoc, tile->codsty[0].nlayers),
1614                 e->REpoc,
1615                 FFMIN(e->CEpoc, s->ncomponents),
1616                 e->Ppoc, &tp_index
1617                 );
1618             if (ret < 0)
1619                 return ret;
1620         }
1621     } else {
1622         ret = jpeg2000_decode_packets_po_iteration(s, tile,
1623             0, 0,
1624             tile->codsty[0].nlayers,
1625             33,
1626             s->ncomponents,
1627             tile->codsty[0].prog_order,
1628             &tp_index
1629         );
1630     }
1631     /* EOC marker reached */
1632     bytestream2_skip(&s->g, 2);
1633 
1634     return ret;
1635 }
1636 
1637 /* TIER-1 routines */
decode_sigpass(Jpeg2000T1Context * t1,int width,int height,int bpno,int bandno,int vert_causal_ctx_csty_symbol)1638 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
1639                            int bpno, int bandno,
1640                            int vert_causal_ctx_csty_symbol)
1641 {
1642     int mask = 3 << (bpno - 1), y0, x, y;
1643 
1644     for (y0 = 0; y0 < height; y0 += 4)
1645         for (x = 0; x < width; x++)
1646             for (y = y0; y < height && y < y0 + 4; y++) {
1647                 int flags_mask = -1;
1648                 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1649                     flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1650                 if ((t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB & flags_mask)
1651                 && !(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1652                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, bandno))) {
1653                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, &xorbit);
1654                         if (t1->mqc.raw)
1655                              t1->data[(y) * t1->stride + x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
1656                         else
1657                              t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
1658                                                -mask : mask;
1659 
1660                         ff_jpeg2000_set_significance(t1, x, y,
1661                                                      t1->data[(y) * t1->stride + x] < 0);
1662                     }
1663                     t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_VIS;
1664                 }
1665             }
1666 }
1667 
decode_refpass(Jpeg2000T1Context * t1,int width,int height,int bpno,int vert_causal_ctx_csty_symbol)1668 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
1669                            int bpno, int vert_causal_ctx_csty_symbol)
1670 {
1671     int phalf, nhalf;
1672     int y0, x, y;
1673 
1674     phalf = 1 << (bpno - 1);
1675     nhalf = -phalf;
1676 
1677     for (y0 = 0; y0 < height; y0 += 4)
1678         for (x = 0; x < width; x++)
1679             for (y = y0; y < height && y < y0 + 4; y++)
1680                 if ((t1->flags[(y + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
1681                     int flags_mask = (vert_causal_ctx_csty_symbol && y == y0 + 3) ?
1682                         ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S) : -1;
1683                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask);
1684                     int r     = ff_mqc_decode(&t1->mqc,
1685                                               t1->mqc.cx_states + ctxno)
1686                                 ? phalf : nhalf;
1687                     t1->data[(y) * t1->stride + x]          += t1->data[(y) * t1->stride + x] < 0 ? -r : r;
1688                     t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_REF;
1689                 }
1690 }
1691 
decode_clnpass(Jpeg2000DecoderContext * s,Jpeg2000T1Context * t1,int width,int height,int bpno,int bandno,int seg_symbols,int vert_causal_ctx_csty_symbol)1692 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
1693                            int width, int height, int bpno, int bandno,
1694                            int seg_symbols, int vert_causal_ctx_csty_symbol)
1695 {
1696     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
1697 
1698     for (y0 = 0; y0 < height; y0 += 4) {
1699         for (x = 0; x < width; x++) {
1700             int flags_mask = -1;
1701             if (vert_causal_ctx_csty_symbol)
1702                 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1703             if (y0 + 3 < height &&
1704                 !((t1->flags[(y0 + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1705                   (t1->flags[(y0 + 2) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1706                   (t1->flags[(y0 + 3) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1707                   (t1->flags[(y0 + 4) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {
1708                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
1709                     continue;
1710                 runlen = ff_mqc_decode(&t1->mqc,
1711                                        t1->mqc.cx_states + MQC_CX_UNI);
1712                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
1713                                                        t1->mqc.cx_states +
1714                                                        MQC_CX_UNI);
1715                 dec = 1;
1716             } else {
1717                 runlen = 0;
1718                 dec    = 0;
1719             }
1720 
1721             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
1722                 int flags_mask = -1;
1723                 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1724                     flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1725                 if (!dec) {
1726                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1727                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask,
1728                                                                                              bandno));
1729                     }
1730                 }
1731                 if (dec) {
1732                     int xorbit;
1733                     int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask,
1734                                                         &xorbit);
1735                     t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc,
1736                                                     t1->mqc.cx_states + ctxno) ^
1737                                       xorbit)
1738                                      ? -mask : mask;
1739                     ff_jpeg2000_set_significance(t1, x, y, t1->data[(y) * t1->stride + x] < 0);
1740                 }
1741                 dec = 0;
1742                 t1->flags[(y + 1) * t1->stride + x + 1] &= ~JPEG2000_T1_VIS;
1743             }
1744         }
1745     }
1746     if (seg_symbols) {
1747         int val;
1748         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1749         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1750         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1751         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1752         if (val != 0xa)
1753             av_log(s->avctx, AV_LOG_ERROR,
1754                    "Segmentation symbol value incorrect\n");
1755     }
1756 }
1757 
decode_cblk(Jpeg2000DecoderContext * s,Jpeg2000CodingStyle * codsty,Jpeg2000T1Context * t1,Jpeg2000Cblk * cblk,int width,int height,int bandpos,uint8_t roi_shift)1758 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
1759                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
1760                        int width, int height, int bandpos, uint8_t roi_shift)
1761 {
1762     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1 + roi_shift;
1763     int pass_cnt = 0;
1764     int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
1765     int term_cnt = 0;
1766     int coder_type;
1767 
1768     av_assert0(width <= 1024U && height <= 1024U);
1769     av_assert0(width*height <= 4096);
1770 
1771     memset(t1->data, 0, t1->stride * height * sizeof(*t1->data));
1772 
1773     /* If code-block contains no compressed data: nothing to do. */
1774     if (!cblk->length)
1775         return 0;
1776 
1777     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
1778 
1779     cblk->data[cblk->length] = 0xff;
1780     cblk->data[cblk->length+1] = 0xff;
1781     ff_mqc_initdec(&t1->mqc, cblk->data, 0, 1);
1782 
1783     while (passno--) {
1784         if (bpno < 0 || bpno > 29) {
1785             av_log(s->avctx, AV_LOG_ERROR, "bpno became invalid\n");
1786             return AVERROR_INVALIDDATA;
1787         }
1788         switch(pass_t) {
1789         case 0:
1790             decode_sigpass(t1, width, height, bpno + 1, bandpos,
1791                            vert_causal_ctx_csty_symbol);
1792             break;
1793         case 1:
1794             decode_refpass(t1, width, height, bpno + 1, vert_causal_ctx_csty_symbol);
1795             break;
1796         case 2:
1797             av_assert2(!t1->mqc.raw);
1798             decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
1799                            codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1800                            vert_causal_ctx_csty_symbol);
1801             break;
1802         }
1803         if (codsty->cblk_style & JPEG2000_CBLK_RESET) // XXX no testcase for just this
1804             ff_mqc_init_contexts(&t1->mqc);
1805 
1806         if (passno && (coder_type = needs_termination(codsty->cblk_style, pass_cnt))) {
1807             if (term_cnt >= cblk->nb_terminations) {
1808                 av_log(s->avctx, AV_LOG_ERROR, "Missing needed termination \n");
1809                 return AVERROR_INVALIDDATA;
1810             }
1811             if (FFABS(cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp) > 0) {
1812                 av_log(s->avctx, AV_LOG_WARNING, "Mid mismatch %"PTRDIFF_SPECIFIER" in pass %d of %d\n",
1813                     cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp,
1814                     pass_cnt, cblk->npasses);
1815             }
1816 
1817             ff_mqc_initdec(&t1->mqc, cblk->data + cblk->data_start[++term_cnt], coder_type == 2, 0);
1818         }
1819 
1820         pass_t++;
1821         if (pass_t == 3) {
1822             bpno--;
1823             pass_t = 0;
1824         }
1825         pass_cnt ++;
1826     }
1827 
1828     if (cblk->data + cblk->length - 2 > t1->mqc.bp) {
1829         av_log(s->avctx, AV_LOG_WARNING, "End mismatch %"PTRDIFF_SPECIFIER"\n",
1830                cblk->data + cblk->length - 2 - t1->mqc.bp);
1831     }
1832 
1833     if (cblk->data + cblk->length < t1->mqc.bp) {
1834         av_log(s->avctx, AV_LOG_WARNING, "Synthetic End of Stream Marker Read.\n");
1835     }
1836 
1837     return 1;
1838 }
1839 
roi_shift_param(Jpeg2000Component * comp,int quan_parameter)1840 static inline int roi_shift_param(Jpeg2000Component *comp,
1841                                    int quan_parameter)
1842 {
1843     uint8_t roi_shift;
1844     int val;
1845     roi_shift = comp->roi_shift;
1846     val = (quan_parameter < 0)?-quan_parameter:quan_parameter;
1847 
1848     if (val > (1 << roi_shift))
1849         return (quan_parameter < 0)?-(val >> roi_shift):(val >> roi_shift);
1850     return quan_parameter;
1851 }
1852 
1853 /* TODO: Verify dequantization for lossless case
1854  * comp->data can be float or int
1855  * band->stepsize can be float or int
1856  * depending on the type of DWT transformation.
1857  * see ISO/IEC 15444-1:2002 A.6.1 */
1858 
1859 /* Float dequantization of a codeblock.*/
dequantization_float(int x,int y,Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1,Jpeg2000Band * band)1860 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1861                                  Jpeg2000Component *comp,
1862                                  Jpeg2000T1Context *t1, Jpeg2000Band *band)
1863 {
1864     int i, j;
1865     int w = cblk->coord[0][1] - cblk->coord[0][0];
1866     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1867         float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1868         int *src = t1->data + j*t1->stride;
1869         for (i = 0; i < w; ++i)
1870             datap[i] = src[i] * band->f_stepsize;
1871     }
1872 }
1873 
1874 /* Integer dequantization of a codeblock.*/
dequantization_int(int x,int y,Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1,Jpeg2000Band * band)1875 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1876                                Jpeg2000Component *comp,
1877                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
1878 {
1879     int i, j;
1880     int w = cblk->coord[0][1] - cblk->coord[0][0];
1881     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1882         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1883         int *src = t1->data + j*t1->stride;
1884         if (band->i_stepsize == 32768) {
1885             for (i = 0; i < w; ++i)
1886                 datap[i] = src[i] / 2;
1887         } else {
1888             // This should be VERY uncommon
1889             for (i = 0; i < w; ++i)
1890                 datap[i] = (src[i] * (int64_t)band->i_stepsize) / 65536;
1891         }
1892     }
1893 }
1894 
dequantization_int_97(int x,int y,Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1,Jpeg2000Band * band)1895 static void dequantization_int_97(int x, int y, Jpeg2000Cblk *cblk,
1896                                Jpeg2000Component *comp,
1897                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
1898 {
1899     int i, j;
1900     int w = cblk->coord[0][1] - cblk->coord[0][0];
1901     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1902         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1903         int *src = t1->data + j*t1->stride;
1904         for (i = 0; i < w; ++i)
1905             datap[i] = (src[i] * (int64_t)band->i_stepsize + (1<<15)) >> 16;
1906     }
1907 }
1908 
mct_decode(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile)1909 static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1910 {
1911     int i, csize = 1;
1912     void *src[3];
1913 
1914     for (i = 1; i < 3; i++) {
1915         if (tile->codsty[0].transform != tile->codsty[i].transform) {
1916             av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
1917             return;
1918         }
1919         if (memcmp(tile->comp[0].coord, tile->comp[i].coord, sizeof(tile->comp[0].coord))) {
1920             av_log(s->avctx, AV_LOG_ERROR, "Coords mismatch, MCT not supported\n");
1921             return;
1922         }
1923     }
1924 
1925     for (i = 0; i < 3; i++)
1926         if (tile->codsty[0].transform == FF_DWT97)
1927             src[i] = tile->comp[i].f_data;
1928         else
1929             src[i] = tile->comp[i].i_data;
1930 
1931     for (i = 0; i < 2; i++)
1932         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1933 
1934     s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
1935 }
1936 
roi_scale_cblk(Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1)1937 static inline void roi_scale_cblk(Jpeg2000Cblk *cblk,
1938                                   Jpeg2000Component *comp,
1939                                   Jpeg2000T1Context *t1)
1940 {
1941     int i, j;
1942     int w = cblk->coord[0][1] - cblk->coord[0][0];
1943     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1944         int *src = t1->data + j*t1->stride;
1945         for (i = 0; i < w; ++i)
1946             src[i] = roi_shift_param(comp, src[i]);
1947     }
1948 }
1949 
tile_codeblocks(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile)1950 static inline void tile_codeblocks(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1951 {
1952     Jpeg2000T1Context t1;
1953 
1954     int compno, reslevelno, bandno;
1955 
1956     /* Loop on tile components */
1957     for (compno = 0; compno < s->ncomponents; compno++) {
1958         Jpeg2000Component *comp     = tile->comp + compno;
1959         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1960         int coded = 0;
1961 
1962         t1.stride = (1<<codsty->log2_cblk_width) + 2;
1963 
1964         /* Loop on resolution levels */
1965         for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1966             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1967             /* Loop on bands */
1968             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1969                 int nb_precincts, precno;
1970                 Jpeg2000Band *band = rlevel->band + bandno;
1971                 int cblkno = 0, bandpos;
1972 
1973                 bandpos = bandno + (reslevelno > 0);
1974 
1975                 if (band->coord[0][0] == band->coord[0][1] ||
1976                     band->coord[1][0] == band->coord[1][1])
1977                     continue;
1978 
1979                 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1980                 /* Loop on precincts */
1981                 for (precno = 0; precno < nb_precincts; precno++) {
1982                     Jpeg2000Prec *prec = band->prec + precno;
1983 
1984                     /* Loop on codeblocks */
1985                     for (cblkno = 0;
1986                          cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height;
1987                          cblkno++) {
1988                         int x, y;
1989                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1990                         int ret = decode_cblk(s, codsty, &t1, cblk,
1991                                     cblk->coord[0][1] - cblk->coord[0][0],
1992                                     cblk->coord[1][1] - cblk->coord[1][0],
1993                                     bandpos, comp->roi_shift);
1994                         if (ret)
1995                             coded = 1;
1996                         else
1997                             continue;
1998                         x = cblk->coord[0][0] - band->coord[0][0];
1999                         y = cblk->coord[1][0] - band->coord[1][0];
2000 
2001                         if (comp->roi_shift)
2002                             roi_scale_cblk(cblk, comp, &t1);
2003                         if (codsty->transform == FF_DWT97)
2004                             dequantization_float(x, y, cblk, comp, &t1, band);
2005                         else if (codsty->transform == FF_DWT97_INT)
2006                             dequantization_int_97(x, y, cblk, comp, &t1, band);
2007                         else
2008                             dequantization_int(x, y, cblk, comp, &t1, band);
2009                    } /* end cblk */
2010                 } /*end prec */
2011             } /* end band */
2012         } /* end reslevel */
2013 
2014         /* inverse DWT */
2015         if (coded)
2016             ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
2017 
2018     } /*end comp */
2019 }
2020 
2021 #define WRITE_FRAME(D, PIXEL)                                                                     \
2022     static inline void write_frame_ ## D(Jpeg2000DecoderContext * s, Jpeg2000Tile * tile,         \
2023                                          AVFrame * picture, int precision)                        \
2024     {                                                                                             \
2025         const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(s->avctx->pix_fmt);               \
2026         int planar    = !!(pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR);                              \
2027         int pixelsize = planar ? 1 : pixdesc->nb_components;                                      \
2028                                                                                                   \
2029         int compno;                                                                               \
2030         int x, y;                                                                                 \
2031                                                                                                   \
2032         for (compno = 0; compno < s->ncomponents; compno++) {                                     \
2033             Jpeg2000Component *comp     = tile->comp + compno;                                    \
2034             Jpeg2000CodingStyle *codsty = tile->codsty + compno;                                  \
2035             PIXEL *line;                                                                          \
2036             float *datap     = comp->f_data;                                                      \
2037             int32_t *i_datap = comp->i_data;                                                      \
2038             int cbps         = s->cbps[compno];                                                   \
2039             int w            = tile->comp[compno].coord[0][1] -                                   \
2040                                ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[compno]);            \
2041             int h            = tile->comp[compno].coord[1][1] -                                   \
2042                                ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[compno]);            \
2043             int plane        = 0;                                                                 \
2044                                                                                                   \
2045             if (planar)                                                                           \
2046                 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);                 \
2047                                                                                                   \
2048             y    = tile->comp[compno].coord[1][0] -                                               \
2049                    ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[compno]);                        \
2050             line = (PIXEL *)picture->data[plane] + y * (picture->linesize[plane] / sizeof(PIXEL));\
2051             for (; y < h; y++) {                                                                  \
2052                 PIXEL *dst;                                                                       \
2053                                                                                                   \
2054                 x   = tile->comp[compno].coord[0][0] -                                            \
2055                       ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[compno]);                     \
2056                 dst = line + x * pixelsize + compno*!planar;                                      \
2057                                                                                                   \
2058                 if (codsty->transform == FF_DWT97) {                                              \
2059                     for (; x < w; x++) {                                                          \
2060                         int val = lrintf(*datap) + (1 << (cbps - 1));                             \
2061                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */                  \
2062                         val  = av_clip(val, 0, (1 << cbps) - 1);                                  \
2063                         *dst = val << (precision - cbps);                                         \
2064                         datap++;                                                                  \
2065                         dst += pixelsize;                                                         \
2066                     }                                                                             \
2067                 } else {                                                                          \
2068                     for (; x < w; x++) {                                                          \
2069                         int val = *i_datap + (1 << (cbps - 1));                                   \
2070                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */                  \
2071                         val  = av_clip(val, 0, (1 << cbps) - 1);                                  \
2072                         *dst = val << (precision - cbps);                                         \
2073                         i_datap++;                                                                \
2074                         dst += pixelsize;                                                         \
2075                     }                                                                             \
2076                 }                                                                                 \
2077                 line += picture->linesize[plane] / sizeof(PIXEL);                                 \
2078             }                                                                                     \
2079         }                                                                                         \
2080                                                                                                   \
2081     }
2082 
2083 WRITE_FRAME(8, uint8_t)
2084 WRITE_FRAME(16, uint16_t)
2085 
2086 #undef WRITE_FRAME
2087 
jpeg2000_decode_tile(AVCodecContext * avctx,void * td,int jobnr,int threadnr)2088 static int jpeg2000_decode_tile(AVCodecContext *avctx, void *td,
2089                                 int jobnr, int threadnr)
2090 {
2091     Jpeg2000DecoderContext *s = avctx->priv_data;
2092     AVFrame *picture = td;
2093     Jpeg2000Tile *tile = s->tile + jobnr;
2094 
2095     tile_codeblocks(s, tile);
2096 
2097     /* inverse MCT transformation */
2098     if (tile->codsty[0].mct)
2099         mct_decode(s, tile);
2100 
2101     if (s->precision <= 8) {
2102         write_frame_8(s, tile, picture, 8);
2103     } else {
2104         int precision = picture->format == AV_PIX_FMT_XYZ12 ||
2105                         picture->format == AV_PIX_FMT_RGB48 ||
2106                         picture->format == AV_PIX_FMT_RGBA64 ||
2107                         picture->format == AV_PIX_FMT_GRAY16 ? 16 : s->precision;
2108 
2109         write_frame_16(s, tile, picture, precision);
2110     }
2111 
2112     return 0;
2113 }
2114 
jpeg2000_dec_cleanup(Jpeg2000DecoderContext * s)2115 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
2116 {
2117     int tileno, compno;
2118     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
2119         if (s->tile[tileno].comp) {
2120             for (compno = 0; compno < s->ncomponents; compno++) {
2121                 Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
2122                 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
2123 
2124                 ff_jpeg2000_cleanup(comp, codsty);
2125             }
2126             av_freep(&s->tile[tileno].comp);
2127             av_freep(&s->tile[tileno].packed_headers);
2128             s->tile[tileno].packed_headers_size = 0;
2129         }
2130     }
2131     av_freep(&s->packed_headers);
2132     s->packed_headers_size = 0;
2133     memset(&s->packed_headers_stream, 0, sizeof(s->packed_headers_stream));
2134     av_freep(&s->tile);
2135     memset(s->codsty, 0, sizeof(s->codsty));
2136     memset(s->qntsty, 0, sizeof(s->qntsty));
2137     memset(s->properties, 0, sizeof(s->properties));
2138     memset(&s->poc  , 0, sizeof(s->poc));
2139     s->numXtiles = s->numYtiles = 0;
2140     s->ncomponents = 0;
2141 }
2142 
jpeg2000_read_main_headers(Jpeg2000DecoderContext * s)2143 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
2144 {
2145     Jpeg2000CodingStyle *codsty = s->codsty;
2146     Jpeg2000QuantStyle *qntsty  = s->qntsty;
2147     Jpeg2000POC         *poc    = &s->poc;
2148     uint8_t *properties         = s->properties;
2149 
2150     for (;;) {
2151         int len, ret = 0;
2152         uint16_t marker;
2153         int oldpos;
2154 
2155         if (bytestream2_get_bytes_left(&s->g) < 2) {
2156             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
2157             break;
2158         }
2159 
2160         marker = bytestream2_get_be16u(&s->g);
2161         oldpos = bytestream2_tell(&s->g);
2162         if (marker >= 0xFF30 && marker <= 0xFF3F)
2163             continue;
2164         if (marker == JPEG2000_SOD) {
2165             Jpeg2000Tile *tile;
2166             Jpeg2000TilePart *tp;
2167 
2168             if (!s->tile) {
2169                 av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
2170                 return AVERROR_INVALIDDATA;
2171             }
2172             if (s->curtileno < 0) {
2173                 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
2174                 return AVERROR_INVALIDDATA;
2175             }
2176 
2177             tile = s->tile + s->curtileno;
2178             tp = tile->tile_part + tile->tp_idx;
2179             if (tp->tp_end < s->g.buffer) {
2180                 av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
2181                 return AVERROR_INVALIDDATA;
2182             }
2183 
2184             if (s->has_ppm) {
2185                 uint32_t tp_header_size = bytestream2_get_be32(&s->packed_headers_stream);
2186                 if (bytestream2_get_bytes_left(&s->packed_headers_stream) < tp_header_size)
2187                     return AVERROR_INVALIDDATA;
2188                 bytestream2_init(&tp->header_tpg, s->packed_headers_stream.buffer, tp_header_size);
2189                 bytestream2_skip(&s->packed_headers_stream, tp_header_size);
2190             }
2191             if (tile->has_ppt && tile->tp_idx == 0) {
2192                 bytestream2_init(&tile->packed_headers_stream, tile->packed_headers, tile->packed_headers_size);
2193             }
2194 
2195             bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
2196             bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
2197 
2198             continue;
2199         }
2200         if (marker == JPEG2000_EOC)
2201             break;
2202 
2203         len = bytestream2_get_be16(&s->g);
2204         if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) {
2205             if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
2206                 av_log(s->avctx, AV_LOG_ERROR, "Invalid len %d left=%d\n", len, bytestream2_get_bytes_left(&s->g));
2207                 return AVERROR_INVALIDDATA;
2208             }
2209             av_log(s->avctx, AV_LOG_WARNING, "Missing EOC Marker.\n");
2210             break;
2211         }
2212 
2213         switch (marker) {
2214         case JPEG2000_SIZ:
2215             if (s->ncomponents) {
2216                 av_log(s->avctx, AV_LOG_ERROR, "Duplicate SIZ\n");
2217                 return AVERROR_INVALIDDATA;
2218             }
2219             ret = get_siz(s);
2220             if (!s->tile)
2221                 s->numXtiles = s->numYtiles = 0;
2222             break;
2223         case JPEG2000_COC:
2224             ret = get_coc(s, codsty, properties);
2225             break;
2226         case JPEG2000_COD:
2227             ret = get_cod(s, codsty, properties);
2228             break;
2229         case JPEG2000_RGN:
2230             ret = get_rgn(s, len);
2231             break;
2232         case JPEG2000_QCC:
2233             ret = get_qcc(s, len, qntsty, properties);
2234             break;
2235         case JPEG2000_QCD:
2236             ret = get_qcd(s, len, qntsty, properties);
2237             break;
2238         case JPEG2000_POC:
2239             ret = get_poc(s, len, poc);
2240             break;
2241         case JPEG2000_SOT:
2242             if (!s->in_tile_headers) {
2243                 s->in_tile_headers = 1;
2244                 if (s->has_ppm) {
2245                     bytestream2_init(&s->packed_headers_stream, s->packed_headers, s->packed_headers_size);
2246                 }
2247             }
2248             if (!(ret = get_sot(s, len))) {
2249                 av_assert1(s->curtileno >= 0);
2250                 codsty = s->tile[s->curtileno].codsty;
2251                 qntsty = s->tile[s->curtileno].qntsty;
2252                 poc    = &s->tile[s->curtileno].poc;
2253                 properties = s->tile[s->curtileno].properties;
2254             }
2255             break;
2256         case JPEG2000_PLM:
2257             // the PLM marker is ignored
2258         case JPEG2000_COM:
2259             // the comment is ignored
2260             bytestream2_skip(&s->g, len - 2);
2261             break;
2262         case JPEG2000_CRG:
2263             ret = read_crg(s, len);
2264             break;
2265         case JPEG2000_TLM:
2266             // Tile-part lengths
2267             ret = get_tlm(s, len);
2268             break;
2269         case JPEG2000_PLT:
2270             // Packet length, tile-part header
2271             ret = get_plt(s, len);
2272             break;
2273         case JPEG2000_PPM:
2274             // Packed headers, main header
2275             if (s->in_tile_headers) {
2276                 av_log(s->avctx, AV_LOG_ERROR, "PPM Marker can only be in Main header\n");
2277                 return AVERROR_INVALIDDATA;
2278             }
2279             ret = get_ppm(s, len);
2280             break;
2281         case JPEG2000_PPT:
2282             // Packed headers, tile-part header
2283             if (s->has_ppm) {
2284                 av_log(s->avctx, AV_LOG_ERROR,
2285                        "Cannot have both PPT and PPM marker.\n");
2286                 return AVERROR_INVALIDDATA;
2287             }
2288 
2289             ret = get_ppt(s, len);
2290             break;
2291         default:
2292             av_log(s->avctx, AV_LOG_ERROR,
2293                    "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
2294                    marker, bytestream2_tell(&s->g) - 4);
2295             bytestream2_skip(&s->g, len - 2);
2296             break;
2297         }
2298         if (bytestream2_tell(&s->g) - oldpos != len || ret) {
2299             av_log(s->avctx, AV_LOG_ERROR,
2300                    "error during processing marker segment %.4"PRIx16"\n",
2301                    marker);
2302             return ret ? ret : -1;
2303         }
2304     }
2305     return 0;
2306 }
2307 
2308 /* Read bit stream packets --> T2 operation. */
jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext * s)2309 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
2310 {
2311     int ret = 0;
2312     int tileno;
2313 
2314     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
2315         Jpeg2000Tile *tile = s->tile + tileno;
2316 
2317         if ((ret = init_tile(s, tileno)) < 0)
2318             return ret;
2319 
2320         if ((ret = jpeg2000_decode_packets(s, tile)) < 0)
2321             return ret;
2322     }
2323 
2324     return 0;
2325 }
2326 
jp2_find_codestream(Jpeg2000DecoderContext * s)2327 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
2328 {
2329     uint32_t atom_size, atom, atom_end;
2330     int search_range = 10;
2331 
2332     while (search_range
2333            &&
2334            bytestream2_get_bytes_left(&s->g) >= 8) {
2335         atom_size = bytestream2_get_be32u(&s->g);
2336         atom      = bytestream2_get_be32u(&s->g);
2337         if (atom_size == 1) {
2338             if (bytestream2_get_be32u(&s->g)) {
2339                 avpriv_request_sample(s->avctx, "Huge atom");
2340                 return 0;
2341             }
2342             atom_size = bytestream2_get_be32u(&s->g);
2343             if (atom_size < 16 || (int64_t)bytestream2_tell(&s->g) + atom_size - 16 > INT_MAX)
2344                 return AVERROR_INVALIDDATA;
2345             atom_end  = bytestream2_tell(&s->g) + atom_size - 16;
2346         } else {
2347             if (atom_size <  8 || (int64_t)bytestream2_tell(&s->g) + atom_size -  8 > INT_MAX)
2348                 return AVERROR_INVALIDDATA;
2349             atom_end  = bytestream2_tell(&s->g) + atom_size -  8;
2350         }
2351 
2352         if (atom == JP2_CODESTREAM)
2353             return 1;
2354 
2355         if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
2356             return 0;
2357 
2358         if (atom == JP2_HEADER &&
2359                    atom_size >= 16) {
2360             uint32_t atom2_size, atom2, atom2_end;
2361             do {
2362                 if (bytestream2_get_bytes_left(&s->g) < 8)
2363                     break;
2364                 atom2_size = bytestream2_get_be32u(&s->g);
2365                 atom2      = bytestream2_get_be32u(&s->g);
2366                 atom2_end  = bytestream2_tell(&s->g) + atom2_size - 8;
2367                 if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
2368                     break;
2369                 atom2_size -= 8;
2370                 if (atom2 == JP2_CODESTREAM) {
2371                     return 1;
2372                 } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
2373                     int method = bytestream2_get_byteu(&s->g);
2374                     bytestream2_skipu(&s->g, 2);
2375                     if (method == 1) {
2376                         s->colour_space = bytestream2_get_be32u(&s->g);
2377                     }
2378                 } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
2379                     int i, size, colour_count, colour_channels, colour_depth[3];
2380                     colour_count = bytestream2_get_be16u(&s->g);
2381                     colour_channels = bytestream2_get_byteu(&s->g);
2382                     // FIXME: Do not ignore channel_sign
2383                     colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2384                     colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2385                     colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2386                     size = (colour_depth[0] + 7 >> 3) * colour_count +
2387                            (colour_depth[1] + 7 >> 3) * colour_count +
2388                            (colour_depth[2] + 7 >> 3) * colour_count;
2389                     if (colour_count > AVPALETTE_COUNT ||
2390                         colour_channels != 3 ||
2391                         colour_depth[0] > 16 ||
2392                         colour_depth[1] > 16 ||
2393                         colour_depth[2] > 16 ||
2394                         atom2_size < size) {
2395                         avpriv_request_sample(s->avctx, "Unknown palette");
2396                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2397                         continue;
2398                     }
2399                     s->pal8 = 1;
2400                     for (i = 0; i < colour_count; i++) {
2401                         uint32_t r, g, b;
2402                         if (colour_depth[0] <= 8) {
2403                             r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
2404                             r |= r >> colour_depth[0];
2405                         } else {
2406                             r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
2407                         }
2408                         if (colour_depth[1] <= 8) {
2409                             g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
2410                             g |= g >> colour_depth[1];
2411                         } else {
2412                             g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
2413                         }
2414                         if (colour_depth[2] <= 8) {
2415                             b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
2416                             b |= b >> colour_depth[2];
2417                         } else {
2418                             b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
2419                         }
2420                         s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
2421                     }
2422                 } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
2423                     int n = bytestream2_get_be16u(&s->g);
2424                     for (; n>0; n--) {
2425                         int cn   = bytestream2_get_be16(&s->g);
2426                         int av_unused typ  = bytestream2_get_be16(&s->g);
2427                         int asoc = bytestream2_get_be16(&s->g);
2428                         if (cn < 4 && asoc < 4)
2429                             s->cdef[cn] = asoc;
2430                     }
2431                 } else if (atom2 == MKBETAG('r','e','s',' ') && atom2_size >= 18) {
2432                     int64_t vnum, vden, hnum, hden, vexp, hexp;
2433                     uint32_t resx;
2434                     bytestream2_skip(&s->g, 4);
2435                     resx = bytestream2_get_be32u(&s->g);
2436                     if (resx != MKBETAG('r','e','s','c') && resx != MKBETAG('r','e','s','d')) {
2437                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2438                         continue;
2439                     }
2440                     vnum = bytestream2_get_be16u(&s->g);
2441                     vden = bytestream2_get_be16u(&s->g);
2442                     hnum = bytestream2_get_be16u(&s->g);
2443                     hden = bytestream2_get_be16u(&s->g);
2444                     vexp = bytestream2_get_byteu(&s->g);
2445                     hexp = bytestream2_get_byteu(&s->g);
2446                     if (!vnum || !vden || !hnum || !hden) {
2447                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2448                         av_log(s->avctx, AV_LOG_WARNING, "RES box invalid\n");
2449                         continue;
2450                     }
2451                     if (vexp > hexp) {
2452                         vexp -= hexp;
2453                         hexp = 0;
2454                     } else {
2455                         hexp -= vexp;
2456                         vexp = 0;
2457                     }
2458                     if (   INT64_MAX / (hnum * vden) > pow(10, hexp)
2459                         && INT64_MAX / (vnum * hden) > pow(10, vexp))
2460                         av_reduce(&s->sar.den, &s->sar.num,
2461                                   hnum * vden * pow(10, hexp),
2462                                   vnum * hden * pow(10, vexp),
2463                                   INT32_MAX);
2464                 }
2465                 bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2466             } while (atom_end - atom2_end >= 8);
2467         } else {
2468             search_range--;
2469         }
2470         bytestream2_seek(&s->g, atom_end, SEEK_SET);
2471     }
2472 
2473     return 0;
2474 }
2475 
jpeg2000_decode_init(AVCodecContext * avctx)2476 static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
2477 {
2478     Jpeg2000DecoderContext *s = avctx->priv_data;
2479 
2480     if (avctx->lowres)
2481         av_log(avctx, AV_LOG_WARNING, "lowres is overriden by reduction_factor but set anyway\n");
2482     if (!s->reduction_factor && avctx->lowres < JPEG2000_MAX_RESLEVELS) {
2483         s->reduction_factor = avctx->lowres;
2484     }
2485     if (avctx->lowres != s->reduction_factor && avctx->lowres)
2486         return AVERROR(EINVAL);
2487 
2488     ff_jpeg2000dsp_init(&s->dsp);
2489     ff_jpeg2000_init_tier1_luts();
2490 
2491     return 0;
2492 }
2493 
jpeg2000_decode_frame(AVCodecContext * avctx,AVFrame * picture,int * got_frame,AVPacket * avpkt)2494 static int jpeg2000_decode_frame(AVCodecContext *avctx, AVFrame *picture,
2495                                  int *got_frame, AVPacket *avpkt)
2496 {
2497     Jpeg2000DecoderContext *s = avctx->priv_data;
2498     int ret;
2499 
2500     s->avctx     = avctx;
2501     bytestream2_init(&s->g, avpkt->data, avpkt->size);
2502     s->curtileno = -1;
2503     memset(s->cdef, -1, sizeof(s->cdef));
2504 
2505     if (bytestream2_get_bytes_left(&s->g) < 2) {
2506         ret = AVERROR_INVALIDDATA;
2507         goto end;
2508     }
2509 
2510     // check if the image is in jp2 format
2511     if (bytestream2_get_bytes_left(&s->g) >= 12 &&
2512        (bytestream2_get_be32u(&s->g) == 12) &&
2513        (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
2514        (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
2515         if (!jp2_find_codestream(s)) {
2516             av_log(avctx, AV_LOG_ERROR,
2517                    "Could not find Jpeg2000 codestream atom.\n");
2518             ret = AVERROR_INVALIDDATA;
2519             goto end;
2520         }
2521     } else {
2522         bytestream2_seek(&s->g, 0, SEEK_SET);
2523     }
2524 
2525     while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
2526         bytestream2_skip(&s->g, 1);
2527 
2528     if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
2529         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
2530         ret = AVERROR_INVALIDDATA;
2531         goto end;
2532     }
2533     if (ret = jpeg2000_read_main_headers(s))
2534         goto end;
2535 
2536     /* get picture buffer */
2537     if ((ret = ff_thread_get_buffer(avctx, picture, 0)) < 0)
2538         goto end;
2539     picture->pict_type = AV_PICTURE_TYPE_I;
2540     picture->key_frame = 1;
2541 
2542     if (ret = jpeg2000_read_bitstream_packets(s))
2543         goto end;
2544 
2545     for (int x = 0; x < s->ncomponents; x++) {
2546         if (s->cdef[x] < 0) {
2547             for (x = 0; x < s->ncomponents; x++) {
2548                 s->cdef[x] = x + 1;
2549             }
2550             if ((s->ncomponents & 1) == 0)
2551                 s->cdef[s->ncomponents-1] = 0;
2552             break;
2553         }
2554     }
2555 
2556     avctx->execute2(avctx, jpeg2000_decode_tile, picture, NULL, s->numXtiles * s->numYtiles);
2557 
2558     jpeg2000_dec_cleanup(s);
2559 
2560     *got_frame = 1;
2561 
2562     if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
2563         memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
2564     if (s->sar.num && s->sar.den)
2565         avctx->sample_aspect_ratio = s->sar;
2566     s->sar.num = s->sar.den = 0;
2567 
2568     return bytestream2_tell(&s->g);
2569 
2570 end:
2571     jpeg2000_dec_cleanup(s);
2572     return ret;
2573 }
2574 
2575 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
2576 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2577 
2578 static const AVOption options[] = {
2579     { "lowres",  "Lower the decoding resolution by a power of two",
2580         OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
2581     { NULL },
2582 };
2583 
2584 static const AVClass jpeg2000_class = {
2585     .class_name = "jpeg2000",
2586     .item_name  = av_default_item_name,
2587     .option     = options,
2588     .version    = LIBAVUTIL_VERSION_INT,
2589 };
2590 
2591 const FFCodec ff_jpeg2000_decoder = {
2592     .p.name           = "jpeg2000",
2593     .p.long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
2594     .p.type           = AVMEDIA_TYPE_VIDEO,
2595     .p.id             = AV_CODEC_ID_JPEG2000,
2596     .p.capabilities   = AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_DR1,
2597     .priv_data_size   = sizeof(Jpeg2000DecoderContext),
2598     .init             = jpeg2000_decode_init,
2599     FF_CODEC_DECODE_CB(jpeg2000_decode_frame),
2600     .p.priv_class     = &jpeg2000_class,
2601     .p.max_lowres     = 5,
2602     .p.profiles       = NULL_IF_CONFIG_SMALL(ff_jpeg2000_profiles),
2603     .caps_internal    = FF_CODEC_CAP_INIT_THREADSAFE,
2604 };
2605