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.

1444 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->ncomponents) {
  205. case 1:
  206. if (s->precision > 8)
  207. s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
  208. else
  209. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  210. break;
  211. case 3:
  212. switch (s->avctx->profile) {
  213. case FF_PROFILE_JPEG2000_DCINEMA_2K:
  214. case FF_PROFILE_JPEG2000_DCINEMA_4K:
  215. /* XYZ color-space for digital cinema profiles */
  216. s->avctx->pix_fmt = AV_PIX_FMT_XYZ12;
  217. break;
  218. default:
  219. if (s->precision > 8)
  220. s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
  221. else
  222. s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
  223. break;
  224. }
  225. break;
  226. case 4:
  227. s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
  228. break;
  229. default:
  230. /* pixel format can not be identified */
  231. s->avctx->pix_fmt = AV_PIX_FMT_NONE;
  232. break;
  233. }
  234. return 0;
  235. }
  236. /* get common part for COD and COC segments */
  237. static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
  238. {
  239. uint8_t byte;
  240. if (bytestream2_get_bytes_left(&s->g) < 5)
  241. return AVERROR_INVALIDDATA;
  242. /* nreslevels = number of resolution levels
  243. = number of decomposition level +1 */
  244. c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
  245. if (c->nreslevels > JPEG2000_MAX_RESLEVELS)
  246. return AVERROR_INVALIDDATA;
  247. /* compute number of resolution levels to decode */
  248. if (c->nreslevels < s->reduction_factor)
  249. c->nreslevels2decode = 1;
  250. else
  251. c->nreslevels2decode = c->nreslevels - s->reduction_factor;
  252. c->log2_cblk_width = bytestream2_get_byteu(&s->g) + 2; // cblk width
  253. c->log2_cblk_height = bytestream2_get_byteu(&s->g) + 2; // cblk height
  254. if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
  255. c->log2_cblk_width + c->log2_cblk_height > 12) {
  256. av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
  257. return AVERROR_INVALIDDATA;
  258. }
  259. c->cblk_style = bytestream2_get_byteu(&s->g);
  260. if (c->cblk_style != 0) { // cblk style
  261. avpriv_request_sample(s->avctx, "Support for extra cblk styles");
  262. return AVERROR_PATCHWELCOME;
  263. }
  264. c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
  265. /* set integer 9/7 DWT in case of BITEXACT flag */
  266. if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
  267. c->transform = FF_DWT97_INT;
  268. if (c->csty & JPEG2000_CSTY_PREC) {
  269. int i;
  270. for (i = 0; i < c->nreslevels; i++) {
  271. byte = bytestream2_get_byte(&s->g);
  272. c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
  273. c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
  274. }
  275. } else {
  276. memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
  277. memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
  278. }
  279. return 0;
  280. }
  281. /* get coding parameters for a particular tile or whole image*/
  282. static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  283. uint8_t *properties)
  284. {
  285. Jpeg2000CodingStyle tmp;
  286. int compno, ret;
  287. if (bytestream2_get_bytes_left(&s->g) < 5)
  288. return AVERROR_INVALIDDATA;
  289. tmp.csty = bytestream2_get_byteu(&s->g);
  290. // get progression order
  291. tmp.prog_order = bytestream2_get_byteu(&s->g);
  292. tmp.nlayers = bytestream2_get_be16u(&s->g);
  293. tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
  294. if (tmp.mct && s->ncomponents < 3) {
  295. av_log(s->avctx, AV_LOG_ERROR,
  296. "MCT %d with too few components (%d)\n",
  297. tmp.mct, s->ncomponents);
  298. return AVERROR_INVALIDDATA;
  299. }
  300. if ((ret = get_cox(s, &tmp)) < 0)
  301. return ret;
  302. for (compno = 0; compno < s->ncomponents; compno++)
  303. if (!(properties[compno] & HAD_COC))
  304. memcpy(c + compno, &tmp, sizeof(tmp));
  305. return 0;
  306. }
  307. /* Get coding parameters for a component in the whole image or a
  308. * particular tile. */
  309. static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  310. uint8_t *properties)
  311. {
  312. int compno, ret;
  313. if (bytestream2_get_bytes_left(&s->g) < 2)
  314. return AVERROR_INVALIDDATA;
  315. compno = bytestream2_get_byteu(&s->g);
  316. if (compno >= s->ncomponents) {
  317. av_log(s->avctx, AV_LOG_ERROR,
  318. "Invalid compno %d. There are %d components in the image.\n",
  319. compno, s->ncomponents);
  320. return AVERROR_INVALIDDATA;
  321. }
  322. c += compno;
  323. c->csty = bytestream2_get_byteu(&s->g);
  324. if ((ret = get_cox(s, c)) < 0)
  325. return ret;
  326. properties[compno] |= HAD_COC;
  327. return 0;
  328. }
  329. /* Get common part for QCD and QCC segments. */
  330. static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
  331. {
  332. int i, x;
  333. if (bytestream2_get_bytes_left(&s->g) < 1)
  334. return AVERROR_INVALIDDATA;
  335. x = bytestream2_get_byteu(&s->g); // Sqcd
  336. q->nguardbits = x >> 5;
  337. q->quantsty = x & 0x1f;
  338. if (q->quantsty == JPEG2000_QSTY_NONE) {
  339. n -= 3;
  340. if (bytestream2_get_bytes_left(&s->g) < n ||
  341. n > JPEG2000_MAX_DECLEVELS)
  342. return AVERROR_INVALIDDATA;
  343. for (i = 0; i < n; i++)
  344. q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
  345. } else if (q->quantsty == JPEG2000_QSTY_SI) {
  346. if (bytestream2_get_bytes_left(&s->g) < 2)
  347. return AVERROR_INVALIDDATA;
  348. x = bytestream2_get_be16u(&s->g);
  349. q->expn[0] = x >> 11;
  350. q->mant[0] = x & 0x7ff;
  351. for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
  352. int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
  353. q->expn[i] = curexpn;
  354. q->mant[i] = q->mant[0];
  355. }
  356. } else {
  357. n = (n - 3) >> 1;
  358. if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
  359. n > JPEG2000_MAX_DECLEVELS)
  360. return AVERROR_INVALIDDATA;
  361. for (i = 0; i < n; i++) {
  362. x = bytestream2_get_be16u(&s->g);
  363. q->expn[i] = x >> 11;
  364. q->mant[i] = x & 0x7ff;
  365. }
  366. }
  367. return 0;
  368. }
  369. /* Get quantization parameters for a particular tile or a whole image. */
  370. static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  371. uint8_t *properties)
  372. {
  373. Jpeg2000QuantStyle tmp;
  374. int compno, ret;
  375. if ((ret = get_qcx(s, n, &tmp)) < 0)
  376. return ret;
  377. for (compno = 0; compno < s->ncomponents; compno++)
  378. if (!(properties[compno] & HAD_QCC))
  379. memcpy(q + compno, &tmp, sizeof(tmp));
  380. return 0;
  381. }
  382. /* Get quantization parameters for a component in the whole image
  383. * on in a particular tile. */
  384. static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  385. uint8_t *properties)
  386. {
  387. int compno;
  388. if (bytestream2_get_bytes_left(&s->g) < 1)
  389. return AVERROR_INVALIDDATA;
  390. compno = bytestream2_get_byteu(&s->g);
  391. if (compno >= s->ncomponents) {
  392. av_log(s->avctx, AV_LOG_ERROR,
  393. "Invalid compno %d. There are %d components in the image.\n",
  394. compno, s->ncomponents);
  395. return AVERROR_INVALIDDATA;
  396. }
  397. properties[compno] |= HAD_QCC;
  398. return get_qcx(s, n - 1, q + compno);
  399. }
  400. /* Get start of tile segment. */
  401. static int get_sot(Jpeg2000DecoderContext *s, int n)
  402. {
  403. Jpeg2000TilePart *tp;
  404. uint16_t Isot;
  405. uint32_t Psot;
  406. uint8_t TPsot;
  407. if (bytestream2_get_bytes_left(&s->g) < 8)
  408. return AVERROR_INVALIDDATA;
  409. Isot = bytestream2_get_be16u(&s->g); // Isot
  410. if (Isot >= s->numXtiles * s->numYtiles)
  411. return AVERROR_INVALIDDATA;
  412. if (Isot) {
  413. avpriv_request_sample(s->avctx, "Support for more than one tile");
  414. return AVERROR_PATCHWELCOME;
  415. }
  416. Psot = bytestream2_get_be32u(&s->g); // Psot
  417. TPsot = bytestream2_get_byteu(&s->g); // TPsot
  418. /* Read TNSot but not used */
  419. bytestream2_get_byteu(&s->g); // TNsot
  420. if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
  421. av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot);
  422. return AVERROR_INVALIDDATA;
  423. }
  424. if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
  425. avpriv_request_sample(s->avctx, "Support for %d components", TPsot);
  426. return AVERROR_PATCHWELCOME;
  427. }
  428. tp = s->tile[s->curtileno].tile_part + TPsot;
  429. tp->tile_index = Isot;
  430. tp->tp_len = Psot;
  431. tp->tp_idx = TPsot;
  432. /* Start of bit stream. Pointer to SOD marker
  433. * Check SOD marker is present. */
  434. if (JPEG2000_SOD == bytestream2_get_be16(&s->g)) {
  435. bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_len - n - 4);
  436. bytestream2_skip(&s->g, tp->tp_len - n - 4);
  437. } else {
  438. av_log(s->avctx, AV_LOG_ERROR, "SOD marker not found \n");
  439. return AVERROR_INVALIDDATA;
  440. }
  441. /* End address of bit stream =
  442. * start address + (Psot - size of SOT HEADER(n)
  443. * - size of SOT MARKER(2) - size of SOD marker(2) */
  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. /* copy codsty, qnsty to tile. TODO: Is it the best way?
  495. * codsty, qnsty is an array of 4 structs Jpeg2000CodingStyle
  496. * and Jpeg2000QuantStyle */
  497. memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(*tile->codsty));
  498. memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(*tile->qntsty));
  499. for (compno = 0; compno < s->ncomponents; compno++) {
  500. Jpeg2000Component *comp = tile->comp + compno;
  501. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  502. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  503. int ret; // global bandno
  504. comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
  505. comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
  506. comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
  507. comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
  508. comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
  509. comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
  510. comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
  511. comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
  512. if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
  513. s->cbps[compno], s->cdx[compno],
  514. s->cdy[compno], s->avctx))
  515. return ret;
  516. }
  517. return 0;
  518. }
  519. /* Read the number of coding passes. */
  520. static int getnpasses(Jpeg2000DecoderContext *s)
  521. {
  522. int num;
  523. if (!get_bits(s, 1))
  524. return 1;
  525. if (!get_bits(s, 1))
  526. return 2;
  527. if ((num = get_bits(s, 2)) != 3)
  528. return num < 0 ? num : 3 + num;
  529. if ((num = get_bits(s, 5)) != 31)
  530. return num < 0 ? num : 6 + num;
  531. num = get_bits(s, 7);
  532. return num < 0 ? num : 37 + num;
  533. }
  534. static int getlblockinc(Jpeg2000DecoderContext *s)
  535. {
  536. int res = 0, ret;
  537. while (ret = get_bits(s, 1)) {
  538. if (ret < 0)
  539. return ret;
  540. res++;
  541. }
  542. return res;
  543. }
  544. static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
  545. Jpeg2000CodingStyle *codsty,
  546. Jpeg2000ResLevel *rlevel, int precno,
  547. int layno, uint8_t *expn, int numgbits)
  548. {
  549. int bandno, cblkno, ret, nb_code_blocks;
  550. if (!(ret = get_bits(s, 1))) {
  551. jpeg2000_flush(s);
  552. return 0;
  553. } else if (ret < 0)
  554. return ret;
  555. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  556. Jpeg2000Band *band = rlevel->band + bandno;
  557. Jpeg2000Prec *prec = band->prec + precno;
  558. if (band->coord[0][0] == band->coord[0][1] ||
  559. band->coord[1][0] == band->coord[1][1])
  560. continue;
  561. nb_code_blocks = prec->nb_codeblocks_height *
  562. prec->nb_codeblocks_width;
  563. for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  564. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  565. int incl, newpasses, llen;
  566. if (cblk->npasses)
  567. incl = get_bits(s, 1);
  568. else
  569. incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
  570. if (!incl)
  571. continue;
  572. else if (incl < 0)
  573. return incl;
  574. if (!cblk->npasses) {
  575. int v = expn[bandno] + numgbits - 1 -
  576. tag_tree_decode(s, prec->zerobits + cblkno, 100);
  577. if (v < 0) {
  578. av_log(s->avctx, AV_LOG_ERROR,
  579. "nonzerobits %d invalid\n", v);
  580. return AVERROR_INVALIDDATA;
  581. }
  582. cblk->nonzerobits = v;
  583. }
  584. if ((newpasses = getnpasses(s)) < 0)
  585. return newpasses;
  586. if ((llen = getlblockinc(s)) < 0)
  587. return llen;
  588. cblk->lblock += llen;
  589. if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
  590. return ret;
  591. if (ret > sizeof(cblk->data)) {
  592. avpriv_request_sample(s->avctx,
  593. "Block with lengthinc greater than %zu",
  594. sizeof(cblk->data));
  595. return AVERROR_PATCHWELCOME;
  596. }
  597. cblk->lengthinc = ret;
  598. cblk->npasses += newpasses;
  599. }
  600. }
  601. jpeg2000_flush(s);
  602. if (codsty->csty & JPEG2000_CSTY_EPH) {
  603. if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
  604. bytestream2_skip(&s->g, 2);
  605. else
  606. av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
  607. }
  608. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  609. Jpeg2000Band *band = rlevel->band + bandno;
  610. Jpeg2000Prec *prec = band->prec + precno;
  611. nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
  612. for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  613. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  614. if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)
  615. return AVERROR_INVALIDDATA;
  616. /* Code-block data can be empty. In that case initialize data
  617. * with 0xFFFF. */
  618. if (cblk->lengthinc > 0) {
  619. bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
  620. } else {
  621. cblk->data[0] = 0xFF;
  622. cblk->data[1] = 0xFF;
  623. }
  624. cblk->length += cblk->lengthinc;
  625. cblk->lengthinc = 0;
  626. }
  627. }
  628. return 0;
  629. }
  630. static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  631. {
  632. int layno, reslevelno, compno, precno, ok_reslevel, ret;
  633. uint8_t prog_order = tile->codsty[0].prog_order;
  634. uint16_t x;
  635. uint16_t y;
  636. s->bit_index = 8;
  637. switch (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. default:
  705. break;
  706. }
  707. /* EOC marker reached */
  708. bytestream2_skip(&s->g, 2);
  709. return 0;
  710. }
  711. /* TIER-1 routines */
  712. static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
  713. int bpno, int bandno)
  714. {
  715. int mask = 3 << (bpno - 1), y0, x, y;
  716. for (y0 = 0; y0 < height; y0 += 4)
  717. for (x = 0; x < width; x++)
  718. for (y = y0; y < height && y < y0 + 4; y++)
  719. if ((t1->flags[y + 1][x + 1] & JPEG2000_T1_SIG_NB)
  720. && !(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  721. if (ff_mqc_decode(&t1->mqc,
  722. t1->mqc.cx_states +
  723. ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
  724. bandno))) {
  725. int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
  726. &xorbit);
  727. t1->data[y][x] =
  728. (ff_mqc_decode(&t1->mqc,
  729. t1->mqc.cx_states + ctxno) ^ xorbit)
  730. ? -mask : mask;
  731. ff_jpeg2000_set_significance(t1, x, y,
  732. t1->data[y][x] < 0);
  733. }
  734. t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
  735. }
  736. }
  737. static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
  738. int bpno)
  739. {
  740. int phalf, nhalf;
  741. int y0, x, y;
  742. phalf = 1 << (bpno - 1);
  743. nhalf = -phalf;
  744. for (y0 = 0; y0 < height; y0 += 4)
  745. for (x = 0; x < width; x++)
  746. for (y = y0; y < height && y < y0 + 4; y++)
  747. if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
  748. int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
  749. int r = ff_mqc_decode(&t1->mqc,
  750. t1->mqc.cx_states + ctxno)
  751. ? phalf : nhalf;
  752. t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
  753. t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
  754. }
  755. }
  756. static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
  757. int width, int height, int bpno, int bandno,
  758. int seg_symbols)
  759. {
  760. int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
  761. for (y0 = 0; y0 < height; y0 += 4)
  762. for (x = 0; x < width; x++) {
  763. if (y0 + 3 < height &&
  764. !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  765. (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  766. (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  767. (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
  768. if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
  769. continue;
  770. runlen = ff_mqc_decode(&t1->mqc,
  771. t1->mqc.cx_states + MQC_CX_UNI);
  772. runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
  773. t1->mqc.cx_states +
  774. MQC_CX_UNI);
  775. dec = 1;
  776. } else {
  777. runlen = 0;
  778. dec = 0;
  779. }
  780. for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
  781. if (!dec) {
  782. if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))
  783. dec = ff_mqc_decode(&t1->mqc,
  784. t1->mqc.cx_states +
  785. ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
  786. bandno));
  787. }
  788. if (dec) {
  789. int xorbit;
  790. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
  791. &xorbit);
  792. t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
  793. t1->mqc.cx_states + ctxno) ^
  794. xorbit)
  795. ? -mask : mask;
  796. ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
  797. }
  798. dec = 0;
  799. t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
  800. }
  801. }
  802. if (seg_symbols) {
  803. int val;
  804. val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  805. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  806. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  807. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  808. if (val != 0xa)
  809. av_log(s->avctx, AV_LOG_ERROR,
  810. "Segmentation symbol value incorrect\n");
  811. }
  812. }
  813. static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
  814. Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
  815. int width, int height, int bandpos)
  816. {
  817. int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
  818. for (y = 0; y < height; y++)
  819. memset(t1->data[y], 0, width * sizeof(**t1->data));
  820. /* If code-block contains no compressed data: nothing to do. */
  821. if (!cblk->length)
  822. return 0;
  823. for (y = 0; y < height + 2; y++)
  824. memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
  825. ff_mqc_initdec(&t1->mqc, cblk->data);
  826. cblk->data[cblk->length] = 0xff;
  827. cblk->data[cblk->length + 1] = 0xff;
  828. while (passno--) {
  829. switch (pass_t) {
  830. case 0:
  831. decode_sigpass(t1, width, height, bpno + 1, bandpos);
  832. break;
  833. case 1:
  834. decode_refpass(t1, width, height, bpno + 1);
  835. break;
  836. case 2:
  837. decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
  838. codsty->cblk_style & JPEG2000_CBLK_SEGSYM);
  839. break;
  840. }
  841. pass_t++;
  842. if (pass_t == 3) {
  843. bpno--;
  844. pass_t = 0;
  845. }
  846. }
  847. return 0;
  848. }
  849. /* TODO: Verify dequantization for lossless case
  850. * comp->data can be float or int
  851. * band->stepsize can be float or int
  852. * depending on the type of DWT transformation.
  853. * see ISO/IEC 15444-1:2002 A.6.1 */
  854. /* Float dequantization of a codeblock.*/
  855. static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
  856. Jpeg2000Component *comp,
  857. Jpeg2000T1Context *t1, Jpeg2000Band *band)
  858. {
  859. int i, j, idx;
  860. float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
  861. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
  862. for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
  863. idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
  864. datap[idx] = (float)(t1->data[j][i]) * band->f_stepsize;
  865. }
  866. }
  867. /* Integer dequantization of a codeblock.*/
  868. static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
  869. Jpeg2000Component *comp,
  870. Jpeg2000T1Context *t1, Jpeg2000Band *band)
  871. {
  872. int i, j, idx;
  873. int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
  874. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
  875. for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
  876. idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
  877. datap[idx] =
  878. ((int32_t)(t1->data[j][i]) * band->i_stepsize + (1 << 15)) >> 16;
  879. }
  880. }
  881. /* Inverse ICT parameters in float and integer.
  882. * int value = (float value) * (1<<16) */
  883. static const float f_ict_params[4] = {
  884. 1.402f,
  885. 0.34413f,
  886. 0.71414f,
  887. 1.772f
  888. };
  889. static const int i_ict_params[4] = {
  890. 91881,
  891. 22553,
  892. 46802,
  893. 116130
  894. };
  895. static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  896. {
  897. int i, csize = 1;
  898. int32_t *src[3], i0, i1, i2;
  899. float *srcf[3], i0f, i1f, i2f;
  900. for (i = 0; i < 3; i++)
  901. if (tile->codsty[0].transform == FF_DWT97)
  902. srcf[i] = tile->comp[i].f_data;
  903. else
  904. src [i] = tile->comp[i].i_data;
  905. for (i = 0; i < 2; i++)
  906. csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
  907. switch (tile->codsty[0].transform) {
  908. case FF_DWT97:
  909. for (i = 0; i < csize; i++) {
  910. i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
  911. i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
  912. - (f_ict_params[2] * *srcf[2]);
  913. i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
  914. *srcf[0]++ = i0f;
  915. *srcf[1]++ = i1f;
  916. *srcf[2]++ = i2f;
  917. }
  918. break;
  919. case FF_DWT97_INT:
  920. for (i = 0; i < csize; i++) {
  921. i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
  922. i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
  923. - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
  924. i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
  925. *src[0]++ = i0;
  926. *src[1]++ = i1;
  927. *src[2]++ = i2;
  928. }
  929. break;
  930. case FF_DWT53:
  931. for (i = 0; i < csize; i++) {
  932. i1 = *src[0] - (*src[2] + *src[1] >> 2);
  933. i0 = i1 + *src[2];
  934. i2 = i1 + *src[1];
  935. *src[0]++ = i0;
  936. *src[1]++ = i1;
  937. *src[2]++ = i2;
  938. }
  939. break;
  940. }
  941. }
  942. static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
  943. AVFrame *picture)
  944. {
  945. int compno, reslevelno, bandno;
  946. int x, y;
  947. uint8_t *line;
  948. Jpeg2000T1Context t1;
  949. /* Loop on tile components */
  950. for (compno = 0; compno < s->ncomponents; compno++) {
  951. Jpeg2000Component *comp = tile->comp + compno;
  952. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  953. /* Loop on resolution levels */
  954. for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
  955. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  956. /* Loop on bands */
  957. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  958. uint16_t nb_precincts, precno;
  959. Jpeg2000Band *band = rlevel->band + bandno;
  960. int cblkno = 0, bandpos;
  961. bandpos = bandno + (reslevelno > 0);
  962. nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
  963. /* Loop on precincts */
  964. for (precno = 0; precno < nb_precincts; precno++) {
  965. Jpeg2000Prec *prec = band->prec + precno;
  966. /* Loop on codeblocks */
  967. for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
  968. int x, y;
  969. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  970. decode_cblk(s, codsty, &t1, cblk,
  971. cblk->coord[0][1] - cblk->coord[0][0],
  972. cblk->coord[1][1] - cblk->coord[1][0],
  973. bandpos);
  974. x = cblk->coord[0][0];
  975. y = cblk->coord[1][0];
  976. if (codsty->transform == FF_DWT97)
  977. dequantization_float(x, y, cblk, comp, &t1, band);
  978. else
  979. dequantization_int(x, y, cblk, comp, &t1, band);
  980. } /* end cblk */
  981. } /*end prec */
  982. } /* end band */
  983. } /* end reslevel */
  984. /* inverse DWT */
  985. ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
  986. } /*end comp */
  987. /* inverse MCT transformation */
  988. if (tile->codsty[0].mct)
  989. mct_decode(s, tile);
  990. if (s->precision <= 8) {
  991. for (compno = 0; compno < s->ncomponents; compno++) {
  992. Jpeg2000Component *comp = tile->comp + compno;
  993. float *datap = comp->f_data;
  994. int32_t *i_datap = comp->i_data;
  995. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  996. line = picture->data[0] + y * picture->linesize[0];
  997. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  998. uint8_t *dst;
  999. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  1000. dst = line + x * s->ncomponents + compno;
  1001. for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
  1002. int val;
  1003. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1004. if (tile->codsty->transform == FF_DWT97)
  1005. val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
  1006. else
  1007. val = *i_datap + (1 << (s->cbps[compno] - 1));
  1008. val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
  1009. *dst = val << (8 - s->cbps[compno]);
  1010. datap++;
  1011. i_datap++;
  1012. dst += s->ncomponents;
  1013. }
  1014. line += picture->linesize[0];
  1015. }
  1016. }
  1017. } else {
  1018. for (compno = 0; compno < s->ncomponents; compno++) {
  1019. Jpeg2000Component *comp = tile->comp + compno;
  1020. float *datap = comp->f_data;
  1021. int32_t *i_datap = comp->i_data;
  1022. uint16_t *linel;
  1023. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  1024. linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
  1025. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  1026. uint16_t *dst;
  1027. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  1028. dst = linel + (x * s->ncomponents + compno);
  1029. for (; x < s->avctx->width; x += s->cdx[compno]) {
  1030. int val;
  1031. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1032. if (tile->codsty->transform == FF_DWT97)
  1033. val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
  1034. else
  1035. val = *i_datap + (1 << (s->cbps[compno] - 1));
  1036. val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
  1037. /* align 12 bit values in little-endian mode */
  1038. *dst = val << (16 - s->cbps[compno]);
  1039. datap++;
  1040. i_datap++;
  1041. dst += s->ncomponents;
  1042. }
  1043. linel += picture->linesize[0] >> 1;
  1044. }
  1045. }
  1046. }
  1047. return 0;
  1048. }
  1049. static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
  1050. {
  1051. int tileno, compno;
  1052. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  1053. for (compno = 0; compno < s->ncomponents; compno++) {
  1054. Jpeg2000Component *comp = s->tile[tileno].comp + compno;
  1055. Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
  1056. ff_jpeg2000_cleanup(comp, codsty);
  1057. }
  1058. av_freep(&s->tile[tileno].comp);
  1059. }
  1060. av_freep(&s->tile);
  1061. }
  1062. static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
  1063. {
  1064. Jpeg2000CodingStyle *codsty = s->codsty;
  1065. Jpeg2000QuantStyle *qntsty = s->qntsty;
  1066. uint8_t *properties = s->properties;
  1067. for (;;) {
  1068. int len, ret = 0;
  1069. uint16_t marker;
  1070. int oldpos;
  1071. if (bytestream2_get_bytes_left(&s->g) < 2) {
  1072. av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
  1073. break;
  1074. }
  1075. marker = bytestream2_get_be16u(&s->g);
  1076. oldpos = bytestream2_tell(&s->g);
  1077. if (marker == JPEG2000_SOD) {
  1078. Jpeg2000Tile *tile;
  1079. Jpeg2000TilePart *tp;
  1080. if (s->curtileno < 0) {
  1081. av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
  1082. return AVERROR_INVALIDDATA;
  1083. }
  1084. tile = s->tile + s->curtileno;
  1085. tp = tile->tile_part + tile->tp_idx;
  1086. bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
  1087. bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
  1088. continue;
  1089. }
  1090. if (marker == JPEG2000_EOC)
  1091. break;
  1092. len = bytestream2_get_be16u(&s->g);
  1093. if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
  1094. return AVERROR_INVALIDDATA;
  1095. switch (marker) {
  1096. case JPEG2000_SIZ:
  1097. ret = get_siz(s);
  1098. break;
  1099. case JPEG2000_COC:
  1100. ret = get_coc(s, codsty, properties);
  1101. break;
  1102. case JPEG2000_COD:
  1103. ret = get_cod(s, codsty, properties);
  1104. break;
  1105. case JPEG2000_QCC:
  1106. ret = get_qcc(s, len, qntsty, properties);
  1107. break;
  1108. case JPEG2000_QCD:
  1109. ret = get_qcd(s, len, qntsty, properties);
  1110. break;
  1111. case JPEG2000_SOT:
  1112. ret = get_sot(s, len);
  1113. break;
  1114. case JPEG2000_COM:
  1115. // the comment is ignored
  1116. bytestream2_skip(&s->g, len - 2);
  1117. break;
  1118. case JPEG2000_TLM:
  1119. // Tile-part lengths
  1120. ret = get_tlm(s, len);
  1121. break;
  1122. default:
  1123. av_log(s->avctx, AV_LOG_ERROR,
  1124. "unsupported marker 0x%.4X at pos 0x%X\n",
  1125. marker, bytestream2_tell(&s->g) - 4);
  1126. bytestream2_skip(&s->g, len - 2);
  1127. break;
  1128. }
  1129. if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {
  1130. av_log(s->avctx, AV_LOG_ERROR,
  1131. "error during processing marker segment %.4x\n", marker);
  1132. return ret ? ret : -1;
  1133. }
  1134. }
  1135. return 0;
  1136. }
  1137. /* Read bit stream packets --> T2 operation. */
  1138. static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
  1139. {
  1140. int ret = 0;
  1141. Jpeg2000Tile *tile = s->tile + s->curtileno;
  1142. if (ret = init_tile(s, s->curtileno))
  1143. return ret;
  1144. if (ret = jpeg2000_decode_packets(s, tile))
  1145. return ret;
  1146. return 0;
  1147. }
  1148. static int jp2_find_codestream(Jpeg2000DecoderContext *s)
  1149. {
  1150. uint32_t atom_size, atom;
  1151. int found_codestream = 0, search_range = 10;
  1152. while(!found_codestream && search_range
  1153. &&
  1154. bytestream2_get_bytes_left(&s->g) >= 8) {
  1155. atom_size = bytestream2_get_be32u(&s->g);
  1156. atom = bytestream2_get_be32u(&s->g);
  1157. if (atom == JP2_CODESTREAM) {
  1158. found_codestream = 1;
  1159. } else {
  1160. if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
  1161. return 0;
  1162. bytestream2_skipu(&s->g, atom_size - 8);
  1163. search_range--;
  1164. }
  1165. }
  1166. if (found_codestream)
  1167. return 1;
  1168. return 0;
  1169. }
  1170. static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
  1171. int *got_frame, AVPacket *avpkt)
  1172. {
  1173. Jpeg2000DecoderContext *s = avctx->priv_data;
  1174. ThreadFrame frame = { .f = data };
  1175. AVFrame *picture = data;
  1176. int tileno, ret;
  1177. s->avctx = avctx;
  1178. bytestream2_init(&s->g, avpkt->data, avpkt->size);
  1179. s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
  1180. if (bytestream2_get_bytes_left(&s->g) < 2) {
  1181. ret = AVERROR_INVALIDDATA;
  1182. goto end;
  1183. }
  1184. // check if the image is in jp2 format
  1185. if (bytestream2_get_bytes_left(&s->g) >= 12 &&
  1186. (bytestream2_get_be32u(&s->g) == 12) &&
  1187. (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
  1188. (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
  1189. if (!jp2_find_codestream(s)) {
  1190. av_log(avctx, AV_LOG_ERROR,
  1191. "Could not find Jpeg2000 codestream atom.\n");
  1192. ret = AVERROR_INVALIDDATA;
  1193. goto end;
  1194. }
  1195. } else {
  1196. bytestream2_seek(&s->g, 0, SEEK_SET);
  1197. }
  1198. if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
  1199. av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
  1200. ret = AVERROR_INVALIDDATA;
  1201. goto end;
  1202. }
  1203. if (ret = jpeg2000_read_main_headers(s))
  1204. goto end;
  1205. /* get picture buffer */
  1206. if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {
  1207. av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");
  1208. goto end;
  1209. }
  1210. picture->pict_type = AV_PICTURE_TYPE_I;
  1211. picture->key_frame = 1;
  1212. if (ret = jpeg2000_read_bitstream_packets(s))
  1213. goto end;
  1214. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
  1215. if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
  1216. goto end;
  1217. jpeg2000_dec_cleanup(s);
  1218. *got_frame = 1;
  1219. return bytestream2_tell(&s->g);
  1220. end:
  1221. jpeg2000_dec_cleanup(s);
  1222. return ret;
  1223. }
  1224. static void jpeg2000_init_static_data(AVCodec *codec)
  1225. {
  1226. ff_jpeg2000_init_tier1_luts();
  1227. }
  1228. #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
  1229. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1230. static const AVOption options[] = {
  1231. { "lowres", "Lower the decoding resolution by a power of two",
  1232. OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
  1233. { NULL },
  1234. };
  1235. static const AVProfile profiles[] = {
  1236. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
  1237. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
  1238. { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
  1239. { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
  1240. { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
  1241. { FF_PROFILE_UNKNOWN },
  1242. };
  1243. static const AVClass class = {
  1244. .class_name = "jpeg2000",
  1245. .item_name = av_default_item_name,
  1246. .option = options,
  1247. .version = LIBAVUTIL_VERSION_INT,
  1248. };
  1249. AVCodec ff_jpeg2000_decoder = {
  1250. .name = "jpeg2000",
  1251. .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
  1252. .type = AVMEDIA_TYPE_VIDEO,
  1253. .id = AV_CODEC_ID_JPEG2000,
  1254. .capabilities = CODEC_CAP_FRAME_THREADS,
  1255. .priv_data_size = sizeof(Jpeg2000DecoderContext),
  1256. .init_static_data = jpeg2000_init_static_data,
  1257. .decode = jpeg2000_decode_frame,
  1258. .priv_class = &class,
  1259. .profiles = NULL_IF_CONFIG_SMALL(profiles)
  1260. };