• 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             cblk->nb_lengthinc = 0;
1287         }
1288     }
1289     // Save state of stream
1290     tile->tile_part[*tp_index].tpg = s->g;
1291     return 0;
1292 
1293 skip_data:
1294     if (codsty->csty & JPEG2000_CSTY_EPH) {
1295         if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
1296             bytestream2_skip(&s->g, 2);
1297         else
1298             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));
1299     }
1300     if (s->has_ppm) {
1301         tile->tile_part[*tp_index].header_tpg = s->g;
1302         select_stream(s, tile, tp_index, codsty);
1303     } else if (tile->has_ppt) {
1304         tile->packed_headers_stream = s->g;
1305         select_stream(s, tile, tp_index, codsty);
1306     }
1307     tile->tile_part[*tp_index].tpg = s->g;
1308     return 0;
1309 }
1310 
jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile,int RSpoc,int CSpoc,int LYEpoc,int REpoc,int CEpoc,int Ppoc,int * tp_index)1311 static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
1312                                              int RSpoc, int CSpoc,
1313                                              int LYEpoc, int REpoc, int CEpoc,
1314                                              int Ppoc, int *tp_index)
1315 {
1316     int ret = 0;
1317     int layno, reslevelno, compno, precno, ok_reslevel;
1318     int x, y;
1319     int step_x, step_y;
1320 
1321     switch (Ppoc) {
1322     case JPEG2000_PGOD_RLCP:
1323         av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");
1324         ok_reslevel = 1;
1325         for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1326             ok_reslevel = 0;
1327             for (layno = 0; layno < LYEpoc; layno++) {
1328                 for (compno = CSpoc; compno < CEpoc; compno++) {
1329                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1330                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1331                     if (reslevelno < codsty->nreslevels) {
1332                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
1333                                                 reslevelno;
1334                         ok_reslevel = 1;
1335                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
1336                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1337                                                               codsty, rlevel,
1338                                                               precno, layno,
1339                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1340                                                               qntsty->nguardbits)) < 0)
1341                                 return ret;
1342                     }
1343                 }
1344             }
1345         }
1346         break;
1347 
1348     case JPEG2000_PGOD_LRCP:
1349         av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");
1350         for (layno = 0; layno < LYEpoc; layno++) {
1351             ok_reslevel = 1;
1352             for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1353                 ok_reslevel = 0;
1354                 for (compno = CSpoc; compno < CEpoc; compno++) {
1355                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1356                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1357                     if (reslevelno < codsty->nreslevels) {
1358                         Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
1359                                                 reslevelno;
1360                         ok_reslevel = 1;
1361                         for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
1362                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1363                                                               codsty, rlevel,
1364                                                               precno, layno,
1365                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1366                                                               qntsty->nguardbits)) < 0)
1367                                 return ret;
1368                     }
1369                 }
1370             }
1371         }
1372         break;
1373 
1374     case JPEG2000_PGOD_CPRL:
1375         av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");
1376         for (compno = CSpoc; compno < CEpoc; compno++) {
1377             Jpeg2000Component *comp     = tile->comp + compno;
1378             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1379             Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1380             step_x = 32;
1381             step_y = 32;
1382 
1383             if (RSpoc >= FFMIN(codsty->nreslevels, REpoc))
1384                 continue;
1385 
1386             for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1387                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1388                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1389                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1390                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1391             }
1392             if (step_x >= 31 || step_y >= 31){
1393                 avpriv_request_sample(s->avctx, "CPRL with large step");
1394                 return AVERROR_PATCHWELCOME;
1395             }
1396             step_x = 1<<step_x;
1397             step_y = 1<<step_y;
1398 
1399             for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1400                 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1401                     for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1402                         unsigned prcx, prcy;
1403                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1404                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1405                         int xc = x / s->cdx[compno];
1406                         int yc = y / s->cdy[compno];
1407 
1408                         if (yc % (1LL << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check
1409                             continue;
1410 
1411                         if (xc % (1LL << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check
1412                             continue;
1413 
1414                         // check if a precinct exists
1415                         prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;
1416                         prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;
1417                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1418                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1419 
1420                         precno = prcx + rlevel->num_precincts_x * prcy;
1421 
1422                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1423                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1424                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1425                             continue;
1426                         }
1427 
1428                         for (layno = 0; layno < LYEpoc; layno++) {
1429                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
1430                                                               precno, layno,
1431                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1432                                                               qntsty->nguardbits)) < 0)
1433                                 return ret;
1434                         }
1435                     }
1436                 }
1437             }
1438         }
1439         break;
1440 
1441     case JPEG2000_PGOD_RPCL:
1442         av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");
1443         ok_reslevel = 1;
1444         for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {
1445             ok_reslevel = 0;
1446             step_x = 30;
1447             step_y = 30;
1448             for (compno = CSpoc; compno < CEpoc; compno++) {
1449                 Jpeg2000Component *comp     = tile->comp + compno;
1450                 Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1451 
1452                 if (reslevelno < codsty->nreslevels) {
1453                     uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1454                     Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1455                     step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1456                     step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1457                 }
1458             }
1459             step_x = 1<<step_x;
1460             step_y = 1<<step_y;
1461 
1462             for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1463                 for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1464                     for (compno = CSpoc; compno < CEpoc; compno++) {
1465                         Jpeg2000Component *comp     = tile->comp + compno;
1466                         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1467                         Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1468                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1469                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1470                         unsigned prcx, prcy;
1471                         int trx0, try0;
1472 
1473                         if (!s->cdx[compno] || !s->cdy[compno])
1474                             return AVERROR_INVALIDDATA;
1475 
1476                         if (reslevelno >= codsty->nreslevels)
1477                             continue;
1478 
1479                         trx0 = ff_jpeg2000_ceildiv(tile->coord[0][0], (int64_t)s->cdx[compno] << reducedresno);
1480                         try0 = ff_jpeg2000_ceildiv(tile->coord[1][0], (int64_t)s->cdy[compno] << reducedresno);
1481 
1482                         if (!(y % ((uint64_t)s->cdy[compno] << (rlevel->log2_prec_height + reducedresno)) == 0 ||
1483                              (y == tile->coord[1][0] && ((int64_t)try0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_height)))))
1484                             continue;
1485 
1486                         if (!(x % ((uint64_t)s->cdx[compno] << (rlevel->log2_prec_width + reducedresno)) == 0 ||
1487                              (x == tile->coord[0][0] && ((int64_t)trx0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_width)))))
1488                             continue;
1489 
1490                         // check if a precinct exists
1491                         prcx   = ff_jpeg2000_ceildiv(x, (int64_t)s->cdx[compno] << reducedresno) >> rlevel->log2_prec_width;
1492                         prcy   = ff_jpeg2000_ceildiv(y, (int64_t)s->cdy[compno] << reducedresno) >> rlevel->log2_prec_height;
1493                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1494                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1495 
1496                         precno = prcx + rlevel->num_precincts_x * prcy;
1497 
1498                         ok_reslevel = 1;
1499                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1500                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1501                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1502                             continue;
1503                         }
1504 
1505                         for (layno = 0; layno < LYEpoc; layno++) {
1506                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index,
1507                                                               codsty, rlevel,
1508                                                               precno, layno,
1509                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1510                                                               qntsty->nguardbits)) < 0)
1511                                 return ret;
1512                         }
1513                     }
1514                 }
1515             }
1516         }
1517         break;
1518 
1519     case JPEG2000_PGOD_PCRL:
1520         av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL\n");
1521         step_x = 32;
1522         step_y = 32;
1523         for (compno = CSpoc; compno < CEpoc; compno++) {
1524             Jpeg2000Component *comp     = tile->comp + compno;
1525             Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1526 
1527             for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1528                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1529                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1530                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1531                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1532             }
1533         }
1534         if (step_x >= 31 || step_y >= 31){
1535             avpriv_request_sample(s->avctx, "PCRL with large step");
1536             return AVERROR_PATCHWELCOME;
1537         }
1538         step_x = 1<<step_x;
1539         step_y = 1<<step_y;
1540 
1541         for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {
1542             for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {
1543                 for (compno = CSpoc; compno < CEpoc; compno++) {
1544                     Jpeg2000Component *comp     = tile->comp + compno;
1545                     Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1546                     Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;
1547 
1548                     if (!s->cdx[compno] || !s->cdy[compno])
1549                         return AVERROR_INVALIDDATA;
1550 
1551                     for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {
1552                         unsigned prcx, prcy;
1553                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1554                         Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1555                         int trx0, try0;
1556 
1557                         trx0 = ff_jpeg2000_ceildiv(tile->coord[0][0], (int64_t)s->cdx[compno] << reducedresno);
1558                         try0 = ff_jpeg2000_ceildiv(tile->coord[1][0], (int64_t)s->cdy[compno] << reducedresno);
1559 
1560                         if (!(y % ((uint64_t)s->cdy[compno] << (rlevel->log2_prec_height + reducedresno)) == 0 ||
1561                              (y == tile->coord[1][0] && ((int64_t)try0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_height)))))
1562                              continue;
1563 
1564                         if (!(x % ((uint64_t)s->cdx[compno] << (rlevel->log2_prec_width + reducedresno)) == 0 ||
1565                              (x == tile->coord[0][0] && ((int64_t)trx0 << reducedresno) % (1ULL << (reducedresno + rlevel->log2_prec_width)))))
1566                              continue;
1567 
1568                         // check if a precinct exists
1569                         prcx   = ff_jpeg2000_ceildiv(x, (int64_t)s->cdx[compno] << reducedresno) >> rlevel->log2_prec_width;
1570                         prcy   = ff_jpeg2000_ceildiv(y, (int64_t)s->cdy[compno] << reducedresno) >> rlevel->log2_prec_height;
1571                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;
1572                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;
1573 
1574                         precno = prcx + rlevel->num_precincts_x * prcy;
1575 
1576                         if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {
1577                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1578                                    prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);
1579                             continue;
1580                         }
1581 
1582                         for (layno = 0; layno < LYEpoc; layno++) {
1583                             if ((ret = jpeg2000_decode_packet(s, tile, tp_index, codsty, rlevel,
1584                                                               precno, layno,
1585                                                               qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
1586                                                               qntsty->nguardbits)) < 0)
1587                                 return ret;
1588                         }
1589                     }
1590                 }
1591             }
1592         }
1593         break;
1594 
1595     default:
1596         break;
1597     }
1598 
1599     return ret;
1600 }
1601 
jpeg2000_decode_packets(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile)1602 static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1603 {
1604     int ret = AVERROR_BUG;
1605     int i;
1606     int tp_index = 0;
1607 
1608     s->bit_index = 8;
1609     if (tile->poc.nb_poc) {
1610         for (i=0; i<tile->poc.nb_poc; i++) {
1611             Jpeg2000POCEntry *e = &tile->poc.poc[i];
1612             ret = jpeg2000_decode_packets_po_iteration(s, tile,
1613                 e->RSpoc, e->CSpoc,
1614                 FFMIN(e->LYEpoc, tile->codsty[0].nlayers),
1615                 e->REpoc,
1616                 FFMIN(e->CEpoc, s->ncomponents),
1617                 e->Ppoc, &tp_index
1618                 );
1619             if (ret < 0)
1620                 return ret;
1621         }
1622     } else {
1623         ret = jpeg2000_decode_packets_po_iteration(s, tile,
1624             0, 0,
1625             tile->codsty[0].nlayers,
1626             33,
1627             s->ncomponents,
1628             tile->codsty[0].prog_order,
1629             &tp_index
1630         );
1631     }
1632     /* EOC marker reached */
1633     bytestream2_skip(&s->g, 2);
1634 
1635     return ret;
1636 }
1637 
1638 /* TIER-1 routines */
decode_sigpass(Jpeg2000T1Context * t1,int width,int height,int bpno,int bandno,int vert_causal_ctx_csty_symbol)1639 static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
1640                            int bpno, int bandno,
1641                            int vert_causal_ctx_csty_symbol)
1642 {
1643     int mask = 3 << (bpno - 1), y0, x, y;
1644 
1645     for (y0 = 0; y0 < height; y0 += 4)
1646         for (x = 0; x < width; x++)
1647             for (y = y0; y < height && y < y0 + 4; y++) {
1648                 int flags_mask = -1;
1649                 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1650                     flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1651                 if ((t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB & flags_mask)
1652                 && !(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1653                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, bandno))) {
1654                         int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask, &xorbit);
1655                         if (t1->mqc.raw)
1656                              t1->data[(y) * t1->stride + x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
1657                         else
1658                              t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
1659                                                -mask : mask;
1660 
1661                         ff_jpeg2000_set_significance(t1, x, y,
1662                                                      t1->data[(y) * t1->stride + x] < 0);
1663                     }
1664                     t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_VIS;
1665                 }
1666             }
1667 }
1668 
decode_refpass(Jpeg2000T1Context * t1,int width,int height,int bpno,int vert_causal_ctx_csty_symbol)1669 static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
1670                            int bpno, int vert_causal_ctx_csty_symbol)
1671 {
1672     int phalf, nhalf;
1673     int y0, x, y;
1674 
1675     phalf = 1 << (bpno - 1);
1676     nhalf = -phalf;
1677 
1678     for (y0 = 0; y0 < height; y0 += 4)
1679         for (x = 0; x < width; x++)
1680             for (y = y0; y < height && y < y0 + 4; y++)
1681                 if ((t1->flags[(y + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
1682                     int flags_mask = (vert_causal_ctx_csty_symbol && y == y0 + 3) ?
1683                         ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S) : -1;
1684                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask);
1685                     int r     = ff_mqc_decode(&t1->mqc,
1686                                               t1->mqc.cx_states + ctxno)
1687                                 ? phalf : nhalf;
1688                     t1->data[(y) * t1->stride + x]          += t1->data[(y) * t1->stride + x] < 0 ? -r : r;
1689                     t1->flags[(y + 1) * t1->stride + x + 1] |= JPEG2000_T1_REF;
1690                 }
1691 }
1692 
decode_clnpass(Jpeg2000DecoderContext * s,Jpeg2000T1Context * t1,int width,int height,int bpno,int bandno,int seg_symbols,int vert_causal_ctx_csty_symbol)1693 static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
1694                            int width, int height, int bpno, int bandno,
1695                            int seg_symbols, int vert_causal_ctx_csty_symbol)
1696 {
1697     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
1698 
1699     for (y0 = 0; y0 < height; y0 += 4) {
1700         for (x = 0; x < width; x++) {
1701             int flags_mask = -1;
1702             if (vert_causal_ctx_csty_symbol)
1703                 flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1704             if (y0 + 3 < height &&
1705                 !((t1->flags[(y0 + 1) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1706                   (t1->flags[(y0 + 2) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1707                   (t1->flags[(y0 + 3) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1708                   (t1->flags[(y0 + 4) * t1->stride + x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {
1709                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
1710                     continue;
1711                 runlen = ff_mqc_decode(&t1->mqc,
1712                                        t1->mqc.cx_states + MQC_CX_UNI);
1713                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
1714                                                        t1->mqc.cx_states +
1715                                                        MQC_CX_UNI);
1716                 dec = 1;
1717             } else {
1718                 runlen = 0;
1719                 dec    = 0;
1720             }
1721 
1722             for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
1723                 int flags_mask = -1;
1724                 if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1725                     flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);
1726                 if (!dec) {
1727                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1728                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1] & flags_mask,
1729                                                                                              bandno));
1730                     }
1731                 }
1732                 if (dec) {
1733                     int xorbit;
1734                     int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y + 1) * t1->stride + x + 1] & flags_mask,
1735                                                         &xorbit);
1736                     t1->data[(y) * t1->stride + x] = (ff_mqc_decode(&t1->mqc,
1737                                                     t1->mqc.cx_states + ctxno) ^
1738                                       xorbit)
1739                                      ? -mask : mask;
1740                     ff_jpeg2000_set_significance(t1, x, y, t1->data[(y) * t1->stride + x] < 0);
1741                 }
1742                 dec = 0;
1743                 t1->flags[(y + 1) * t1->stride + x + 1] &= ~JPEG2000_T1_VIS;
1744             }
1745         }
1746     }
1747     if (seg_symbols) {
1748         int val;
1749         val = 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         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1753         if (val != 0xa)
1754             av_log(s->avctx, AV_LOG_ERROR,
1755                    "Segmentation symbol value incorrect\n");
1756     }
1757 }
1758 
decode_cblk(Jpeg2000DecoderContext * s,Jpeg2000CodingStyle * codsty,Jpeg2000T1Context * t1,Jpeg2000Cblk * cblk,int width,int height,int bandpos,uint8_t roi_shift)1759 static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
1760                        Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
1761                        int width, int height, int bandpos, uint8_t roi_shift)
1762 {
1763     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1 + roi_shift;
1764     int pass_cnt = 0;
1765     int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
1766     int term_cnt = 0;
1767     int coder_type;
1768 
1769     av_assert0(width <= 1024U && height <= 1024U);
1770     av_assert0(width*height <= 4096);
1771 
1772     memset(t1->data, 0, t1->stride * height * sizeof(*t1->data));
1773 
1774     /* If code-block contains no compressed data: nothing to do. */
1775     if (!cblk->length)
1776         return 0;
1777 
1778     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
1779 
1780     cblk->data[cblk->length] = 0xff;
1781     cblk->data[cblk->length+1] = 0xff;
1782     ff_mqc_initdec(&t1->mqc, cblk->data, 0, 1);
1783 
1784     while (passno--) {
1785         if (bpno < 0 || bpno > 29) {
1786             av_log(s->avctx, AV_LOG_ERROR, "bpno became invalid\n");
1787             return AVERROR_INVALIDDATA;
1788         }
1789         switch(pass_t) {
1790         case 0:
1791             decode_sigpass(t1, width, height, bpno + 1, bandpos,
1792                            vert_causal_ctx_csty_symbol);
1793             break;
1794         case 1:
1795             decode_refpass(t1, width, height, bpno + 1, vert_causal_ctx_csty_symbol);
1796             break;
1797         case 2:
1798             av_assert2(!t1->mqc.raw);
1799             decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
1800                            codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1801                            vert_causal_ctx_csty_symbol);
1802             break;
1803         }
1804         if (codsty->cblk_style & JPEG2000_CBLK_RESET) // XXX no testcase for just this
1805             ff_mqc_init_contexts(&t1->mqc);
1806 
1807         if (passno && (coder_type = needs_termination(codsty->cblk_style, pass_cnt))) {
1808             if (term_cnt >= cblk->nb_terminations) {
1809                 av_log(s->avctx, AV_LOG_ERROR, "Missing needed termination \n");
1810                 return AVERROR_INVALIDDATA;
1811             }
1812             if (FFABS(cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp) > 0) {
1813                 av_log(s->avctx, AV_LOG_WARNING, "Mid mismatch %"PTRDIFF_SPECIFIER" in pass %d of %d\n",
1814                     cblk->data + cblk->data_start[term_cnt + 1] - 2 - t1->mqc.bp,
1815                     pass_cnt, cblk->npasses);
1816             }
1817 
1818             ff_mqc_initdec(&t1->mqc, cblk->data + cblk->data_start[++term_cnt], coder_type == 2, 0);
1819         }
1820 
1821         pass_t++;
1822         if (pass_t == 3) {
1823             bpno--;
1824             pass_t = 0;
1825         }
1826         pass_cnt ++;
1827     }
1828 
1829     if (cblk->data + cblk->length - 2 > t1->mqc.bp) {
1830         av_log(s->avctx, AV_LOG_WARNING, "End mismatch %"PTRDIFF_SPECIFIER"\n",
1831                cblk->data + cblk->length - 2 - t1->mqc.bp);
1832     }
1833 
1834     if (cblk->data + cblk->length < t1->mqc.bp) {
1835         av_log(s->avctx, AV_LOG_WARNING, "Synthetic End of Stream Marker Read.\n");
1836     }
1837 
1838     return 1;
1839 }
1840 
roi_shift_param(Jpeg2000Component * comp,int quan_parameter)1841 static inline int roi_shift_param(Jpeg2000Component *comp,
1842                                    int quan_parameter)
1843 {
1844     uint8_t roi_shift;
1845     int val;
1846     roi_shift = comp->roi_shift;
1847     val = (quan_parameter < 0)?-quan_parameter:quan_parameter;
1848 
1849     if (val > (1 << roi_shift))
1850         return (quan_parameter < 0)?-(val >> roi_shift):(val >> roi_shift);
1851     return quan_parameter;
1852 }
1853 
1854 /* TODO: Verify dequantization for lossless case
1855  * comp->data can be float or int
1856  * band->stepsize can be float or int
1857  * depending on the type of DWT transformation.
1858  * see ISO/IEC 15444-1:2002 A.6.1 */
1859 
1860 /* Float dequantization of a codeblock.*/
dequantization_float(int x,int y,Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1,Jpeg2000Band * band)1861 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1862                                  Jpeg2000Component *comp,
1863                                  Jpeg2000T1Context *t1, Jpeg2000Band *band)
1864 {
1865     int i, j;
1866     int w = cblk->coord[0][1] - cblk->coord[0][0];
1867     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1868         float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1869         int *src = t1->data + j*t1->stride;
1870         for (i = 0; i < w; ++i)
1871             datap[i] = src[i] * band->f_stepsize;
1872     }
1873 }
1874 
1875 /* Integer dequantization of a codeblock.*/
dequantization_int(int x,int y,Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1,Jpeg2000Band * band)1876 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1877                                Jpeg2000Component *comp,
1878                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
1879 {
1880     int i, j;
1881     int w = cblk->coord[0][1] - cblk->coord[0][0];
1882     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1883         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1884         int *src = t1->data + j*t1->stride;
1885         if (band->i_stepsize == 32768) {
1886             for (i = 0; i < w; ++i)
1887                 datap[i] = src[i] / 2;
1888         } else {
1889             // This should be VERY uncommon
1890             for (i = 0; i < w; ++i)
1891                 datap[i] = (src[i] * (int64_t)band->i_stepsize) / 65536;
1892         }
1893     }
1894 }
1895 
dequantization_int_97(int x,int y,Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1,Jpeg2000Band * band)1896 static void dequantization_int_97(int x, int y, Jpeg2000Cblk *cblk,
1897                                Jpeg2000Component *comp,
1898                                Jpeg2000T1Context *t1, Jpeg2000Band *band)
1899 {
1900     int i, j;
1901     int w = cblk->coord[0][1] - cblk->coord[0][0];
1902     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1903         int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1904         int *src = t1->data + j*t1->stride;
1905         for (i = 0; i < w; ++i)
1906             datap[i] = (src[i] * (int64_t)band->i_stepsize + (1<<15)) >> 16;
1907     }
1908 }
1909 
mct_decode(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile)1910 static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1911 {
1912     int i, csize = 1;
1913     void *src[3];
1914 
1915     for (i = 1; i < 3; i++) {
1916         if (tile->codsty[0].transform != tile->codsty[i].transform) {
1917             av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
1918             return;
1919         }
1920         if (memcmp(tile->comp[0].coord, tile->comp[i].coord, sizeof(tile->comp[0].coord))) {
1921             av_log(s->avctx, AV_LOG_ERROR, "Coords mismatch, MCT not supported\n");
1922             return;
1923         }
1924     }
1925 
1926     for (i = 0; i < 3; i++)
1927         if (tile->codsty[0].transform == FF_DWT97)
1928             src[i] = tile->comp[i].f_data;
1929         else
1930             src[i] = tile->comp[i].i_data;
1931 
1932     for (i = 0; i < 2; i++)
1933         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1934 
1935     s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
1936 }
1937 
roi_scale_cblk(Jpeg2000Cblk * cblk,Jpeg2000Component * comp,Jpeg2000T1Context * t1)1938 static inline void roi_scale_cblk(Jpeg2000Cblk *cblk,
1939                                   Jpeg2000Component *comp,
1940                                   Jpeg2000T1Context *t1)
1941 {
1942     int i, j;
1943     int w = cblk->coord[0][1] - cblk->coord[0][0];
1944     for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1945         int *src = t1->data + j*t1->stride;
1946         for (i = 0; i < w; ++i)
1947             src[i] = roi_shift_param(comp, src[i]);
1948     }
1949 }
1950 
tile_codeblocks(Jpeg2000DecoderContext * s,Jpeg2000Tile * tile)1951 static inline void tile_codeblocks(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
1952 {
1953     Jpeg2000T1Context t1;
1954 
1955     int compno, reslevelno, bandno;
1956 
1957     /* Loop on tile components */
1958     for (compno = 0; compno < s->ncomponents; compno++) {
1959         Jpeg2000Component *comp     = tile->comp + compno;
1960         Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1961         int coded = 0;
1962 
1963         t1.stride = (1<<codsty->log2_cblk_width) + 2;
1964 
1965         /* Loop on resolution levels */
1966         for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1967             Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1968             /* Loop on bands */
1969             for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1970                 int nb_precincts, precno;
1971                 Jpeg2000Band *band = rlevel->band + bandno;
1972                 int cblkno = 0, bandpos;
1973 
1974                 bandpos = bandno + (reslevelno > 0);
1975 
1976                 if (band->coord[0][0] == band->coord[0][1] ||
1977                     band->coord[1][0] == band->coord[1][1])
1978                     continue;
1979 
1980                 nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1981                 /* Loop on precincts */
1982                 for (precno = 0; precno < nb_precincts; precno++) {
1983                     Jpeg2000Prec *prec = band->prec + precno;
1984 
1985                     /* Loop on codeblocks */
1986                     for (cblkno = 0;
1987                          cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height;
1988                          cblkno++) {
1989                         int x, y;
1990                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1991                         int ret = decode_cblk(s, codsty, &t1, cblk,
1992                                     cblk->coord[0][1] - cblk->coord[0][0],
1993                                     cblk->coord[1][1] - cblk->coord[1][0],
1994                                     bandpos, comp->roi_shift);
1995                         if (ret)
1996                             coded = 1;
1997                         else
1998                             continue;
1999                         x = cblk->coord[0][0] - band->coord[0][0];
2000                         y = cblk->coord[1][0] - band->coord[1][0];
2001 
2002                         if (comp->roi_shift)
2003                             roi_scale_cblk(cblk, comp, &t1);
2004                         if (codsty->transform == FF_DWT97)
2005                             dequantization_float(x, y, cblk, comp, &t1, band);
2006                         else if (codsty->transform == FF_DWT97_INT)
2007                             dequantization_int_97(x, y, cblk, comp, &t1, band);
2008                         else
2009                             dequantization_int(x, y, cblk, comp, &t1, band);
2010                    } /* end cblk */
2011                 } /*end prec */
2012             } /* end band */
2013         } /* end reslevel */
2014 
2015         /* inverse DWT */
2016         if (coded)
2017             ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
2018 
2019     } /*end comp */
2020 }
2021 
2022 #define WRITE_FRAME(D, PIXEL)                                                                     \
2023     static inline void write_frame_ ## D(Jpeg2000DecoderContext * s, Jpeg2000Tile * tile,         \
2024                                          AVFrame * picture, int precision)                        \
2025     {                                                                                             \
2026         const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(s->avctx->pix_fmt);               \
2027         int planar    = !!(pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR);                              \
2028         int pixelsize = planar ? 1 : pixdesc->nb_components;                                      \
2029                                                                                                   \
2030         int compno;                                                                               \
2031         int x, y;                                                                                 \
2032                                                                                                   \
2033         for (compno = 0; compno < s->ncomponents; compno++) {                                     \
2034             Jpeg2000Component *comp     = tile->comp + compno;                                    \
2035             Jpeg2000CodingStyle *codsty = tile->codsty + compno;                                  \
2036             PIXEL *line;                                                                          \
2037             float *datap     = comp->f_data;                                                      \
2038             int32_t *i_datap = comp->i_data;                                                      \
2039             int cbps         = s->cbps[compno];                                                   \
2040             int w            = tile->comp[compno].coord[0][1] -                                   \
2041                                ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[compno]);            \
2042             int h            = tile->comp[compno].coord[1][1] -                                   \
2043                                ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[compno]);            \
2044             int plane        = 0;                                                                 \
2045                                                                                                   \
2046             if (planar)                                                                           \
2047                 plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);                 \
2048                                                                                                   \
2049             y    = tile->comp[compno].coord[1][0] -                                               \
2050                    ff_jpeg2000_ceildiv(s->image_offset_y, s->cdy[compno]);                        \
2051             line = (PIXEL *)picture->data[plane] + y * (picture->linesize[plane] / sizeof(PIXEL));\
2052             for (; y < h; y++) {                                                                  \
2053                 PIXEL *dst;                                                                       \
2054                                                                                                   \
2055                 x   = tile->comp[compno].coord[0][0] -                                            \
2056                       ff_jpeg2000_ceildiv(s->image_offset_x, s->cdx[compno]);                     \
2057                 dst = line + x * pixelsize + compno*!planar;                                      \
2058                                                                                                   \
2059                 if (codsty->transform == FF_DWT97) {                                              \
2060                     for (; x < w; x++) {                                                          \
2061                         int val = lrintf(*datap) + (1 << (cbps - 1));                             \
2062                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */                  \
2063                         val  = av_clip(val, 0, (1 << cbps) - 1);                                  \
2064                         *dst = val << (precision - cbps);                                         \
2065                         datap++;                                                                  \
2066                         dst += pixelsize;                                                         \
2067                     }                                                                             \
2068                 } else {                                                                          \
2069                     for (; x < w; x++) {                                                          \
2070                         int val = *i_datap + (1 << (cbps - 1));                                   \
2071                         /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */                  \
2072                         val  = av_clip(val, 0, (1 << cbps) - 1);                                  \
2073                         *dst = val << (precision - cbps);                                         \
2074                         i_datap++;                                                                \
2075                         dst += pixelsize;                                                         \
2076                     }                                                                             \
2077                 }                                                                                 \
2078                 line += picture->linesize[plane] / sizeof(PIXEL);                                 \
2079             }                                                                                     \
2080         }                                                                                         \
2081                                                                                                   \
2082     }
2083 
2084 WRITE_FRAME(8, uint8_t)
2085 WRITE_FRAME(16, uint16_t)
2086 
2087 #undef WRITE_FRAME
2088 
jpeg2000_decode_tile(AVCodecContext * avctx,void * td,int jobnr,int threadnr)2089 static int jpeg2000_decode_tile(AVCodecContext *avctx, void *td,
2090                                 int jobnr, int threadnr)
2091 {
2092     Jpeg2000DecoderContext *s = avctx->priv_data;
2093     AVFrame *picture = td;
2094     Jpeg2000Tile *tile = s->tile + jobnr;
2095 
2096     tile_codeblocks(s, tile);
2097 
2098     /* inverse MCT transformation */
2099     if (tile->codsty[0].mct)
2100         mct_decode(s, tile);
2101 
2102     if (s->precision <= 8) {
2103         write_frame_8(s, tile, picture, 8);
2104     } else {
2105         int precision = picture->format == AV_PIX_FMT_XYZ12 ||
2106                         picture->format == AV_PIX_FMT_RGB48 ||
2107                         picture->format == AV_PIX_FMT_RGBA64 ||
2108                         picture->format == AV_PIX_FMT_GRAY16 ? 16 : s->precision;
2109 
2110         write_frame_16(s, tile, picture, precision);
2111     }
2112 
2113     return 0;
2114 }
2115 
jpeg2000_dec_cleanup(Jpeg2000DecoderContext * s)2116 static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
2117 {
2118     int tileno, compno;
2119     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
2120         if (s->tile[tileno].comp) {
2121             for (compno = 0; compno < s->ncomponents; compno++) {
2122                 Jpeg2000Component *comp     = s->tile[tileno].comp   + compno;
2123                 Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
2124 
2125                 ff_jpeg2000_cleanup(comp, codsty);
2126             }
2127             av_freep(&s->tile[tileno].comp);
2128             av_freep(&s->tile[tileno].packed_headers);
2129             s->tile[tileno].packed_headers_size = 0;
2130         }
2131     }
2132     av_freep(&s->packed_headers);
2133     s->packed_headers_size = 0;
2134     memset(&s->packed_headers_stream, 0, sizeof(s->packed_headers_stream));
2135     av_freep(&s->tile);
2136     memset(s->codsty, 0, sizeof(s->codsty));
2137     memset(s->qntsty, 0, sizeof(s->qntsty));
2138     memset(s->properties, 0, sizeof(s->properties));
2139     memset(&s->poc  , 0, sizeof(s->poc));
2140     s->numXtiles = s->numYtiles = 0;
2141     s->ncomponents = 0;
2142 }
2143 
jpeg2000_read_main_headers(Jpeg2000DecoderContext * s)2144 static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
2145 {
2146     Jpeg2000CodingStyle *codsty = s->codsty;
2147     Jpeg2000QuantStyle *qntsty  = s->qntsty;
2148     Jpeg2000POC         *poc    = &s->poc;
2149     uint8_t *properties         = s->properties;
2150 
2151     for (;;) {
2152         int len, ret = 0;
2153         uint16_t marker;
2154         int oldpos;
2155 
2156         if (bytestream2_get_bytes_left(&s->g) < 2) {
2157             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
2158             break;
2159         }
2160 
2161         marker = bytestream2_get_be16u(&s->g);
2162         oldpos = bytestream2_tell(&s->g);
2163         if (marker >= 0xFF30 && marker <= 0xFF3F)
2164             continue;
2165         if (marker == JPEG2000_SOD) {
2166             Jpeg2000Tile *tile;
2167             Jpeg2000TilePart *tp;
2168 
2169             if (!s->tile) {
2170                 av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
2171                 return AVERROR_INVALIDDATA;
2172             }
2173             if (s->curtileno < 0) {
2174                 av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
2175                 return AVERROR_INVALIDDATA;
2176             }
2177 
2178             tile = s->tile + s->curtileno;
2179             tp = tile->tile_part + tile->tp_idx;
2180             if (tp->tp_end < s->g.buffer) {
2181                 av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
2182                 return AVERROR_INVALIDDATA;
2183             }
2184 
2185             if (s->has_ppm) {
2186                 uint32_t tp_header_size = bytestream2_get_be32(&s->packed_headers_stream);
2187                 if (bytestream2_get_bytes_left(&s->packed_headers_stream) < tp_header_size)
2188                     return AVERROR_INVALIDDATA;
2189                 bytestream2_init(&tp->header_tpg, s->packed_headers_stream.buffer, tp_header_size);
2190                 bytestream2_skip(&s->packed_headers_stream, tp_header_size);
2191             }
2192             if (tile->has_ppt && tile->tp_idx == 0) {
2193                 bytestream2_init(&tile->packed_headers_stream, tile->packed_headers, tile->packed_headers_size);
2194             }
2195 
2196             bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
2197             bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
2198 
2199             continue;
2200         }
2201         if (marker == JPEG2000_EOC)
2202             break;
2203 
2204         len = bytestream2_get_be16(&s->g);
2205         if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) {
2206             if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
2207                 av_log(s->avctx, AV_LOG_ERROR, "Invalid len %d left=%d\n", len, bytestream2_get_bytes_left(&s->g));
2208                 return AVERROR_INVALIDDATA;
2209             }
2210             av_log(s->avctx, AV_LOG_WARNING, "Missing EOC Marker.\n");
2211             break;
2212         }
2213 
2214         switch (marker) {
2215         case JPEG2000_SIZ:
2216             if (s->ncomponents) {
2217                 av_log(s->avctx, AV_LOG_ERROR, "Duplicate SIZ\n");
2218                 return AVERROR_INVALIDDATA;
2219             }
2220             ret = get_siz(s);
2221             if (!s->tile)
2222                 s->numXtiles = s->numYtiles = 0;
2223             break;
2224         case JPEG2000_COC:
2225             ret = get_coc(s, codsty, properties);
2226             break;
2227         case JPEG2000_COD:
2228             ret = get_cod(s, codsty, properties);
2229             break;
2230         case JPEG2000_RGN:
2231             ret = get_rgn(s, len);
2232             break;
2233         case JPEG2000_QCC:
2234             ret = get_qcc(s, len, qntsty, properties);
2235             break;
2236         case JPEG2000_QCD:
2237             ret = get_qcd(s, len, qntsty, properties);
2238             break;
2239         case JPEG2000_POC:
2240             ret = get_poc(s, len, poc);
2241             break;
2242         case JPEG2000_SOT:
2243             if (!s->in_tile_headers) {
2244                 s->in_tile_headers = 1;
2245                 if (s->has_ppm) {
2246                     bytestream2_init(&s->packed_headers_stream, s->packed_headers, s->packed_headers_size);
2247                 }
2248             }
2249             if (!(ret = get_sot(s, len))) {
2250                 av_assert1(s->curtileno >= 0);
2251                 codsty = s->tile[s->curtileno].codsty;
2252                 qntsty = s->tile[s->curtileno].qntsty;
2253                 poc    = &s->tile[s->curtileno].poc;
2254                 properties = s->tile[s->curtileno].properties;
2255             }
2256             break;
2257         case JPEG2000_PLM:
2258             // the PLM marker is ignored
2259         case JPEG2000_COM:
2260             // the comment is ignored
2261             bytestream2_skip(&s->g, len - 2);
2262             break;
2263         case JPEG2000_CRG:
2264             ret = read_crg(s, len);
2265             break;
2266         case JPEG2000_TLM:
2267             // Tile-part lengths
2268             ret = get_tlm(s, len);
2269             break;
2270         case JPEG2000_PLT:
2271             // Packet length, tile-part header
2272             ret = get_plt(s, len);
2273             break;
2274         case JPEG2000_PPM:
2275             // Packed headers, main header
2276             if (s->in_tile_headers) {
2277                 av_log(s->avctx, AV_LOG_ERROR, "PPM Marker can only be in Main header\n");
2278                 return AVERROR_INVALIDDATA;
2279             }
2280             ret = get_ppm(s, len);
2281             break;
2282         case JPEG2000_PPT:
2283             // Packed headers, tile-part header
2284             if (s->has_ppm) {
2285                 av_log(s->avctx, AV_LOG_ERROR,
2286                        "Cannot have both PPT and PPM marker.\n");
2287                 return AVERROR_INVALIDDATA;
2288             }
2289 
2290             ret = get_ppt(s, len);
2291             break;
2292         default:
2293             av_log(s->avctx, AV_LOG_ERROR,
2294                    "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
2295                    marker, bytestream2_tell(&s->g) - 4);
2296             bytestream2_skip(&s->g, len - 2);
2297             break;
2298         }
2299         if (bytestream2_tell(&s->g) - oldpos != len || ret) {
2300             av_log(s->avctx, AV_LOG_ERROR,
2301                    "error during processing marker segment %.4"PRIx16"\n",
2302                    marker);
2303             return ret ? ret : -1;
2304         }
2305     }
2306     return 0;
2307 }
2308 
2309 /* Read bit stream packets --> T2 operation. */
jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext * s)2310 static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
2311 {
2312     int ret = 0;
2313     int tileno;
2314 
2315     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
2316         Jpeg2000Tile *tile = s->tile + tileno;
2317 
2318         if ((ret = init_tile(s, tileno)) < 0)
2319             return ret;
2320 
2321         if ((ret = jpeg2000_decode_packets(s, tile)) < 0)
2322             return ret;
2323     }
2324 
2325     return 0;
2326 }
2327 
jp2_find_codestream(Jpeg2000DecoderContext * s)2328 static int jp2_find_codestream(Jpeg2000DecoderContext *s)
2329 {
2330     uint32_t atom_size, atom, atom_end;
2331     int search_range = 10;
2332 
2333     while (search_range
2334            &&
2335            bytestream2_get_bytes_left(&s->g) >= 8) {
2336         atom_size = bytestream2_get_be32u(&s->g);
2337         atom      = bytestream2_get_be32u(&s->g);
2338         if (atom_size == 1) {
2339             if (bytestream2_get_be32u(&s->g)) {
2340                 avpriv_request_sample(s->avctx, "Huge atom");
2341                 return 0;
2342             }
2343             atom_size = bytestream2_get_be32u(&s->g);
2344             if (atom_size < 16 || (int64_t)bytestream2_tell(&s->g) + atom_size - 16 > INT_MAX)
2345                 return AVERROR_INVALIDDATA;
2346             atom_end  = bytestream2_tell(&s->g) + atom_size - 16;
2347         } else {
2348             if (atom_size <  8 || (int64_t)bytestream2_tell(&s->g) + atom_size -  8 > INT_MAX)
2349                 return AVERROR_INVALIDDATA;
2350             atom_end  = bytestream2_tell(&s->g) + atom_size -  8;
2351         }
2352 
2353         if (atom == JP2_CODESTREAM)
2354             return 1;
2355 
2356         if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
2357             return 0;
2358 
2359         if (atom == JP2_HEADER &&
2360                    atom_size >= 16) {
2361             uint32_t atom2_size, atom2, atom2_end;
2362             do {
2363                 if (bytestream2_get_bytes_left(&s->g) < 8)
2364                     break;
2365                 atom2_size = bytestream2_get_be32u(&s->g);
2366                 atom2      = bytestream2_get_be32u(&s->g);
2367                 atom2_end  = bytestream2_tell(&s->g) + atom2_size - 8;
2368                 if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
2369                     break;
2370                 atom2_size -= 8;
2371                 if (atom2 == JP2_CODESTREAM) {
2372                     return 1;
2373                 } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
2374                     int method = bytestream2_get_byteu(&s->g);
2375                     bytestream2_skipu(&s->g, 2);
2376                     if (method == 1) {
2377                         s->colour_space = bytestream2_get_be32u(&s->g);
2378                     }
2379                 } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
2380                     int i, size, colour_count, colour_channels, colour_depth[3];
2381                     colour_count = bytestream2_get_be16u(&s->g);
2382                     colour_channels = bytestream2_get_byteu(&s->g);
2383                     // FIXME: Do not ignore channel_sign
2384                     colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2385                     colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2386                     colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
2387                     size = (colour_depth[0] + 7 >> 3) * colour_count +
2388                            (colour_depth[1] + 7 >> 3) * colour_count +
2389                            (colour_depth[2] + 7 >> 3) * colour_count;
2390                     if (colour_count > AVPALETTE_COUNT ||
2391                         colour_channels != 3 ||
2392                         colour_depth[0] > 16 ||
2393                         colour_depth[1] > 16 ||
2394                         colour_depth[2] > 16 ||
2395                         atom2_size < size) {
2396                         avpriv_request_sample(s->avctx, "Unknown palette");
2397                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2398                         continue;
2399                     }
2400                     s->pal8 = 1;
2401                     for (i = 0; i < colour_count; i++) {
2402                         uint32_t r, g, b;
2403                         if (colour_depth[0] <= 8) {
2404                             r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
2405                             r |= r >> colour_depth[0];
2406                         } else {
2407                             r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
2408                         }
2409                         if (colour_depth[1] <= 8) {
2410                             g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
2411                             g |= g >> colour_depth[1];
2412                         } else {
2413                             g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
2414                         }
2415                         if (colour_depth[2] <= 8) {
2416                             b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
2417                             b |= b >> colour_depth[2];
2418                         } else {
2419                             b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
2420                         }
2421                         s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
2422                     }
2423                 } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
2424                     int n = bytestream2_get_be16u(&s->g);
2425                     for (; n>0; n--) {
2426                         int cn   = bytestream2_get_be16(&s->g);
2427                         int av_unused typ  = bytestream2_get_be16(&s->g);
2428                         int asoc = bytestream2_get_be16(&s->g);
2429                         if (cn < 4 && asoc < 4)
2430                             s->cdef[cn] = asoc;
2431                     }
2432                 } else if (atom2 == MKBETAG('r','e','s',' ') && atom2_size >= 18) {
2433                     int64_t vnum, vden, hnum, hden, vexp, hexp;
2434                     uint32_t resx;
2435                     bytestream2_skip(&s->g, 4);
2436                     resx = bytestream2_get_be32u(&s->g);
2437                     if (resx != MKBETAG('r','e','s','c') && resx != MKBETAG('r','e','s','d')) {
2438                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2439                         continue;
2440                     }
2441                     vnum = bytestream2_get_be16u(&s->g);
2442                     vden = bytestream2_get_be16u(&s->g);
2443                     hnum = bytestream2_get_be16u(&s->g);
2444                     hden = bytestream2_get_be16u(&s->g);
2445                     vexp = bytestream2_get_byteu(&s->g);
2446                     hexp = bytestream2_get_byteu(&s->g);
2447                     if (!vnum || !vden || !hnum || !hden) {
2448                         bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2449                         av_log(s->avctx, AV_LOG_WARNING, "RES box invalid\n");
2450                         continue;
2451                     }
2452                     if (vexp > hexp) {
2453                         vexp -= hexp;
2454                         hexp = 0;
2455                     } else {
2456                         hexp -= vexp;
2457                         vexp = 0;
2458                     }
2459                     if (   INT64_MAX / (hnum * vden) > pow(10, hexp)
2460                         && INT64_MAX / (vnum * hden) > pow(10, vexp))
2461                         av_reduce(&s->sar.den, &s->sar.num,
2462                                   hnum * vden * pow(10, hexp),
2463                                   vnum * hden * pow(10, vexp),
2464                                   INT32_MAX);
2465                 }
2466                 bytestream2_seek(&s->g, atom2_end, SEEK_SET);
2467             } while (atom_end - atom2_end >= 8);
2468         } else {
2469             search_range--;
2470         }
2471         bytestream2_seek(&s->g, atom_end, SEEK_SET);
2472     }
2473 
2474     return 0;
2475 }
2476 
jpeg2000_decode_init(AVCodecContext * avctx)2477 static av_cold int jpeg2000_decode_init(AVCodecContext *avctx)
2478 {
2479     Jpeg2000DecoderContext *s = avctx->priv_data;
2480 
2481     if (avctx->lowres)
2482         av_log(avctx, AV_LOG_WARNING, "lowres is overriden by reduction_factor but set anyway\n");
2483     if (!s->reduction_factor && avctx->lowres < JPEG2000_MAX_RESLEVELS) {
2484         s->reduction_factor = avctx->lowres;
2485     }
2486     if (avctx->lowres != s->reduction_factor && avctx->lowres)
2487         return AVERROR(EINVAL);
2488 
2489     ff_jpeg2000dsp_init(&s->dsp);
2490     ff_jpeg2000_init_tier1_luts();
2491 
2492     return 0;
2493 }
2494 
jpeg2000_decode_frame(AVCodecContext * avctx,AVFrame * picture,int * got_frame,AVPacket * avpkt)2495 static int jpeg2000_decode_frame(AVCodecContext *avctx, AVFrame *picture,
2496                                  int *got_frame, AVPacket *avpkt)
2497 {
2498     Jpeg2000DecoderContext *s = avctx->priv_data;
2499     int ret;
2500 
2501     s->avctx     = avctx;
2502     bytestream2_init(&s->g, avpkt->data, avpkt->size);
2503     s->curtileno = -1;
2504     memset(s->cdef, -1, sizeof(s->cdef));
2505 
2506     if (bytestream2_get_bytes_left(&s->g) < 2) {
2507         ret = AVERROR_INVALIDDATA;
2508         goto end;
2509     }
2510 
2511     // check if the image is in jp2 format
2512     if (bytestream2_get_bytes_left(&s->g) >= 12 &&
2513        (bytestream2_get_be32u(&s->g) == 12) &&
2514        (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
2515        (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
2516         if (!jp2_find_codestream(s)) {
2517             av_log(avctx, AV_LOG_ERROR,
2518                    "Could not find Jpeg2000 codestream atom.\n");
2519             ret = AVERROR_INVALIDDATA;
2520             goto end;
2521         }
2522     } else {
2523         bytestream2_seek(&s->g, 0, SEEK_SET);
2524     }
2525 
2526     while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
2527         bytestream2_skip(&s->g, 1);
2528 
2529     if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
2530         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
2531         ret = AVERROR_INVALIDDATA;
2532         goto end;
2533     }
2534     if (ret = jpeg2000_read_main_headers(s))
2535         goto end;
2536 
2537     /* get picture buffer */
2538     if ((ret = ff_thread_get_buffer(avctx, picture, 0)) < 0)
2539         goto end;
2540     picture->pict_type = AV_PICTURE_TYPE_I;
2541     picture->key_frame = 1;
2542 
2543     if (ret = jpeg2000_read_bitstream_packets(s))
2544         goto end;
2545 
2546     for (int x = 0; x < s->ncomponents; x++) {
2547         if (s->cdef[x] < 0) {
2548             for (x = 0; x < s->ncomponents; x++) {
2549                 s->cdef[x] = x + 1;
2550             }
2551             if ((s->ncomponents & 1) == 0)
2552                 s->cdef[s->ncomponents-1] = 0;
2553             break;
2554         }
2555     }
2556 
2557     avctx->execute2(avctx, jpeg2000_decode_tile, picture, NULL, s->numXtiles * s->numYtiles);
2558 
2559     jpeg2000_dec_cleanup(s);
2560 
2561     *got_frame = 1;
2562 
2563     if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
2564         memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
2565     if (s->sar.num && s->sar.den)
2566         avctx->sample_aspect_ratio = s->sar;
2567     s->sar.num = s->sar.den = 0;
2568 
2569     return bytestream2_tell(&s->g);
2570 
2571 end:
2572     jpeg2000_dec_cleanup(s);
2573     return ret;
2574 }
2575 
2576 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
2577 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2578 
2579 static const AVOption options[] = {
2580     { "lowres",  "Lower the decoding resolution by a power of two",
2581         OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
2582     { NULL },
2583 };
2584 
2585 static const AVClass jpeg2000_class = {
2586     .class_name = "jpeg2000",
2587     .item_name  = av_default_item_name,
2588     .option     = options,
2589     .version    = LIBAVUTIL_VERSION_INT,
2590 };
2591 
2592 const FFCodec ff_jpeg2000_decoder = {
2593     .p.name           = "jpeg2000",
2594     .p.long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
2595     .p.type           = AVMEDIA_TYPE_VIDEO,
2596     .p.id             = AV_CODEC_ID_JPEG2000,
2597     .p.capabilities   = AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_DR1,
2598     .priv_data_size   = sizeof(Jpeg2000DecoderContext),
2599     .init             = jpeg2000_decode_init,
2600     FF_CODEC_DECODE_CB(jpeg2000_decode_frame),
2601     .p.priv_class     = &jpeg2000_class,
2602     .p.max_lowres     = 5,
2603     .p.profiles       = NULL_IF_CONFIG_SMALL(ff_jpeg2000_profiles),
2604     .caps_internal    = FF_CODEC_CAP_INIT_THREADSAFE,
2605 };
2606