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.

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