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.

1810 lines
58KB

  1. /*
  2. * OpenEXR (.exr) image decoder
  3. * Copyright (c) 2006 Industrial Light & Magic, a division of Lucas Digital Ltd. LLC
  4. * Copyright (c) 2009 Jimmy Christensen
  5. *
  6. * B44/B44A, Tile added by Jokyo Images support by CNC - French National Center for Cinema
  7. *
  8. * This file is part of FFmpeg.
  9. *
  10. * FFmpeg is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * FFmpeg is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with FFmpeg; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. /**
  25. * @file
  26. * OpenEXR decoder
  27. * @author Jimmy Christensen
  28. *
  29. * For more information on the OpenEXR format, visit:
  30. * http://openexr.com/
  31. *
  32. * exr_flt2uint() and exr_halflt2uint() is credited to Reimar Döffinger.
  33. * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner.
  34. */
  35. #include <float.h>
  36. #include <zlib.h>
  37. #include "libavutil/common.h"
  38. #include "libavutil/imgutils.h"
  39. #include "libavutil/intfloat.h"
  40. #include "libavutil/opt.h"
  41. #include "libavutil/color_utils.h"
  42. #include "avcodec.h"
  43. #include "bytestream.h"
  44. #include "get_bits.h"
  45. #include "internal.h"
  46. #include "mathops.h"
  47. #include "thread.h"
  48. enum ExrCompr {
  49. EXR_RAW,
  50. EXR_RLE,
  51. EXR_ZIP1,
  52. EXR_ZIP16,
  53. EXR_PIZ,
  54. EXR_PXR24,
  55. EXR_B44,
  56. EXR_B44A,
  57. EXR_UNKN,
  58. };
  59. enum ExrPixelType {
  60. EXR_UINT,
  61. EXR_HALF,
  62. EXR_FLOAT,
  63. EXR_UNKNOWN,
  64. };
  65. enum ExrTileLevelMode {
  66. EXR_TILE_LEVEL_ONE,
  67. EXR_TILE_LEVEL_MIPMAP,
  68. EXR_TILE_LEVEL_RIPMAP,
  69. EXR_TILE_LEVEL_UNKNOWN,
  70. };
  71. enum ExrTileLevelRound {
  72. EXR_TILE_ROUND_UP,
  73. EXR_TILE_ROUND_DOWN,
  74. EXR_TILE_ROUND_UNKNOWN,
  75. };
  76. typedef struct EXRChannel {
  77. int xsub, ysub;
  78. enum ExrPixelType pixel_type;
  79. } EXRChannel;
  80. typedef struct EXRTileAttribute {
  81. int32_t xSize;
  82. int32_t ySize;
  83. enum ExrTileLevelMode level_mode;
  84. enum ExrTileLevelRound level_round;
  85. } EXRTileAttribute;
  86. typedef struct EXRThreadData {
  87. uint8_t *uncompressed_data;
  88. int uncompressed_size;
  89. uint8_t *tmp;
  90. int tmp_size;
  91. uint8_t *bitmap;
  92. uint16_t *lut;
  93. } EXRThreadData;
  94. typedef struct EXRContext {
  95. AVClass *class;
  96. AVFrame *picture;
  97. AVCodecContext *avctx;
  98. enum ExrCompr compression;
  99. enum ExrPixelType pixel_type;
  100. int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
  101. const AVPixFmtDescriptor *desc;
  102. int w, h;
  103. uint32_t xmax, xmin;
  104. uint32_t ymax, ymin;
  105. uint32_t xdelta, ydelta;
  106. int ysize, xsize;
  107. uint64_t scan_line_size;
  108. int scan_lines_per_block;
  109. EXRTileAttribute tile_attr; /* header data attribute of tile */
  110. int is_tile; /* 0 if scanline, 1 if tile */
  111. GetByteContext gb;
  112. const uint8_t *buf;
  113. int buf_size;
  114. EXRChannel *channels;
  115. int nb_channels;
  116. int current_channel_offset;
  117. EXRThreadData *thread_data;
  118. const char *layer;
  119. enum AVColorTransferCharacteristic apply_trc_type;
  120. float gamma;
  121. uint16_t gamma_table[65536];
  122. } EXRContext;
  123. /* -15 stored using a single precision bias of 127 */
  124. #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
  125. /* max exponent value in single precision that will be converted
  126. * to Inf or Nan when stored as a half-float */
  127. #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
  128. /* 255 is the max exponent biased value */
  129. #define FLOAT_MAX_BIASED_EXP (0xFF << 23)
  130. #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
  131. /**
  132. * Convert a half float as a uint16_t into a full float.
  133. *
  134. * @param hf half float as uint16_t
  135. *
  136. * @return float value
  137. */
  138. static union av_intfloat32 exr_half2float(uint16_t hf)
  139. {
  140. unsigned int sign = (unsigned int) (hf >> 15);
  141. unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
  142. unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
  143. union av_intfloat32 f;
  144. if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
  145. // we have a half-float NaN or Inf
  146. // half-float NaNs will be converted to a single precision NaN
  147. // half-float Infs will be converted to a single precision Inf
  148. exp = FLOAT_MAX_BIASED_EXP;
  149. if (mantissa)
  150. mantissa = (1 << 23) - 1; // set all bits to indicate a NaN
  151. } else if (exp == 0x0) {
  152. // convert half-float zero/denorm to single precision value
  153. if (mantissa) {
  154. mantissa <<= 1;
  155. exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
  156. // check for leading 1 in denorm mantissa
  157. while ((mantissa & (1 << 10))) {
  158. // for every leading 0, decrement single precision exponent by 1
  159. // and shift half-float mantissa value to the left
  160. mantissa <<= 1;
  161. exp -= (1 << 23);
  162. }
  163. // clamp the mantissa to 10-bits
  164. mantissa &= ((1 << 10) - 1);
  165. // shift left to generate single-precision mantissa of 23-bits
  166. mantissa <<= 13;
  167. }
  168. } else {
  169. // shift left to generate single-precision mantissa of 23-bits
  170. mantissa <<= 13;
  171. // generate single precision biased exponent value
  172. exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
  173. }
  174. f.i = (sign << 31) | exp | mantissa;
  175. return f;
  176. }
  177. /**
  178. * Convert from 32-bit float as uint32_t to uint16_t.
  179. *
  180. * @param v 32-bit float
  181. *
  182. * @return normalized 16-bit unsigned int
  183. */
  184. static inline uint16_t exr_flt2uint(uint32_t v)
  185. {
  186. unsigned int exp = v >> 23;
  187. // "HACK": negative values result in exp< 0, so clipping them to 0
  188. // is also handled by this condition, avoids explicit check for sign bit.
  189. if (exp <= 127 + 7 - 24) // we would shift out all bits anyway
  190. return 0;
  191. if (exp >= 127)
  192. return 0xffff;
  193. v &= 0x007fffff;
  194. return (v + (1 << 23)) >> (127 + 7 - exp);
  195. }
  196. /**
  197. * Convert from 16-bit float as uint16_t to uint16_t.
  198. *
  199. * @param v 16-bit float
  200. *
  201. * @return normalized 16-bit unsigned int
  202. */
  203. static inline uint16_t exr_halflt2uint(uint16_t v)
  204. {
  205. unsigned exp = 14 - (v >> 10);
  206. if (exp >= 14) {
  207. if (exp == 14)
  208. return (v >> 9) & 1;
  209. else
  210. return (v & 0x8000) ? 0 : 0xffff;
  211. }
  212. v <<= 6;
  213. return (v + (1 << 16)) >> (exp + 1);
  214. }
  215. static void predictor(uint8_t *src, int size)
  216. {
  217. uint8_t *t = src + 1;
  218. uint8_t *stop = src + size;
  219. while (t < stop) {
  220. int d = (int) t[-1] + (int) t[0] - 128;
  221. t[0] = d;
  222. ++t;
  223. }
  224. }
  225. static void reorder_pixels(uint8_t *src, uint8_t *dst, int size)
  226. {
  227. const int8_t *t1 = src;
  228. const int8_t *t2 = src + (size + 1) / 2;
  229. int8_t *s = dst;
  230. int8_t *stop = s + size;
  231. while (1) {
  232. if (s < stop)
  233. *(s++) = *(t1++);
  234. else
  235. break;
  236. if (s < stop)
  237. *(s++) = *(t2++);
  238. else
  239. break;
  240. }
  241. }
  242. static int zip_uncompress(const uint8_t *src, int compressed_size,
  243. int uncompressed_size, EXRThreadData *td)
  244. {
  245. unsigned long dest_len = uncompressed_size;
  246. if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
  247. dest_len != uncompressed_size)
  248. return AVERROR_INVALIDDATA;
  249. predictor(td->tmp, uncompressed_size);
  250. reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
  251. return 0;
  252. }
  253. static int rle_uncompress(const uint8_t *src, int compressed_size,
  254. int uncompressed_size, EXRThreadData *td)
  255. {
  256. uint8_t *d = td->tmp;
  257. const int8_t *s = src;
  258. int ssize = compressed_size;
  259. int dsize = uncompressed_size;
  260. uint8_t *dend = d + dsize;
  261. int count;
  262. while (ssize > 0) {
  263. count = *s++;
  264. if (count < 0) {
  265. count = -count;
  266. if ((dsize -= count) < 0 ||
  267. (ssize -= count + 1) < 0)
  268. return AVERROR_INVALIDDATA;
  269. while (count--)
  270. *d++ = *s++;
  271. } else {
  272. count++;
  273. if ((dsize -= count) < 0 ||
  274. (ssize -= 2) < 0)
  275. return AVERROR_INVALIDDATA;
  276. while (count--)
  277. *d++ = *s;
  278. s++;
  279. }
  280. }
  281. if (dend != d)
  282. return AVERROR_INVALIDDATA;
  283. predictor(td->tmp, uncompressed_size);
  284. reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
  285. return 0;
  286. }
  287. #define USHORT_RANGE (1 << 16)
  288. #define BITMAP_SIZE (1 << 13)
  289. static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
  290. {
  291. int i, k = 0;
  292. for (i = 0; i < USHORT_RANGE; i++)
  293. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  294. lut[k++] = i;
  295. i = k - 1;
  296. memset(lut + k, 0, (USHORT_RANGE - k) * 2);
  297. return i;
  298. }
  299. static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
  300. {
  301. int i;
  302. for (i = 0; i < dsize; ++i)
  303. dst[i] = lut[dst[i]];
  304. }
  305. #define HUF_ENCBITS 16 // literal (value) bit length
  306. #define HUF_DECBITS 14 // decoding bit size (>= 8)
  307. #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size
  308. #define HUF_DECSIZE (1 << HUF_DECBITS) // decoding table size
  309. #define HUF_DECMASK (HUF_DECSIZE - 1)
  310. typedef struct HufDec {
  311. int len;
  312. int lit;
  313. int *p;
  314. } HufDec;
  315. static void huf_canonical_code_table(uint64_t *hcode)
  316. {
  317. uint64_t c, n[59] = { 0 };
  318. int i;
  319. for (i = 0; i < HUF_ENCSIZE; ++i)
  320. n[hcode[i]] += 1;
  321. c = 0;
  322. for (i = 58; i > 0; --i) {
  323. uint64_t nc = ((c + n[i]) >> 1);
  324. n[i] = c;
  325. c = nc;
  326. }
  327. for (i = 0; i < HUF_ENCSIZE; ++i) {
  328. int l = hcode[i];
  329. if (l > 0)
  330. hcode[i] = l | (n[l]++ << 6);
  331. }
  332. }
  333. #define SHORT_ZEROCODE_RUN 59
  334. #define LONG_ZEROCODE_RUN 63
  335. #define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
  336. #define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN)
  337. static int huf_unpack_enc_table(GetByteContext *gb,
  338. int32_t im, int32_t iM, uint64_t *hcode)
  339. {
  340. GetBitContext gbit;
  341. int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
  342. if (ret < 0)
  343. return ret;
  344. for (; im <= iM; im++) {
  345. uint64_t l = hcode[im] = get_bits(&gbit, 6);
  346. if (l == LONG_ZEROCODE_RUN) {
  347. int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
  348. if (im + zerun > iM + 1)
  349. return AVERROR_INVALIDDATA;
  350. while (zerun--)
  351. hcode[im++] = 0;
  352. im--;
  353. } else if (l >= SHORT_ZEROCODE_RUN) {
  354. int zerun = l - SHORT_ZEROCODE_RUN + 2;
  355. if (im + zerun > iM + 1)
  356. return AVERROR_INVALIDDATA;
  357. while (zerun--)
  358. hcode[im++] = 0;
  359. im--;
  360. }
  361. }
  362. bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
  363. huf_canonical_code_table(hcode);
  364. return 0;
  365. }
  366. static int huf_build_dec_table(const uint64_t *hcode, int im,
  367. int iM, HufDec *hdecod)
  368. {
  369. for (; im <= iM; im++) {
  370. uint64_t c = hcode[im] >> 6;
  371. int i, l = hcode[im] & 63;
  372. if (c >> l)
  373. return AVERROR_INVALIDDATA;
  374. if (l > HUF_DECBITS) {
  375. HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
  376. if (pl->len)
  377. return AVERROR_INVALIDDATA;
  378. pl->lit++;
  379. pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
  380. if (!pl->p)
  381. return AVERROR(ENOMEM);
  382. pl->p[pl->lit - 1] = im;
  383. } else if (l) {
  384. HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
  385. for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
  386. if (pl->len || pl->p)
  387. return AVERROR_INVALIDDATA;
  388. pl->len = l;
  389. pl->lit = im;
  390. }
  391. }
  392. }
  393. return 0;
  394. }
  395. #define get_char(c, lc, gb) \
  396. { \
  397. c = (c << 8) | bytestream2_get_byte(gb); \
  398. lc += 8; \
  399. }
  400. #define get_code(po, rlc, c, lc, gb, out, oe, outb) \
  401. { \
  402. if (po == rlc) { \
  403. if (lc < 8) \
  404. get_char(c, lc, gb); \
  405. lc -= 8; \
  406. \
  407. cs = c >> lc; \
  408. \
  409. if (out + cs > oe || out == outb) \
  410. return AVERROR_INVALIDDATA; \
  411. \
  412. s = out[-1]; \
  413. \
  414. while (cs-- > 0) \
  415. *out++ = s; \
  416. } else if (out < oe) { \
  417. *out++ = po; \
  418. } else { \
  419. return AVERROR_INVALIDDATA; \
  420. } \
  421. }
  422. static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
  423. GetByteContext *gb, int nbits,
  424. int rlc, int no, uint16_t *out)
  425. {
  426. uint64_t c = 0;
  427. uint16_t *outb = out;
  428. uint16_t *oe = out + no;
  429. const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
  430. uint8_t cs, s;
  431. int i, lc = 0;
  432. while (gb->buffer < ie) {
  433. get_char(c, lc, gb);
  434. while (lc >= HUF_DECBITS) {
  435. const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
  436. if (pl.len) {
  437. lc -= pl.len;
  438. get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
  439. } else {
  440. int j;
  441. if (!pl.p)
  442. return AVERROR_INVALIDDATA;
  443. for (j = 0; j < pl.lit; j++) {
  444. int l = hcode[pl.p[j]] & 63;
  445. while (lc < l && bytestream2_get_bytes_left(gb) > 0)
  446. get_char(c, lc, gb);
  447. if (lc >= l) {
  448. if ((hcode[pl.p[j]] >> 6) ==
  449. ((c >> (lc - l)) & ((1LL << l) - 1))) {
  450. lc -= l;
  451. get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb);
  452. break;
  453. }
  454. }
  455. }
  456. if (j == pl.lit)
  457. return AVERROR_INVALIDDATA;
  458. }
  459. }
  460. }
  461. i = (8 - nbits) & 7;
  462. c >>= i;
  463. lc -= i;
  464. while (lc > 0) {
  465. const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
  466. if (pl.len) {
  467. lc -= pl.len;
  468. get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
  469. } else {
  470. return AVERROR_INVALIDDATA;
  471. }
  472. }
  473. if (out - outb != no)
  474. return AVERROR_INVALIDDATA;
  475. return 0;
  476. }
  477. static int huf_uncompress(GetByteContext *gb,
  478. uint16_t *dst, int dst_size)
  479. {
  480. int32_t src_size, im, iM;
  481. uint32_t nBits;
  482. uint64_t *freq;
  483. HufDec *hdec;
  484. int ret, i;
  485. src_size = bytestream2_get_le32(gb);
  486. im = bytestream2_get_le32(gb);
  487. iM = bytestream2_get_le32(gb);
  488. bytestream2_skip(gb, 4);
  489. nBits = bytestream2_get_le32(gb);
  490. if (im < 0 || im >= HUF_ENCSIZE ||
  491. iM < 0 || iM >= HUF_ENCSIZE ||
  492. src_size < 0)
  493. return AVERROR_INVALIDDATA;
  494. bytestream2_skip(gb, 4);
  495. freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
  496. hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
  497. if (!freq || !hdec) {
  498. ret = AVERROR(ENOMEM);
  499. goto fail;
  500. }
  501. if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
  502. goto fail;
  503. if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
  504. ret = AVERROR_INVALIDDATA;
  505. goto fail;
  506. }
  507. if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
  508. goto fail;
  509. ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
  510. fail:
  511. for (i = 0; i < HUF_DECSIZE; i++)
  512. if (hdec)
  513. av_freep(&hdec[i].p);
  514. av_free(freq);
  515. av_free(hdec);
  516. return ret;
  517. }
  518. static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
  519. {
  520. int16_t ls = l;
  521. int16_t hs = h;
  522. int hi = hs;
  523. int ai = ls + (hi & 1) + (hi >> 1);
  524. int16_t as = ai;
  525. int16_t bs = ai - hi;
  526. *a = as;
  527. *b = bs;
  528. }
  529. #define NBITS 16
  530. #define A_OFFSET (1 << (NBITS - 1))
  531. #define MOD_MASK ((1 << NBITS) - 1)
  532. static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
  533. {
  534. int m = l;
  535. int d = h;
  536. int bb = (m - (d >> 1)) & MOD_MASK;
  537. int aa = (d + bb - A_OFFSET) & MOD_MASK;
  538. *b = bb;
  539. *a = aa;
  540. }
  541. static void wav_decode(uint16_t *in, int nx, int ox,
  542. int ny, int oy, uint16_t mx)
  543. {
  544. int w14 = (mx < (1 << 14));
  545. int n = (nx > ny) ? ny : nx;
  546. int p = 1;
  547. int p2;
  548. while (p <= n)
  549. p <<= 1;
  550. p >>= 1;
  551. p2 = p;
  552. p >>= 1;
  553. while (p >= 1) {
  554. uint16_t *py = in;
  555. uint16_t *ey = in + oy * (ny - p2);
  556. uint16_t i00, i01, i10, i11;
  557. int oy1 = oy * p;
  558. int oy2 = oy * p2;
  559. int ox1 = ox * p;
  560. int ox2 = ox * p2;
  561. for (; py <= ey; py += oy2) {
  562. uint16_t *px = py;
  563. uint16_t *ex = py + ox * (nx - p2);
  564. for (; px <= ex; px += ox2) {
  565. uint16_t *p01 = px + ox1;
  566. uint16_t *p10 = px + oy1;
  567. uint16_t *p11 = p10 + ox1;
  568. if (w14) {
  569. wdec14(*px, *p10, &i00, &i10);
  570. wdec14(*p01, *p11, &i01, &i11);
  571. wdec14(i00, i01, px, p01);
  572. wdec14(i10, i11, p10, p11);
  573. } else {
  574. wdec16(*px, *p10, &i00, &i10);
  575. wdec16(*p01, *p11, &i01, &i11);
  576. wdec16(i00, i01, px, p01);
  577. wdec16(i10, i11, p10, p11);
  578. }
  579. }
  580. if (nx & p) {
  581. uint16_t *p10 = px + oy1;
  582. if (w14)
  583. wdec14(*px, *p10, &i00, p10);
  584. else
  585. wdec16(*px, *p10, &i00, p10);
  586. *px = i00;
  587. }
  588. }
  589. if (ny & p) {
  590. uint16_t *px = py;
  591. uint16_t *ex = py + ox * (nx - p2);
  592. for (; px <= ex; px += ox2) {
  593. uint16_t *p01 = px + ox1;
  594. if (w14)
  595. wdec14(*px, *p01, &i00, p01);
  596. else
  597. wdec16(*px, *p01, &i00, p01);
  598. *px = i00;
  599. }
  600. }
  601. p2 = p;
  602. p >>= 1;
  603. }
  604. }
  605. static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
  606. int dsize, EXRThreadData *td)
  607. {
  608. GetByteContext gb;
  609. uint16_t maxval, min_non_zero, max_non_zero;
  610. uint16_t *ptr;
  611. uint16_t *tmp = (uint16_t *)td->tmp;
  612. uint8_t *out;
  613. int ret, i, j;
  614. if (!td->bitmap)
  615. td->bitmap = av_malloc(BITMAP_SIZE);
  616. if (!td->lut)
  617. td->lut = av_malloc(1 << 17);
  618. if (!td->bitmap || !td->lut) {
  619. av_freep(&td->bitmap);
  620. av_freep(&td->lut);
  621. return AVERROR(ENOMEM);
  622. }
  623. bytestream2_init(&gb, src, ssize);
  624. min_non_zero = bytestream2_get_le16(&gb);
  625. max_non_zero = bytestream2_get_le16(&gb);
  626. if (max_non_zero >= BITMAP_SIZE)
  627. return AVERROR_INVALIDDATA;
  628. memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
  629. if (min_non_zero <= max_non_zero)
  630. bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
  631. max_non_zero - min_non_zero + 1);
  632. memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
  633. maxval = reverse_lut(td->bitmap, td->lut);
  634. ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
  635. if (ret)
  636. return ret;
  637. ptr = tmp;
  638. for (i = 0; i < s->nb_channels; i++) {
  639. EXRChannel *channel = &s->channels[i];
  640. int size = channel->pixel_type;
  641. for (j = 0; j < size; j++)
  642. wav_decode(ptr + j, s->xsize, size, s->ysize,
  643. s->xsize * size, maxval);
  644. ptr += s->xsize * s->ysize * size;
  645. }
  646. apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
  647. out = td->uncompressed_data;
  648. for (i = 0; i < s->ysize; i++)
  649. for (j = 0; j < s->nb_channels; j++) {
  650. uint16_t *in = tmp + j * s->xsize * s->ysize + i * s->xsize;
  651. memcpy(out, in, s->xsize * 2);
  652. out += s->xsize * 2;
  653. }
  654. return 0;
  655. }
  656. static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
  657. int compressed_size, int uncompressed_size,
  658. EXRThreadData *td)
  659. {
  660. unsigned long dest_len, expected_len;
  661. const uint8_t *in = td->tmp;
  662. uint8_t *out;
  663. int c, i, j;
  664. if (s->pixel_type == EXR_FLOAT)
  665. expected_len = (uncompressed_size / 4) * 3; /* PRX 24 store float in 24 bit instead of 32 */
  666. else
  667. expected_len = uncompressed_size;
  668. dest_len = expected_len;
  669. if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
  670. return AVERROR_INVALIDDATA;
  671. } else if (dest_len != expected_len) {
  672. return AVERROR_INVALIDDATA;
  673. }
  674. out = td->uncompressed_data;
  675. for (i = 0; i < s->ysize; i++)
  676. for (c = 0; c < s->nb_channels; c++) {
  677. EXRChannel *channel = &s->channels[c];
  678. const uint8_t *ptr[4];
  679. uint32_t pixel = 0;
  680. switch (channel->pixel_type) {
  681. case EXR_FLOAT:
  682. ptr[0] = in;
  683. ptr[1] = ptr[0] + s->xsize;
  684. ptr[2] = ptr[1] + s->xsize;
  685. in = ptr[2] + s->xsize;
  686. for (j = 0; j < s->xsize; ++j) {
  687. uint32_t diff = (*(ptr[0]++) << 24) |
  688. (*(ptr[1]++) << 16) |
  689. (*(ptr[2]++) << 8);
  690. pixel += diff;
  691. bytestream_put_le32(&out, pixel);
  692. }
  693. break;
  694. case EXR_HALF:
  695. ptr[0] = in;
  696. ptr[1] = ptr[0] + s->xsize;
  697. in = ptr[1] + s->xsize;
  698. for (j = 0; j < s->xsize; j++) {
  699. uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
  700. pixel += diff;
  701. bytestream_put_le16(&out, pixel);
  702. }
  703. break;
  704. default:
  705. return AVERROR_INVALIDDATA;
  706. }
  707. }
  708. return 0;
  709. }
  710. static void unpack_14(const uint8_t b[14], uint16_t s[16])
  711. {
  712. unsigned short shift = (b[ 2] >> 2);
  713. unsigned short bias = (0x20 << shift);
  714. int i;
  715. s[ 0] = (b[0] << 8) | b[1];
  716. s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
  717. s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
  718. s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias;
  719. s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias;
  720. s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
  721. s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
  722. s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias;
  723. s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias;
  724. s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
  725. s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
  726. s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias;
  727. s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias;
  728. s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
  729. s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
  730. s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias;
  731. for (i = 0; i < 16; ++i) {
  732. if (s[i] & 0x8000)
  733. s[i] &= 0x7fff;
  734. else
  735. s[i] = ~s[i];
  736. }
  737. }
  738. static void unpack_3(const uint8_t b[3], uint16_t s[16])
  739. {
  740. int i;
  741. s[0] = (b[0] << 8) | b[1];
  742. if (s[0] & 0x8000)
  743. s[0] &= 0x7fff;
  744. else
  745. s[0] = ~s[0];
  746. for (i = 1; i < 16; i++)
  747. s[i] = s[0];
  748. }
  749. static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
  750. int uncompressed_size, EXRThreadData *td) {
  751. const int8_t *sr = src;
  752. int stayToUncompress = compressed_size;
  753. int nbB44BlockW, nbB44BlockH;
  754. int indexHgX, indexHgY, indexOut, indexTmp;
  755. uint16_t tmpBuffer[16]; /* B44 use 4x4 half float pixel */
  756. int c, iY, iX, y, x;
  757. /* calc B44 block count */
  758. nbB44BlockW = s->xsize / 4;
  759. if ((s->xsize % 4) != 0)
  760. nbB44BlockW++;
  761. nbB44BlockH = s->ysize / 4;
  762. if ((s->ysize % 4) != 0)
  763. nbB44BlockH++;
  764. for (c = 0; c < s->nb_channels; c++) {
  765. for (iY = 0; iY < nbB44BlockH; iY++) {
  766. for (iX = 0; iX < nbB44BlockW; iX++) {/* For each B44 block */
  767. if (stayToUncompress < 3) {
  768. av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stayToUncompress);
  769. return AVERROR_INVALIDDATA;
  770. }
  771. if (src[compressed_size - stayToUncompress + 2] == 0xfc) { /* B44A block */
  772. unpack_3(sr, tmpBuffer);
  773. sr += 3;
  774. stayToUncompress -= 3;
  775. } else {/* B44 Block */
  776. if (stayToUncompress < 14) {
  777. av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stayToUncompress);
  778. return AVERROR_INVALIDDATA;
  779. }
  780. unpack_14(sr, tmpBuffer);
  781. sr += 14;
  782. stayToUncompress -= 14;
  783. }
  784. /* copy data to uncompress buffer (B44 block can exceed target resolution)*/
  785. indexHgX = iX * 4;
  786. indexHgY = iY * 4;
  787. for (y = indexHgY; y < FFMIN(indexHgY + 4, s->ysize); y++) {
  788. for (x = indexHgX; x < FFMIN(indexHgX + 4, s->xsize); x++) {
  789. indexOut = (c * s->xsize + y * s->xsize * s->nb_channels + x) * 2;
  790. indexTmp = (y-indexHgY) * 4 + (x-indexHgX);
  791. td->uncompressed_data[indexOut] = tmpBuffer[indexTmp] & 0xff;
  792. td->uncompressed_data[indexOut + 1] = tmpBuffer[indexTmp] >> 8;
  793. }
  794. }
  795. }
  796. }
  797. }
  798. return 0;
  799. }
  800. static int decode_block(AVCodecContext *avctx, void *tdata,
  801. int jobnr, int threadnr)
  802. {
  803. EXRContext *s = avctx->priv_data;
  804. AVFrame *const p = s->picture;
  805. EXRThreadData *td = &s->thread_data[threadnr];
  806. const uint8_t *channel_buffer[4] = { 0 };
  807. const uint8_t *buf = s->buf;
  808. uint64_t line_offset, uncompressed_size;
  809. uint32_t xdelta = s->xdelta;
  810. uint16_t *ptr_x;
  811. uint8_t *ptr;
  812. uint32_t data_size, line, col = 0;
  813. uint32_t tileX, tileY, tileLevelX, tileLevelY;
  814. int channelLineSize, indexSrc, tX, tY, tCh;
  815. const uint8_t *src;
  816. int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components; /* nb pixel to add at the right of the datawindow */
  817. int bxmin = s->xmin * 2 * s->desc->nb_components; /* nb pixel to add at the left of the datawindow */
  818. int i, x, buf_size = s->buf_size;
  819. float one_gamma = 1.0f / s->gamma;
  820. avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
  821. int ret;
  822. line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
  823. if (s->is_tile) {
  824. if (line_offset > buf_size - 20)
  825. return AVERROR_INVALIDDATA;
  826. src = buf + line_offset + 20;
  827. tileX = AV_RL32(src - 20);
  828. tileY = AV_RL32(src - 16);
  829. tileLevelX = AV_RL32(src - 12);
  830. tileLevelY = AV_RL32(src - 8);
  831. data_size = AV_RL32(src - 4);
  832. if (data_size <= 0 || data_size > buf_size)
  833. return AVERROR_INVALIDDATA;
  834. if (tileLevelX || tileLevelY) { /* tile level, is not the full res level */
  835. avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
  836. return AVERROR_PATCHWELCOME;
  837. }
  838. line = s->tile_attr.ySize * tileY;
  839. col = s->tile_attr.xSize * tileX;
  840. s->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tileY * s->tile_attr.ySize);
  841. s->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tileX * s->tile_attr.xSize);
  842. uncompressed_size = s->current_channel_offset * s->ysize * s->xsize;
  843. if (col) { /* not the first tile of the line */
  844. bxmin = 0; axmax = 0; /* doesn't add pixel at the left of the datawindow */
  845. }
  846. if ((col + s->xsize) != s->xdelta)/* not the last tile of the line */
  847. axmax = 0; /* doesn't add pixel at the right of the datawindow */
  848. } else {
  849. if (line_offset > buf_size - 8)
  850. return AVERROR_INVALIDDATA;
  851. src = buf + line_offset + 8;
  852. line = AV_RL32(src - 8);
  853. if (line < s->ymin || line > s->ymax)
  854. return AVERROR_INVALIDDATA;
  855. data_size = AV_RL32(src - 4);
  856. if (data_size <= 0 || data_size > buf_size)
  857. return AVERROR_INVALIDDATA;
  858. s->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
  859. s->xsize = s->xdelta;
  860. uncompressed_size = s->scan_line_size * s->ysize;
  861. if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
  862. line_offset > buf_size - uncompressed_size)) ||
  863. (s->compression != EXR_RAW && (data_size > uncompressed_size ||
  864. line_offset > buf_size - data_size))) {
  865. return AVERROR_INVALIDDATA;
  866. }
  867. }
  868. if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
  869. av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
  870. if (!td->tmp)
  871. return AVERROR(ENOMEM);
  872. }
  873. if (data_size < uncompressed_size) {
  874. av_fast_padded_malloc(&td->uncompressed_data,
  875. &td->uncompressed_size, uncompressed_size);
  876. if (!td->uncompressed_data)
  877. return AVERROR(ENOMEM);
  878. ret = AVERROR_INVALIDDATA;
  879. switch (s->compression) {
  880. case EXR_ZIP1:
  881. case EXR_ZIP16:
  882. ret = zip_uncompress(src, data_size, uncompressed_size, td);
  883. break;
  884. case EXR_PIZ:
  885. ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
  886. break;
  887. case EXR_PXR24:
  888. ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
  889. break;
  890. case EXR_RLE:
  891. ret = rle_uncompress(src, data_size, uncompressed_size, td);
  892. break;
  893. case EXR_B44:
  894. case EXR_B44A:
  895. ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
  896. break;
  897. }
  898. if (ret < 0) {
  899. av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
  900. return ret;
  901. }
  902. src = td->uncompressed_data;
  903. }
  904. if (s->is_tile) {
  905. indexSrc = 0;
  906. channelLineSize = s->xsize * 2;
  907. if (s->pixel_type == EXR_FLOAT)
  908. channelLineSize *= 2;
  909. /* reorganise tile data to have each channel one after the other instead of line by line */
  910. for (tY = 0; tY < s->ysize; tY ++) {
  911. for (tCh = 0; tCh < s->nb_channels; tCh++) {
  912. for (tX = 0; tX < channelLineSize; tX++) {
  913. td->tmp[tCh * channelLineSize * s->ysize + tY * channelLineSize + tX] = src[indexSrc];
  914. indexSrc++;
  915. }
  916. }
  917. }
  918. channel_buffer[0] = td->tmp + s->xsize * s->channel_offsets[0] * s->ysize;
  919. channel_buffer[1] = td->tmp + s->xsize * s->channel_offsets[1] * s->ysize;
  920. channel_buffer[2] = td->tmp + s->xsize * s->channel_offsets[2] * s->ysize;
  921. if (s->channel_offsets[3] >= 0)
  922. channel_buffer[3] = td->tmp + s->xsize * s->channel_offsets[3];
  923. } else {
  924. channel_buffer[0] = src + xdelta * s->channel_offsets[0];
  925. channel_buffer[1] = src + xdelta * s->channel_offsets[1];
  926. channel_buffer[2] = src + xdelta * s->channel_offsets[2];
  927. if (s->channel_offsets[3] >= 0)
  928. channel_buffer[3] = src + xdelta * s->channel_offsets[3];
  929. }
  930. ptr = p->data[0] + line * p->linesize[0] + (col * s->desc->nb_components * 2);
  931. for (i = 0;
  932. i < s->ysize; i++, ptr += p->linesize[0]) {
  933. const uint8_t *r, *g, *b, *a;
  934. r = channel_buffer[0];
  935. g = channel_buffer[1];
  936. b = channel_buffer[2];
  937. if (channel_buffer[3])
  938. a = channel_buffer[3];
  939. ptr_x = (uint16_t *) ptr;
  940. // Zero out the start if xmin is not 0
  941. memset(ptr_x, 0, bxmin);
  942. ptr_x += s->xmin * s->desc->nb_components;
  943. if (s->pixel_type == EXR_FLOAT) {
  944. // 32-bit
  945. if (trc_func) {
  946. for (x = 0; x < s->xsize; x++) {
  947. union av_intfloat32 t;
  948. t.i = bytestream_get_le32(&r);
  949. t.f = trc_func(t.f);
  950. *ptr_x++ = exr_flt2uint(t.i);
  951. t.i = bytestream_get_le32(&g);
  952. t.f = trc_func(t.f);
  953. *ptr_x++ = exr_flt2uint(t.i);
  954. t.i = bytestream_get_le32(&b);
  955. t.f = trc_func(t.f);
  956. *ptr_x++ = exr_flt2uint(t.i);
  957. if (channel_buffer[3])
  958. *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
  959. }
  960. } else {
  961. for (x = 0; x < s->xsize; x++) {
  962. union av_intfloat32 t;
  963. t.i = bytestream_get_le32(&r);
  964. if (t.f > 0.0f) /* avoid negative values */
  965. t.f = powf(t.f, one_gamma);
  966. *ptr_x++ = exr_flt2uint(t.i);
  967. t.i = bytestream_get_le32(&g);
  968. if (t.f > 0.0f)
  969. t.f = powf(t.f, one_gamma);
  970. *ptr_x++ = exr_flt2uint(t.i);
  971. t.i = bytestream_get_le32(&b);
  972. if (t.f > 0.0f)
  973. t.f = powf(t.f, one_gamma);
  974. *ptr_x++ = exr_flt2uint(t.i);
  975. if (channel_buffer[3])
  976. *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
  977. }
  978. }
  979. } else {
  980. // 16-bit
  981. for (x = 0; x < s->xsize; x++) {
  982. *ptr_x++ = s->gamma_table[bytestream_get_le16(&r)];
  983. *ptr_x++ = s->gamma_table[bytestream_get_le16(&g)];
  984. *ptr_x++ = s->gamma_table[bytestream_get_le16(&b)];
  985. if (channel_buffer[3])
  986. *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));
  987. }
  988. }
  989. // Zero out the end if xmax+1 is not w
  990. memset(ptr_x, 0, axmax);
  991. if (s->is_tile) {
  992. channel_buffer[0] += channelLineSize;
  993. channel_buffer[1] += channelLineSize;
  994. channel_buffer[2] += channelLineSize;
  995. if (channel_buffer[3])
  996. channel_buffer[3] += channelLineSize;
  997. } else {
  998. channel_buffer[0] += s->scan_line_size;
  999. channel_buffer[1] += s->scan_line_size;
  1000. channel_buffer[2] += s->scan_line_size;
  1001. if (channel_buffer[3])
  1002. channel_buffer[3] += s->scan_line_size;
  1003. }
  1004. }
  1005. return 0;
  1006. }
  1007. /**
  1008. * Check if the variable name corresponds to its data type.
  1009. *
  1010. * @param s the EXRContext
  1011. * @param value_name name of the variable to check
  1012. * @param value_type type of the variable to check
  1013. * @param minimum_length minimum length of the variable data
  1014. *
  1015. * @return bytes to read containing variable data
  1016. * -1 if variable is not found
  1017. * 0 if buffer ended prematurely
  1018. */
  1019. static int check_header_variable(EXRContext *s,
  1020. const char *value_name,
  1021. const char *value_type,
  1022. unsigned int minimum_length)
  1023. {
  1024. int var_size = -1;
  1025. if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
  1026. !strcmp(s->gb.buffer, value_name)) {
  1027. // found value_name, jump to value_type (null terminated strings)
  1028. s->gb.buffer += strlen(value_name) + 1;
  1029. if (!strcmp(s->gb.buffer, value_type)) {
  1030. s->gb.buffer += strlen(value_type) + 1;
  1031. var_size = bytestream2_get_le32(&s->gb);
  1032. // don't go read past boundaries
  1033. if (var_size > bytestream2_get_bytes_left(&s->gb))
  1034. var_size = 0;
  1035. } else {
  1036. // value_type not found, reset the buffer
  1037. s->gb.buffer -= strlen(value_name) + 1;
  1038. av_log(s->avctx, AV_LOG_WARNING,
  1039. "Unknown data type %s for header variable %s.\n",
  1040. value_type, value_name);
  1041. }
  1042. }
  1043. return var_size;
  1044. }
  1045. static int decode_header(EXRContext *s)
  1046. {
  1047. int magic_number, version, i, flags, sar = 0;
  1048. s->current_channel_offset = 0;
  1049. s->xmin = ~0;
  1050. s->xmax = ~0;
  1051. s->ymin = ~0;
  1052. s->ymax = ~0;
  1053. s->xdelta = ~0;
  1054. s->ydelta = ~0;
  1055. s->channel_offsets[0] = -1;
  1056. s->channel_offsets[1] = -1;
  1057. s->channel_offsets[2] = -1;
  1058. s->channel_offsets[3] = -1;
  1059. s->pixel_type = EXR_UNKNOWN;
  1060. s->compression = EXR_UNKN;
  1061. s->nb_channels = 0;
  1062. s->w = 0;
  1063. s->h = 0;
  1064. s->tile_attr.xSize = -1;
  1065. s->tile_attr.ySize = -1;
  1066. s->is_tile = 0;
  1067. if (bytestream2_get_bytes_left(&s->gb) < 10) {
  1068. av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
  1069. return AVERROR_INVALIDDATA;
  1070. }
  1071. magic_number = bytestream2_get_le32(&s->gb);
  1072. if (magic_number != 20000630) {
  1073. /* As per documentation of OpenEXR, it is supposed to be
  1074. * int 20000630 little-endian */
  1075. av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
  1076. return AVERROR_INVALIDDATA;
  1077. }
  1078. version = bytestream2_get_byte(&s->gb);
  1079. if (version != 2) {
  1080. avpriv_report_missing_feature(s->avctx, "Version %d", version);
  1081. return AVERROR_PATCHWELCOME;
  1082. }
  1083. flags = bytestream2_get_le24(&s->gb);
  1084. if (flags == 0x00)
  1085. s->is_tile = 0;
  1086. else if (flags & 0x02)
  1087. s->is_tile = 1;
  1088. else{
  1089. avpriv_report_missing_feature(s->avctx, "flags %d", flags);
  1090. return AVERROR_PATCHWELCOME;
  1091. }
  1092. // Parse the header
  1093. while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
  1094. int var_size;
  1095. if ((var_size = check_header_variable(s, "channels",
  1096. "chlist", 38)) >= 0) {
  1097. GetByteContext ch_gb;
  1098. if (!var_size)
  1099. return AVERROR_INVALIDDATA;
  1100. bytestream2_init(&ch_gb, s->gb.buffer, var_size);
  1101. while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
  1102. EXRChannel *channel;
  1103. enum ExrPixelType current_pixel_type;
  1104. int channel_index = -1;
  1105. int xsub, ysub;
  1106. if (strcmp(s->layer, "") != 0) {
  1107. if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
  1108. ch_gb.buffer += strlen(s->layer);
  1109. if (*ch_gb.buffer == '.')
  1110. ch_gb.buffer++; /* skip dot if not given */
  1111. av_log(s->avctx, AV_LOG_INFO,
  1112. "Layer %s.%s matched.\n", s->layer, ch_gb.buffer);
  1113. }
  1114. }
  1115. if (!strcmp(ch_gb.buffer, "R") ||
  1116. !strcmp(ch_gb.buffer, "X") ||
  1117. !strcmp(ch_gb.buffer, "U"))
  1118. channel_index = 0;
  1119. else if (!strcmp(ch_gb.buffer, "G") ||
  1120. !strcmp(ch_gb.buffer, "Y") ||
  1121. !strcmp(ch_gb.buffer, "V"))
  1122. channel_index = 1;
  1123. else if (!strcmp(ch_gb.buffer, "B") ||
  1124. !strcmp(ch_gb.buffer, "Z") ||
  1125. !strcmp(ch_gb.buffer, "W"))
  1126. channel_index = 2;
  1127. else if (!strcmp(ch_gb.buffer, "A"))
  1128. channel_index = 3;
  1129. else
  1130. av_log(s->avctx, AV_LOG_WARNING,
  1131. "Unsupported channel %.256s.\n", ch_gb.buffer);
  1132. /* skip until you get a 0 */
  1133. while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
  1134. bytestream2_get_byte(&ch_gb))
  1135. continue;
  1136. if (bytestream2_get_bytes_left(&ch_gb) < 4) {
  1137. av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
  1138. return AVERROR_INVALIDDATA;
  1139. }
  1140. current_pixel_type = bytestream2_get_le32(&ch_gb);
  1141. if (current_pixel_type >= EXR_UNKNOWN) {
  1142. avpriv_report_missing_feature(s->avctx, "Pixel type %d",
  1143. current_pixel_type);
  1144. return AVERROR_PATCHWELCOME;
  1145. }
  1146. bytestream2_skip(&ch_gb, 4);
  1147. xsub = bytestream2_get_le32(&ch_gb);
  1148. ysub = bytestream2_get_le32(&ch_gb);
  1149. if (xsub != 1 || ysub != 1) {
  1150. avpriv_report_missing_feature(s->avctx,
  1151. "Subsampling %dx%d",
  1152. xsub, ysub);
  1153. return AVERROR_PATCHWELCOME;
  1154. }
  1155. if (s->channel_offsets[channel_index] == -1){/* channel have not been previously assign */
  1156. if (channel_index >= 0) {
  1157. if (s->pixel_type != EXR_UNKNOWN &&
  1158. s->pixel_type != current_pixel_type) {
  1159. av_log(s->avctx, AV_LOG_ERROR,
  1160. "RGB channels not of the same depth.\n");
  1161. return AVERROR_INVALIDDATA;
  1162. }
  1163. s->pixel_type = current_pixel_type;
  1164. s->channel_offsets[channel_index] = s->current_channel_offset;
  1165. }
  1166. }
  1167. s->channels = av_realloc(s->channels,
  1168. ++s->nb_channels * sizeof(EXRChannel));
  1169. if (!s->channels)
  1170. return AVERROR(ENOMEM);
  1171. channel = &s->channels[s->nb_channels - 1];
  1172. channel->pixel_type = current_pixel_type;
  1173. channel->xsub = xsub;
  1174. channel->ysub = ysub;
  1175. s->current_channel_offset += 1 << current_pixel_type;
  1176. }
  1177. /* Check if all channels are set with an offset or if the channels
  1178. * are causing an overflow */
  1179. if (FFMIN3(s->channel_offsets[0],
  1180. s->channel_offsets[1],
  1181. s->channel_offsets[2]) < 0) {
  1182. if (s->channel_offsets[0] < 0)
  1183. av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
  1184. if (s->channel_offsets[1] < 0)
  1185. av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
  1186. if (s->channel_offsets[2] < 0)
  1187. av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
  1188. return AVERROR_INVALIDDATA;
  1189. }
  1190. // skip one last byte and update main gb
  1191. s->gb.buffer = ch_gb.buffer + 1;
  1192. continue;
  1193. } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
  1194. 31)) >= 0) {
  1195. if (!var_size)
  1196. return AVERROR_INVALIDDATA;
  1197. s->xmin = bytestream2_get_le32(&s->gb);
  1198. s->ymin = bytestream2_get_le32(&s->gb);
  1199. s->xmax = bytestream2_get_le32(&s->gb);
  1200. s->ymax = bytestream2_get_le32(&s->gb);
  1201. s->xdelta = (s->xmax - s->xmin) + 1;
  1202. s->ydelta = (s->ymax - s->ymin) + 1;
  1203. continue;
  1204. } else if ((var_size = check_header_variable(s, "displayWindow",
  1205. "box2i", 34)) >= 0) {
  1206. if (!var_size)
  1207. return AVERROR_INVALIDDATA;
  1208. bytestream2_skip(&s->gb, 8);
  1209. s->w = bytestream2_get_le32(&s->gb) + 1;
  1210. s->h = bytestream2_get_le32(&s->gb) + 1;
  1211. continue;
  1212. } else if ((var_size = check_header_variable(s, "lineOrder",
  1213. "lineOrder", 25)) >= 0) {
  1214. int line_order;
  1215. if (!var_size)
  1216. return AVERROR_INVALIDDATA;
  1217. line_order = bytestream2_get_byte(&s->gb);
  1218. av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
  1219. if (line_order > 2) {
  1220. av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
  1221. return AVERROR_INVALIDDATA;
  1222. }
  1223. continue;
  1224. } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
  1225. "float", 31)) >= 0) {
  1226. if (!var_size)
  1227. return AVERROR_INVALIDDATA;
  1228. sar = bytestream2_get_le32(&s->gb);
  1229. continue;
  1230. } else if ((var_size = check_header_variable(s, "compression",
  1231. "compression", 29)) >= 0) {
  1232. if (!var_size)
  1233. return AVERROR_INVALIDDATA;
  1234. if (s->compression == EXR_UNKN)
  1235. s->compression = bytestream2_get_byte(&s->gb);
  1236. else
  1237. av_log(s->avctx, AV_LOG_WARNING,
  1238. "Found more than one compression attribute.\n");
  1239. continue;
  1240. } else if ((var_size = check_header_variable(s, "tiles",
  1241. "tiledesc", 22)) >= 0) {
  1242. if (!s->is_tile)
  1243. av_log(s->avctx, AV_LOG_WARNING,
  1244. "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
  1245. s->tile_attr.xSize = bytestream2_get_le32(&s->gb);
  1246. s->tile_attr.ySize = bytestream2_get_le32(&s->gb);
  1247. char tileLevel = bytestream2_get_byte(&s->gb);
  1248. s->tile_attr.level_mode = tileLevel & 0x0f;
  1249. s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
  1250. if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN){
  1251. avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
  1252. s->tile_attr.level_mode);
  1253. return AVERROR_PATCHWELCOME;
  1254. }
  1255. if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
  1256. avpriv_report_missing_feature(s->avctx, "Tile level round %d",
  1257. s->tile_attr.level_round);
  1258. return AVERROR_PATCHWELCOME;
  1259. }
  1260. continue;
  1261. }
  1262. // Check if there are enough bytes for a header
  1263. if (bytestream2_get_bytes_left(&s->gb) <= 9) {
  1264. av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
  1265. return AVERROR_INVALIDDATA;
  1266. }
  1267. // Process unknown variables
  1268. for (i = 0; i < 2; i++) // value_name and value_type
  1269. while (bytestream2_get_byte(&s->gb) != 0);
  1270. // Skip variable length
  1271. bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb));
  1272. }
  1273. ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255));
  1274. if (s->compression == EXR_UNKN) {
  1275. av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
  1276. return AVERROR_INVALIDDATA;
  1277. }
  1278. if (s->is_tile) {
  1279. if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
  1280. av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
  1281. return AVERROR_INVALIDDATA;
  1282. }
  1283. }
  1284. s->scan_line_size = s->xdelta * s->current_channel_offset;
  1285. if (bytestream2_get_bytes_left(&s->gb) <= 0) {
  1286. av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
  1287. return AVERROR_INVALIDDATA;
  1288. }
  1289. // aaand we are done
  1290. bytestream2_skip(&s->gb, 1);
  1291. return 0;
  1292. }
  1293. static int decode_frame(AVCodecContext *avctx, void *data,
  1294. int *got_frame, AVPacket *avpkt)
  1295. {
  1296. EXRContext *s = avctx->priv_data;
  1297. ThreadFrame frame = { .f = data };
  1298. AVFrame *picture = data;
  1299. uint8_t *ptr;
  1300. int y, ret;
  1301. int out_line_size;
  1302. int nb_blocks;/* nb scanline or nb tile */
  1303. bytestream2_init(&s->gb, avpkt->data, avpkt->size);
  1304. if ((ret = decode_header(s)) < 0)
  1305. return ret;
  1306. switch (s->pixel_type) {
  1307. case EXR_FLOAT:
  1308. case EXR_HALF:
  1309. if (s->channel_offsets[3] >= 0)
  1310. avctx->pix_fmt = AV_PIX_FMT_RGBA64;
  1311. else
  1312. avctx->pix_fmt = AV_PIX_FMT_RGB48;
  1313. break;
  1314. case EXR_UINT:
  1315. avpriv_request_sample(avctx, "32-bit unsigned int");
  1316. return AVERROR_PATCHWELCOME;
  1317. default:
  1318. av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
  1319. return AVERROR_INVALIDDATA;
  1320. }
  1321. if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
  1322. avctx->color_trc = s->apply_trc_type;
  1323. switch (s->compression) {
  1324. case EXR_RAW:
  1325. case EXR_RLE:
  1326. case EXR_ZIP1:
  1327. s->scan_lines_per_block = 1;
  1328. break;
  1329. case EXR_PXR24:
  1330. case EXR_ZIP16:
  1331. s->scan_lines_per_block = 16;
  1332. break;
  1333. case EXR_PIZ:
  1334. case EXR_B44:
  1335. case EXR_B44A:
  1336. s->scan_lines_per_block = 32;
  1337. break;
  1338. default:
  1339. avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
  1340. return AVERROR_PATCHWELCOME;
  1341. }
  1342. /* Verify the xmin, xmax, ymin, ymax and xdelta before setting
  1343. * the actual image size. */
  1344. if (s->xmin > s->xmax ||
  1345. s->ymin > s->ymax ||
  1346. s->xdelta != s->xmax - s->xmin + 1 ||
  1347. s->xmax >= s->w ||
  1348. s->ymax >= s->h) {
  1349. av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
  1350. return AVERROR_INVALIDDATA;
  1351. }
  1352. if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
  1353. return ret;
  1354. s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  1355. if (!s->desc)
  1356. return AVERROR_INVALIDDATA;
  1357. out_line_size = avctx->width * 2 * s->desc->nb_components;
  1358. if (s->is_tile) {
  1359. nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
  1360. ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
  1361. } else { /* scanline */
  1362. nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
  1363. s->scan_lines_per_block;
  1364. }
  1365. if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
  1366. return ret;
  1367. if (bytestream2_get_bytes_left(&s->gb) < nb_blocks * 8)
  1368. return AVERROR_INVALIDDATA;
  1369. // save pointer we are going to use in decode_block
  1370. s->buf = avpkt->data;
  1371. s->buf_size = avpkt->size;
  1372. ptr = picture->data[0];
  1373. // Zero out the start if ymin is not 0
  1374. for (y = 0; y < s->ymin; y++) {
  1375. memset(ptr, 0, out_line_size);
  1376. ptr += picture->linesize[0];
  1377. }
  1378. s->picture = picture;
  1379. avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
  1380. // Zero out the end if ymax+1 is not h
  1381. for (y = s->ymax + 1; y < avctx->height; y++) {
  1382. memset(ptr, 0, out_line_size);
  1383. ptr += picture->linesize[0];
  1384. }
  1385. picture->pict_type = AV_PICTURE_TYPE_I;
  1386. *got_frame = 1;
  1387. return avpkt->size;
  1388. }
  1389. static av_cold int decode_init(AVCodecContext *avctx)
  1390. {
  1391. EXRContext *s = avctx->priv_data;
  1392. uint32_t i;
  1393. union av_intfloat32 t;
  1394. float one_gamma = 1.0f / s->gamma;
  1395. avpriv_trc_function trc_func = NULL;
  1396. s->avctx = avctx;
  1397. trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
  1398. if (trc_func) {
  1399. for (i = 0; i < 65536; ++i) {
  1400. t = exr_half2float(i);
  1401. t.f = trc_func(t.f);
  1402. s->gamma_table[i] = exr_flt2uint(t.i);
  1403. }
  1404. } else {
  1405. if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
  1406. for (i = 0; i < 65536; ++i)
  1407. s->gamma_table[i] = exr_halflt2uint(i);
  1408. } else {
  1409. for (i = 0; i < 65536; ++i) {
  1410. t = exr_half2float(i);
  1411. /* If negative value we reuse half value */
  1412. if (t.f <= 0.0f) {
  1413. s->gamma_table[i] = exr_halflt2uint(i);
  1414. } else {
  1415. t.f = powf(t.f, one_gamma);
  1416. s->gamma_table[i] = exr_flt2uint(t.i);
  1417. }
  1418. }
  1419. }
  1420. }
  1421. // allocate thread data, used for non EXR_RAW compreesion types
  1422. s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
  1423. if (!s->thread_data)
  1424. return AVERROR_INVALIDDATA;
  1425. return 0;
  1426. }
  1427. #if HAVE_THREADS
  1428. static int decode_init_thread_copy(AVCodecContext *avctx)
  1429. { EXRContext *s = avctx->priv_data;
  1430. // allocate thread data, used for non EXR_RAW compreesion types
  1431. s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
  1432. if (!s->thread_data)
  1433. return AVERROR_INVALIDDATA;
  1434. return 0;
  1435. }
  1436. #endif
  1437. static av_cold int decode_end(AVCodecContext *avctx)
  1438. {
  1439. EXRContext *s = avctx->priv_data;
  1440. int i;
  1441. for (i = 0; i < avctx->thread_count; i++) {
  1442. EXRThreadData *td = &s->thread_data[i];
  1443. av_freep(&td->uncompressed_data);
  1444. av_freep(&td->tmp);
  1445. av_freep(&td->bitmap);
  1446. av_freep(&td->lut);
  1447. }
  1448. av_freep(&s->thread_data);
  1449. av_freep(&s->channels);
  1450. return 0;
  1451. }
  1452. #define OFFSET(x) offsetof(EXRContext, x)
  1453. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1454. static const AVOption options[] = {
  1455. { "layer", "Set the decoding layer", OFFSET(layer),
  1456. AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
  1457. { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
  1458. AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
  1459. // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
  1460. { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
  1461. AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
  1462. { "bt709", "BT.709", 0,
  1463. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1464. { "gamma", "gamma", 0,
  1465. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1466. { "gamma22", "BT.470 M", 0,
  1467. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1468. { "gamma28", "BT.470 BG", 0,
  1469. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1470. { "smpte170m", "SMPTE 170 M", 0,
  1471. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1472. { "smpte240m", "SMPTE 240 M", 0,
  1473. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1474. { "linear", "Linear", 0,
  1475. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1476. { "log", "Log", 0,
  1477. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1478. { "log_sqrt", "Log square root", 0,
  1479. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1480. { "iec61966_2_4", "IEC 61966-2-4", 0,
  1481. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1482. { "bt1361", "BT.1361", 0,
  1483. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1484. { "iec61966_2_1", "IEC 61966-2-1", 0,
  1485. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1486. { "bt2020_10bit", "BT.2020 - 10 bit", 0,
  1487. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1488. { "bt2020_12bit", "BT.2020 - 12 bit", 0,
  1489. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1490. { "smpte2084", "SMPTE ST 2084", 0,
  1491. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1492. { "smpte428_1", "SMPTE ST 428-1", 0,
  1493. AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
  1494. { NULL },
  1495. };
  1496. static const AVClass exr_class = {
  1497. .class_name = "EXR",
  1498. .item_name = av_default_item_name,
  1499. .option = options,
  1500. .version = LIBAVUTIL_VERSION_INT,
  1501. };
  1502. AVCodec ff_exr_decoder = {
  1503. .name = "exr",
  1504. .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"),
  1505. .type = AVMEDIA_TYPE_VIDEO,
  1506. .id = AV_CODEC_ID_EXR,
  1507. .priv_data_size = sizeof(EXRContext),
  1508. .init = decode_init,
  1509. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1510. .close = decode_end,
  1511. .decode = decode_frame,
  1512. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
  1513. AV_CODEC_CAP_SLICE_THREADS,
  1514. .priv_class = &exr_class,
  1515. };