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
6 * B44/B44A, Tile, UINT32 added by Jokyo Images support by CNC - French National Center for Cinema
8 * This file is part of FFmpeg.
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.
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.
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
28 * @author Jimmy Christensen
30 * For more information on the OpenEXR format, visit:
33 * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner.
39 #include "libavutil/avassert.h"
40 #include "libavutil/common.h"
41 #include "libavutil/imgutils.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/avstring.h"
44 #include "libavutil/opt.h"
45 #include "libavutil/color_utils.h"
48 #include "bytestream.h"
81 enum ExrTileLevelMode {
83 EXR_TILE_LEVEL_MIPMAP,
84 EXR_TILE_LEVEL_RIPMAP,
85 EXR_TILE_LEVEL_UNKNOWN,
88 enum ExrTileLevelRound {
91 EXR_TILE_ROUND_UNKNOWN,
94 typedef struct EXRChannel {
96 enum ExrPixelType pixel_type;
99 typedef struct EXRTileAttribute {
102 enum ExrTileLevelMode level_mode;
103 enum ExrTileLevelRound level_round;
106 typedef struct EXRThreadData {
107 uint8_t *uncompressed_data;
108 int uncompressed_size;
118 int channel_line_size;
121 typedef struct EXRContext {
124 AVCodecContext *avctx;
128 BswapDSPContext bbdsp;
131 enum ExrCompr compression;
132 enum ExrPixelType pixel_type;
133 int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
134 const AVPixFmtDescriptor *desc;
140 uint32_t xdelta, ydelta;
142 int scan_lines_per_block;
144 EXRTileAttribute tile_attr; /* header data attribute of tile */
145 int is_tile; /* 0 if scanline, 1 if tile */
149 int is_luma;/* 1 if there is an Y plane */
155 EXRChannel *channels;
157 int current_channel_offset;
158 uint32_t chunk_count;
160 EXRThreadData *thread_data;
165 enum AVColorTransferCharacteristic apply_trc_type;
167 union av_intfloat32 gamma_table[65536];
170 /* -15 stored using a single precision bias of 127 */
171 #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
173 /* max exponent value in single precision that will be converted
174 * to Inf or Nan when stored as a half-float */
175 #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
177 /* 255 is the max exponent biased value */
178 #define FLOAT_MAX_BIASED_EXP (0xFF << 23)
180 #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
183 * Convert a half float as a uint16_t into a full float.
185 * @param hf half float as uint16_t
187 * @return float value
189 static union av_intfloat32 exr_half2float(uint16_t hf)
191 unsigned int sign = (unsigned int) (hf >> 15);
192 unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
193 unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
194 union av_intfloat32 f;
196 if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
197 // we have a half-float NaN or Inf
198 // half-float NaNs will be converted to a single precision NaN
199 // half-float Infs will be converted to a single precision Inf
200 exp = FLOAT_MAX_BIASED_EXP;
201 mantissa <<= 13; // preserve half-float NaN bits if set
202 } else if (exp == 0x0) {
203 // convert half-float zero/denorm to single precision value
206 exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
207 // check for leading 1 in denorm mantissa
208 while (!(mantissa & (1 << 10))) {
209 // for every leading 0, decrement single precision exponent by 1
210 // and shift half-float mantissa value to the left
214 // clamp the mantissa to 10 bits
215 mantissa &= ((1 << 10) - 1);
216 // shift left to generate single-precision mantissa of 23 bits
220 // shift left to generate single-precision mantissa of 23 bits
222 // generate single precision biased exponent value
223 exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
226 f.i = (sign << 31) | exp | mantissa;
231 static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
232 int uncompressed_size, EXRThreadData *td)
234 unsigned long dest_len = uncompressed_size;
236 if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
237 dest_len != uncompressed_size)
238 return AVERROR_INVALIDDATA;
240 av_assert1(uncompressed_size % 2 == 0);
242 s->dsp.predictor(td->tmp, uncompressed_size);
243 s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
248 static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size,
249 int uncompressed_size, EXRThreadData *td)
251 uint8_t *d = td->tmp;
252 const int8_t *s = src;
253 int ssize = compressed_size;
254 int dsize = uncompressed_size;
255 uint8_t *dend = d + dsize;
264 if ((dsize -= count) < 0 ||
265 (ssize -= count + 1) < 0)
266 return AVERROR_INVALIDDATA;
273 if ((dsize -= count) < 0 ||
275 return AVERROR_INVALIDDATA;
285 return AVERROR_INVALIDDATA;
287 av_assert1(uncompressed_size % 2 == 0);
289 ctx->dsp.predictor(td->tmp, uncompressed_size);
290 ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
295 #define USHORT_RANGE (1 << 16)
296 #define BITMAP_SIZE (1 << 13)
298 static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
302 for (i = 0; i < USHORT_RANGE; i++)
303 if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
308 memset(lut + k, 0, (USHORT_RANGE - k) * 2);
313 static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
317 for (i = 0; i < dsize; ++i)
318 dst[i] = lut[dst[i]];
321 #define HUF_ENCBITS 16 // literal (value) bit length
322 #define HUF_DECBITS 14 // decoding bit size (>= 8)
324 #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size
325 #define HUF_DECSIZE (1 << HUF_DECBITS) // decoding table size
326 #define HUF_DECMASK (HUF_DECSIZE - 1)
328 typedef struct HufDec {
334 static void huf_canonical_code_table(uint64_t *hcode)
336 uint64_t c, n[59] = { 0 };
339 for (i = 0; i < HUF_ENCSIZE; ++i)
343 for (i = 58; i > 0; --i) {
344 uint64_t nc = ((c + n[i]) >> 1);
349 for (i = 0; i < HUF_ENCSIZE; ++i) {
353 hcode[i] = l | (n[l]++ << 6);
357 #define SHORT_ZEROCODE_RUN 59
358 #define LONG_ZEROCODE_RUN 63
359 #define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
360 #define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN)
362 static int huf_unpack_enc_table(GetByteContext *gb,
363 int32_t im, int32_t iM, uint64_t *hcode)
366 int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
370 for (; im <= iM; im++) {
371 uint64_t l = hcode[im] = get_bits(&gbit, 6);
373 if (l == LONG_ZEROCODE_RUN) {
374 int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
376 if (im + zerun > iM + 1)
377 return AVERROR_INVALIDDATA;
383 } else if (l >= SHORT_ZEROCODE_RUN) {
384 int zerun = l - SHORT_ZEROCODE_RUN + 2;
386 if (im + zerun > iM + 1)
387 return AVERROR_INVALIDDATA;
396 bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
397 huf_canonical_code_table(hcode);
402 static int huf_build_dec_table(const uint64_t *hcode, int im,
403 int iM, HufDec *hdecod)
405 for (; im <= iM; im++) {
406 uint64_t c = hcode[im] >> 6;
407 int i, l = hcode[im] & 63;
410 return AVERROR_INVALIDDATA;
412 if (l > HUF_DECBITS) {
413 HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
415 return AVERROR_INVALIDDATA;
419 pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
421 return AVERROR(ENOMEM);
423 pl->p[pl->lit - 1] = im;
425 HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
427 for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
428 if (pl->len || pl->p)
429 return AVERROR_INVALIDDATA;
439 #define get_char(c, lc, gb) \
441 c = (c << 8) | bytestream2_get_byte(gb); \
445 #define get_code(po, rlc, c, lc, gb, out, oe, outb) \
449 get_char(c, lc, gb); \
454 if (out + cs > oe || out == outb) \
455 return AVERROR_INVALIDDATA; \
461 } else if (out < oe) { \
464 return AVERROR_INVALIDDATA; \
468 static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
469 GetByteContext *gb, int nbits,
470 int rlc, int no, uint16_t *out)
473 uint16_t *outb = out;
474 uint16_t *oe = out + no;
475 const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
480 while (gb->buffer < ie) {
483 while (lc >= HUF_DECBITS) {
484 const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
488 get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
493 return AVERROR_INVALIDDATA;
495 for (j = 0; j < pl.lit; j++) {
496 int l = hcode[pl.p[j]] & 63;
498 while (lc < l && bytestream2_get_bytes_left(gb) > 0)
502 if ((hcode[pl.p[j]] >> 6) ==
503 ((c >> (lc - l)) & ((1LL << l) - 1))) {
505 get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb);
512 return AVERROR_INVALIDDATA;
522 const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
524 if (pl.len && lc >= pl.len) {
526 get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
528 return AVERROR_INVALIDDATA;
532 if (out - outb != no)
533 return AVERROR_INVALIDDATA;
537 static int huf_uncompress(GetByteContext *gb,
538 uint16_t *dst, int dst_size)
540 int32_t src_size, im, iM;
546 src_size = bytestream2_get_le32(gb);
547 im = bytestream2_get_le32(gb);
548 iM = bytestream2_get_le32(gb);
549 bytestream2_skip(gb, 4);
550 nBits = bytestream2_get_le32(gb);
551 if (im < 0 || im >= HUF_ENCSIZE ||
552 iM < 0 || iM >= HUF_ENCSIZE ||
554 return AVERROR_INVALIDDATA;
556 bytestream2_skip(gb, 4);
558 freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
559 hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
560 if (!freq || !hdec) {
561 ret = AVERROR(ENOMEM);
565 if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
568 if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
569 ret = AVERROR_INVALIDDATA;
573 if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
575 ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
578 for (i = 0; i < HUF_DECSIZE; i++)
580 av_freep(&hdec[i].p);
588 static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
593 int ai = ls + (hi & 1) + (hi >> 1);
595 int16_t bs = ai - hi;
602 #define A_OFFSET (1 << (NBITS - 1))
603 #define MOD_MASK ((1 << NBITS) - 1)
605 static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
609 int bb = (m - (d >> 1)) & MOD_MASK;
610 int aa = (d + bb - A_OFFSET) & MOD_MASK;
615 static void wav_decode(uint16_t *in, int nx, int ox,
616 int ny, int oy, uint16_t mx)
618 int w14 = (mx < (1 << 14));
619 int n = (nx > ny) ? ny : nx;
632 uint16_t *ey = in + oy * (ny - p2);
633 uint16_t i00, i01, i10, i11;
639 for (; py <= ey; py += oy2) {
641 uint16_t *ex = py + ox * (nx - p2);
643 for (; px <= ex; px += ox2) {
644 uint16_t *p01 = px + ox1;
645 uint16_t *p10 = px + oy1;
646 uint16_t *p11 = p10 + ox1;
649 wdec14(*px, *p10, &i00, &i10);
650 wdec14(*p01, *p11, &i01, &i11);
651 wdec14(i00, i01, px, p01);
652 wdec14(i10, i11, p10, p11);
654 wdec16(*px, *p10, &i00, &i10);
655 wdec16(*p01, *p11, &i01, &i11);
656 wdec16(i00, i01, px, p01);
657 wdec16(i10, i11, p10, p11);
662 uint16_t *p10 = px + oy1;
665 wdec14(*px, *p10, &i00, p10);
667 wdec16(*px, *p10, &i00, p10);
675 uint16_t *ex = py + ox * (nx - p2);
677 for (; px <= ex; px += ox2) {
678 uint16_t *p01 = px + ox1;
681 wdec14(*px, *p01, &i00, p01);
683 wdec16(*px, *p01, &i00, p01);
694 static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
695 int dsize, EXRThreadData *td)
698 uint16_t maxval, min_non_zero, max_non_zero;
700 uint16_t *tmp = (uint16_t *)td->tmp;
704 int pixel_half_size;/* 1 for half, 2 for float and uint32 */
709 td->bitmap = av_malloc(BITMAP_SIZE);
711 td->lut = av_malloc(1 << 17);
712 if (!td->bitmap || !td->lut) {
713 av_freep(&td->bitmap);
715 return AVERROR(ENOMEM);
718 bytestream2_init(&gb, src, ssize);
719 min_non_zero = bytestream2_get_le16(&gb);
720 max_non_zero = bytestream2_get_le16(&gb);
722 if (max_non_zero >= BITMAP_SIZE)
723 return AVERROR_INVALIDDATA;
725 memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
726 if (min_non_zero <= max_non_zero)
727 bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
728 max_non_zero - min_non_zero + 1);
729 memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
731 maxval = reverse_lut(td->bitmap, td->lut);
733 ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
738 for (i = 0; i < s->nb_channels; i++) {
739 channel = &s->channels[i];
741 if (channel->pixel_type == EXR_HALF)
746 for (j = 0; j < pixel_half_size; j++)
747 wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize,
748 td->xsize * pixel_half_size, maxval);
749 ptr += td->xsize * td->ysize * pixel_half_size;
752 apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
754 out = (uint16_t *)td->uncompressed_data;
755 for (i = 0; i < td->ysize; i++) {
757 for (j = 0; j < s->nb_channels; j++) {
758 channel = &s->channels[j];
759 if (channel->pixel_type == EXR_HALF)
764 in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size;
765 tmp_offset += pixel_half_size;
768 s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size);
770 memcpy(out, in, td->xsize * 2 * pixel_half_size);
772 out += td->xsize * pixel_half_size;
779 static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
780 int compressed_size, int uncompressed_size,
783 unsigned long dest_len, expected_len = 0;
784 const uint8_t *in = td->tmp;
788 for (i = 0; i < s->nb_channels; i++) {
789 if (s->channels[i].pixel_type == EXR_FLOAT) {
790 expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */
791 } else if (s->channels[i].pixel_type == EXR_HALF) {
792 expected_len += (td->xsize * td->ysize * 2);
794 expected_len += (td->xsize * td->ysize * 4);
798 dest_len = expected_len;
800 if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
801 return AVERROR_INVALIDDATA;
802 } else if (dest_len != expected_len) {
803 return AVERROR_INVALIDDATA;
806 out = td->uncompressed_data;
807 for (i = 0; i < td->ysize; i++)
808 for (c = 0; c < s->nb_channels; c++) {
809 EXRChannel *channel = &s->channels[c];
810 const uint8_t *ptr[4];
813 switch (channel->pixel_type) {
816 ptr[1] = ptr[0] + td->xsize;
817 ptr[2] = ptr[1] + td->xsize;
818 in = ptr[2] + td->xsize;
820 for (j = 0; j < td->xsize; ++j) {
821 uint32_t diff = ((unsigned)*(ptr[0]++) << 24) |
822 (*(ptr[1]++) << 16) |
825 bytestream_put_le32(&out, pixel);
830 ptr[1] = ptr[0] + td->xsize;
831 in = ptr[1] + td->xsize;
832 for (j = 0; j < td->xsize; j++) {
833 uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
836 bytestream_put_le16(&out, pixel);
841 ptr[1] = ptr[0] + s->xdelta;
842 ptr[2] = ptr[1] + s->xdelta;
843 ptr[3] = ptr[2] + s->xdelta;
844 in = ptr[3] + s->xdelta;
846 for (j = 0; j < s->xdelta; ++j) {
847 uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) |
848 (*(ptr[1]++) << 16) |
849 (*(ptr[2]++) << 8 ) |
852 bytestream_put_le32(&out, pixel);
856 return AVERROR_INVALIDDATA;
863 static void unpack_14(const uint8_t b[14], uint16_t s[16])
865 unsigned short shift = (b[ 2] >> 2) & 15;
866 unsigned short bias = (0x20 << shift);
869 s[ 0] = (b[0] << 8) | b[1];
871 s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
872 s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
873 s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias;
875 s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias;
876 s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
877 s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
878 s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias;
880 s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias;
881 s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
882 s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
883 s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias;
885 s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias;
886 s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
887 s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
888 s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias;
890 for (i = 0; i < 16; ++i) {
898 static void unpack_3(const uint8_t b[3], uint16_t s[16])
902 s[0] = (b[0] << 8) | b[1];
909 for (i = 1; i < 16; i++)
914 static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
915 int uncompressed_size, EXRThreadData *td) {
916 const int8_t *sr = src;
917 int stay_to_uncompress = compressed_size;
918 int nb_b44_block_w, nb_b44_block_h;
919 int index_tl_x, index_tl_y, index_out, index_tmp;
920 uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */
922 int target_channel_offset = 0;
924 /* calc B44 block count */
925 nb_b44_block_w = td->xsize / 4;
926 if ((td->xsize % 4) != 0)
929 nb_b44_block_h = td->ysize / 4;
930 if ((td->ysize % 4) != 0)
933 for (c = 0; c < s->nb_channels; c++) {
934 if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
935 for (iY = 0; iY < nb_b44_block_h; iY++) {
936 for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */
937 if (stay_to_uncompress < 3) {
938 av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress);
939 return AVERROR_INVALIDDATA;
942 if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */
943 unpack_3(sr, tmp_buffer);
945 stay_to_uncompress -= 3;
946 } else {/* B44 Block */
947 if (stay_to_uncompress < 14) {
948 av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress);
949 return AVERROR_INVALIDDATA;
951 unpack_14(sr, tmp_buffer);
953 stay_to_uncompress -= 14;
956 /* copy data to uncompress buffer (B44 block can exceed target resolution)*/
960 for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) {
961 for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {
962 index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;
963 index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);
964 td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;
965 td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;
970 target_channel_offset += 2;
971 } else {/* Float or UINT 32 channel */
972 if (stay_to_uncompress < td->ysize * td->xsize * 4) {
973 av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress);
974 return AVERROR_INVALIDDATA;
977 for (y = 0; y < td->ysize; y++) {
978 index_out = target_channel_offset * td->xsize + y * td->channel_line_size;
979 memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);
982 target_channel_offset += 4;
984 stay_to_uncompress -= td->ysize * td->xsize * 4;
991 static int decode_block(AVCodecContext *avctx, void *tdata,
992 int jobnr, int threadnr)
994 EXRContext *s = avctx->priv_data;
995 AVFrame *const p = s->picture;
996 EXRThreadData *td = &s->thread_data[threadnr];
997 const uint8_t *channel_buffer[4] = { 0 };
998 const uint8_t *buf = s->buf;
999 uint64_t line_offset, uncompressed_size;
1003 uint64_t tile_x, tile_y, tile_level_x, tile_level_y;
1005 int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components;
1006 int bxmin = 0, axmax = 0, window_xoffset = 0;
1007 int window_xmin, window_xmax, window_ymin, window_ymax;
1008 int data_xoffset, data_yoffset, data_window_offset, xsize, ysize;
1009 int i, x, buf_size = s->buf_size;
1010 int c, rgb_channel_count;
1011 float one_gamma = 1.0f / s->gamma;
1012 avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1015 line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
1018 if (buf_size < 20 || line_offset > buf_size - 20)
1019 return AVERROR_INVALIDDATA;
1021 src = buf + line_offset + 20;
1022 if (s->is_multipart)
1025 tile_x = AV_RL32(src - 20);
1026 tile_y = AV_RL32(src - 16);
1027 tile_level_x = AV_RL32(src - 12);
1028 tile_level_y = AV_RL32(src - 8);
1030 data_size = AV_RL32(src - 4);
1031 if (data_size <= 0 || data_size > buf_size - line_offset - 20)
1032 return AVERROR_INVALIDDATA;
1034 if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */
1035 avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
1036 return AVERROR_PATCHWELCOME;
1039 line = s->ymin + s->tile_attr.ySize * tile_y;
1040 col = s->tile_attr.xSize * tile_x;
1042 if (line < s->ymin || line > s->ymax ||
1043 s->xmin + col < s->xmin || s->xmin + col > s->xmax)
1044 return AVERROR_INVALIDDATA;
1046 td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);
1047 td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);
1049 if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
1050 return AVERROR_INVALIDDATA;
1052 td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1053 uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1055 if (buf_size < 8 || line_offset > buf_size - 8)
1056 return AVERROR_INVALIDDATA;
1058 src = buf + line_offset + 8;
1059 if (s->is_multipart)
1061 line = AV_RL32(src - 8);
1063 if (line < s->ymin || line > s->ymax)
1064 return AVERROR_INVALIDDATA;
1066 data_size = AV_RL32(src - 4);
1067 if (data_size <= 0 || data_size > buf_size - line_offset - 8)
1068 return AVERROR_INVALIDDATA;
1070 td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
1071 td->xsize = s->xdelta;
1073 if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
1074 return AVERROR_INVALIDDATA;
1076 td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1077 uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1079 if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
1080 line_offset > buf_size - uncompressed_size)) ||
1081 (s->compression != EXR_RAW && (data_size > uncompressed_size ||
1082 line_offset > buf_size - data_size))) {
1083 return AVERROR_INVALIDDATA;
1087 window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col));
1088 window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize));
1089 window_ymin = FFMIN(avctx->height, FFMAX(0, line ));
1090 window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize));
1091 xsize = window_xmax - window_xmin;
1092 ysize = window_ymax - window_ymin;
1094 /* tile or scanline not visible skip decoding */
1095 if (xsize <= 0 || ysize <= 0)
1098 /* is the first tile or is a scanline */
1101 /* pixels to add at the left of the display window */
1102 window_xoffset = FFMAX(0, s->xmin);
1103 /* bytes to add at the left of the display window */
1104 bxmin = window_xoffset * step;
1107 /* is the last tile or is a scanline */
1108 if(col + td->xsize == s->xdelta) {
1109 window_xmax = avctx->width;
1110 /* bytes to add at the right of the display window */
1111 axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step;
1114 if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
1115 av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
1117 return AVERROR(ENOMEM);
1120 if (data_size < uncompressed_size) {
1121 av_fast_padded_malloc(&td->uncompressed_data,
1122 &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */
1124 if (!td->uncompressed_data)
1125 return AVERROR(ENOMEM);
1127 ret = AVERROR_INVALIDDATA;
1128 switch (s->compression) {
1131 ret = zip_uncompress(s, src, data_size, uncompressed_size, td);
1134 ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
1137 ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
1140 ret = rle_uncompress(s, src, data_size, uncompressed_size, td);
1144 ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
1148 av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
1151 src = td->uncompressed_data;
1154 /* offsets to crop data outside display window */
1155 data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4);
1156 data_yoffset = FFABS(FFMIN(0, line));
1157 data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset;
1160 channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset;
1161 channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
1162 channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset;
1163 rgb_channel_count = 3;
1164 } else { /* put y data in the first channel_buffer */
1165 channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
1166 rgb_channel_count = 1;
1168 if (s->channel_offsets[3] >= 0)
1169 channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset;
1171 if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1173 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1174 int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count;
1176 channel_buffer[1] = channel_buffer[0];
1177 channel_buffer[2] = channel_buffer[0];
1180 for (c = 0; c < channel_count; c++) {
1181 int plane = s->desc->comp[c].plane;
1182 ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4);
1184 for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) {
1186 union av_intfloat32 *ptr_x;
1188 src = channel_buffer[c];
1189 ptr_x = (union av_intfloat32 *)ptr;
1191 // Zero out the start if xmin is not 0
1192 memset(ptr_x, 0, bxmin);
1193 ptr_x += window_xoffset;
1195 if (s->pixel_type == EXR_FLOAT) {
1197 union av_intfloat32 t;
1198 if (trc_func && c < 3) {
1199 for (x = 0; x < xsize; x++) {
1200 t.i = bytestream_get_le32(&src);
1201 t.f = trc_func(t.f);
1205 for (x = 0; x < xsize; x++) {
1206 t.i = bytestream_get_le32(&src);
1207 if (t.f > 0.0f && c < 3) /* avoid negative values */
1208 t.f = powf(t.f, one_gamma);
1212 } else if (s->pixel_type == EXR_HALF) {
1214 if (c < 3 || !trc_func) {
1215 for (x = 0; x < xsize; x++) {
1216 *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)];
1219 for (x = 0; x < xsize; x++) {
1220 *ptr_x++ = exr_half2float(bytestream_get_le16(&src));;
1225 // Zero out the end if xmax+1 is not w
1226 memset(ptr_x, 0, axmax);
1227 channel_buffer[c] += td->channel_line_size;
1232 av_assert1(s->pixel_type == EXR_UINT);
1233 ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2);
1235 for (i = 0; i < ysize; i++, ptr += p->linesize[0]) {
1238 const uint8_t *rgb[3];
1241 for (c = 0; c < rgb_channel_count; c++) {
1242 rgb[c] = channel_buffer[c];
1245 if (channel_buffer[3])
1246 a = channel_buffer[3];
1248 ptr_x = (uint16_t *) ptr;
1250 // Zero out the start if xmin is not 0
1251 memset(ptr_x, 0, bxmin);
1252 ptr_x += window_xoffset * s->desc->nb_components;
1254 for (x = 0; x < xsize; x++) {
1255 for (c = 0; c < rgb_channel_count; c++) {
1256 *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;
1259 if (channel_buffer[3])
1260 *ptr_x++ = bytestream_get_le32(&a) >> 16;
1263 // Zero out the end if xmax+1 is not w
1264 memset(ptr_x, 0, axmax);
1266 channel_buffer[0] += td->channel_line_size;
1267 channel_buffer[1] += td->channel_line_size;
1268 channel_buffer[2] += td->channel_line_size;
1269 if (channel_buffer[3])
1270 channel_buffer[3] += td->channel_line_size;
1277 static void skip_header_chunk(EXRContext *s)
1279 GetByteContext *gb = &s->gb;
1281 while (bytestream2_get_bytes_left(gb) > 0) {
1282 if (!bytestream2_peek_byte(gb))
1285 // Process unknown variables
1286 for (int i = 0; i < 2; i++) // value_name and value_type
1287 while (bytestream2_get_byte(gb) != 0);
1289 // Skip variable length
1290 bytestream2_skip(gb, bytestream2_get_le32(gb));
1295 * Check if the variable name corresponds to its data type.
1297 * @param s the EXRContext
1298 * @param value_name name of the variable to check
1299 * @param value_type type of the variable to check
1300 * @param minimum_length minimum length of the variable data
1302 * @return bytes to read containing variable data
1303 * -1 if variable is not found
1304 * 0 if buffer ended prematurely
1306 static int check_header_variable(EXRContext *s,
1307 const char *value_name,
1308 const char *value_type,
1309 unsigned int minimum_length)
1311 GetByteContext *gb = &s->gb;
1314 if (bytestream2_get_bytes_left(gb) >= minimum_length &&
1315 !strcmp(gb->buffer, value_name)) {
1316 // found value_name, jump to value_type (null terminated strings)
1317 gb->buffer += strlen(value_name) + 1;
1318 if (!strcmp(gb->buffer, value_type)) {
1319 gb->buffer += strlen(value_type) + 1;
1320 var_size = bytestream2_get_le32(gb);
1321 // don't go read past boundaries
1322 if (var_size > bytestream2_get_bytes_left(gb))
1325 // value_type not found, reset the buffer
1326 gb->buffer -= strlen(value_name) + 1;
1327 av_log(s->avctx, AV_LOG_WARNING,
1328 "Unknown data type %s for header variable %s.\n",
1329 value_type, value_name);
1336 static int decode_header(EXRContext *s, AVFrame *frame)
1338 AVDictionary *metadata = NULL;
1339 GetByteContext *gb = &s->gb;
1340 int magic_number, version, i, flags;
1341 int layer_match = 0;
1343 int dup_channels = 0;
1345 s->current_channel_offset = 0;
1352 s->channel_offsets[0] = -1;
1353 s->channel_offsets[1] = -1;
1354 s->channel_offsets[2] = -1;
1355 s->channel_offsets[3] = -1;
1356 s->pixel_type = EXR_UNKNOWN;
1357 s->compression = EXR_UNKN;
1361 s->tile_attr.xSize = -1;
1362 s->tile_attr.ySize = -1;
1364 s->is_multipart = 0;
1366 s->current_part = 0;
1368 if (bytestream2_get_bytes_left(gb) < 10) {
1369 av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1370 return AVERROR_INVALIDDATA;
1373 magic_number = bytestream2_get_le32(gb);
1374 if (magic_number != 20000630) {
1375 /* As per documentation of OpenEXR, it is supposed to be
1376 * int 20000630 little-endian */
1377 av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1378 return AVERROR_INVALIDDATA;
1381 version = bytestream2_get_byte(gb);
1383 avpriv_report_missing_feature(s->avctx, "Version %d", version);
1384 return AVERROR_PATCHWELCOME;
1387 flags = bytestream2_get_le24(gb);
1392 s->is_multipart = 1;
1394 avpriv_report_missing_feature(s->avctx, "deep data");
1395 return AVERROR_PATCHWELCOME;
1399 while (bytestream2_get_bytes_left(gb) > 0) {
1402 while (s->is_multipart && s->current_part < s->selected_part &&
1403 bytestream2_get_bytes_left(gb) > 0) {
1404 if (bytestream2_peek_byte(gb)) {
1405 skip_header_chunk(s);
1407 bytestream2_skip(gb, 1);
1408 if (!bytestream2_peek_byte(gb))
1411 bytestream2_skip(gb, 1);
1415 if (!bytestream2_peek_byte(gb)) {
1416 if (!s->is_multipart)
1418 bytestream2_skip(gb, 1);
1419 if (s->current_part == s->selected_part) {
1420 while (bytestream2_get_bytes_left(gb) > 0) {
1421 if (bytestream2_peek_byte(gb)) {
1422 skip_header_chunk(s);
1424 bytestream2_skip(gb, 1);
1425 if (!bytestream2_peek_byte(gb))
1430 if (!bytestream2_peek_byte(gb))
1435 if ((var_size = check_header_variable(s, "channels",
1436 "chlist", 38)) >= 0) {
1437 GetByteContext ch_gb;
1439 ret = AVERROR_INVALIDDATA;
1443 bytestream2_init(&ch_gb, gb->buffer, var_size);
1445 while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1446 EXRChannel *channel;
1447 enum ExrPixelType current_pixel_type;
1448 int channel_index = -1;
1451 if (strcmp(s->layer, "") != 0) {
1452 if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1454 av_log(s->avctx, AV_LOG_INFO,
1455 "Channel match layer : %s.\n", ch_gb.buffer);
1456 ch_gb.buffer += strlen(s->layer);
1457 if (*ch_gb.buffer == '.')
1458 ch_gb.buffer++; /* skip dot if not given */
1461 av_log(s->avctx, AV_LOG_INFO,
1462 "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1468 if (layer_match) { /* only search channel if the layer match is valid */
1469 if (!av_strcasecmp(ch_gb.buffer, "R") ||
1470 !av_strcasecmp(ch_gb.buffer, "X") ||
1471 !av_strcasecmp(ch_gb.buffer, "U")) {
1474 } else if (!av_strcasecmp(ch_gb.buffer, "G") ||
1475 !av_strcasecmp(ch_gb.buffer, "V")) {
1478 } else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
1481 } else if (!av_strcasecmp(ch_gb.buffer, "B") ||
1482 !av_strcasecmp(ch_gb.buffer, "Z") ||
1483 !av_strcasecmp(ch_gb.buffer, "W")) {
1486 } else if (!av_strcasecmp(ch_gb.buffer, "A")) {
1489 av_log(s->avctx, AV_LOG_WARNING,
1490 "Unsupported channel %.256s.\n", ch_gb.buffer);
1494 /* skip until you get a 0 */
1495 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1496 bytestream2_get_byte(&ch_gb))
1499 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1500 av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1501 ret = AVERROR_INVALIDDATA;
1505 current_pixel_type = bytestream2_get_le32(&ch_gb);
1506 if (current_pixel_type >= EXR_UNKNOWN) {
1507 avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1508 current_pixel_type);
1509 ret = AVERROR_PATCHWELCOME;
1513 bytestream2_skip(&ch_gb, 4);
1514 xsub = bytestream2_get_le32(&ch_gb);
1515 ysub = bytestream2_get_le32(&ch_gb);
1517 if (xsub != 1 || ysub != 1) {
1518 avpriv_report_missing_feature(s->avctx,
1519 "Subsampling %dx%d",
1521 ret = AVERROR_PATCHWELCOME;
1525 if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */
1526 if (s->pixel_type != EXR_UNKNOWN &&
1527 s->pixel_type != current_pixel_type) {
1528 av_log(s->avctx, AV_LOG_ERROR,
1529 "RGB channels not of the same depth.\n");
1530 ret = AVERROR_INVALIDDATA;
1533 s->pixel_type = current_pixel_type;
1534 s->channel_offsets[channel_index] = s->current_channel_offset;
1535 } else if (channel_index >= 0) {
1536 av_log(s->avctx, AV_LOG_WARNING,
1537 "Multiple channels with index %d.\n", channel_index);
1538 if (++dup_channels > 10) {
1539 ret = AVERROR_INVALIDDATA;
1544 s->channels = av_realloc(s->channels,
1545 ++s->nb_channels * sizeof(EXRChannel));
1547 ret = AVERROR(ENOMEM);
1550 channel = &s->channels[s->nb_channels - 1];
1551 channel->pixel_type = current_pixel_type;
1552 channel->xsub = xsub;
1553 channel->ysub = ysub;
1555 if (current_pixel_type == EXR_HALF) {
1556 s->current_channel_offset += 2;
1557 } else {/* Float or UINT32 */
1558 s->current_channel_offset += 4;
1562 /* Check if all channels are set with an offset or if the channels
1563 * are causing an overflow */
1564 if (!s->is_luma) {/* if we expected to have at least 3 channels */
1565 if (FFMIN3(s->channel_offsets[0],
1566 s->channel_offsets[1],
1567 s->channel_offsets[2]) < 0) {
1568 if (s->channel_offsets[0] < 0)
1569 av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1570 if (s->channel_offsets[1] < 0)
1571 av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1572 if (s->channel_offsets[2] < 0)
1573 av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1574 ret = AVERROR_INVALIDDATA;
1579 // skip one last byte and update main gb
1580 gb->buffer = ch_gb.buffer + 1;
1582 } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1584 int xmin, ymin, xmax, ymax;
1586 ret = AVERROR_INVALIDDATA;
1590 xmin = bytestream2_get_le32(gb);
1591 ymin = bytestream2_get_le32(gb);
1592 xmax = bytestream2_get_le32(gb);
1593 ymax = bytestream2_get_le32(gb);
1595 if (xmin > xmax || ymin > ymax ||
1596 (unsigned)xmax - xmin >= INT_MAX ||
1597 (unsigned)ymax - ymin >= INT_MAX) {
1598 ret = AVERROR_INVALIDDATA;
1605 s->xdelta = (s->xmax - s->xmin) + 1;
1606 s->ydelta = (s->ymax - s->ymin) + 1;
1609 } else if ((var_size = check_header_variable(s, "displayWindow",
1610 "box2i", 34)) >= 0) {
1611 int32_t sx, sy, dx, dy;
1614 ret = AVERROR_INVALIDDATA;
1618 sx = bytestream2_get_le32(gb);
1619 sy = bytestream2_get_le32(gb);
1620 dx = bytestream2_get_le32(gb);
1621 dy = bytestream2_get_le32(gb);
1627 } else if ((var_size = check_header_variable(s, "lineOrder",
1628 "lineOrder", 25)) >= 0) {
1631 ret = AVERROR_INVALIDDATA;
1635 line_order = bytestream2_get_byte(gb);
1636 av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1637 if (line_order > 2) {
1638 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1639 ret = AVERROR_INVALIDDATA;
1644 } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1645 "float", 31)) >= 0) {
1647 ret = AVERROR_INVALIDDATA;
1651 s->sar = bytestream2_get_le32(gb);
1654 } else if ((var_size = check_header_variable(s, "compression",
1655 "compression", 29)) >= 0) {
1657 ret = AVERROR_INVALIDDATA;
1661 if (s->compression == EXR_UNKN)
1662 s->compression = bytestream2_get_byte(gb);
1664 bytestream2_skip(gb, 1);
1665 av_log(s->avctx, AV_LOG_WARNING,
1666 "Found more than one compression attribute.\n");
1670 } else if ((var_size = check_header_variable(s, "tiles",
1671 "tiledesc", 22)) >= 0) {
1675 av_log(s->avctx, AV_LOG_WARNING,
1676 "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
1678 s->tile_attr.xSize = bytestream2_get_le32(gb);
1679 s->tile_attr.ySize = bytestream2_get_le32(gb);
1681 tileLevel = bytestream2_get_byte(gb);
1682 s->tile_attr.level_mode = tileLevel & 0x0f;
1683 s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
1685 if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) {
1686 avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
1687 s->tile_attr.level_mode);
1688 ret = AVERROR_PATCHWELCOME;
1692 if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
1693 avpriv_report_missing_feature(s->avctx, "Tile level round %d",
1694 s->tile_attr.level_round);
1695 ret = AVERROR_PATCHWELCOME;
1700 } else if ((var_size = check_header_variable(s, "writer",
1701 "string", 1)) >= 0) {
1702 uint8_t key[256] = { 0 };
1704 bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1705 av_dict_set(&metadata, "writer", key, 0);
1708 } else if ((var_size = check_header_variable(s, "framesPerSecond",
1709 "rational", 33)) >= 0) {
1711 ret = AVERROR_INVALIDDATA;
1715 s->avctx->framerate.num = bytestream2_get_le32(gb);
1716 s->avctx->framerate.den = bytestream2_get_le32(gb);
1719 } else if ((var_size = check_header_variable(s, "chunkCount",
1722 s->chunk_count = bytestream2_get_le32(gb);
1725 } else if ((var_size = check_header_variable(s, "type",
1726 "string", 16)) >= 0) {
1727 uint8_t key[256] = { 0 };
1729 bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1730 if (strncmp("scanlineimage", key, var_size) &&
1731 strncmp("tiledimage", key, var_size))
1732 return AVERROR_PATCHWELCOME;
1737 // Check if there are enough bytes for a header
1738 if (bytestream2_get_bytes_left(gb) <= 9) {
1739 av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1740 ret = AVERROR_INVALIDDATA;
1744 // Process unknown variables
1745 for (i = 0; i < 2; i++) // value_name and value_type
1746 while (bytestream2_get_byte(gb) != 0);
1748 // Skip variable length
1749 bytestream2_skip(gb, bytestream2_get_le32(gb));
1752 if (s->compression == EXR_UNKN) {
1753 av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1754 ret = AVERROR_INVALIDDATA;
1759 if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1760 av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1761 ret = AVERROR_INVALIDDATA;
1766 if (bytestream2_get_bytes_left(gb) <= 0) {
1767 av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1768 ret = AVERROR_INVALIDDATA;
1772 frame->metadata = metadata;
1774 // aaand we are done
1775 bytestream2_skip(gb, 1);
1778 av_dict_free(&metadata);
1782 static int decode_frame(AVCodecContext *avctx, void *data,
1783 int *got_frame, AVPacket *avpkt)
1785 EXRContext *s = avctx->priv_data;
1786 GetByteContext *gb = &s->gb;
1787 ThreadFrame frame = { .f = data };
1788 AVFrame *picture = data;
1791 int i, y, ret, ymax;
1794 int nb_blocks; /* nb scanline or nb tile */
1795 uint64_t start_offset_table;
1796 uint64_t start_next_scanline;
1797 PutByteContext offset_table_writer;
1799 bytestream2_init(gb, avpkt->data, avpkt->size);
1801 if ((ret = decode_header(s, picture)) < 0)
1804 switch (s->pixel_type) {
1807 if (s->channel_offsets[3] >= 0) {
1809 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1811 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1812 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1816 avctx->pix_fmt = AV_PIX_FMT_GBRPF32;
1818 avctx->pix_fmt = AV_PIX_FMT_GRAYF32;
1823 if (s->channel_offsets[3] >= 0) {
1825 avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1827 avctx->pix_fmt = AV_PIX_FMT_YA16;
1831 avctx->pix_fmt = AV_PIX_FMT_RGB48;
1833 avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1838 av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1839 return AVERROR_INVALIDDATA;
1842 if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1843 avctx->color_trc = s->apply_trc_type;
1845 switch (s->compression) {
1849 s->scan_lines_per_block = 1;
1853 s->scan_lines_per_block = 16;
1858 s->scan_lines_per_block = 32;
1861 avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1862 return AVERROR_PATCHWELCOME;
1865 /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.
1866 * It's possible for the data window can larger or outside the display window */
1867 if (s->xmin > s->xmax || s->ymin > s->ymax ||
1868 s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {
1869 av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1870 return AVERROR_INVALIDDATA;
1873 if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1876 ff_set_sar(s->avctx, av_d2q(av_int2float(s->sar), 255));
1878 s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1880 return AVERROR_INVALIDDATA;
1882 if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1883 planes = s->desc->nb_components;
1884 out_line_size = avctx->width * 4;
1887 out_line_size = avctx->width * 2 * s->desc->nb_components;
1891 nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
1892 ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
1893 } else { /* scanline */
1894 nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1895 s->scan_lines_per_block;
1898 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1901 if (bytestream2_get_bytes_left(gb)/8 < nb_blocks)
1902 return AVERROR_INVALIDDATA;
1904 // check offset table and recreate it if need
1905 if (!s->is_tile && bytestream2_peek_le64(gb) == 0) {
1906 av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n");
1908 start_offset_table = bytestream2_tell(gb);
1909 start_next_scanline = start_offset_table + nb_blocks * 8;
1910 bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);
1912 for (y = 0; y < nb_blocks; y++) {
1913 /* write offset of prev scanline in offset table */
1914 bytestream2_put_le64(&offset_table_writer, start_next_scanline);
1916 /* get len of next scanline */
1917 bytestream2_seek(gb, start_next_scanline + 4, SEEK_SET);/* skip line number */
1918 start_next_scanline += (bytestream2_get_le32(gb) + 8);
1920 bytestream2_seek(gb, start_offset_table, SEEK_SET);
1923 // save pointer we are going to use in decode_block
1924 s->buf = avpkt->data;
1925 s->buf_size = avpkt->size;
1927 // Zero out the start if ymin is not 0
1928 for (i = 0; i < planes; i++) {
1929 ptr = picture->data[i];
1930 for (y = 0; y < FFMIN(s->ymin, s->h); y++) {
1931 memset(ptr, 0, out_line_size);
1932 ptr += picture->linesize[i];
1936 s->picture = picture;
1938 avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
1940 ymax = FFMAX(0, s->ymax + 1);
1941 // Zero out the end if ymax+1 is not h
1942 if (ymax < avctx->height)
1943 for (i = 0; i < planes; i++) {
1944 ptr = picture->data[i] + (ymax * picture->linesize[i]);
1945 for (y = ymax; y < avctx->height; y++) {
1946 memset(ptr, 0, out_line_size);
1947 ptr += picture->linesize[i];
1951 picture->pict_type = AV_PICTURE_TYPE_I;
1957 static av_cold int decode_init(AVCodecContext *avctx)
1959 EXRContext *s = avctx->priv_data;
1961 union av_intfloat32 t;
1962 float one_gamma = 1.0f / s->gamma;
1963 avpriv_trc_function trc_func = NULL;
1967 ff_exrdsp_init(&s->dsp);
1970 ff_bswapdsp_init(&s->bbdsp);
1973 trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1975 for (i = 0; i < 65536; ++i) {
1976 t = exr_half2float(i);
1977 t.f = trc_func(t.f);
1978 s->gamma_table[i] = t;
1981 if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1982 for (i = 0; i < 65536; ++i) {
1983 s->gamma_table[i] = exr_half2float(i);
1986 for (i = 0; i < 65536; ++i) {
1987 t = exr_half2float(i);
1988 /* If negative value we reuse half value */
1990 s->gamma_table[i] = t;
1992 t.f = powf(t.f, one_gamma);
1993 s->gamma_table[i] = t;
1999 // allocate thread data, used for non EXR_RAW compression types
2000 s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
2001 if (!s->thread_data)
2002 return AVERROR_INVALIDDATA;
2007 static av_cold int decode_end(AVCodecContext *avctx)
2009 EXRContext *s = avctx->priv_data;
2011 for (i = 0; i < avctx->thread_count; i++) {
2012 EXRThreadData *td = &s->thread_data[i];
2013 av_freep(&td->uncompressed_data);
2015 av_freep(&td->bitmap);
2019 av_freep(&s->thread_data);
2020 av_freep(&s->channels);
2025 #define OFFSET(x) offsetof(EXRContext, x)
2026 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2027 static const AVOption options[] = {
2028 { "layer", "Set the decoding layer", OFFSET(layer),
2029 AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
2030 { "part", "Set the decoding part", OFFSET(selected_part),
2031 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
2032 { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
2033 AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
2035 // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
2036 { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
2037 AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
2038 { "bt709", "BT.709", 0,
2039 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2040 { "gamma", "gamma", 0,
2041 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2042 { "gamma22", "BT.470 M", 0,
2043 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2044 { "gamma28", "BT.470 BG", 0,
2045 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2046 { "smpte170m", "SMPTE 170 M", 0,
2047 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2048 { "smpte240m", "SMPTE 240 M", 0,
2049 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2050 { "linear", "Linear", 0,
2051 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2053 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2054 { "log_sqrt", "Log square root", 0,
2055 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2056 { "iec61966_2_4", "IEC 61966-2-4", 0,
2057 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2058 { "bt1361", "BT.1361", 0,
2059 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2060 { "iec61966_2_1", "IEC 61966-2-1", 0,
2061 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2062 { "bt2020_10bit", "BT.2020 - 10 bit", 0,
2063 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2064 { "bt2020_12bit", "BT.2020 - 12 bit", 0,
2065 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2066 { "smpte2084", "SMPTE ST 2084", 0,
2067 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2068 { "smpte428_1", "SMPTE ST 428-1", 0,
2069 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2074 static const AVClass exr_class = {
2075 .class_name = "EXR",
2076 .item_name = av_default_item_name,
2078 .version = LIBAVUTIL_VERSION_INT,
2081 AVCodec ff_exr_decoder = {
2083 .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"),
2084 .type = AVMEDIA_TYPE_VIDEO,
2085 .id = AV_CODEC_ID_EXR,
2086 .priv_data_size = sizeof(EXRContext),
2087 .init = decode_init,
2088 .close = decode_end,
2089 .decode = decode_frame,
2090 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
2091 AV_CODEC_CAP_SLICE_THREADS,
2092 .priv_class = &exr_class,