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.

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