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.

1376 lines
48KB

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