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.

1494 lines
52KB

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