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.

1397 lines
49KB

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