FFmpeg  2.6.9
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
jpeg2000dec.c
Go to the documentation of this file.
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 
30 #include "libavutil/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/common.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "avcodec.h"
36 #include "bytestream.h"
37 #include "internal.h"
38 #include "thread.h"
39 #include "jpeg2000.h"
40 #include "jpeg2000dsp.h"
41 
42 #define JP2_SIG_TYPE 0x6A502020
43 #define JP2_SIG_VALUE 0x0D0A870A
44 #define JP2_CODESTREAM 0x6A703263
45 #define JP2_HEADER 0x6A703268
46 
47 #define HAD_COC 0x01
48 #define HAD_QCC 0x02
49 
50 typedef struct Jpeg2000TilePart {
51  uint8_t tile_index; // Tile index who refers the tile-part
52  const uint8_t *tp_end;
53  GetByteContext tpg; // bit stream in tile-part
55 
56 /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
57  * one per component, so tile_part elements have a size of 3 */
58 typedef struct Jpeg2000Tile {
64  uint16_t tp_idx; // Tile-part index
65 } Jpeg2000Tile;
66 
67 typedef struct Jpeg2000DecoderContext {
68  AVClass *class;
71 
72  int width, height;
75  uint8_t cbps[4]; // bits per sample in particular components
76  uint8_t sgnd[4]; // if a component is signed
78  int cdx[4], cdy[4];
79  int precision;
82  uint32_t palette[256];
83  int8_t pal8;
84  int cdef[4];
86  unsigned numXtiles, numYtiles;
88 
91 
92  int bit_index;
93 
94  int curtileno;
95 
98 
99  /*options parameters*/
102 
103 /* get_bits functions for JPEG2000 packet bitstream
104  * It is a get_bit function with a bit-stuffing routine. If the value of the
105  * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
106  * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
108 {
109  int res = 0;
110 
111  while (--n >= 0) {
112  res <<= 1;
113  if (s->bit_index == 0) {
114  s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
115  }
116  s->bit_index--;
117  res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
118  }
119  return res;
120 }
121 
123 {
124  if (bytestream2_get_byte(&s->g) == 0xff)
125  bytestream2_skip(&s->g, 1);
126  s->bit_index = 8;
127 }
128 
129 /* decode the value stored in node */
131  int threshold)
132 {
133  Jpeg2000TgtNode *stack[30];
134  int sp = -1, curval = 0;
135 
136  if (!node)
137  return AVERROR_INVALIDDATA;
138 
139  while (node && !node->vis) {
140  stack[++sp] = node;
141  node = node->parent;
142  }
143 
144  if (node)
145  curval = node->val;
146  else
147  curval = stack[sp]->val;
148 
149  while (curval < threshold && sp >= 0) {
150  if (curval < stack[sp]->val)
151  curval = stack[sp]->val;
152  while (curval < threshold) {
153  int ret;
154  if ((ret = get_bits(s, 1)) > 0) {
155  stack[sp]->vis++;
156  break;
157  } else if (!ret)
158  curval++;
159  else
160  return ret;
161  }
162  stack[sp]->val = curval;
163  sp--;
164  }
165  return curval;
166 }
167 
168 static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
169  int bpc, uint32_t log2_chroma_wh, int pal8)
170 {
171  int match = 1;
172  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
173 
174  if (desc->nb_components != components) {
175  return 0;
176  }
177 
178  switch (components) {
179  case 4:
180  match = match && desc->comp[3].depth_minus1 + 1 >= bpc &&
181  (log2_chroma_wh >> 14 & 3) == 0 &&
182  (log2_chroma_wh >> 12 & 3) == 0;
183  case 3:
184  match = match && desc->comp[2].depth_minus1 + 1 >= bpc &&
185  (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
186  (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h;
187  case 2:
188  match = match && desc->comp[1].depth_minus1 + 1 >= bpc &&
189  (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w &&
190  (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h;
191 
192  case 1:
193  match = match && desc->comp[0].depth_minus1 + 1 >= bpc &&
194  (log2_chroma_wh >> 2 & 3) == 0 &&
195  (log2_chroma_wh & 3) == 0 &&
196  (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
197  }
198  return match;
199 }
200 
201 // pix_fmts with lower bpp have to be listed before
202 // similar pix_fmts with higher bpp.
203 #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
204 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16,AV_PIX_FMT_YA16
205 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
206  AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
207  AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
208  AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
209  AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
210  AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
211  AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
212  AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
213  AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
214  AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
215  AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
216 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12
217 
226 
227 /* marker segments */
228 /* get sizes and offsets of image, tiles; number of components */
230 {
231  int i;
232  int ncomponents;
233  uint32_t log2_chroma_wh = 0;
234  const enum AVPixelFormat *possible_fmts = NULL;
235  int possible_fmts_nb = 0;
236 
237  if (bytestream2_get_bytes_left(&s->g) < 36)
238  return AVERROR_INVALIDDATA;
239 
240  s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
241  s->width = bytestream2_get_be32u(&s->g); // Width
242  s->height = bytestream2_get_be32u(&s->g); // Height
243  s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
244  s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
245  s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
246  s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
247  s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
248  s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
249  ncomponents = bytestream2_get_be16u(&s->g); // CSiz
250 
251  if (s->image_offset_x || s->image_offset_y) {
252  avpriv_request_sample(s->avctx, "Support for image offsets");
253  return AVERROR_PATCHWELCOME;
254  }
255  if (s->width > 32768U || s->height > 32768U) {
256  avpriv_request_sample(s->avctx, "Large Dimensions");
257  return AVERROR_PATCHWELCOME;
258  }
259 
260  if (ncomponents <= 0) {
261  av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
262  s->ncomponents);
263  return AVERROR_INVALIDDATA;
264  }
265 
266  if (ncomponents > 4) {
267  avpriv_request_sample(s->avctx, "Support for %d components",
268  s->ncomponents);
269  return AVERROR_PATCHWELCOME;
270  }
271 
272  s->ncomponents = ncomponents;
273 
274  if (s->tile_width <= 0 || s->tile_height <= 0) {
275  av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
276  s->tile_width, s->tile_height);
277  return AVERROR_INVALIDDATA;
278  }
279 
280  if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
281  return AVERROR_INVALIDDATA;
282 
283  for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
284  uint8_t x = bytestream2_get_byteu(&s->g);
285  s->cbps[i] = (x & 0x7f) + 1;
286  s->precision = FFMAX(s->cbps[i], s->precision);
287  s->sgnd[i] = !!(x & 0x80);
288  s->cdx[i] = bytestream2_get_byteu(&s->g);
289  s->cdy[i] = bytestream2_get_byteu(&s->g);
290  if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
291  || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
292  av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
293  return AVERROR_INVALIDDATA;
294  }
295  log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
296  }
297 
300 
301  if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
302  s->numXtiles = s->numYtiles = 0;
303  return AVERROR(EINVAL);
304  }
305 
306  s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
307  if (!s->tile) {
308  s->numXtiles = s->numYtiles = 0;
309  return AVERROR(ENOMEM);
310  }
311 
312  for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
313  Jpeg2000Tile *tile = s->tile + i;
314 
315  tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
316  if (!tile->comp)
317  return AVERROR(ENOMEM);
318  }
319 
320  /* compute image size with reduction factor */
322  s->reduction_factor);
324  s->reduction_factor);
325 
328  possible_fmts = xyz_pix_fmts;
329  possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
330  } else {
331  switch (s->colour_space) {
332  case 16:
333  possible_fmts = rgb_pix_fmts;
334  possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
335  break;
336  case 17:
337  possible_fmts = gray_pix_fmts;
338  possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
339  break;
340  case 18:
341  possible_fmts = yuv_pix_fmts;
342  possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
343  break;
344  default:
345  possible_fmts = all_pix_fmts;
346  possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
347  break;
348  }
349  }
350  for (i = 0; i < possible_fmts_nb; ++i) {
351  if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
352  s->avctx->pix_fmt = possible_fmts[i];
353  break;
354  }
355  }
356  if (i == possible_fmts_nb) {
358  "Unknown pix_fmt, profile: %d, colour_space: %d, "
359  "components: %d, precision: %d, "
360  "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
361  s->avctx->profile, s->colour_space, ncomponents, s->precision,
362  ncomponents > 2 ? s->cdx[1] : 0,
363  ncomponents > 2 ? s->cdy[1] : 0,
364  ncomponents > 2 ? s->cdx[2] : 0,
365  ncomponents > 2 ? s->cdy[2] : 0);
366  return AVERROR_PATCHWELCOME;
367  }
369  return 0;
370 }
371 
372 /* get common part for COD and COC segments */
374 {
375  uint8_t byte;
376 
377  if (bytestream2_get_bytes_left(&s->g) < 5)
378  return AVERROR_INVALIDDATA;
379 
380  /* nreslevels = number of resolution levels
381  = number of decomposition level +1 */
382  c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
384  av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
385  return AVERROR_INVALIDDATA;
386  }
387 
388  if (c->nreslevels <= s->reduction_factor) {
389  /* we are forced to update reduction_factor as its requested value is
390  not compatible with this bitstream, and as we might have used it
391  already in setup earlier we have to fail this frame until
392  reinitialization is implemented */
393  av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1);
394  s->reduction_factor = c->nreslevels - 1;
395  return AVERROR(EINVAL);
396  }
397 
398  /* compute number of resolution levels to decode */
400 
401  c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
402  c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
403 
404  if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
405  c->log2_cblk_width + c->log2_cblk_height > 12) {
406  av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
407  return AVERROR_INVALIDDATA;
408  }
409 
410  if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) {
411  avpriv_request_sample(s->avctx, "cblk size > 64");
412  return AVERROR_PATCHWELCOME;
413  }
414 
415  c->cblk_style = bytestream2_get_byteu(&s->g);
416  if (c->cblk_style != 0) { // cblk style
417  av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
418  }
419  c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
420  /* set integer 9/7 DWT in case of BITEXACT flag */
421  if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
422  c->transform = FF_DWT97_INT;
423 
424  if (c->csty & JPEG2000_CSTY_PREC) {
425  int i;
426  for (i = 0; i < c->nreslevels; i++) {
427  byte = bytestream2_get_byte(&s->g);
428  c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
429  c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
430  }
431  } else {
432  memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
433  memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
434  }
435  return 0;
436 }
437 
438 /* get coding parameters for a particular tile or whole image*/
440  uint8_t *properties)
441 {
443  int compno, ret;
444 
445  if (bytestream2_get_bytes_left(&s->g) < 5)
446  return AVERROR_INVALIDDATA;
447 
448  tmp.csty = bytestream2_get_byteu(&s->g);
449 
450  // get progression order
451  tmp.prog_order = bytestream2_get_byteu(&s->g);
452 
453  tmp.nlayers = bytestream2_get_be16u(&s->g);
454  tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
455 
456  if (tmp.mct && s->ncomponents < 3) {
458  "MCT %"PRIu8" with too few components (%d)\n",
459  tmp.mct, s->ncomponents);
460  return AVERROR_INVALIDDATA;
461  }
462 
463  if ((ret = get_cox(s, &tmp)) < 0)
464  return ret;
465 
466  for (compno = 0; compno < s->ncomponents; compno++)
467  if (!(properties[compno] & HAD_COC))
468  memcpy(c + compno, &tmp, sizeof(tmp));
469  return 0;
470 }
471 
472 /* Get coding parameters for a component in the whole image or a
473  * particular tile. */
475  uint8_t *properties)
476 {
477  int compno, ret;
478 
479  if (bytestream2_get_bytes_left(&s->g) < 2)
480  return AVERROR_INVALIDDATA;
481 
482  compno = bytestream2_get_byteu(&s->g);
483 
484  if (compno >= s->ncomponents) {
486  "Invalid compno %d. There are %d components in the image.\n",
487  compno, s->ncomponents);
488  return AVERROR_INVALIDDATA;
489  }
490 
491  c += compno;
492  c->csty = bytestream2_get_byteu(&s->g);
493 
494  if ((ret = get_cox(s, c)) < 0)
495  return ret;
496 
497  properties[compno] |= HAD_COC;
498  return 0;
499 }
500 
501 /* Get common part for QCD and QCC segments. */
503 {
504  int i, x;
505 
506  if (bytestream2_get_bytes_left(&s->g) < 1)
507  return AVERROR_INVALIDDATA;
508 
509  x = bytestream2_get_byteu(&s->g); // Sqcd
510 
511  q->nguardbits = x >> 5;
512  q->quantsty = x & 0x1f;
513 
514  if (q->quantsty == JPEG2000_QSTY_NONE) {
515  n -= 3;
516  if (bytestream2_get_bytes_left(&s->g) < n ||
518  return AVERROR_INVALIDDATA;
519  for (i = 0; i < n; i++)
520  q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
521  } else if (q->quantsty == JPEG2000_QSTY_SI) {
522  if (bytestream2_get_bytes_left(&s->g) < 2)
523  return AVERROR_INVALIDDATA;
524  x = bytestream2_get_be16u(&s->g);
525  q->expn[0] = x >> 11;
526  q->mant[0] = x & 0x7ff;
527  for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
528  int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
529  q->expn[i] = curexpn;
530  q->mant[i] = q->mant[0];
531  }
532  } else {
533  n = (n - 3) >> 1;
534  if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
536  return AVERROR_INVALIDDATA;
537  for (i = 0; i < n; i++) {
538  x = bytestream2_get_be16u(&s->g);
539  q->expn[i] = x >> 11;
540  q->mant[i] = x & 0x7ff;
541  }
542  }
543  return 0;
544 }
545 
546 /* Get quantization parameters for a particular tile or a whole image. */
548  uint8_t *properties)
549 {
550  Jpeg2000QuantStyle tmp;
551  int compno, ret;
552 
553  memset(&tmp, 0, sizeof(tmp));
554 
555  if ((ret = get_qcx(s, n, &tmp)) < 0)
556  return ret;
557  for (compno = 0; compno < s->ncomponents; compno++)
558  if (!(properties[compno] & HAD_QCC))
559  memcpy(q + compno, &tmp, sizeof(tmp));
560  return 0;
561 }
562 
563 /* Get quantization parameters for a component in the whole image
564  * on in a particular tile. */
566  uint8_t *properties)
567 {
568  int compno;
569 
570  if (bytestream2_get_bytes_left(&s->g) < 1)
571  return AVERROR_INVALIDDATA;
572 
573  compno = bytestream2_get_byteu(&s->g);
574 
575  if (compno >= s->ncomponents) {
577  "Invalid compno %d. There are %d components in the image.\n",
578  compno, s->ncomponents);
579  return AVERROR_INVALIDDATA;
580  }
581 
582  properties[compno] |= HAD_QCC;
583  return get_qcx(s, n - 1, q + compno);
584 }
585 
586 /* Get start of tile segment. */
588 {
589  Jpeg2000TilePart *tp;
590  uint16_t Isot;
591  uint32_t Psot;
592  uint8_t TPsot;
593 
594  if (bytestream2_get_bytes_left(&s->g) < 8)
595  return AVERROR_INVALIDDATA;
596 
597  s->curtileno = 0;
598  Isot = bytestream2_get_be16u(&s->g); // Isot
599  if (Isot >= s->numXtiles * s->numYtiles)
600  return AVERROR_INVALIDDATA;
601 
602  s->curtileno = Isot;
603  Psot = bytestream2_get_be32u(&s->g); // Psot
604  TPsot = bytestream2_get_byteu(&s->g); // TPsot
605 
606  /* Read TNSot but not used */
607  bytestream2_get_byteu(&s->g); // TNsot
608 
609  if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
610  av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);
611  return AVERROR_INVALIDDATA;
612  }
613 
614  if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
615  avpriv_request_sample(s->avctx, "Support for %"PRIu8" components", TPsot);
616  return AVERROR_PATCHWELCOME;
617  }
618 
619  s->tile[Isot].tp_idx = TPsot;
620  tp = s->tile[Isot].tile_part + TPsot;
621  tp->tile_index = Isot;
622  tp->tp_end = s->g.buffer + Psot - n - 2;
623 
624  if (!TPsot) {
625  Jpeg2000Tile *tile = s->tile + s->curtileno;
626 
627  /* copy defaults */
628  memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
629  memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
630  }
631 
632  return 0;
633 }
634 
635 /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
636  * Used to know the number of tile parts and lengths.
637  * There may be multiple TLMs in the header.
638  * TODO: The function is not used for tile-parts management, nor anywhere else.
639  * It can be useful to allocate memory for tile parts, before managing the SOT
640  * markers. Parsing the TLM header is needed to increment the input header
641  * buffer.
642  * This marker is mandatory for DCI. */
644 {
645  uint8_t Stlm, ST, SP, tile_tlm, i;
646  bytestream2_get_byte(&s->g); /* Ztlm: skipped */
647  Stlm = bytestream2_get_byte(&s->g);
648 
649  // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
650  ST = (Stlm >> 4) & 0x03;
651  // TODO: Manage case of ST = 0b11 --> raise error
652  SP = (Stlm >> 6) & 0x01;
653  tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
654  for (i = 0; i < tile_tlm; i++) {
655  switch (ST) {
656  case 0:
657  break;
658  case 1:
659  bytestream2_get_byte(&s->g);
660  break;
661  case 2:
662  bytestream2_get_be16(&s->g);
663  break;
664  case 3:
665  bytestream2_get_be32(&s->g);
666  break;
667  }
668  if (SP == 0) {
669  bytestream2_get_be16(&s->g);
670  } else {
671  bytestream2_get_be32(&s->g);
672  }
673  }
674  return 0;
675 }
676 
677 static int init_tile(Jpeg2000DecoderContext *s, int tileno)
678 {
679  int compno;
680  int tilex = tileno % s->numXtiles;
681  int tiley = tileno / s->numXtiles;
682  Jpeg2000Tile *tile = s->tile + tileno;
683 
684  if (!tile->comp)
685  return AVERROR(ENOMEM);
686 
687  for (compno = 0; compno < s->ncomponents; compno++) {
688  Jpeg2000Component *comp = tile->comp + compno;
689  Jpeg2000CodingStyle *codsty = tile->codsty + compno;
690  Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
691  int ret; // global bandno
692 
693  comp->coord_o[0][0] = av_clip(tilex * (int64_t)s->tile_width + s->tile_offset_x, s->image_offset_x, s->width);
694  comp->coord_o[0][1] = av_clip((tilex + 1) * (int64_t)s->tile_width + s->tile_offset_x, s->image_offset_x, s->width);
695  comp->coord_o[1][0] = av_clip(tiley * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
696  comp->coord_o[1][1] = av_clip((tiley + 1) * (int64_t)s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);
697 
698  comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
699  comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
700  comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
701  comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
702 
703  if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
704  s->cbps[compno], s->cdx[compno],
705  s->cdy[compno], s->avctx))
706  return ret;
707  }
708  return 0;
709 }
710 
711 /* Read the number of coding passes. */
713 {
714  int num;
715  if (!get_bits(s, 1))
716  return 1;
717  if (!get_bits(s, 1))
718  return 2;
719  if ((num = get_bits(s, 2)) != 3)
720  return num < 0 ? num : 3 + num;
721  if ((num = get_bits(s, 5)) != 31)
722  return num < 0 ? num : 6 + num;
723  num = get_bits(s, 7);
724  return num < 0 ? num : 37 + num;
725 }
726 
728 {
729  int res = 0, ret;
730  while (ret = get_bits(s, 1)) {
731  if (ret < 0)
732  return ret;
733  res++;
734  }
735  return res;
736 }
737 
739  Jpeg2000CodingStyle *codsty,
740  Jpeg2000ResLevel *rlevel, int precno,
741  int layno, uint8_t *expn, int numgbits)
742 {
743  int bandno, cblkno, ret, nb_code_blocks;
744 
745  if (!(ret = get_bits(s, 1))) {
746  jpeg2000_flush(s);
747  return 0;
748  } else if (ret < 0)
749  return ret;
750 
751  for (bandno = 0; bandno < rlevel->nbands; bandno++) {
752  Jpeg2000Band *band = rlevel->band + bandno;
753  Jpeg2000Prec *prec = band->prec + precno;
754 
755  if (band->coord[0][0] == band->coord[0][1] ||
756  band->coord[1][0] == band->coord[1][1])
757  continue;
758  nb_code_blocks = prec->nb_codeblocks_height *
759  prec->nb_codeblocks_width;
760  for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
761  Jpeg2000Cblk *cblk = prec->cblk + cblkno;
762  int incl, newpasses, llen;
763 
764  if (cblk->npasses)
765  incl = get_bits(s, 1);
766  else
767  incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
768  if (!incl)
769  continue;
770  else if (incl < 0)
771  return incl;
772 
773  if (!cblk->npasses) {
774  int v = expn[bandno] + numgbits - 1 -
775  tag_tree_decode(s, prec->zerobits + cblkno, 100);
776  if (v < 0) {
778  "nonzerobits %d invalid\n", v);
779  return AVERROR_INVALIDDATA;
780  }
781  cblk->nonzerobits = v;
782  }
783  if ((newpasses = getnpasses(s)) < 0)
784  return newpasses;
785  if ((llen = getlblockinc(s)) < 0)
786  return llen;
787  cblk->lblock += llen;
788  if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
789  return ret;
790  if (ret > sizeof(cblk->data)) {
792  "Block with lengthinc greater than %"SIZE_SPECIFIER"",
793  sizeof(cblk->data));
794  return AVERROR_PATCHWELCOME;
795  }
796  cblk->lengthinc = ret;
797  cblk->npasses += newpasses;
798  }
799  }
800  jpeg2000_flush(s);
801 
802  if (codsty->csty & JPEG2000_CSTY_EPH) {
803  if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
804  bytestream2_skip(&s->g, 2);
805  else
806  av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
807  }
808 
809  for (bandno = 0; bandno < rlevel->nbands; bandno++) {
810  Jpeg2000Band *band = rlevel->band + bandno;
811  Jpeg2000Prec *prec = band->prec + precno;
812 
813  nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
814  for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
815  Jpeg2000Cblk *cblk = prec->cblk + cblkno;
816  if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
817  || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2
818  ) {
820  "Block length %"PRIu16" or lengthinc %d is too large\n",
821  cblk->length, cblk->lengthinc);
822  return AVERROR_INVALIDDATA;
823  }
824 
825  bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc);
826  cblk->length += cblk->lengthinc;
827  cblk->lengthinc = 0;
828  }
829  }
830  return 0;
831 }
832 
834 {
835  int ret = 0;
836  int layno, reslevelno, compno, precno, ok_reslevel;
837  int x, y;
838 
839  s->bit_index = 8;
840  switch (tile->codsty[0].prog_order) {
841  case JPEG2000_PGOD_RLCP:
842  avpriv_request_sample(s->avctx, "Progression order RLCP");
843 
844  case JPEG2000_PGOD_LRCP:
845  for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
846  ok_reslevel = 1;
847  for (reslevelno = 0; ok_reslevel; reslevelno++) {
848  ok_reslevel = 0;
849  for (compno = 0; compno < s->ncomponents; compno++) {
850  Jpeg2000CodingStyle *codsty = tile->codsty + compno;
851  Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
852  if (reslevelno < codsty->nreslevels) {
853  Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
854  reslevelno;
855  ok_reslevel = 1;
856  for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
857  if ((ret = jpeg2000_decode_packet(s,
858  codsty, rlevel,
859  precno, layno,
860  qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
861  qntsty->nguardbits)) < 0)
862  return ret;
863  }
864  }
865  }
866  }
867  break;
868 
869  case JPEG2000_PGOD_CPRL:
870  for (compno = 0; compno < s->ncomponents; compno++) {
871  Jpeg2000CodingStyle *codsty = tile->codsty + compno;
872  Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
873 
874  /* Set bit stream buffer address according to tile-part.
875  * For DCinema one tile-part per component, so can be
876  * indexed by component. */
877  s->g = tile->tile_part[compno].tpg;
878 
879  /* Position loop (y axis)
880  * TODO: Automate computing of step 256.
881  * Fixed here, but to be computed before entering here. */
882  for (y = 0; y < s->height; y += 256) {
883  /* Position loop (y axis)
884  * TODO: automate computing of step 256.
885  * Fixed here, but to be computed before entering here. */
886  for (x = 0; x < s->width; x += 256) {
887  for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
888  uint16_t prcx, prcy;
889  uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
890  Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
891 
892  if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
893  (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
894  continue;
895 
896  if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
897  (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
898  continue;
899 
900  // check if a precinct exists
901  prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
902  prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
903  precno = prcx + rlevel->num_precincts_x * prcy;
904 
905  if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y)
906  return AVERROR_PATCHWELCOME;
907 
908  for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
909  if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
910  precno, layno,
911  qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
912  qntsty->nguardbits)) < 0)
913  return ret;
914  }
915  }
916  }
917  }
918  }
919  break;
920 
921  case JPEG2000_PGOD_RPCL:
922  avpriv_request_sample(s->avctx, "Progression order RPCL");
923  ret = AVERROR_PATCHWELCOME;
924  break;
925 
926  case JPEG2000_PGOD_PCRL:
927  avpriv_request_sample(s->avctx, "Progression order PCRL");
928  ret = AVERROR_PATCHWELCOME;
929  break;
930 
931  default:
932  break;
933  }
934 
935  /* EOC marker reached */
936  bytestream2_skip(&s->g, 2);
937 
938  return ret;
939 }
940 
941 /* TIER-1 routines */
943  int bpno, int bandno, int bpass_csty_symbol,
944  int vert_causal_ctx_csty_symbol)
945 {
946  int mask = 3 << (bpno - 1), y0, x, y;
947 
948  for (y0 = 0; y0 < height; y0 += 4)
949  for (x = 0; x < width; x++)
950  for (y = y0; y < height && y < y0 + 4; y++) {
951  if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
952  && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
953  int flags_mask = -1;
954  if (vert_causal_ctx_csty_symbol && y == y0 + 3)
956  if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
957  int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
958  if (bpass_csty_symbol)
959  t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
960  else
961  t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
962  -mask : mask;
963 
965  t1->data[y][x] < 0);
966  }
967  t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
968  }
969  }
970 }
971 
973  int bpno)
974 {
975  int phalf, nhalf;
976  int y0, x, y;
977 
978  phalf = 1 << (bpno - 1);
979  nhalf = -phalf;
980 
981  for (y0 = 0; y0 < height; y0 += 4)
982  for (x = 0; x < width; x++)
983  for (y = y0; y < height && y < y0 + 4; y++)
984  if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
985  int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
986  int r = ff_mqc_decode(&t1->mqc,
987  t1->mqc.cx_states + ctxno)
988  ? phalf : nhalf;
989  t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
990  t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
991  }
992 }
993 
995  int width, int height, int bpno, int bandno,
996  int seg_symbols, int vert_causal_ctx_csty_symbol)
997 {
998  int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
999 
1000  for (y0 = 0; y0 < height; y0 += 4) {
1001  for (x = 0; x < width; x++) {
1002  if (y0 + 3 < height &&
1003  !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1004  (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1005  (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
1006  (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
1007  if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
1008  continue;
1009  runlen = ff_mqc_decode(&t1->mqc,
1010  t1->mqc.cx_states + MQC_CX_UNI);
1011  runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
1012  t1->mqc.cx_states +
1013  MQC_CX_UNI);
1014  dec = 1;
1015  } else {
1016  runlen = 0;
1017  dec = 0;
1018  }
1019 
1020  for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
1021  if (!dec) {
1022  if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
1023  int flags_mask = -1;
1024  if (vert_causal_ctx_csty_symbol && y == y0 + 3)
1026  dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
1027  bandno));
1028  }
1029  }
1030  if (dec) {
1031  int xorbit;
1032  int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
1033  &xorbit);
1034  t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
1035  t1->mqc.cx_states + ctxno) ^
1036  xorbit)
1037  ? -mask : mask;
1038  ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
1039  }
1040  dec = 0;
1041  t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
1042  }
1043  }
1044  }
1045  if (seg_symbols) {
1046  int val;
1047  val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1048  val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1049  val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1050  val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
1051  if (val != 0xa)
1053  "Segmentation symbol value incorrect\n");
1054  }
1055 }
1056 
1059  int width, int height, int bandpos)
1060 {
1061  int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
1062  int clnpass_cnt = 0;
1063  int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
1064  int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
1065 
1066  av_assert0(width <= JPEG2000_MAX_CBLKW);
1067  av_assert0(height <= JPEG2000_MAX_CBLKH);
1068 
1069  for (y = 0; y < height; y++)
1070  memset(t1->data[y], 0, width * sizeof(**t1->data));
1071 
1072  /* If code-block contains no compressed data: nothing to do. */
1073  if (!cblk->length)
1074  return 0;
1075 
1076  for (y = 0; y < height + 2; y++)
1077  memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
1078 
1079  cblk->data[cblk->length] = 0xff;
1080  cblk->data[cblk->length+1] = 0xff;
1081  ff_mqc_initdec(&t1->mqc, cblk->data);
1082 
1083  while (passno--) {
1084  if (bpno < 0) {
1085  av_log(s->avctx, AV_LOG_ERROR, "bpno became negative\n");
1086  return AVERROR_INVALIDDATA;
1087  }
1088  switch(pass_t) {
1089  case 0:
1090  decode_sigpass(t1, width, height, bpno + 1, bandpos,
1091  bpass_csty_symbol && (clnpass_cnt >= 4),
1092  vert_causal_ctx_csty_symbol);
1093  break;
1094  case 1:
1095  decode_refpass(t1, width, height, bpno + 1);
1096  if (bpass_csty_symbol && clnpass_cnt >= 4)
1097  ff_mqc_initdec(&t1->mqc, cblk->data);
1098  break;
1099  case 2:
1100  decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
1101  codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
1102  vert_causal_ctx_csty_symbol);
1103  clnpass_cnt = clnpass_cnt + 1;
1104  if (bpass_csty_symbol && clnpass_cnt >= 4)
1105  ff_mqc_initdec(&t1->mqc, cblk->data);
1106  break;
1107  }
1108 
1109  pass_t++;
1110  if (pass_t == 3) {
1111  bpno--;
1112  pass_t = 0;
1113  }
1114  }
1115  return 0;
1116 }
1117 
1118 /* TODO: Verify dequantization for lossless case
1119  * comp->data can be float or int
1120  * band->stepsize can be float or int
1121  * depending on the type of DWT transformation.
1122  * see ISO/IEC 15444-1:2002 A.6.1 */
1123 
1124 /* Float dequantization of a codeblock.*/
1125 static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
1128 {
1129  int i, j;
1130  int w = cblk->coord[0][1] - cblk->coord[0][0];
1131  for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1132  float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1133  int *src = t1->data[j];
1134  for (i = 0; i < w; ++i)
1135  datap[i] = src[i] * band->f_stepsize;
1136  }
1137 }
1138 
1139 /* Integer dequantization of a codeblock.*/
1140 static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
1143 {
1144  int i, j;
1145  int w = cblk->coord[0][1] - cblk->coord[0][0];
1146  for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
1147  int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
1148  int *src = t1->data[j];
1149  for (i = 0; i < w; ++i)
1150  datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15;
1151  }
1152 }
1153 
1155 {
1156  int i, csize = 1;
1157  void *src[3];
1158 
1159  for (i = 1; i < 3; i++) {
1160  if (tile->codsty[0].transform != tile->codsty[i].transform) {
1161  av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
1162  return;
1163  }
1164  if (memcmp(tile->comp[0].coord, tile->comp[i].coord, sizeof(tile->comp[0].coord))) {
1165  av_log(s->avctx, AV_LOG_ERROR, "Coords mismatch, MCT not supported\n");
1166  return;
1167  }
1168  }
1169 
1170  for (i = 0; i < 3; i++)
1171  if (tile->codsty[0].transform == FF_DWT97)
1172  src[i] = tile->comp[i].f_data;
1173  else
1174  src[i] = tile->comp[i].i_data;
1175 
1176  for (i = 0; i < 2; i++)
1177  csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
1178 
1179  s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);
1180 }
1181 
1183  AVFrame *picture)
1184 {
1185  const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
1186  int compno, reslevelno, bandno;
1187  int x, y;
1188  int planar = !!(pixdesc->flags & AV_PIX_FMT_FLAG_PLANAR);
1189  int pixelsize = planar ? 1 : pixdesc->nb_components;
1190 
1191  uint8_t *line;
1193 
1194  /* Loop on tile components */
1195  for (compno = 0; compno < s->ncomponents; compno++) {
1196  Jpeg2000Component *comp = tile->comp + compno;
1197  Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1198 
1199  /* Loop on resolution levels */
1200  for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
1201  Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1202  /* Loop on bands */
1203  for (bandno = 0; bandno < rlevel->nbands; bandno++) {
1204  int nb_precincts, precno;
1205  Jpeg2000Band *band = rlevel->band + bandno;
1206  int cblkno = 0, bandpos;
1207 
1208  bandpos = bandno + (reslevelno > 0);
1209 
1210  if (band->coord[0][0] == band->coord[0][1] ||
1211  band->coord[1][0] == band->coord[1][1])
1212  continue;
1213 
1214  nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
1215  /* Loop on precincts */
1216  for (precno = 0; precno < nb_precincts; precno++) {
1217  Jpeg2000Prec *prec = band->prec + precno;
1218 
1219  /* Loop on codeblocks */
1220  for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
1221  int x, y;
1222  Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1223  decode_cblk(s, codsty, &t1, cblk,
1224  cblk->coord[0][1] - cblk->coord[0][0],
1225  cblk->coord[1][1] - cblk->coord[1][0],
1226  bandpos);
1227 
1228  x = cblk->coord[0][0];
1229  y = cblk->coord[1][0];
1230 
1231  if (codsty->transform == FF_DWT97)
1232  dequantization_float(x, y, cblk, comp, &t1, band);
1233  else
1234  dequantization_int(x, y, cblk, comp, &t1, band);
1235  } /* end cblk */
1236  } /*end prec */
1237  } /* end band */
1238  } /* end reslevel */
1239 
1240  /* inverse DWT */
1241  ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
1242  } /*end comp */
1243 
1244  /* inverse MCT transformation */
1245  if (tile->codsty[0].mct)
1246  mct_decode(s, tile);
1247 
1248  for (x = 0; x < s->ncomponents; x++) {
1249  if (s->cdef[x] < 0) {
1250  for (x = 0; x < s->ncomponents; x++) {
1251  s->cdef[x] = x + 1;
1252  }
1253  if ((s->ncomponents & 1) == 0)
1254  s->cdef[s->ncomponents-1] = 0;
1255  break;
1256  }
1257  }
1258 
1259  if (s->precision <= 8) {
1260  for (compno = 0; compno < s->ncomponents; compno++) {
1261  Jpeg2000Component *comp = tile->comp + compno;
1262  Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1263  float *datap = comp->f_data;
1264  int32_t *i_datap = comp->i_data;
1265  int cbps = s->cbps[compno];
1266  int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1267  int plane = 0;
1268 
1269  if (planar)
1270  plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
1271 
1272 
1273  y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1274  line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane];
1275  for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1276  uint8_t *dst;
1277 
1278  x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1279  dst = line + x / s->cdx[compno] * pixelsize + compno*!planar;
1280 
1281  if (codsty->transform == FF_DWT97) {
1282  for (; x < w; x += s->cdx[compno]) {
1283  int val = lrintf(*datap) + (1 << (cbps - 1));
1284  /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1285  val = av_clip(val, 0, (1 << cbps) - 1);
1286  *dst = val << (8 - cbps);
1287  datap++;
1288  dst += pixelsize;
1289  }
1290  } else {
1291  for (; x < w; x += s->cdx[compno]) {
1292  int val = *i_datap + (1 << (cbps - 1));
1293  /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1294  val = av_clip(val, 0, (1 << cbps) - 1);
1295  *dst = val << (8 - cbps);
1296  i_datap++;
1297  dst += pixelsize;
1298  }
1299  }
1300  line += picture->linesize[plane];
1301  }
1302  }
1303  } else {
1304  for (compno = 0; compno < s->ncomponents; compno++) {
1305  Jpeg2000Component *comp = tile->comp + compno;
1306  Jpeg2000CodingStyle *codsty = tile->codsty + compno;
1307  float *datap = comp->f_data;
1308  int32_t *i_datap = comp->i_data;
1309  uint16_t *linel;
1310  int cbps = s->cbps[compno];
1311  int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
1312  int plane = 0;
1313 
1314  if (planar)
1315  plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
1316 
1317  y = tile->comp[compno].coord[1][0] - s->image_offset_y;
1318  linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1);
1319  for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
1320  uint16_t *dst;
1321 
1322  x = tile->comp[compno].coord[0][0] - s->image_offset_x;
1323  dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar);
1324  if (codsty->transform == FF_DWT97) {
1325  for (; x < w; x += s-> cdx[compno]) {
1326  int val = lrintf(*datap) + (1 << (cbps - 1));
1327  /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1328  val = av_clip(val, 0, (1 << cbps) - 1);
1329  /* align 12 bit values in little-endian mode */
1330  *dst = val << (16 - cbps);
1331  datap++;
1332  dst += pixelsize;
1333  }
1334  } else {
1335  for (; x < w; x += s-> cdx[compno]) {
1336  int val = *i_datap + (1 << (cbps - 1));
1337  /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
1338  val = av_clip(val, 0, (1 << cbps) - 1);
1339  /* align 12 bit values in little-endian mode */
1340  *dst = val << (16 - cbps);
1341  i_datap++;
1342  dst += pixelsize;
1343  }
1344  }
1345  linel += picture->linesize[plane] >> 1;
1346  }
1347  }
1348  }
1349 
1350  return 0;
1351 }
1352 
1354 {
1355  int tileno, compno;
1356  for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1357  if (s->tile[tileno].comp) {
1358  for (compno = 0; compno < s->ncomponents; compno++) {
1359  Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1360  Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
1361 
1362  ff_jpeg2000_cleanup(comp, codsty);
1363  }
1364  av_freep(&s->tile[tileno].comp);
1365  }
1366  }
1367  av_freep(&s->tile);
1368  memset(s->codsty, 0, sizeof(s->codsty));
1369  memset(s->qntsty, 0, sizeof(s->qntsty));
1370  s->numXtiles = s->numYtiles = 0;
1371  s->ncomponents = 0;
1372 }
1373 
1375 {
1376  Jpeg2000CodingStyle *codsty = s->codsty;
1377  Jpeg2000QuantStyle *qntsty = s->qntsty;
1378  uint8_t *properties = s->properties;
1379 
1380  for (;;) {
1381  int len, ret = 0;
1382  uint16_t marker;
1383  int oldpos;
1384 
1385  if (bytestream2_get_bytes_left(&s->g) < 2) {
1386  av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
1387  break;
1388  }
1389 
1390  marker = bytestream2_get_be16u(&s->g);
1391  oldpos = bytestream2_tell(&s->g);
1392 
1393  if (marker == JPEG2000_SOD) {
1394  Jpeg2000Tile *tile;
1395  Jpeg2000TilePart *tp;
1396 
1397  if (!s->tile) {
1398  av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
1399  return AVERROR_INVALIDDATA;
1400  }
1401  if (s->curtileno < 0) {
1402  av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
1403  return AVERROR_INVALIDDATA;
1404  }
1405 
1406  tile = s->tile + s->curtileno;
1407  tp = tile->tile_part + tile->tp_idx;
1408  if (tp->tp_end < s->g.buffer) {
1409  av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
1410  return AVERROR_INVALIDDATA;
1411  }
1412  bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
1413  bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
1414 
1415  continue;
1416  }
1417  if (marker == JPEG2000_EOC)
1418  break;
1419 
1420  len = bytestream2_get_be16(&s->g);
1421  if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
1422  return AVERROR_INVALIDDATA;
1423 
1424  switch (marker) {
1425  case JPEG2000_SIZ:
1426  if (s->ncomponents) {
1427  av_log(s->avctx, AV_LOG_ERROR, "Duplicate SIZ\n");
1428  return AVERROR_INVALIDDATA;
1429  }
1430  ret = get_siz(s);
1431  if (!s->tile)
1432  s->numXtiles = s->numYtiles = 0;
1433  break;
1434  case JPEG2000_COC:
1435  ret = get_coc(s, codsty, properties);
1436  break;
1437  case JPEG2000_COD:
1438  ret = get_cod(s, codsty, properties);
1439  break;
1440  case JPEG2000_QCC:
1441  ret = get_qcc(s, len, qntsty, properties);
1442  break;
1443  case JPEG2000_QCD:
1444  ret = get_qcd(s, len, qntsty, properties);
1445  break;
1446  case JPEG2000_SOT:
1447  if (!(ret = get_sot(s, len))) {
1448  av_assert1(s->curtileno >= 0);
1449  codsty = s->tile[s->curtileno].codsty;
1450  qntsty = s->tile[s->curtileno].qntsty;
1451  properties = s->tile[s->curtileno].properties;
1452  }
1453  break;
1454  case JPEG2000_COM:
1455  // the comment is ignored
1456  bytestream2_skip(&s->g, len - 2);
1457  break;
1458  case JPEG2000_TLM:
1459  // Tile-part lengths
1460  ret = get_tlm(s, len);
1461  break;
1462  default:
1464  "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
1465  marker, bytestream2_tell(&s->g) - 4);
1466  bytestream2_skip(&s->g, len - 2);
1467  break;
1468  }
1469  if (bytestream2_tell(&s->g) - oldpos != len || ret) {
1471  "error during processing marker segment %.4"PRIx16"\n",
1472  marker);
1473  return ret ? ret : -1;
1474  }
1475  }
1476  return 0;
1477 }
1478 
1479 /* Read bit stream packets --> T2 operation. */
1481 {
1482  int ret = 0;
1483  int tileno;
1484 
1485  for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
1486  Jpeg2000Tile *tile = s->tile + tileno;
1487 
1488  if (ret = init_tile(s, tileno))
1489  return ret;
1490 
1491  s->g = tile->tile_part[0].tpg;
1492  if (ret = jpeg2000_decode_packets(s, tile))
1493  return ret;
1494  }
1495 
1496  return 0;
1497 }
1498 
1500 {
1501  uint32_t atom_size, atom, atom_end;
1502  int search_range = 10;
1503 
1504  while (search_range
1505  &&
1506  bytestream2_get_bytes_left(&s->g) >= 8) {
1507  atom_size = bytestream2_get_be32u(&s->g);
1508  atom = bytestream2_get_be32u(&s->g);
1509  atom_end = bytestream2_tell(&s->g) + atom_size - 8;
1510 
1511  if (atom == JP2_CODESTREAM)
1512  return 1;
1513 
1514  if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
1515  return 0;
1516 
1517  if (atom == JP2_HEADER &&
1518  atom_size >= 16) {
1519  uint32_t atom2_size, atom2, atom2_end;
1520  do {
1521  atom2_size = bytestream2_get_be32u(&s->g);
1522  atom2 = bytestream2_get_be32u(&s->g);
1523  atom2_end = bytestream2_tell(&s->g) + atom2_size - 8;
1524  if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
1525  break;
1526  if (atom2 == JP2_CODESTREAM) {
1527  return 1;
1528  } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
1529  int method = bytestream2_get_byteu(&s->g);
1530  bytestream2_skipu(&s->g, 2);
1531  if (method == 1) {
1532  s->colour_space = bytestream2_get_be32u(&s->g);
1533  }
1534  } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
1535  int i, size, colour_count, colour_channels, colour_depth[3];
1536  uint32_t r, g, b;
1537  colour_count = bytestream2_get_be16u(&s->g);
1538  colour_channels = bytestream2_get_byteu(&s->g);
1539  // FIXME: Do not ignore channel_sign
1540  colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1541  colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1542  colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
1543  size = (colour_depth[0] + 7 >> 3) * colour_count +
1544  (colour_depth[1] + 7 >> 3) * colour_count +
1545  (colour_depth[2] + 7 >> 3) * colour_count;
1546  if (colour_count > 256 ||
1547  colour_channels != 3 ||
1548  colour_depth[0] > 16 ||
1549  colour_depth[1] > 16 ||
1550  colour_depth[2] > 16 ||
1551  atom2_size < size) {
1552  avpriv_request_sample(s->avctx, "Unknown palette");
1553  bytestream2_seek(&s->g, atom2_end, SEEK_SET);
1554  continue;
1555  }
1556  s->pal8 = 1;
1557  for (i = 0; i < colour_count; i++) {
1558  if (colour_depth[0] <= 8) {
1559  r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
1560  r |= r >> colour_depth[0];
1561  } else {
1562  r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
1563  }
1564  if (colour_depth[1] <= 8) {
1565  g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
1566  r |= r >> colour_depth[1];
1567  } else {
1568  g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
1569  }
1570  if (colour_depth[2] <= 8) {
1571  b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
1572  r |= r >> colour_depth[2];
1573  } else {
1574  b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
1575  }
1576  s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
1577  }
1578  } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
1579  int n = bytestream2_get_be16u(&s->g);
1580  for (; n>0; n--) {
1581  int cn = bytestream2_get_be16(&s->g);
1582  int av_unused typ = bytestream2_get_be16(&s->g);
1583  int asoc = bytestream2_get_be16(&s->g);
1584  if (cn < 4 && asoc < 4)
1585  s->cdef[cn] = asoc;
1586  }
1587  }
1588  bytestream2_seek(&s->g, atom2_end, SEEK_SET);
1589  } while (atom_end - atom2_end >= 8);
1590  } else {
1591  search_range--;
1592  }
1593  bytestream2_seek(&s->g, atom_end, SEEK_SET);
1594  }
1595 
1596  return 0;
1597 }
1598 
1600 {
1602 
1603  ff_jpeg2000dsp_init(&s->dsp);
1604 
1605  return 0;
1606 }
1607 
1608 static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
1609  int *got_frame, AVPacket *avpkt)
1610 {
1612  ThreadFrame frame = { .f = data };
1613  AVFrame *picture = data;
1614  int tileno, ret;
1615 
1616  s->avctx = avctx;
1617  bytestream2_init(&s->g, avpkt->data, avpkt->size);
1618  s->curtileno = -1;
1619  memset(s->cdef, -1, sizeof(s->cdef));
1620 
1621  if (bytestream2_get_bytes_left(&s->g) < 2) {
1622  ret = AVERROR_INVALIDDATA;
1623  goto end;
1624  }
1625 
1626  // check if the image is in jp2 format
1627  if (bytestream2_get_bytes_left(&s->g) >= 12 &&
1628  (bytestream2_get_be32u(&s->g) == 12) &&
1629  (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
1630  (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
1631  if (!jp2_find_codestream(s)) {
1632  av_log(avctx, AV_LOG_ERROR,
1633  "Could not find Jpeg2000 codestream atom.\n");
1634  ret = AVERROR_INVALIDDATA;
1635  goto end;
1636  }
1637  } else {
1638  bytestream2_seek(&s->g, 0, SEEK_SET);
1639  }
1640 
1641  while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
1642  bytestream2_skip(&s->g, 1);
1643 
1644  if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
1645  av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
1646  ret = AVERROR_INVALIDDATA;
1647  goto end;
1648  }
1649  if (ret = jpeg2000_read_main_headers(s))
1650  goto end;
1651 
1652  /* get picture buffer */
1653  if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1654  goto end;
1655  picture->pict_type = AV_PICTURE_TYPE_I;
1656  picture->key_frame = 1;
1657 
1658  if (ret = jpeg2000_read_bitstream_packets(s))
1659  goto end;
1660 
1661  for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
1662  if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
1663  goto end;
1664 
1666 
1667  *got_frame = 1;
1668 
1669  if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
1670  memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
1671 
1672  return bytestream2_tell(&s->g);
1673 
1674 end:
1676  return ret;
1677 }
1678 
1680 {
1683 }
1684 
1685 #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
1686 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1687 
1688 static const AVOption options[] = {
1689  { "lowres", "Lower the decoding resolution by a power of two",
1690  OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
1691  { NULL },
1692 };
1693 
1694 static const AVProfile profiles[] = {
1695  { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
1696  { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
1697  { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
1698  { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
1699  { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
1700  { FF_PROFILE_UNKNOWN },
1701 };
1702 
1703 static const AVClass jpeg2000_class = {
1704  .class_name = "jpeg2000",
1705  .item_name = av_default_item_name,
1706  .option = options,
1707  .version = LIBAVUTIL_VERSION_INT,
1708 };
1709 
1711  .name = "jpeg2000",
1712  .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1713  .type = AVMEDIA_TYPE_VIDEO,
1714  .id = AV_CODEC_ID_JPEG2000,
1715  .capabilities = CODEC_CAP_FRAME_THREADS,
1716  .priv_data_size = sizeof(Jpeg2000DecoderContext),
1720  .priv_class = &jpeg2000_class,
1721  .max_lowres = 5,
1722  .profiles = NULL_IF_CONFIG_SMALL(profiles)
1723 };