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.

1481 lines
53KB

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