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