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.

1441 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. Jpeg2000CodingStyle *codsty;
  493. Jpeg2000QuantStyle *qntsty;
  494. if (!tile->comp)
  495. return AVERROR(ENOMEM);
  496. /* copy codsty, qnsty to tile. TODO: Is it the best way?
  497. * codsty, qnsty is an array of 4 structs Jpeg2000CodingStyle
  498. * and Jpeg2000QuantStyle */
  499. memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(*codsty));
  500. memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(*qntsty));
  501. for (compno = 0; compno < s->ncomponents; compno++) {
  502. Jpeg2000Component *comp = tile->comp + compno;
  503. int ret; // global bandno
  504. codsty = tile->codsty + compno;
  505. qntsty = tile->qntsty + compno;
  506. comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
  507. comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
  508. comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
  509. comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
  510. comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
  511. comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
  512. comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
  513. comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
  514. if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
  515. s->cbps[compno], s->cdx[compno],
  516. s->cdy[compno], s->avctx))
  517. return ret;
  518. }
  519. return 0;
  520. }
  521. /* Read the number of coding passes. */
  522. static int getnpasses(Jpeg2000DecoderContext *s)
  523. {
  524. int num;
  525. if (!get_bits(s, 1))
  526. return 1;
  527. if (!get_bits(s, 1))
  528. return 2;
  529. if ((num = get_bits(s, 2)) != 3)
  530. return num < 0 ? num : 3 + num;
  531. if ((num = get_bits(s, 5)) != 31)
  532. return num < 0 ? num : 6 + num;
  533. num = get_bits(s, 7);
  534. return num < 0 ? num : 37 + num;
  535. }
  536. static int getlblockinc(Jpeg2000DecoderContext *s)
  537. {
  538. int res = 0, ret;
  539. while (ret = get_bits(s, 1)) {
  540. if (ret < 0)
  541. return ret;
  542. res++;
  543. }
  544. return res;
  545. }
  546. static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
  547. Jpeg2000CodingStyle *codsty,
  548. Jpeg2000ResLevel *rlevel, int precno,
  549. int layno, uint8_t *expn, int numgbits)
  550. {
  551. int bandno, cblkno, ret, nb_code_blocks;
  552. if (!(ret = get_bits(s, 1))) {
  553. jpeg2000_flush(s);
  554. return 0;
  555. } else if (ret < 0)
  556. return ret;
  557. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  558. Jpeg2000Band *band = rlevel->band + bandno;
  559. Jpeg2000Prec *prec = band->prec + precno;
  560. if (band->coord[0][0] == band->coord[0][1] ||
  561. band->coord[1][0] == band->coord[1][1])
  562. continue;
  563. nb_code_blocks = prec->nb_codeblocks_height *
  564. prec->nb_codeblocks_width;
  565. for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  566. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  567. int incl, newpasses, llen;
  568. if (cblk->npasses)
  569. incl = get_bits(s, 1);
  570. else
  571. incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
  572. if (!incl)
  573. continue;
  574. else if (incl < 0)
  575. return incl;
  576. if (!cblk->npasses) {
  577. int v = expn[bandno] + numgbits - 1 -
  578. tag_tree_decode(s, prec->zerobits + cblkno, 100);
  579. if (v < 0) {
  580. av_log(s->avctx, AV_LOG_ERROR,
  581. "nonzerobits %d invalid\n", v);
  582. return AVERROR_INVALIDDATA;
  583. }
  584. cblk->nonzerobits = v;
  585. }
  586. if ((newpasses = getnpasses(s)) < 0)
  587. return newpasses;
  588. if ((llen = getlblockinc(s)) < 0)
  589. return llen;
  590. cblk->lblock += llen;
  591. if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
  592. return ret;
  593. if (ret > sizeof(cblk->data)) {
  594. avpriv_request_sample(s->avctx,
  595. "Block with lengthinc greater than %zu",
  596. sizeof(cblk->data));
  597. return AVERROR_PATCHWELCOME;
  598. }
  599. cblk->lengthinc = ret;
  600. cblk->npasses += newpasses;
  601. }
  602. }
  603. jpeg2000_flush(s);
  604. if (codsty->csty & JPEG2000_CSTY_EPH) {
  605. if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
  606. bytestream2_skip(&s->g, 2);
  607. else
  608. av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
  609. }
  610. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  611. Jpeg2000Band *band = rlevel->band + bandno;
  612. Jpeg2000Prec *prec = band->prec + precno;
  613. nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
  614. for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  615. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  616. if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)
  617. return AVERROR_INVALIDDATA;
  618. /* Code-block data can be empty. In that case initialize data
  619. * with 0xFFFF. */
  620. if (cblk->lengthinc > 0) {
  621. bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
  622. } else {
  623. cblk->data[0] = 0xFF;
  624. cblk->data[1] = 0xFF;
  625. }
  626. cblk->length += cblk->lengthinc;
  627. cblk->lengthinc = 0;
  628. }
  629. }
  630. return 0;
  631. }
  632. static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  633. {
  634. int layno, reslevelno, compno, precno, ok_reslevel, ret;
  635. uint8_t prog_order = tile->codsty[0].prog_order;
  636. uint16_t x;
  637. uint16_t y;
  638. s->bit_index = 8;
  639. switch (prog_order) {
  640. case JPEG2000_PGOD_LRCP:
  641. for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
  642. ok_reslevel = 1;
  643. for (reslevelno = 0; ok_reslevel; reslevelno++) {
  644. ok_reslevel = 0;
  645. for (compno = 0; compno < s->ncomponents; compno++) {
  646. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  647. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  648. if (reslevelno < codsty->nreslevels) {
  649. Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
  650. reslevelno;
  651. ok_reslevel = 1;
  652. for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
  653. if ((ret = jpeg2000_decode_packet(s,
  654. codsty, rlevel,
  655. precno, layno,
  656. qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  657. qntsty->nguardbits)) < 0)
  658. return ret;
  659. }
  660. }
  661. }
  662. }
  663. break;
  664. case JPEG2000_PGOD_CPRL:
  665. for (compno = 0; compno < s->ncomponents; compno++) {
  666. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  667. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  668. /* Set bit stream buffer address according to tile-part.
  669. * For DCinema one tile-part per component, so can be
  670. * indexed by component. */
  671. s->g = tile->tile_part[compno].tpg;
  672. /* Position loop (y axis)
  673. * TODO: Automate computing of step 256.
  674. * Fixed here, but to be computed before entering here. */
  675. for (y = 0; y < s->height; y += 256) {
  676. /* Position loop (y axis)
  677. * TODO: automate computing of step 256.
  678. * Fixed here, but to be computed before entering here. */
  679. for (x = 0; x < s->width; x += 256) {
  680. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  681. uint16_t prcx, prcy;
  682. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  683. Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
  684. if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
  685. (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
  686. continue;
  687. if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
  688. (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
  689. continue;
  690. // check if a precinct exists
  691. prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
  692. prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
  693. precno = prcx + rlevel->num_precincts_x * prcy;
  694. for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
  695. if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
  696. precno, layno,
  697. qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
  698. qntsty->nguardbits)) < 0)
  699. return ret;
  700. }
  701. }
  702. }
  703. }
  704. }
  705. break;
  706. default:
  707. break;
  708. }
  709. /* EOC marker reached */
  710. bytestream2_skip(&s->g, 2);
  711. return 0;
  712. }
  713. /* TIER-1 routines */
  714. static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
  715. int bpno, int bandno)
  716. {
  717. int mask = 3 << (bpno - 1), y0, x, y;
  718. for (y0 = 0; y0 < height; y0 += 4)
  719. for (x = 0; x < width; x++)
  720. for (y = y0; y < height && y < y0 + 4; y++)
  721. if ((t1->flags[y + 1][x + 1] & JPEG2000_T1_SIG_NB)
  722. && !(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  723. if (ff_mqc_decode(&t1->mqc,
  724. t1->mqc.cx_states +
  725. ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
  726. bandno))) {
  727. int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
  728. &xorbit);
  729. t1->data[y][x] =
  730. (ff_mqc_decode(&t1->mqc,
  731. t1->mqc.cx_states + ctxno) ^ xorbit)
  732. ? -mask : mask;
  733. ff_jpeg2000_set_significance(t1, x, y,
  734. t1->data[y][x] < 0);
  735. }
  736. t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
  737. }
  738. }
  739. static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
  740. int bpno)
  741. {
  742. int phalf, nhalf;
  743. int y0, x, y;
  744. phalf = 1 << (bpno - 1);
  745. nhalf = -phalf;
  746. for (y0 = 0; y0 < height; y0 += 4)
  747. for (x = 0; x < width; x++)
  748. for (y = y0; y < height && y < y0 + 4; y++)
  749. if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
  750. int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
  751. int r = ff_mqc_decode(&t1->mqc,
  752. t1->mqc.cx_states + ctxno)
  753. ? phalf : nhalf;
  754. t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
  755. t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
  756. }
  757. }
  758. static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
  759. int width, int height, int bpno, int bandno,
  760. int seg_symbols)
  761. {
  762. int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
  763. for (y0 = 0; y0 < height; y0 += 4)
  764. for (x = 0; x < width; x++) {
  765. if (y0 + 3 < height &&
  766. !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  767. (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  768. (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  769. (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
  770. if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
  771. continue;
  772. runlen = ff_mqc_decode(&t1->mqc,
  773. t1->mqc.cx_states + MQC_CX_UNI);
  774. runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
  775. t1->mqc.cx_states +
  776. MQC_CX_UNI);
  777. dec = 1;
  778. } else {
  779. runlen = 0;
  780. dec = 0;
  781. }
  782. for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
  783. if (!dec) {
  784. if (!(t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)))
  785. dec = ff_mqc_decode(&t1->mqc,
  786. t1->mqc.cx_states +
  787. ff_jpeg2000_getsigctxno(t1->flags[y + 1][x + 1],
  788. bandno));
  789. }
  790. if (dec) {
  791. int xorbit;
  792. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
  793. &xorbit);
  794. t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
  795. t1->mqc.cx_states + ctxno) ^
  796. xorbit)
  797. ? -mask : mask;
  798. ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
  799. }
  800. dec = 0;
  801. t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
  802. }
  803. }
  804. if (seg_symbols) {
  805. int val;
  806. val = 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. val = (val << 1) + 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. if (val != 0xa)
  811. av_log(s->avctx, AV_LOG_ERROR,
  812. "Segmentation symbol value incorrect\n");
  813. }
  814. }
  815. static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
  816. Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
  817. int width, int height, int bandpos)
  818. {
  819. int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
  820. for (y = 0; y < height; y++)
  821. memset(t1->data[y], 0, width * sizeof(width));
  822. /* If code-block contains no compressed data: nothing to do. */
  823. if (!cblk->length)
  824. return 0;
  825. for (y = 0; y < height + 2; y++)
  826. memset(t1->flags[y], 0, (width + 2) * sizeof(width));
  827. ff_mqc_initdec(&t1->mqc, cblk->data);
  828. cblk->data[cblk->length] = 0xff;
  829. cblk->data[cblk->length + 1] = 0xff;
  830. while (passno--) {
  831. switch (pass_t) {
  832. case 0:
  833. decode_sigpass(t1, width, height, bpno + 1, bandpos);
  834. break;
  835. case 1:
  836. decode_refpass(t1, width, height, bpno + 1);
  837. break;
  838. case 2:
  839. decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
  840. codsty->cblk_style & JPEG2000_CBLK_SEGSYM);
  841. break;
  842. }
  843. pass_t++;
  844. if (pass_t == 3) {
  845. bpno--;
  846. pass_t = 0;
  847. }
  848. }
  849. return 0;
  850. }
  851. /* TODO: Verify dequantization for lossless case
  852. * comp->data can be float or int
  853. * band->stepsize can be float or int
  854. * depending on the type of DWT transformation.
  855. * see ISO/IEC 15444-1:2002 A.6.1 */
  856. /* Float dequantization of a codeblock.*/
  857. static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
  858. Jpeg2000Component *comp,
  859. Jpeg2000T1Context *t1, Jpeg2000Band *band)
  860. {
  861. int i, j, idx;
  862. float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
  863. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
  864. for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
  865. idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
  866. datap[idx] = (float)(t1->data[j][i]) * band->f_stepsize;
  867. }
  868. }
  869. /* Integer dequantization of a codeblock.*/
  870. static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
  871. Jpeg2000Component *comp,
  872. Jpeg2000T1Context *t1, Jpeg2000Band *band)
  873. {
  874. int i, j, idx;
  875. int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];
  876. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)
  877. for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
  878. idx = (comp->coord[0][1] - comp->coord[0][0]) * j + i;
  879. datap[idx] =
  880. ((int32_t)(t1->data[j][i]) * band->i_stepsize + (1 << 15)) >> 16;
  881. }
  882. }
  883. /* Inverse ICT parameters in float and integer.
  884. * int value = (float value) * (1<<16) */
  885. static const float f_ict_params[4] = {
  886. 1.402f,
  887. 0.34413f,
  888. 0.71414f,
  889. 1.772f
  890. };
  891. static const int i_ict_params[4] = {
  892. 91881,
  893. 22553,
  894. 46802,
  895. 116130
  896. };
  897. static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  898. {
  899. int i, csize = 1;
  900. int32_t *src[3], i0, i1, i2;
  901. float *srcf[3], i0f, i1f, i2f;
  902. for (i = 0; i < 3; i++)
  903. if (tile->codsty[0].transform == FF_DWT97)
  904. srcf[i] = tile->comp[i].f_data;
  905. else
  906. src [i] = tile->comp[i].i_data;
  907. for (i = 0; i < 2; i++)
  908. csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
  909. switch (tile->codsty[0].transform) {
  910. case FF_DWT97:
  911. for (i = 0; i < csize; i++) {
  912. i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
  913. i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
  914. - (f_ict_params[2] * *srcf[2]);
  915. i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
  916. *srcf[0]++ = i0f;
  917. *srcf[1]++ = i1f;
  918. *srcf[2]++ = i2f;
  919. }
  920. break;
  921. case FF_DWT97_INT:
  922. for (i = 0; i < csize; i++) {
  923. i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
  924. i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
  925. - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
  926. i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
  927. *src[0]++ = i0;
  928. *src[1]++ = i1;
  929. *src[2]++ = i2;
  930. }
  931. break;
  932. case FF_DWT53:
  933. for (i = 0; i < csize; i++) {
  934. i1 = *src[0] - (*src[2] + *src[1] >> 2);
  935. i0 = i1 + *src[2];
  936. i2 = i1 + *src[1];
  937. *src[0]++ = i0;
  938. *src[1]++ = i1;
  939. *src[2]++ = i2;
  940. }
  941. break;
  942. }
  943. }
  944. static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
  945. AVFrame *picture)
  946. {
  947. int compno, reslevelno, bandno;
  948. int x, y;
  949. uint8_t *line;
  950. Jpeg2000T1Context t1;
  951. /* Loop on tile components */
  952. for (compno = 0; compno < s->ncomponents; compno++) {
  953. Jpeg2000Component *comp = tile->comp + compno;
  954. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  955. /* Loop on resolution levels */
  956. for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
  957. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  958. /* Loop on bands */
  959. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  960. uint16_t nb_precincts, precno;
  961. Jpeg2000Band *band = rlevel->band + bandno;
  962. int cblkno = 0, bandpos;
  963. bandpos = bandno + (reslevelno > 0);
  964. nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
  965. /* Loop on precincts */
  966. for (precno = 0; precno < nb_precincts; precno++) {
  967. Jpeg2000Prec *prec = band->prec + precno;
  968. /* Loop on codeblocks */
  969. for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
  970. int x, y;
  971. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  972. decode_cblk(s, codsty, &t1, cblk,
  973. cblk->coord[0][1] - cblk->coord[0][0],
  974. cblk->coord[1][1] - cblk->coord[1][0],
  975. bandpos);
  976. x = cblk->coord[0][0];
  977. y = cblk->coord[1][0];
  978. if (codsty->transform == FF_DWT97)
  979. dequantization_float(x, y, cblk, comp, &t1, band);
  980. else
  981. dequantization_int(x, y, cblk, comp, &t1, band);
  982. } /* end cblk */
  983. } /*end prec */
  984. } /* end band */
  985. } /* end reslevel */
  986. /* inverse DWT */
  987. ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
  988. } /*end comp */
  989. /* inverse MCT transformation */
  990. if (tile->codsty[0].mct)
  991. mct_decode(s, tile);
  992. if (s->precision <= 8) {
  993. for (compno = 0; compno < s->ncomponents; compno++) {
  994. Jpeg2000Component *comp = tile->comp + compno;
  995. float *datap = comp->f_data;
  996. int32_t *i_datap = comp->i_data;
  997. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  998. line = picture->data[0] + y * picture->linesize[0];
  999. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  1000. uint8_t *dst;
  1001. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  1002. dst = line + x * s->ncomponents + compno;
  1003. for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
  1004. int val;
  1005. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1006. if (tile->codsty->transform == FF_DWT97)
  1007. val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
  1008. else
  1009. val = *i_datap + (1 << (s->cbps[compno] - 1));
  1010. val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
  1011. *dst = val << (8 - s->cbps[compno]);
  1012. datap++;
  1013. i_datap++;
  1014. dst += s->ncomponents;
  1015. }
  1016. line += picture->linesize[0];
  1017. }
  1018. }
  1019. } else {
  1020. for (compno = 0; compno < s->ncomponents; compno++) {
  1021. Jpeg2000Component *comp = tile->comp + compno;
  1022. float *datap = comp->f_data;
  1023. int32_t *i_datap = comp->i_data;
  1024. uint16_t *linel;
  1025. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  1026. linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);
  1027. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  1028. uint16_t *dst;
  1029. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  1030. dst = linel + (x * s->ncomponents + compno);
  1031. for (; x < s->avctx->width; x += s->cdx[compno]) {
  1032. int val;
  1033. /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
  1034. if (tile->codsty->transform == FF_DWT97)
  1035. val = lrintf(*datap) + (1 << (s->cbps[compno] - 1));
  1036. else
  1037. val = *i_datap + (1 << (s->cbps[compno] - 1));
  1038. val = av_clip(val, 0, (1 << s->cbps[compno]) - 1);
  1039. /* align 12 bit values in little-endian mode */
  1040. *dst = val << (16 - s->cbps[compno]);
  1041. datap++;
  1042. i_datap++;
  1043. dst += s->ncomponents;
  1044. }
  1045. linel += picture->linesize[0] >> 1;
  1046. }
  1047. }
  1048. }
  1049. return 0;
  1050. }
  1051. static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
  1052. {
  1053. int tileno, compno;
  1054. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  1055. for (compno = 0; compno < s->ncomponents; compno++) {
  1056. Jpeg2000Component *comp = s->tile[tileno].comp + compno;
  1057. Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
  1058. ff_jpeg2000_cleanup(comp, codsty);
  1059. }
  1060. av_freep(&s->tile[tileno].comp);
  1061. }
  1062. av_freep(&s->tile);
  1063. }
  1064. static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
  1065. {
  1066. Jpeg2000CodingStyle *codsty = s->codsty;
  1067. Jpeg2000QuantStyle *qntsty = s->qntsty;
  1068. uint8_t *properties = s->properties;
  1069. for (;;) {
  1070. int len, ret = 0;
  1071. uint16_t marker;
  1072. int oldpos;
  1073. if (bytestream2_get_bytes_left(&s->g) < 2) {
  1074. av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
  1075. break;
  1076. }
  1077. marker = bytestream2_get_be16u(&s->g);
  1078. oldpos = bytestream2_tell(&s->g);
  1079. if (marker == JPEG2000_SOD) {
  1080. Jpeg2000Tile *tile;
  1081. Jpeg2000TilePart *tp;
  1082. if (s->curtileno < 0) {
  1083. av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
  1084. return AVERROR_INVALIDDATA;
  1085. }
  1086. tile = s->tile + s->curtileno;
  1087. tp = tile->tile_part + tile->tp_idx;
  1088. bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
  1089. bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
  1090. continue;
  1091. }
  1092. if (marker == JPEG2000_EOC)
  1093. break;
  1094. len = bytestream2_get_be16u(&s->g);
  1095. if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
  1096. return AVERROR_INVALIDDATA;
  1097. switch (marker) {
  1098. case JPEG2000_SIZ:
  1099. ret = get_siz(s);
  1100. break;
  1101. case JPEG2000_COC:
  1102. ret = get_coc(s, codsty, properties);
  1103. break;
  1104. case JPEG2000_COD:
  1105. ret = get_cod(s, codsty, properties);
  1106. break;
  1107. case JPEG2000_QCC:
  1108. ret = get_qcc(s, len, qntsty, properties);
  1109. break;
  1110. case JPEG2000_QCD:
  1111. ret = get_qcd(s, len, qntsty, properties);
  1112. break;
  1113. case JPEG2000_SOT:
  1114. ret = get_sot(s, len);
  1115. break;
  1116. case JPEG2000_COM:
  1117. // the comment is ignored
  1118. bytestream2_skip(&s->g, len - 2);
  1119. break;
  1120. case JPEG2000_TLM:
  1121. // Tile-part lengths
  1122. ret = get_tlm(s, len);
  1123. break;
  1124. default:
  1125. av_log(s->avctx, AV_LOG_ERROR,
  1126. "unsupported marker 0x%.4X at pos 0x%X\n",
  1127. marker, bytestream2_tell(&s->g) - 4);
  1128. bytestream2_skip(&s->g, len - 2);
  1129. break;
  1130. }
  1131. if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {
  1132. av_log(s->avctx, AV_LOG_ERROR,
  1133. "error during processing marker segment %.4x\n", marker);
  1134. return ret ? ret : -1;
  1135. }
  1136. }
  1137. return 0;
  1138. }
  1139. /* Read bit stream packets --> T2 operation. */
  1140. static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
  1141. {
  1142. int ret = 0;
  1143. Jpeg2000Tile *tile = s->tile + s->curtileno;
  1144. if (ret = init_tile(s, s->curtileno))
  1145. return ret;
  1146. if (ret = jpeg2000_decode_packets(s, tile))
  1147. return ret;
  1148. return 0;
  1149. }
  1150. static int jp2_find_codestream(Jpeg2000DecoderContext *s)
  1151. {
  1152. uint32_t atom_size, atom;
  1153. int found_codestream = 0, search_range = 10;
  1154. while(!found_codestream && search_range
  1155. &&
  1156. bytestream2_get_bytes_left(&s->g) >= 8) {
  1157. atom_size = bytestream2_get_be32u(&s->g);
  1158. atom = bytestream2_get_be32u(&s->g);
  1159. if (atom == JP2_CODESTREAM) {
  1160. found_codestream = 1;
  1161. } else {
  1162. if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
  1163. return 0;
  1164. bytestream2_skipu(&s->g, atom_size - 8);
  1165. search_range--;
  1166. }
  1167. }
  1168. if (found_codestream)
  1169. return 1;
  1170. return 0;
  1171. }
  1172. static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
  1173. int *got_frame, AVPacket *avpkt)
  1174. {
  1175. Jpeg2000DecoderContext *s = avctx->priv_data;
  1176. ThreadFrame frame = { .f = data };
  1177. AVFrame *picture = data;
  1178. int tileno, ret;
  1179. s->avctx = avctx;
  1180. bytestream2_init(&s->g, avpkt->data, avpkt->size);
  1181. s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles
  1182. if (bytestream2_get_bytes_left(&s->g) < 2)
  1183. return AVERROR_INVALIDDATA;
  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. return AVERROR_INVALIDDATA;
  1193. }
  1194. } else {
  1195. bytestream2_seek(&s->g, 0, SEEK_SET);
  1196. if (bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
  1197. bytestream2_skip(&s->g, 8);
  1198. }
  1199. if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
  1200. av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
  1201. return AVERROR_INVALIDDATA;
  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. *got_frame = 1;
  1218. return bytestream2_tell(&s->g);
  1219. end:
  1220. jpeg2000_dec_cleanup(s);
  1221. return ret;
  1222. }
  1223. static void jpeg2000_init_static_data(AVCodec *codec)
  1224. {
  1225. ff_jpeg2000_init_tier1_luts();
  1226. }
  1227. #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
  1228. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1229. static const AVOption options[] = {
  1230. { "lowres", "Lower the decoding resolution by a power of two",
  1231. OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
  1232. { NULL },
  1233. };
  1234. static const AVProfile profiles[] = {
  1235. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
  1236. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
  1237. { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
  1238. { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
  1239. { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
  1240. { FF_PROFILE_UNKNOWN },
  1241. };
  1242. static const AVClass class = {
  1243. .class_name = "jpeg2000",
  1244. .item_name = av_default_item_name,
  1245. .option = options,
  1246. .version = LIBAVUTIL_VERSION_INT,
  1247. };
  1248. AVCodec ff_jpeg2000_decoder = {
  1249. .name = "jpeg2000",
  1250. .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
  1251. .type = AVMEDIA_TYPE_VIDEO,
  1252. .id = AV_CODEC_ID_JPEG2000,
  1253. .capabilities = CODEC_CAP_FRAME_THREADS,
  1254. .priv_data_size = sizeof(Jpeg2000DecoderContext),
  1255. .init_static_data = jpeg2000_init_static_data,
  1256. .decode = jpeg2000_decode_frame,
  1257. .priv_class = &class,
  1258. .profiles = NULL_IF_CONFIG_SMALL(profiles)
  1259. };