You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1738 lines
64KB

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