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.

1417 lines
50KB

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