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.

1436 lines
50KB

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