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.

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