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.

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