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.

1481 lines
52KB

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