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.

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