You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1441 lines
51KB

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