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.

1450 lines
51KB

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