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.

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