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.

1095 lines
38KB

  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 "avcodec.h"
  28. #include "bytestream.h"
  29. #include "internal.h"
  30. #include "thread.h"
  31. #include "j2k.h"
  32. #include "libavutil/common.h"
  33. #define JP2_SIG_TYPE 0x6A502020
  34. #define JP2_SIG_VALUE 0x0D0A870A
  35. #define JP2_CODESTREAM 0x6A703263
  36. #define HAD_COC 0x01
  37. #define HAD_QCC 0x02
  38. typedef struct Jpeg2000Tile {
  39. Jpeg2000Component *comp;
  40. uint8_t properties[4];
  41. Jpeg2000CodingStyle codsty[4];
  42. Jpeg2000QuantStyle qntsty[4];
  43. } Jpeg2000Tile;
  44. typedef struct Jpeg2000DecoderContext {
  45. AVClass *class;
  46. AVCodecContext *avctx;
  47. AVFrame *picture;
  48. GetByteContext g;
  49. int width, height;
  50. int image_offset_x, image_offset_y;
  51. int tile_offset_x, tile_offset_y;
  52. uint8_t cbps[4]; // bits per sample in particular components
  53. uint8_t sgnd[4]; // if a component is signed
  54. uint8_t properties[4];
  55. int cdx[4], cdy[4];
  56. int precision;
  57. int ncomponents;
  58. int tile_width, tile_height;
  59. int numXtiles, numYtiles;
  60. int maxtilelen;
  61. Jpeg2000CodingStyle codsty[4];
  62. Jpeg2000QuantStyle qntsty[4];
  63. int bit_index;
  64. int curtileno;
  65. Jpeg2000Tile *tile;
  66. } Jpeg2000DecoderContext;
  67. static int get_bits(Jpeg2000DecoderContext *s, int n)
  68. {
  69. int res = 0;
  70. while (--n >= 0) {
  71. res <<= 1;
  72. if (s->bit_index == 0) {
  73. s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
  74. }
  75. s->bit_index--;
  76. res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
  77. }
  78. return res;
  79. }
  80. static void j2k_flush(Jpeg2000DecoderContext *s)
  81. {
  82. if (bytestream2_get_byte(&s->g) == 0xff)
  83. bytestream2_skip(&s->g, 1);
  84. s->bit_index = 8;
  85. }
  86. /* decode the value stored in node */
  87. static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
  88. int threshold)
  89. {
  90. Jpeg2000TgtNode *stack[30];
  91. int sp = -1, curval = 0;
  92. if (!node)
  93. return AVERROR(EINVAL);
  94. while (node && !node->vis) {
  95. stack[++sp] = node;
  96. node = node->parent;
  97. }
  98. if (node)
  99. curval = node->val;
  100. else
  101. curval = stack[sp]->val;
  102. while (curval < threshold && sp >= 0) {
  103. if (curval < stack[sp]->val)
  104. curval = stack[sp]->val;
  105. while (curval < threshold) {
  106. int ret;
  107. if ((ret = get_bits(s, 1)) > 0) {
  108. stack[sp]->vis++;
  109. break;
  110. } else if (!ret)
  111. curval++;
  112. else
  113. return ret;
  114. }
  115. stack[sp]->val = curval;
  116. sp--;
  117. }
  118. return curval;
  119. }
  120. /* marker segments */
  121. /* get sizes and offsets of image, tiles; number of components */
  122. static int get_siz(Jpeg2000DecoderContext *s)
  123. {
  124. int i, ret;
  125. ThreadFrame frame = { .f = s->picture };
  126. if (bytestream2_get_bytes_left(&s->g) < 36)
  127. return AVERROR(EINVAL);
  128. s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
  129. s->width = bytestream2_get_be32u(&s->g); // Width
  130. s->height = bytestream2_get_be32u(&s->g); // Height
  131. s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
  132. s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
  133. s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
  134. s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
  135. s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
  136. s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
  137. s->ncomponents = bytestream2_get_be16u(&s->g); // CSiz
  138. if (s->ncomponents <= 0 || s->ncomponents > 4) {
  139. av_log(s->avctx, AV_LOG_ERROR, "unsupported/invalid ncomponents: %d\n", s->ncomponents);
  140. return AVERROR(EINVAL);
  141. }
  142. if (s->tile_width<=0 || s->tile_height<=0)
  143. return AVERROR(EINVAL);
  144. if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
  145. return AVERROR(EINVAL);
  146. for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
  147. uint8_t x = bytestream2_get_byteu(&s->g);
  148. s->cbps[i] = (x & 0x7f) + 1;
  149. s->precision = FFMAX(s->cbps[i], s->precision);
  150. s->sgnd[i] = !!(x & 0x80);
  151. s->cdx[i] = bytestream2_get_byteu(&s->g);
  152. s->cdy[i] = bytestream2_get_byteu(&s->g);
  153. if (s->cdx[i] != 1 || s->cdy[i] != 1) {
  154. av_log(s->avctx, AV_LOG_ERROR, "unsupported/ CDxy values\n");
  155. }
  156. }
  157. s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
  158. s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
  159. if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(Jpeg2000Tile))
  160. return AVERROR(EINVAL);
  161. s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(*s->tile));
  162. if (!s->tile)
  163. return AVERROR(ENOMEM);
  164. for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
  165. Jpeg2000Tile *tile = s->tile + i;
  166. tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
  167. if (!tile->comp)
  168. return AVERROR(ENOMEM);
  169. }
  170. s->avctx->width = s->width - s->image_offset_x;
  171. s->avctx->height = s->height - s->image_offset_y;
  172. switch(s->ncomponents) {
  173. case 1:
  174. if (s->precision > 8) {
  175. s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
  176. } else {
  177. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  178. }
  179. break;
  180. case 3:
  181. if (s->precision > 8) {
  182. s->avctx->pix_fmt = AV_PIX_FMT_RGB48;
  183. } else {
  184. s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
  185. }
  186. break;
  187. case 4:
  188. s->avctx->pix_fmt = AV_PIX_FMT_RGBA;
  189. break;
  190. }
  191. if ((ret = ff_thread_get_buffer(s->avctx, &frame, 0)) < 0)
  192. return ret;
  193. s->picture->pict_type = AV_PICTURE_TYPE_I;
  194. s->picture->key_frame = 1;
  195. return 0;
  196. }
  197. /* get common part for COD and COC segments */
  198. static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
  199. {
  200. uint8_t byte;
  201. if (bytestream2_get_bytes_left(&s->g) < 5)
  202. return AVERROR(EINVAL);
  203. c->nreslevels = bytestream2_get_byteu(&s->g) + 1; // num of resolution levels - 1
  204. if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
  205. av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
  206. return AVERROR_INVALIDDATA;
  207. }
  208. c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
  209. c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
  210. if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
  211. c->log2_cblk_width + c->log2_cblk_height > 14) {
  212. av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
  213. return AVERROR_INVALIDDATA;
  214. }
  215. c->cblk_style = bytestream2_get_byteu(&s->g);
  216. if (c->cblk_style != 0) { // cblk style
  217. av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
  218. }
  219. c->transform = bytestream2_get_byteu(&s->g); // transformation
  220. if (c->csty & JPEG2000_CSTY_PREC) {
  221. int i;
  222. for (i = 0; i < c->nreslevels; i++) {
  223. byte = bytestream2_get_byte(&s->g);
  224. c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
  225. c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
  226. }
  227. } else {
  228. memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
  229. memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
  230. }
  231. return 0;
  232. }
  233. /* get coding parameters for a particular tile or whole image*/
  234. static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  235. uint8_t *properties)
  236. {
  237. Jpeg2000CodingStyle tmp;
  238. int compno;
  239. if (bytestream2_get_bytes_left(&s->g) < 5)
  240. return AVERROR(EINVAL);
  241. tmp.csty = bytestream2_get_byteu(&s->g);
  242. // get progression order
  243. tmp.prog_order = bytestream2_get_byteu(&s->g);
  244. if (tmp.prog_order) {
  245. av_log(s->avctx, AV_LOG_ERROR, "only LRCP progression supported\n");
  246. }
  247. tmp.nlayers = bytestream2_get_be16u(&s->g);
  248. tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
  249. get_cox(s, &tmp);
  250. for (compno = 0; compno < s->ncomponents; compno++)
  251. if (!(properties[compno] & HAD_COC))
  252. memcpy(c + compno, &tmp, sizeof(tmp));
  253. return 0;
  254. }
  255. /* Get coding parameters for a component in the whole image or a
  256. * particular tile. */
  257. static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
  258. uint8_t *properties)
  259. {
  260. int compno;
  261. if (bytestream2_get_bytes_left(&s->g) < 2)
  262. return AVERROR(EINVAL);
  263. compno = bytestream2_get_byteu(&s->g);
  264. c += compno;
  265. c->csty = bytestream2_get_byte(&s->g);
  266. get_cox(s, c);
  267. properties[compno] |= HAD_COC;
  268. return 0;
  269. }
  270. /* Get common part for QCD and QCC segments. */
  271. static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
  272. {
  273. int i, x;
  274. if (bytestream2_get_bytes_left(&s->g) < 1)
  275. return AVERROR(EINVAL);
  276. x = bytestream2_get_byteu(&s->g); // Sqcd
  277. q->nguardbits = x >> 5;
  278. q->quantsty = x & 0x1f;
  279. if (q->quantsty == JPEG2000_QSTY_NONE) {
  280. n -= 3;
  281. if (bytestream2_get_bytes_left(&s->g) < n || 32*3 < n)
  282. return AVERROR(EINVAL);
  283. for (i = 0; i < n; i++)
  284. q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
  285. } else if (q->quantsty == JPEG2000_QSTY_SI) {
  286. if (bytestream2_get_bytes_left(&s->g) < 2)
  287. return AVERROR(EINVAL);
  288. x = bytestream2_get_be16u(&s->g);
  289. q->expn[0] = x >> 11;
  290. q->mant[0] = x & 0x7ff;
  291. for (i = 1; i < 32 * 3; i++) {
  292. int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
  293. q->expn[i] = curexpn;
  294. q->mant[i] = q->mant[0];
  295. }
  296. } else {
  297. n = (n - 3) >> 1;
  298. if (bytestream2_get_bytes_left(&s->g) < 2 * n || 32*3 < n)
  299. return AVERROR(EINVAL);
  300. for (i = 0; i < n; i++) {
  301. x = bytestream2_get_be16u(&s->g);
  302. q->expn[i] = x >> 11;
  303. q->mant[i] = x & 0x7ff;
  304. }
  305. }
  306. return 0;
  307. }
  308. /* Get quantization parameters for a particular tile or a whole image. */
  309. static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  310. uint8_t *properties)
  311. {
  312. Jpeg2000QuantStyle tmp;
  313. int compno;
  314. if (get_qcx(s, n, &tmp))
  315. return -1;
  316. for (compno = 0; compno < s->ncomponents; compno++)
  317. if (!(properties[compno] & HAD_QCC))
  318. memcpy(q + compno, &tmp, sizeof(Jpeg2000QuantStyle));
  319. return 0;
  320. }
  321. /* Get quantization parameters for a component in the whole image
  322. * on in a particular tile. */
  323. static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
  324. uint8_t *properties)
  325. {
  326. int compno;
  327. if (bytestream2_get_bytes_left(&s->g) < 1)
  328. return AVERROR(EINVAL);
  329. compno = bytestream2_get_byteu(&s->g);
  330. properties[compno] |= HAD_QCC;
  331. return get_qcx(s, n - 1, q + compno);
  332. }
  333. /** get start of tile segment */
  334. static int get_sot(Jpeg2000DecoderContext *s)
  335. {
  336. if (bytestream2_get_bytes_left(&s->g) < 8)
  337. return AVERROR(EINVAL);
  338. s->curtileno = bytestream2_get_be16u(&s->g); ///< Isot
  339. if ((unsigned)s->curtileno >= s->numXtiles * s->numYtiles) {
  340. s->curtileno=0;
  341. return AVERROR(EINVAL);
  342. }
  343. bytestream2_skipu(&s->g, 4); ///< Psot (ignored)
  344. if (!bytestream2_get_byteu(&s->g)) { ///< TPsot
  345. Jpeg2000Tile *tile = s->tile + s->curtileno;
  346. /* copy defaults */
  347. memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
  348. memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
  349. }
  350. bytestream2_get_byteu(&s->g); ///< TNsot
  351. return 0;
  352. }
  353. static int init_tile(Jpeg2000DecoderContext *s, int tileno)
  354. {
  355. int compno;
  356. int tilex = tileno % s->numXtiles;
  357. int tiley = tileno / s->numXtiles;
  358. Jpeg2000Tile *tile = s->tile + tileno;
  359. if (!tile->comp)
  360. return AVERROR(ENOMEM);
  361. for (compno = 0; compno < s->ncomponents; compno++) {
  362. Jpeg2000Component *comp = tile->comp + compno;
  363. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  364. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  365. int ret; // global bandno
  366. comp->coord[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
  367. comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width + s->tile_offset_x, s->width);
  368. comp->coord[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
  369. comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height + s->tile_offset_y, s->height);
  370. if (ret = ff_j2k_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx))
  371. return ret;
  372. }
  373. return 0;
  374. }
  375. /** read the number of coding passes */
  376. static int getnpasses(Jpeg2000DecoderContext *s)
  377. {
  378. int num;
  379. if (!get_bits(s, 1))
  380. return 1;
  381. if (!get_bits(s, 1))
  382. return 2;
  383. if ((num = get_bits(s, 2)) != 3)
  384. return num < 0 ? num : 3 + num;
  385. if ((num = get_bits(s, 5)) != 31)
  386. return num < 0 ? num : 6 + num;
  387. num = get_bits(s, 7);
  388. return num < 0 ? num : 37 + num;
  389. }
  390. static int getlblockinc(Jpeg2000DecoderContext *s)
  391. {
  392. int res = 0, ret;
  393. while (ret = get_bits(s, 1)) {
  394. if (ret < 0)
  395. return ret;
  396. res++;
  397. }
  398. return res;
  399. }
  400. static int decode_packet(Jpeg2000DecoderContext *s,
  401. Jpeg2000CodingStyle *codsty,
  402. Jpeg2000ResLevel *rlevel, int precno,
  403. int layno, uint8_t *expn, int numgbits)
  404. {
  405. int bandno, cblkno, ret, nb_code_blocks;
  406. if (!(ret = get_bits(s, 1))) {
  407. j2k_flush(s);
  408. return 0;
  409. } else if (ret < 0)
  410. return ret;
  411. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  412. Jpeg2000Band *band = rlevel->band + bandno;
  413. Jpeg2000Prec *prec = band->prec + precno;
  414. if (band->coord[0][0] == band->coord[0][1] ||
  415. band->coord[1][0] == band->coord[1][1])
  416. continue;
  417. nb_code_blocks = prec->nb_codeblocks_height *
  418. prec->nb_codeblocks_width;
  419. for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  420. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  421. int incl, newpasses, llen;
  422. if (cblk->npasses)
  423. incl = get_bits(s, 1);
  424. else
  425. incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
  426. if (!incl)
  427. continue;
  428. else if (incl < 0)
  429. return incl;
  430. if (!cblk->npasses)
  431. cblk->nonzerobits = expn[bandno] + numgbits - 1 -
  432. tag_tree_decode(s, prec->zerobits + cblkno,
  433. 100);
  434. if ((newpasses = getnpasses(s)) < 0)
  435. return newpasses;
  436. if ((llen = getlblockinc(s)) < 0)
  437. return llen;
  438. cblk->lblock += llen;
  439. if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
  440. return ret;
  441. cblk->lengthinc = ret;
  442. cblk->npasses += newpasses;
  443. }
  444. }
  445. j2k_flush(s);
  446. if (codsty->csty & JPEG2000_CSTY_EPH) {
  447. if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
  448. bytestream2_skip(&s->g, 2);
  449. else
  450. av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
  451. }
  452. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  453. Jpeg2000Band *band = rlevel->band + bandno;
  454. Jpeg2000Prec *prec = band->prec + precno;
  455. nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
  456. for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
  457. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  458. if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
  459. || sizeof(cblk->data) < cblk->lengthinc
  460. )
  461. return AVERROR(EINVAL);
  462. /* Code-block data can be empty. In that case initialize data
  463. * with 0xFFFF. */
  464. if (cblk->lengthinc > 0) {
  465. bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);
  466. } else {
  467. cblk->data[0] = 0xFF;
  468. cblk->data[1] = 0xFF;
  469. }
  470. cblk->length += cblk->lengthinc;
  471. cblk->lengthinc = 0;
  472. }
  473. }
  474. return 0;
  475. }
  476. static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  477. {
  478. int layno, reslevelno, compno, precno, ok_reslevel;
  479. s->bit_index = 8;
  480. for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
  481. ok_reslevel = 1;
  482. for (reslevelno = 0; ok_reslevel; reslevelno++) {
  483. ok_reslevel = 0;
  484. for (compno = 0; compno < s->ncomponents; compno++) {
  485. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  486. Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
  487. if (reslevelno < codsty->nreslevels) {
  488. Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
  489. ok_reslevel = 1;
  490. for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) {
  491. if (decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn +
  492. (reslevelno ? 3*(reslevelno-1)+1 : 0), qntsty->nguardbits))
  493. return -1;
  494. }
  495. }
  496. }
  497. }
  498. }
  499. return 0;
  500. }
  501. /* TIER-1 routines */
  502. static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol,
  503. int vert_causal_ctx_csty_symbol)
  504. {
  505. int mask = 3 << (bpno - 1), y0, x, y;
  506. for (y0 = 0; y0 < height; y0 += 4)
  507. for (x = 0; x < width; x++)
  508. for (y = y0; y < height && y < y0+4; y++) {
  509. if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
  510. && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  511. int flags_mask = -1;
  512. if (vert_causal_ctx_csty_symbol && y == y0 + 3)
  513. flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
  514. if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
  515. int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
  516. if (bpass_csty_symbol)
  517. t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
  518. else
  519. t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
  520. -mask : mask;
  521. ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
  522. }
  523. t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
  524. }
  525. }
  526. }
  527. static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
  528. int bpno)
  529. {
  530. int phalf, nhalf;
  531. int y0, x, y;
  532. phalf = 1 << (bpno - 1);
  533. nhalf = -phalf;
  534. for (y0 = 0; y0 < height; y0 += 4)
  535. for (x = 0; x < width; x++)
  536. for (y = y0; y < height && y < y0 + 4; y++)
  537. if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
  538. int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
  539. int r = ff_mqc_decode(&t1->mqc,
  540. t1->mqc.cx_states + ctxno)
  541. ? phalf : nhalf;
  542. t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
  543. t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
  544. }
  545. }
  546. static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height,
  547. int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol)
  548. {
  549. int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
  550. for (y0 = 0; y0 < height; y0 += 4) {
  551. for (x = 0; x < width; x++) {
  552. if (y0 + 3 < height &&
  553. !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  554. (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  555. (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  556. (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
  557. if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
  558. continue;
  559. runlen = ff_mqc_decode(&t1->mqc,
  560. t1->mqc.cx_states + MQC_CX_UNI);
  561. runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
  562. t1->mqc.cx_states +
  563. MQC_CX_UNI);
  564. dec = 1;
  565. } else {
  566. runlen = 0;
  567. dec = 0;
  568. }
  569. for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
  570. if (!dec) {
  571. if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
  572. int flags_mask = -1;
  573. if (vert_causal_ctx_csty_symbol && y == y0 + 3)
  574. flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
  575. dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
  576. bandno));
  577. }
  578. }
  579. if (dec) {
  580. int xorbit;
  581. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
  582. &xorbit);
  583. t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
  584. t1->mqc.cx_states + ctxno) ^
  585. xorbit)
  586. ? -mask : mask;
  587. ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
  588. }
  589. dec = 0;
  590. t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
  591. }
  592. }
  593. }
  594. if (seg_symbols) {
  595. int val;
  596. val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  597. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  598. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  599. val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
  600. if (val != 0xa)
  601. av_log(s->avctx, AV_LOG_ERROR,
  602. "Segmentation symbol value incorrect\n");
  603. }
  604. }
  605. static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
  606. Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
  607. int width, int height, int bandpos)
  608. {
  609. int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y, clnpass_cnt = 0;
  610. int bpass_csty_symbol = JPEG2000_CBLK_BYPASS & codsty->cblk_style;
  611. int vert_causal_ctx_csty_symbol = JPEG2000_CBLK_VSC & codsty->cblk_style;
  612. for (y = 0; y < height+2; y++)
  613. memset(t1->flags[y], 0, (width+2)*sizeof(int));
  614. for (y = 0; y < height; y++)
  615. memset(t1->data[y], 0, width*sizeof(int));
  616. cblk->data[cblk->length] = 0xff;
  617. cblk->data[cblk->length+1] = 0xff;
  618. ff_mqc_initdec(&t1->mqc, cblk->data);
  619. while (passno--) {
  620. switch(pass_t) {
  621. case 0: decode_sigpass(t1, width, height, bpno+1, bandpos,
  622. bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol);
  623. break;
  624. case 1: decode_refpass(t1, width, height, bpno+1);
  625. if (bpass_csty_symbol && clnpass_cnt >= 4)
  626. ff_mqc_initdec(&t1->mqc, cblk->data);
  627. break;
  628. case 2: decode_clnpass(s, t1, width, height, bpno+1, bandpos,
  629. codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol);
  630. clnpass_cnt = clnpass_cnt + 1;
  631. if (bpass_csty_symbol && clnpass_cnt >= 4)
  632. ff_mqc_initdec(&t1->mqc, cblk->data);
  633. break;
  634. }
  635. pass_t++;
  636. if (pass_t == 3) {
  637. bpno--;
  638. pass_t = 0;
  639. }
  640. }
  641. return 0;
  642. }
  643. static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  644. {
  645. int i, *src[3], i0, i1, i2, csize = 1;
  646. for (i = 0; i < 3; i++)
  647. src[i] = tile->comp[i].data;
  648. for (i = 0; i < 2; i++)
  649. csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
  650. if (tile->codsty[0].transform == FF_DWT97) {
  651. for (i = 0; i < csize; i++) {
  652. i0 = *src[0] + (*src[2] * 46802 >> 16);
  653. i1 = *src[0] - (*src[1] * 22553 + *src[2] * 46802 >> 16);
  654. i2 = *src[0] + (116130 * *src[1] >> 16);
  655. *src[0]++ = i0;
  656. *src[1]++ = i1;
  657. *src[2]++ = i2;
  658. }
  659. } else{
  660. for (i = 0; i < csize; i++) {
  661. i1 = *src[0] - (*src[2] + *src[1] >> 2);
  662. i0 = i1 + *src[2];
  663. i2 = i1 + *src[1];
  664. *src[0]++ = i0;
  665. *src[1]++ = i1;
  666. *src[2]++ = i2;
  667. }
  668. }
  669. }
  670. static int decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
  671. {
  672. int compno, reslevelno, bandno;
  673. int x, y, *src[4];
  674. uint8_t *line;
  675. Jpeg2000T1Context t1;
  676. /* Loop on tile components */
  677. for (compno = 0; compno < s->ncomponents; compno++) {
  678. Jpeg2000Component *comp = tile->comp + compno;
  679. Jpeg2000CodingStyle *codsty = tile->codsty + compno;
  680. /* Loop on resolution levels */
  681. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  682. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  683. /* Loop on bands */
  684. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  685. int nb_precincts, precno;
  686. Jpeg2000Band *band = rlevel->band + bandno;
  687. int cblkx, cblky, cblkno=0, bandpos;
  688. bandpos = bandno + (reslevelno > 0);
  689. if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
  690. continue;
  691. nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
  692. /* Loop on precincts */
  693. for (precno = 0; precno < nb_precincts; precno++) {
  694. Jpeg2000Prec *prec = band->prec + precno;
  695. /* Loop on codeblocks */
  696. for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
  697. int x, y;
  698. int i, j;
  699. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  700. decode_cblk(s, codsty, &t1, cblk,
  701. cblk->coord[0][1] - cblk->coord[0][0],
  702. cblk->coord[1][1] - cblk->coord[1][0],
  703. bandpos);
  704. /* Manage band offsets */
  705. x = cblk->coord[0][0];
  706. y = cblk->coord[1][0];
  707. if (codsty->transform == FF_DWT53) {
  708. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  709. int *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * (y+j) + x];
  710. int *ptr = t1.data[j];
  711. for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
  712. datap[i] = ptr[i] >> 1;
  713. }
  714. }
  715. } else{
  716. for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
  717. int *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * (y+j) + x];
  718. int *ptr = t1.data[j];
  719. for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {
  720. int tmp = ((int64_t)ptr[i]) * ((int64_t)band->stepsize) >> 16, tmp2;
  721. tmp2 = FFABS(tmp>>1) + (tmp&1);
  722. datap[i] = tmp < 0 ? -tmp2 : tmp2;
  723. }
  724. }
  725. }
  726. } /* end cblk */
  727. } /*end prec */
  728. } /* end band */
  729. } /* end reslevel */
  730. ff_j2k_dwt_decode(&comp->dwt, comp->data);
  731. src[compno] = comp->data;
  732. } /*end comp */
  733. /* inverse MCT transformation */
  734. if (tile->codsty[0].mct)
  735. mct_decode(s, tile);
  736. if (s->precision <= 8) {
  737. for (compno = 0; compno < s->ncomponents; compno++) {
  738. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  739. line = s->picture->data[0] + y * s->picture->linesize[0];
  740. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  741. uint8_t *dst;
  742. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  743. dst = line + x * s->ncomponents + compno;
  744. for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
  745. *src[compno] += 1 << (s->cbps[compno]-1);
  746. if (*src[compno] < 0)
  747. *src[compno] = 0;
  748. else if (*src[compno] >= (1 << s->cbps[compno]))
  749. *src[compno] = (1 << s->cbps[compno]) - 1;
  750. *dst = *src[compno]++;
  751. dst += s->ncomponents;
  752. }
  753. line += s->picture->linesize[0];
  754. }
  755. }
  756. } else {
  757. for (compno = 0; compno < s->ncomponents; compno++) {
  758. y = tile->comp[compno].coord[1][0] - s->image_offset_y;
  759. line = s->picture->data[0] + y * s->picture->linesize[0];
  760. for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
  761. uint16_t *dst;
  762. x = tile->comp[compno].coord[0][0] - s->image_offset_x;
  763. dst = (uint16_t *)(line + (x * s->ncomponents + compno) * 2);
  764. for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {
  765. int32_t val;
  766. val = *src[compno]++ << (16 - s->cbps[compno]);
  767. val += 1 << 15;
  768. val = av_clip(val, 0, (1 << 16) - 1);
  769. *dst = val;
  770. dst += s->ncomponents;
  771. }
  772. line += s->picture->linesize[0];
  773. }
  774. }
  775. }
  776. return 0;
  777. }
  778. static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
  779. {
  780. int tileno, compno;
  781. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
  782. for (compno = 0; compno < s->ncomponents; compno++) {
  783. Jpeg2000Component *comp = s->tile[tileno].comp + compno;
  784. Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
  785. ff_j2k_cleanup(comp, codsty);
  786. }
  787. av_freep(&s->tile[tileno].comp);
  788. }
  789. av_freep(&s->tile);
  790. }
  791. static int decode_codestream(Jpeg2000DecoderContext *s)
  792. {
  793. Jpeg2000CodingStyle *codsty = s->codsty;
  794. Jpeg2000QuantStyle *qntsty = s->qntsty;
  795. uint8_t *properties = s->properties;
  796. for (;;) {
  797. int oldpos, marker, len, ret = 0;
  798. if (bytestream2_get_bytes_left(&s->g) < 2) {
  799. av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
  800. break;
  801. }
  802. marker = bytestream2_get_be16u(&s->g);
  803. av_dlog(s->avctx, "marker 0x%.4X at pos 0x%x\n", marker, bytestream2_tell(&s->g) - 4);
  804. oldpos = bytestream2_tell(&s->g);
  805. if (marker == JPEG2000_SOD) {
  806. Jpeg2000Tile *tile = s->tile + s->curtileno;
  807. if (ret = init_tile(s, s->curtileno)) {
  808. av_log(s->avctx, AV_LOG_ERROR, "tile initialization failed\n");
  809. return ret;
  810. }
  811. if (ret = jpeg2000_decode_packets(s, tile)) {
  812. av_log(s->avctx, AV_LOG_ERROR, "packets decoding failed\n");
  813. return ret;
  814. }
  815. continue;
  816. }
  817. if (marker == JPEG2000_EOC)
  818. break;
  819. if (bytestream2_get_bytes_left(&s->g) < 2)
  820. return AVERROR(EINVAL);
  821. len = bytestream2_get_be16u(&s->g);
  822. switch (marker) {
  823. case JPEG2000_SIZ:
  824. ret = get_siz(s);
  825. if (!s->tile)
  826. s->numXtiles = s->numYtiles = 0;
  827. break;
  828. case JPEG2000_COC:
  829. ret = get_coc(s, codsty, properties);
  830. break;
  831. case JPEG2000_COD:
  832. ret = get_cod(s, codsty, properties);
  833. break;
  834. case JPEG2000_QCC:
  835. ret = get_qcc(s, len, qntsty, properties);
  836. break;
  837. case JPEG2000_QCD:
  838. ret = get_qcd(s, len, qntsty, properties);
  839. break;
  840. case JPEG2000_SOT:
  841. if (!(ret = get_sot(s))) {
  842. codsty = s->tile[s->curtileno].codsty;
  843. qntsty = s->tile[s->curtileno].qntsty;
  844. properties = s->tile[s->curtileno].properties;
  845. }
  846. break;
  847. case JPEG2000_COM:
  848. // the comment is ignored
  849. bytestream2_skip(&s->g, len - 2);
  850. break;
  851. default:
  852. av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%x\n", marker, bytestream2_tell(&s->g) - 4);
  853. bytestream2_skip(&s->g, len - 2);
  854. break;
  855. }
  856. if (bytestream2_tell(&s->g) - oldpos != len || ret) {
  857. av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker);
  858. return ret ? ret : -1;
  859. }
  860. }
  861. return 0;
  862. }
  863. static int jp2_find_codestream(Jpeg2000DecoderContext *s)
  864. {
  865. uint32_t atom_size, atom;
  866. int found_codestream = 0, search_range = 10;
  867. while (!found_codestream && search_range && bytestream2_get_bytes_left(&s->g) >= 8) {
  868. atom_size = bytestream2_get_be32u(&s->g);
  869. atom = bytestream2_get_be32u(&s->g);
  870. if (atom == JP2_CODESTREAM) {
  871. found_codestream = 1;
  872. } else {
  873. if (bytestream2_get_bytes_left(&s->g) < atom_size - 8)
  874. return 0;
  875. bytestream2_skipu(&s->g, atom_size - 8);
  876. search_range--;
  877. }
  878. }
  879. if (found_codestream)
  880. return 1;
  881. return 0;
  882. }
  883. static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
  884. int *got_frame, AVPacket *avpkt)
  885. {
  886. Jpeg2000DecoderContext *s = avctx->priv_data;
  887. AVFrame *picture = data;
  888. int tileno, ret;
  889. s->picture = picture;
  890. s->avctx = avctx;
  891. bytestream2_init(&s->g, avpkt->data, avpkt->size);
  892. s->curtileno = -1;
  893. if (bytestream2_get_bytes_left(&s->g) < 2) {
  894. ret = AVERROR(EINVAL);
  895. goto err_out;
  896. }
  897. // check if the image is in jp2 format
  898. if (bytestream2_get_bytes_left(&s->g) >= 12 &&
  899. (bytestream2_get_be32u(&s->g) == 12) &&
  900. (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
  901. (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
  902. if (!jp2_find_codestream(s)) {
  903. av_log(avctx, AV_LOG_ERROR, "couldn't find jpeg2k codestream atom\n");
  904. ret = -1;
  905. goto err_out;
  906. }
  907. } else {
  908. bytestream2_seek(&s->g, 0, SEEK_SET);
  909. }
  910. if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
  911. av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
  912. ret = -1;
  913. goto err_out;
  914. }
  915. if (ret = decode_codestream(s))
  916. goto err_out;
  917. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
  918. if (ret = decode_tile(s, s->tile + tileno))
  919. goto err_out;
  920. jpeg2000_dec_cleanup(s);
  921. *got_frame = 1;
  922. return bytestream2_tell(&s->g);
  923. err_out:
  924. jpeg2000_dec_cleanup(s);
  925. return ret;
  926. }
  927. static void jpeg2000_init_static_data(AVCodec *codec)
  928. {
  929. ff_jpeg2000_init_tier1_luts();
  930. }
  931. static const AVProfile profiles[] = {
  932. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
  933. { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
  934. { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
  935. { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
  936. { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
  937. { FF_PROFILE_UNKNOWN },
  938. };
  939. AVCodec ff_j2k_decoder = {
  940. .name = "j2k",
  941. .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
  942. .type = AVMEDIA_TYPE_VIDEO,
  943. .id = AV_CODEC_ID_JPEG2000,
  944. .capabilities = CODEC_CAP_EXPERIMENTAL | CODEC_CAP_FRAME_THREADS,
  945. .priv_data_size = sizeof(Jpeg2000DecoderContext),
  946. .init_static_data = jpeg2000_init_static_data,
  947. .decode = jpeg2000_decode_frame,
  948. .profiles = NULL_IF_CONFIG_SMALL(profiles)
  949. };