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.

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