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.

1516 lines
53KB

  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 Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; 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/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[3];
  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. int16_t 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_INVALIDDATA;
  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 > 3) {
  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. s->tile_width > s->width || s->tile_height > s->height) {
  166. av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
  167. s->tile_width, s->tile_height);
  168. return AVERROR_INVALIDDATA;
  169. }
  170. if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
  171. return AVERROR_INVALIDDATA;
  172. for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
  173. uint8_t x = bytestream2_get_byteu(&s->g);
  174. s->cbps[i] = (x & 0x7f) + 1;
  175. s->precision = FFMAX(s->cbps[i], s->precision);
  176. s->sgnd[i] = !!(x & 0x80);
  177. s->cdx[i] = bytestream2_get_byteu(&s->g);
  178. s->cdy[i] = bytestream2_get_byteu(&s->g);
  179. if (s->cdx[i] != 1 || s->cdy[i] != 1) {
  180. avpriv_request_sample(s->avctx,
  181. "CDxy values %d %d for component %d",
  182. s->cdx[i], s->cdy[i], i);
  183. if (!s->cdx[i] || !s->cdy[i])
  184. return AVERROR_INVALIDDATA;
  185. else
  186. return AVERROR_PATCHWELCOME;
  187. }
  188. }
  189. s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
  190. s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
  191. s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
  192. if (!s->tile) {
  193. s->numXtiles = s->numYtiles = 0;
  194. return AVERROR(ENOMEM);
  195. }
  196. for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
  197. Jpeg2000Tile *tile = s->tile + i;
  198. tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
  199. if (!tile->comp)
  200. return AVERROR(ENOMEM);
  201. }
  202. /* compute image size with reduction factor */
  203. s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
  204. s->reduction_factor);
  205. s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
  206. s->reduction_factor);
  207. switch (s->ncomponents) {
  208. case 1:
  209. if (s->precision > 8)
  210. s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
  211. else
  212. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  213. break;
  214. case 3:
  215. switch (s->avctx->profile) {
  216. case FF_PROFILE_JPEG2000_DCINEMA_2K:
  217. case FF_PROFILE_JPEG2000_DCINEMA_4K:
  218. /* XYZ color-space for digital cinema profiles */
  219. s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;
  220. break;
  221. default:
  222. if (s->precision > 8)
  223. s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
  224. else
  225. s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
  226. break;
  227. }
  228. break;
  229. case 4:
  230. s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
  231. break;
  232. default:
  233. /* pixel format can not be identified */
  234. s->avctx->pix_fmt = AV_PIX_FMT_NONE;
  235. break;
  236. }
  237. return 0;
  238. }
  239. /* get common part for COD and COC segments */
  240. static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
  241. {
  242. uint8_t byte;
  243. if (bytestream2_get_bytes_left(&s->g) < 5)
  244. return AVERROR_INVALIDDATA;
  245. /* nreslevels = number of resolution levels
  246. = number of decomposition level +1 */
  247. c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
  248. if (c->nreslevels > JPEG2000_MAX_RESLEVELS)
  249. return AVERROR_INVALIDDATA;
  250. /* compute number of resolution levels to decode */
  251. if (c->nreslevels < s->reduction_factor)
  252. c->nreslevels2decode = 1;
  253. else
  254. c->nreslevels2decode = c->nreslevels - s->reduction_factor;
  255. c->log2_cblk_width = bytestream2_get_byteu(&s->g) + 2; // cblk width
  256. c->log2_cblk_height = bytestream2_get_byteu(&s->g) + 2; // cblk height
  257. if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
  258. c->log2_cblk_width + c->log2_cblk_height > 12) {
  259. av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
  260. return AVERROR_INVALIDDATA;
  261. }
  262. c->cblk_style = bytestream2_get_byteu(&s->g);
  263. if (c->cblk_style != 0) { // cblk style
  264. avpriv_request_sample(s->avctx, "Support for extra cblk styles");
  265. return AVERROR_PATCHWELCOME;
  266. }
  267. c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
  268. /* set integer 9/7 DWT in case of BITEXACT flag */
  269. if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
  270. c->transform = FF_DWT97_INT;
  271. if (c->csty & JPEG2000_CSTY_PREC) {
  272. int i;
  273. for (i = 0; i < c->nreslevels; i++) {
  274. byte = bytestream2_get_byte(&s->g);
  275. c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
  276. c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
  277. }
  278. } else {
  279. memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
  280. memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
  281. }
  282. return 0;
  283. }
  284. /* get coding parameters for a particular tile or whole image*/
  285. static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  286. uint8_t *properties)
  287. {
  288. Jpeg2000CodingStyle tmp;
  289. int compno, ret;
  290. if (bytestream2_get_bytes_left(&s->g) < 5)
  291. return AVERROR_INVALIDDATA;
  292. tmp.csty = bytestream2_get_byteu(&s->g);
  293. // get progression order
  294. tmp.prog_order = bytestream2_get_byteu(&s->g);
  295. tmp.nlayers = bytestream2_get_be16u(&s->g);
  296. tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
  297. if (tmp.mct && s->ncomponents < 3) {
  298. av_log(s->avctx, AV_LOG_ERROR,
  299. "MCT %"PRIu8" with too few components (%d)\n",
  300. tmp.mct, s->ncomponents);
  301. return AVERROR_INVALIDDATA;
  302. }
  303. if ((ret = get_cox(s, &tmp)) < 0)
  304. return ret;
  305. for (compno = 0; compno < s->ncomponents; compno++)
  306. if (!(properties[compno] & HAD_COC))
  307. memcpy(c + compno, &tmp, sizeof(tmp));
  308. return 0;
  309. }
  310. /* Get coding parameters for a component in the whole image or a
  311. * particular tile. */
  312. static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  313. uint8_t *properties)
  314. {
  315. int compno, ret;
  316. if (bytestream2_get_bytes_left(&s->g) < 2)
  317. return AVERROR_INVALIDDATA;
  318. compno = bytestream2_get_byteu(&s->g);
  319. if (compno >= s->ncomponents) {
  320. av_log(s->avctx, AV_LOG_ERROR,
  321. "Invalid compno %d. There are %d components in the image.\n",
  322. compno, s->ncomponents);
  323. return AVERROR_INVALIDDATA;
  324. }
  325. c += compno;
  326. c->csty = bytestream2_get_byteu(&s->g);
  327. if ((ret = get_cox(s, c)) < 0)
  328. return ret;
  329. properties[compno] |= HAD_COC;
  330. return 0;
  331. }
  332. /* Get common part for QCD and QCC segments. */
  333. static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
  334. {
  335. int i, x;
  336. if (bytestream2_get_bytes_left(&s->g) < 1)
  337. return AVERROR_INVALIDDATA;
  338. x = bytestream2_get_byteu(&s->g); // Sqcd
  339. q->nguardbits = x >> 5;
  340. q->quantsty = x & 0x1f;
  341. if (q->quantsty == JPEG2000_QSTY_NONE) {
  342. n -= 3;
  343. if (bytestream2_get_bytes_left(&s->g) < n ||
  344. n > JPEG2000_MAX_DECLEVELS)
  345. return AVERROR_INVALIDDATA;
  346. for (i = 0; i < n; i++)
  347. q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
  348. } else if (q->quantsty == JPEG2000_QSTY_SI) {
  349. if (bytestream2_get_bytes_left(&s->g) < 2)
  350. return AVERROR_INVALIDDATA;
  351. x = bytestream2_get_be16u(&s->g);
  352. q->expn[0] = x >> 11;
  353. q->mant[0] = x & 0x7ff;
  354. for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
  355. int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
  356. q->expn[i] = curexpn;
  357. q->mant[i] = q->mant[0];
  358. }
  359. } else {
  360. n = (n - 3) >> 1;
  361. if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
  362. n > JPEG2000_MAX_DECLEVELS)
  363. return AVERROR_INVALIDDATA;
  364. for (i = 0; i < n; i++) {
  365. x = bytestream2_get_be16u(&s->g);
  366. q->expn[i] = x >> 11;
  367. q->mant[i] = x & 0x7ff;
  368. }
  369. }
  370. return 0;
  371. }
  372. /* Get quantization parameters for a particular tile or a whole image. */
  373. static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  374. uint8_t *properties)
  375. {
  376. Jpeg2000QuantStyle tmp;
  377. int compno, ret;
  378. if ((ret = get_qcx(s, n, &tmp)) < 0)
  379. return ret;
  380. for (compno = 0; compno < s->ncomponents; compno++)
  381. if (!(properties[compno] & HAD_QCC))
  382. memcpy(q + compno, &tmp, sizeof(tmp));
  383. return 0;
  384. }
  385. /* Get quantization parameters for a component in the whole image
  386. * on in a particular tile. */
  387. static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  388. uint8_t *properties)
  389. {
  390. int compno;
  391. if (bytestream2_get_bytes_left(&s->g) < 1)
  392. return AVERROR_INVALIDDATA;
  393. compno = bytestream2_get_byteu(&s->g);
  394. if (compno >= s->ncomponents) {
  395. av_log(s->avctx, AV_LOG_ERROR,
  396. "Invalid compno %d. There are %d components in the image.\n",
  397. compno, s->ncomponents);
  398. return AVERROR_INVALIDDATA;
  399. }
  400. properties[compno] |= HAD_QCC;
  401. return get_qcx(s, n - 1, q + compno);
  402. }
  403. /* Get start of tile segment. */
  404. static int get_sot(Jpeg2000DecoderContext *s, int n)
  405. {
  406. Jpeg2000TilePart *tp;
  407. uint16_t Isot;
  408. uint32_t Psot;
  409. uint8_t TPsot;
  410. if (bytestream2_get_bytes_left(&s->g) < 8)
  411. return AVERROR_INVALIDDATA;
  412. Isot = bytestream2_get_be16u(&s->g); // Isot
  413. if (Isot >= s->numXtiles * s->numYtiles)
  414. return AVERROR_INVALIDDATA;
  415. if (Isot) {
  416. avpriv_request_sample(s->avctx, "Support for more than one tile");
  417. return AVERROR_PATCHWELCOME;
  418. }
  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 %"PRIu32" 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 %"PRIu8" components", TPsot);
  429. return AVERROR_PATCHWELCOME;
  430. }
  431. s->tile[Isot].tp_idx = TPsot;
  432. tp = s->tile[Isot].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. return AVERROR_INVALIDDATA;
  608. /* Code-block data can be empty. In that case initialize data
  609. * with 0xFFFF. */
  610. if (cblk->lengthinc > 0) {
  611. bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
  612. } else {
  613. cblk->data[0] = 0xFF;
  614. cblk->data[1] = 0xFF;
  615. }
  616. cblk->length += cblk->lengthinc;
  617. cblk->lengthinc = 0;
  618. if (cblk->length > sizeof(cblk->data)) {
  619. av_log(s->avctx, AV_LOG_ERROR,
  620. "Block length %"PRIu16" > data size %zd\n",
  621. cblk->length, sizeof(cblk->data));
  622. return AVERROR_INVALIDDATA;
  623. }
  624. }
  625. }
  626. return 0;
  627. }
  628. static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  629. {
  630. int ret = 0;
  631. int layno, reslevelno, compno, precno, ok_reslevel;
  632. int x, y;
  633. s->bit_index = 8;
  634. switch (tile->codsty[0].prog_order) {
  635. case JPEG2000_PGOD_LRCP:
  636. for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
  637. ok_reslevel = 1;
  638. for (reslevelno = 0; ok_reslevel; reslevelno++) {
  639. ok_reslevel = 0;
  640. for (compno = 0; compno < s->ncomponents; compno++) {
  641. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  642. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  643. if (reslevelno < codsty->nreslevels) {
  644. Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
  645. reslevelno;
  646. ok_reslevel = 1;
  647. for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
  648. if ((ret = jpeg2000_decode_packet(s,
  649. codsty, rlevel,
  650. precno, layno,
  651. qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  652. qntsty->nguardbits)) < 0)
  653. return ret;
  654. }
  655. }
  656. }
  657. }
  658. break;
  659. case JPEG2000_PGOD_CPRL:
  660. for (compno = 0; compno < s->ncomponents; compno++) {
  661. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  662. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  663. /* Set bit stream buffer address according to tile-part.
  664. * For DCinema one tile-part per component, so can be
  665. * indexed by component. */
  666. s->g = tile->tile_part[compno].tpg;
  667. /* Position loop (y axis)
  668. * TODO: Automate computing of step 256.
  669. * Fixed here, but to be computed before entering here. */
  670. for (y = 0; y < s->height; y += 256) {
  671. /* Position loop (y axis)
  672. * TODO: automate computing of step 256.
  673. * Fixed here, but to be computed before entering here. */
  674. for (x = 0; x < s->width; x += 256) {
  675. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  676. uint16_t prcx, prcy;
  677. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  678. Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
  679. if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
  680. (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
  681. continue;
  682. if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
  683. (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
  684. continue;
  685. // check if a precinct exists
  686. prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
  687. prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
  688. precno = prcx + rlevel->num_precincts_x * prcy;
  689. for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
  690. if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
  691. precno, layno,
  692. qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  693. qntsty->nguardbits)) < 0)
  694. return ret;
  695. }
  696. }
  697. }
  698. }
  699. }
  700. break;
  701. case JPEG2000_PGOD_RLCP:
  702. avpriv_request_sample(s->avctx, "Progression order RLCP");
  703. ret = AVERROR_PATCHWELCOME;
  704. break;
  705. case JPEG2000_PGOD_RPCL:
  706. avpriv_request_sample(s->avctx, "Progression order RPCL");
  707. ret = AVERROR_PATCHWELCOME;
  708. break;
  709. case JPEG2000_PGOD_PCRL:
  710. avpriv_request_sample(s->avctx, "Progression order PCRL");
  711. ret = AVERROR_PATCHWELCOME;
  712. break;
  713. default:
  714. break;
  715. }
  716. /* EOC marker reached */
  717. bytestream2_skip(&s->g, 2);
  718. return ret;
  719. }
  720. /* TIER-1 routines */
  721. static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
  722. int bpno, int bandno, int bpass_csty_symbol,
  723. int vert_causal_ctx_csty_symbol)
  724. {
  725. int mask = 3 << (bpno - 1), y0, x, y;
  726. for (y0 = 0; y0 < height; y0 += 4)
  727. for (x = 0; x < width; x++)
  728. for (y = y0; y < height && y < y0 + 4; y++) {
  729. if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
  730. && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  731. int flags_mask = -1;
  732. if (vert_causal_ctx_csty_symbol && y == y0 + 3)
  733. flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
  734. if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
  735. int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
  736. if (bpass_csty_symbol)
  737. t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
  738. else
  739. t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
  740. -mask : mask;
  741. ff_jpeg2000_set_significance(t1, x, y,
  742. t1->data[y][x] < 0);
  743. }
  744. t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
  745. }
  746. }
  747. }
  748. static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
  749. int bpno)
  750. {
  751. int phalf, nhalf;
  752. int y0, x, y;
  753. phalf = 1 << (bpno - 1);
  754. nhalf = -phalf;
  755. for (y0 = 0; y0 < height; y0 += 4)
  756. for (x = 0; x < width; x++)
  757. for (y = y0; y < height && y < y0 + 4; y++)
  758. if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
  759. int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
  760. int r = ff_mqc_decode(&t1->mqc,
  761. t1->mqc.cx_states + ctxno)
  762. ? phalf : nhalf;
  763. t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
  764. t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
  765. }
  766. }
  767. static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
  768. int width, int height, int bpno, int bandno,
  769. int seg_symbols, int vert_causal_ctx_csty_symbol)
  770. {
  771. int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
  772. for (y0 = 0; y0 < height; y0 += 4) {
  773. for (x = 0; x < width; x++) {
  774. if (y0 + 3 < height &&
  775. !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  776. (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  777. (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  778. (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
  779. if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
  780. continue;
  781. runlen = ff_mqc_decode(&t1->mqc,
  782. t1->mqc.cx_states + MQC_CX_UNI);
  783. runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
  784. t1->mqc.cx_states +
  785. MQC_CX_UNI);
  786. dec = 1;
  787. } else {
  788. runlen = 0;
  789. dec = 0;
  790. }
  791. for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
  792. if (!dec) {
  793. if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  794. int flags_mask = -1;
  795. if (vert_causal_ctx_csty_symbol && y == y0 + 3)
  796. flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
  797. dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
  798. bandno));
  799. }
  800. }
  801. if (dec) {
  802. int xorbit;
  803. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
  804. &xorbit);
  805. t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
  806. t1->mqc.cx_states + ctxno) ^
  807. xorbit)
  808. ? -mask : mask;
  809. ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
  810. }
  811. dec = 0;
  812. t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
  813. }
  814. }
  815. }
  816. if (seg_symbols) {
  817. int val;
  818. val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  819. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  820. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  821. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  822. if (val != 0xa)
  823. av_log(s->avctx, AV_LOG_ERROR,
  824. "Segmentation symbol value incorrect\n");
  825. }
  826. }
  827. static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
  828. Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
  829. int width, int height, int bandpos)
  830. {
  831. int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
  832. int clnpass_cnt = 0;
  833. int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
  834. int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
  835. for (y = 0; y < height; y++)
  836. memset(t1->data[y], 0, width * sizeof(**t1->data));
  837. /* If code-block contains no compressed data: nothing to do. */
  838. if (!cblk->length)
  839. return 0;
  840. for (y = 0; y < height + 2; y++)
  841. memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
  842. ff_mqc_initdec(&t1->mqc, cblk->data);
  843. cblk->data[cblk->length] = 0xff;
  844. cblk->data[cblk->length + 1] = 0xff;
  845. while (passno--) {
  846. switch (pass_t) {
  847. case 0:
  848. decode_sigpass(t1, width, height, bpno + 1, bandpos,
  849. bpass_csty_symbol && (clnpass_cnt >= 4),
  850. vert_causal_ctx_csty_symbol);
  851. break;
  852. case 1:
  853. decode_refpass(t1, width, height, bpno + 1);
  854. if (bpass_csty_symbol && clnpass_cnt >= 4)
  855. ff_mqc_initdec(&t1->mqc, cblk->data);
  856. break;
  857. case 2:
  858. decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
  859. codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
  860. vert_causal_ctx_csty_symbol);
  861. clnpass_cnt = clnpass_cnt + 1;
  862. if (bpass_csty_symbol && clnpass_cnt >= 4)
  863. ff_mqc_initdec(&t1->mqc, cblk->data);
  864. break;
  865. }
  866. pass_t++;
  867. if (pass_t == 3) {
  868. bpno--;
  869. pass_t = 0;
  870. }
  871. }
  872. return 0;
  873. }
  874. /* TODO: Verify dequantization for lossless case
  875. * comp->data can be float or int
  876. * band->stepsize can be float or int
  877. * depending on the type of DWT transformation.
  878. * see ISO/IEC 15444-1:2002 A.6.1 */
  879. /* Float dequantization of a codeblock.*/
  880. static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
  881. Jpeg2000Component *comp,
  882. Jpeg2000T1Context *t1, Jpeg2000Band *band)
  883. {
  884. int i, j;
  885. int w = cblk->coord[0][1] - cblk->coord[0][0];
  886. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  887. float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
  888. int *src = t1->data[j];
  889. for (i = 0; i < w; ++i)
  890. datap[i] = src[i] * band->f_stepsize;
  891. }
  892. }
  893. /* Integer dequantization of a codeblock.*/
  894. static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
  895. Jpeg2000Component *comp,
  896. Jpeg2000T1Context *t1, Jpeg2000Band *band)
  897. {
  898. int i, j;
  899. int w = cblk->coord[0][1] - cblk->coord[0][0];
  900. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  901. int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
  902. int *src = t1->data[j];
  903. for (i = 0; i < w; ++i)
  904. datap[i] = (src[i] * band->i_stepsize + (1 << 15)) >> 16;
  905. }
  906. }
  907. /* Inverse ICT parameters in float and integer.
  908. * int value = (float value) * (1<<16) */
  909. static const float f_ict_params[4] = {
  910. 1.402f,
  911. 0.34413f,
  912. 0.71414f,
  913. 1.772f
  914. };
  915. static const int i_ict_params[4] = {
  916. 91881,
  917. 22553,
  918. 46802,
  919. 116130
  920. };
  921. static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  922. {
  923. int i, csize = 1;
  924. int32_t *src[3], i0, i1, i2;
  925. float *srcf[3], i0f, i1f, i2f;
  926. for (i = 0; i < 3; i++)
  927. if (tile->codsty[0].transform == FF_DWT97)
  928. srcf[i] = tile->comp[i].f_data;
  929. else
  930. src [i] = tile->comp[i].i_data;
  931. for (i = 0; i < 2; i++)
  932. csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
  933. switch (tile->codsty[0].transform) {
  934. case FF_DWT97:
  935. for (i = 0; i < csize; i++) {
  936. i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
  937. i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
  938. - (f_ict_params[2] * *srcf[2]);
  939. i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
  940. *srcf[0]++ = i0f;
  941. *srcf[1]++ = i1f;
  942. *srcf[2]++ = i2f;
  943. }
  944. break;
  945. case FF_DWT97_INT:
  946. for (i = 0; i < csize; i++) {
  947. i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
  948. i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
  949. - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
  950. i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
  951. *src[0]++ = i0;
  952. *src[1]++ = i1;
  953. *src[2]++ = i2;
  954. }
  955. break;
  956. case FF_DWT53:
  957. for (i = 0; i < csize; i++) {
  958. i1 = *src[0] - (*src[2] + *src[1] >> 2);
  959. i0 = i1 + *src[2];
  960. i2 = i1 + *src[1];
  961. *src[0]++ = i0;
  962. *src[1]++ = i1;
  963. *src[2]++ = i2;
  964. }
  965. break;
  966. }
  967. }
  968. static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
  969. AVFrame *picture)
  970. {
  971. int compno, reslevelno, bandno;
  972. int x, y;
  973. uint8_t *line;
  974. Jpeg2000T1Context t1;
  975. /* Loop on tile components */
  976. for (compno = 0; compno < s->ncomponents; compno++) {
  977. Jpeg2000Component *comp = tile->comp + compno;
  978. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  979. /* Loop on resolution levels */
  980. for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
  981. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  982. /* Loop on bands */
  983. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  984. uint16_t nb_precincts, precno;
  985. Jpeg2000Band *band = rlevel->band + bandno;
  986. int cblkno = 0, bandpos;
  987. bandpos = bandno + (reslevelno > 0);
  988. if (band->coord[0][0] == band->coord[0][1] ||
  989. band->coord[1][0] == band->coord[1][1])
  990. continue;
  991. nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
  992. /* Loop on precincts */
  993. for (precno = 0; precno < nb_precincts; precno++) {
  994. Jpeg2000Prec *prec = band->prec + precno;
  995. /* Loop on codeblocks */
  996. for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
  997. int x, y;
  998. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  999. decode_cblk(s, codsty, &t1, cblk,
  1000. cblk->coord[0][1] - cblk->coord[0][0],
  1001. cblk->coord[1][1] - cblk->coord[1][0],
  1002. bandpos);
  1003. x = cblk->coord[0][0];
  1004. y = cblk->coord[1][0];
  1005. if (codsty->transform == FF_DWT97)
  1006. dequantization_float(x, y, cblk, comp, &t1, band);
  1007. else
  1008. dequantization_int(x, y, cblk, comp, &t1, band);
  1009. } /* end cblk */
  1010. } /*end prec */
  1011. } /* end band */
  1012. } /* end reslevel */
  1013. /* inverse DWT */
  1014. ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
  1015. } /*end comp */
  1016. /* inverse MCT transformation */
  1017. if (tile->codsty[0].mct)
  1018. mct_decode(s, tile);
  1019. if (s->precision <= 8) {
  1020. for (compno = 0; compno < s->ncomponents; compno++) {
  1021. Jpeg2000Component *comp = tile->comp + compno;
  1022. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1023. float *datap = comp->f_data;
  1024. int32_t *i_datap = comp->i_data;
  1025. int cbps = s->cbps[compno];
  1026. int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
  1027. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  1028. line = picture->data[0] + y * picture->linesize[0];
  1029. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  1030. uint8_t *dst;
  1031. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  1032. dst = line + x * s->ncomponents + compno;
  1033. if (codsty->transform == FF_DWT97) {
  1034. for (; x < w; x += s->cdx[compno]) {
  1035. int val = lrintf(*datap) + (1 << (cbps - 1));
  1036. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1037. val = av_clip(val, 0, (1 << cbps) - 1);
  1038. *dst = val << (8 - cbps);
  1039. datap++;
  1040. dst += s->ncomponents;
  1041. }
  1042. } else {
  1043. for (; x < w; x += s->cdx[compno]) {
  1044. int val = *i_datap + (1 << (cbps - 1));
  1045. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1046. val = av_clip(val, 0, (1 << cbps) - 1);
  1047. *dst = val << (8 - cbps);
  1048. i_datap++;
  1049. dst += s->ncomponents;
  1050. }
  1051. }
  1052. line += picture->linesize[0];
  1053. }
  1054. }
  1055. } else {
  1056. for (compno = 0; compno < s->ncomponents; compno++) {
  1057. Jpeg2000Component *comp = tile->comp + compno;
  1058. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  1059. float *datap = comp->f_data;
  1060. int32_t *i_datap = comp->i_data;
  1061. uint16_t *linel;
  1062. int cbps = s->cbps[compno];
  1063. int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
  1064. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  1065. linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
  1066. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  1067. uint16_t *dst;
  1068. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  1069. dst = linel + (x * s->ncomponents + compno);
  1070. if (codsty->transform == FF_DWT97) {
  1071. for (; x < w; x += s-> cdx[compno]) {
  1072. int val = lrintf(*datap) + (1 << (cbps - 1));
  1073. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1074. val = av_clip(val, 0, (1 << cbps) - 1);
  1075. /* align 12 bit values in little-endian mode */
  1076. *dst = val << (16 - cbps);
  1077. datap++;
  1078. dst += s->ncomponents;
  1079. }
  1080. } else {
  1081. for (; x < w; x += s-> cdx[compno]) {
  1082. int val = *i_datap + (1 << (cbps - 1));
  1083. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1084. val = av_clip(val, 0, (1 << cbps) - 1);
  1085. /* align 12 bit values in little-endian mode */
  1086. *dst = val << (16 - cbps);
  1087. i_datap++;
  1088. dst += s->ncomponents;
  1089. }
  1090. }
  1091. linel += picture->linesize[0] >> 1;
  1092. }
  1093. }
  1094. }
  1095. return 0;
  1096. }
  1097. static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
  1098. {
  1099. int tileno, compno;
  1100. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  1101. for (compno = 0; compno < s->ncomponents; compno++) {
  1102. Jpeg2000Component *comp = s->tile[tileno].comp + compno;
  1103. Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
  1104. ff_jpeg2000_cleanup(comp, codsty);
  1105. }
  1106. av_freep(&s->tile[tileno].comp);
  1107. }
  1108. av_freep(&s->tile);
  1109. s->numXtiles = s->numYtiles = 0;
  1110. }
  1111. static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
  1112. {
  1113. Jpeg2000CodingStyle *codsty = s->codsty;
  1114. Jpeg2000QuantStyle *qntsty = s->qntsty;
  1115. uint8_t *properties = s->properties;
  1116. for (;;) {
  1117. int len, ret = 0;
  1118. uint16_t marker;
  1119. int oldpos;
  1120. if (bytestream2_get_bytes_left(&s->g) < 2) {
  1121. av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
  1122. break;
  1123. }
  1124. marker = bytestream2_get_be16u(&s->g);
  1125. oldpos = bytestream2_tell(&s->g);
  1126. if (marker == JPEG2000_SOD) {
  1127. Jpeg2000Tile *tile;
  1128. Jpeg2000TilePart *tp;
  1129. if (s->curtileno < 0) {
  1130. av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
  1131. return AVERROR_INVALIDDATA;
  1132. }
  1133. if (!s->tile) {
  1134. av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
  1135. return AVERROR_INVALIDDATA;
  1136. }
  1137. tile = s->tile + s->curtileno;
  1138. tp = tile->tile_part + tile->tp_idx;
  1139. bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
  1140. bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
  1141. continue;
  1142. }
  1143. if (marker == JPEG2000_EOC)
  1144. break;
  1145. len = bytestream2_get_be16u(&s->g);
  1146. if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
  1147. return AVERROR_INVALIDDATA;
  1148. switch (marker) {
  1149. case JPEG2000_SIZ:
  1150. ret = get_siz(s);
  1151. break;
  1152. case JPEG2000_COC:
  1153. ret = get_coc(s, codsty, properties);
  1154. break;
  1155. case JPEG2000_COD:
  1156. ret = get_cod(s, codsty, properties);
  1157. break;
  1158. case JPEG2000_QCC:
  1159. ret = get_qcc(s, len, qntsty, properties);
  1160. break;
  1161. case JPEG2000_QCD:
  1162. ret = get_qcd(s, len, qntsty, properties);
  1163. break;
  1164. case JPEG2000_SOT:
  1165. if (!(ret = get_sot(s, len))) {
  1166. codsty = s->tile[s->curtileno].codsty;
  1167. qntsty = s->tile[s->curtileno].qntsty;
  1168. properties = s->tile[s->curtileno].properties;
  1169. }
  1170. break;
  1171. case JPEG2000_COM:
  1172. // the comment is ignored
  1173. bytestream2_skip(&s->g, len - 2);
  1174. break;
  1175. case JPEG2000_TLM:
  1176. // Tile-part lengths
  1177. ret = get_tlm(s, len);
  1178. break;
  1179. default:
  1180. av_log(s->avctx, AV_LOG_ERROR,
  1181. "unsupported marker 0x%.4"PRIX16" at pos 0x%X\n",
  1182. marker, bytestream2_tell(&s->g) - 4);
  1183. bytestream2_skip(&s->g, len - 2);
  1184. break;
  1185. }
  1186. if (bytestream2_tell(&s->g) - oldpos != len || ret) {
  1187. av_log(s->avctx, AV_LOG_ERROR,
  1188. "error during processing marker segment %.4"PRIx16"\n",
  1189. marker);
  1190. return ret ? ret : -1;
  1191. }
  1192. }
  1193. return 0;
  1194. }
  1195. /* Read bit stream packets --> T2 operation. */
  1196. static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
  1197. {
  1198. int ret = 0;
  1199. int tileno;
  1200. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  1201. Jpeg2000Tile *tile = s->tile + tileno;
  1202. if (ret = init_tile(s, tileno))
  1203. return ret;
  1204. s->g = tile->tile_part[0].tpg;
  1205. if (ret = jpeg2000_decode_packets(s, tile))
  1206. return ret;
  1207. }
  1208. return 0;
  1209. }
  1210. static int jp2_find_codestream(Jpeg2000DecoderContext *s)
  1211. {
  1212. uint32_t atom_size, atom;
  1213. int found_codestream = 0, search_range = 10;
  1214. while(!found_codestream && search_range
  1215. &&
  1216. bytestream2_get_bytes_left(&s->g) >= 8) {
  1217. atom_size = bytestream2_get_be32u(&s->g);
  1218. atom = bytestream2_get_be32u(&s->g);
  1219. if (atom == JP2_CODESTREAM) {
  1220. found_codestream = 1;
  1221. } else {
  1222. if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
  1223. return 0;
  1224. bytestream2_skipu(&s->g, atom_size - 8);
  1225. search_range--;
  1226. }
  1227. }
  1228. if (found_codestream)
  1229. return 1;
  1230. return 0;
  1231. }
  1232. static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
  1233. int *got_frame, AVPacket *avpkt)
  1234. {
  1235. Jpeg2000DecoderContext *s = avctx->priv_data;
  1236. ThreadFrame frame = { .f = data };
  1237. AVFrame *picture = data;
  1238. int tileno, ret;
  1239. s->avctx = avctx;
  1240. bytestream2_init(&s->g, avpkt->data, avpkt->size);
  1241. s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
  1242. if (bytestream2_get_bytes_left(&s->g) < 2) {
  1243. ret = AVERROR_INVALIDDATA;
  1244. goto end;
  1245. }
  1246. // check if the image is in jp2 format
  1247. if (bytestream2_get_bytes_left(&s->g) >= 12 &&
  1248. (bytestream2_get_be32u(&s->g) == 12) &&
  1249. (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
  1250. (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
  1251. if (!jp2_find_codestream(s)) {
  1252. av_log(avctx, AV_LOG_ERROR,
  1253. "Could not find Jpeg2000 codestream atom.\n");
  1254. ret = AVERROR_INVALIDDATA;
  1255. goto end;
  1256. }
  1257. } else {
  1258. bytestream2_seek(&s->g, 0, SEEK_SET);
  1259. }
  1260. if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
  1261. av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
  1262. ret = AVERROR_INVALIDDATA;
  1263. goto end;
  1264. }
  1265. if (ret = jpeg2000_read_main_headers(s))
  1266. goto end;
  1267. /* get picture buffer */
  1268. if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
  1269. av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
  1270. goto end;
  1271. }
  1272. picture->pict_type = AV_PICTURE_TYPE_I;
  1273. picture->key_frame = 1;
  1274. if (ret = jpeg2000_read_bitstream_packets(s))
  1275. goto end;
  1276. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
  1277. if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
  1278. goto end;
  1279. jpeg2000_dec_cleanup(s);
  1280. *got_frame = 1;
  1281. return bytestream2_tell(&s->g);
  1282. end:
  1283. jpeg2000_dec_cleanup(s);
  1284. return ret;
  1285. }
  1286. static void jpeg2000_init_static_data(AVCodec *codec)
  1287. {
  1288. ff_jpeg2000_init_tier1_luts();
  1289. ff_mqc_init_context_tables();
  1290. }
  1291. #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
  1292. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1293. static const AVOption options[] = {
  1294. { "lowres", "Lower the decoding resolution by a power of two",
  1295. OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
  1296. { NULL },
  1297. };
  1298. static const AVProfile profiles[] = {
  1299. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
  1300. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
  1301. { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
  1302. { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
  1303. { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
  1304. { FF_PROFILE_UNKNOWN },
  1305. };
  1306. static const AVClass class = {
  1307. .class_name = "jpeg2000",
  1308. .item_name = av_default_item_name,
  1309. .option = options,
  1310. .version = LIBAVUTIL_VERSION_INT,
  1311. };
  1312. AVCodec ff_jpeg2000_decoder = {
  1313. .name = "jpeg2000",
  1314. .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
  1315. .type = AVMEDIA_TYPE_VIDEO,
  1316. .id = AV_CODEC_ID_JPEG2000,
  1317. .capabilities = CODEC_CAP_FRAME_THREADS,
  1318. .priv_data_size = sizeof(Jpeg2000DecoderContext),
  1319. .init_static_data = jpeg2000_init_static_data,
  1320. .decode = jpeg2000_decode_frame,
  1321. .priv_class = &class,
  1322. .profiles = NULL_IF_CONFIG_SMALL(profiles)
  1323. };