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 HuffEntry {
100 typedef struct EXRChannel {
102 enum ExrPixelType pixel_type;
105 typedef struct EXRTileAttribute {
108 enum ExrTileLevelMode level_mode;
109 enum ExrTileLevelRound level_round;
112 typedef struct EXRThreadData {
113 uint8_t *uncompressed_data;
114 int uncompressed_size;
124 int channel_line_size;
132 typedef struct EXRContext {
135 AVCodecContext *avctx;
139 BswapDSPContext bbdsp;
142 enum ExrCompr compression;
143 enum ExrPixelType pixel_type;
144 int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
145 const AVPixFmtDescriptor *desc;
151 uint32_t xdelta, ydelta;
153 int scan_lines_per_block;
155 EXRTileAttribute tile_attr; /* header data attribute of tile */
156 int is_tile; /* 0 if scanline, 1 if tile */
160 int is_luma;/* 1 if there is an Y plane */
166 EXRChannel *channels;
168 int current_channel_offset;
169 uint32_t chunk_count;
171 EXRThreadData *thread_data;
176 enum AVColorTransferCharacteristic apply_trc_type;
178 union av_intfloat32 gamma_table[65536];
181 /* -15 stored using a single precision bias of 127 */
182 #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
184 /* max exponent value in single precision that will be converted
185 * to Inf or Nan when stored as a half-float */
186 #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
188 /* 255 is the max exponent biased value */
189 #define FLOAT_MAX_BIASED_EXP (0xFF << 23)
191 #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
194 * Convert a half float as a uint16_t into a full float.
196 * @param hf half float as uint16_t
198 * @return float value
200 static union av_intfloat32 exr_half2float(uint16_t hf)
202 unsigned int sign = (unsigned int) (hf >> 15);
203 unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
204 unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
205 union av_intfloat32 f;
207 if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
208 // we have a half-float NaN or Inf
209 // half-float NaNs will be converted to a single precision NaN
210 // half-float Infs will be converted to a single precision Inf
211 exp = FLOAT_MAX_BIASED_EXP;
212 mantissa <<= 13; // preserve half-float NaN bits if set
213 } else if (exp == 0x0) {
214 // convert half-float zero/denorm to single precision value
217 exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
218 // check for leading 1 in denorm mantissa
219 while (!(mantissa & (1 << 10))) {
220 // for every leading 0, decrement single precision exponent by 1
221 // and shift half-float mantissa value to the left
225 // clamp the mantissa to 10 bits
226 mantissa &= ((1 << 10) - 1);
227 // shift left to generate single-precision mantissa of 23 bits
231 // shift left to generate single-precision mantissa of 23 bits
233 // generate single precision biased exponent value
234 exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
237 f.i = (sign << 31) | exp | mantissa;
242 static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
243 int uncompressed_size, EXRThreadData *td)
245 unsigned long dest_len = uncompressed_size;
247 if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
248 dest_len != uncompressed_size)
249 return AVERROR_INVALIDDATA;
251 av_assert1(uncompressed_size % 2 == 0);
253 s->dsp.predictor(td->tmp, uncompressed_size);
254 s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
259 static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size,
260 int uncompressed_size, EXRThreadData *td)
262 uint8_t *d = td->tmp;
263 const int8_t *s = src;
264 int ssize = compressed_size;
265 int dsize = uncompressed_size;
266 uint8_t *dend = d + dsize;
275 if ((dsize -= count) < 0 ||
276 (ssize -= count + 1) < 0)
277 return AVERROR_INVALIDDATA;
284 if ((dsize -= count) < 0 ||
286 return AVERROR_INVALIDDATA;
296 return AVERROR_INVALIDDATA;
298 av_assert1(uncompressed_size % 2 == 0);
300 ctx->dsp.predictor(td->tmp, uncompressed_size);
301 ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
306 #define USHORT_RANGE (1 << 16)
307 #define BITMAP_SIZE (1 << 13)
309 static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
313 for (i = 0; i < USHORT_RANGE; i++)
314 if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
319 memset(lut + k, 0, (USHORT_RANGE - k) * 2);
324 static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
328 for (i = 0; i < dsize; ++i)
329 dst[i] = lut[dst[i]];
332 #define HUF_ENCBITS 16 // literal (value) bit length
333 #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size
335 static void huf_canonical_code_table(uint64_t *freq)
337 uint64_t c, n[59] = { 0 };
340 for (i = 0; i < HUF_ENCSIZE; i++)
344 for (i = 58; i > 0; --i) {
345 uint64_t nc = ((c + n[i]) >> 1);
350 for (i = 0; i < HUF_ENCSIZE; ++i) {
354 freq[i] = l | (n[l]++ << 6);
358 #define SHORT_ZEROCODE_RUN 59
359 #define LONG_ZEROCODE_RUN 63
360 #define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
361 #define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN)
363 static int huf_unpack_enc_table(GetByteContext *gb,
364 int32_t im, int32_t iM, uint64_t *freq)
367 int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
371 for (; im <= iM; im++) {
372 uint64_t l = freq[im] = get_bits(&gbit, 6);
374 if (l == LONG_ZEROCODE_RUN) {
375 int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
377 if (im + zerun > iM + 1)
378 return AVERROR_INVALIDDATA;
384 } else if (l >= SHORT_ZEROCODE_RUN) {
385 int zerun = l - SHORT_ZEROCODE_RUN + 2;
387 if (im + zerun > iM + 1)
388 return AVERROR_INVALIDDATA;
397 bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
398 huf_canonical_code_table(freq);
403 static int huf_build_dec_table(EXRContext *s,
404 EXRThreadData *td, int im, int iM)
409 for (int i = im; i < iM; i++) {
411 td->he[j].len = td->freq[i] & 63;
412 td->he[j].code = td->freq[i] >> 6;
413 if (td->he[j].len > 32) {
414 avpriv_request_sample(s->avctx, "Too big code length");
415 return AVERROR_PATCHWELCOME;
417 if (td->he[j].len > 0)
423 if (td->run_sym == -1) {
424 avpriv_request_sample(s->avctx, "No place for run symbol");
425 return AVERROR_PATCHWELCOME;
428 td->he[j].sym = td->run_sym;
429 td->he[j].len = td->freq[iM] & 63;
430 if (td->he[j].len > 32) {
431 avpriv_request_sample(s->avctx, "Too big code length");
432 return AVERROR_PATCHWELCOME;
434 td->he[j].code = td->freq[iM] >> 6;
437 ff_free_vlc(&td->vlc);
438 return ff_init_vlc_sparse(&td->vlc, 12, j,
439 &td->he[0].len, sizeof(td->he[0]), sizeof(td->he[0].len),
440 &td->he[0].code, sizeof(td->he[0]), sizeof(td->he[0].code),
441 &td->he[0].sym, sizeof(td->he[0]), sizeof(td->he[0].sym), 0);
444 static int huf_decode(VLC *vlc, GetByteContext *gb, int nbits, int run_sym,
445 int no, uint16_t *out)
450 init_get_bits(&gbit, gb->buffer, nbits);
451 while (get_bits_left(&gbit) > 0 && oe < no) {
452 uint16_t x = get_vlc2(&gbit, vlc->table, 12, 2);
455 int run = get_bits(&gbit, 8);
456 uint16_t fill = out[oe - 1];
468 static int huf_uncompress(EXRContext *s,
471 uint16_t *dst, int dst_size)
473 int32_t src_size, im, iM;
477 src_size = bytestream2_get_le32(gb);
478 im = bytestream2_get_le32(gb);
479 iM = bytestream2_get_le32(gb);
480 bytestream2_skip(gb, 4);
481 nBits = bytestream2_get_le32(gb);
482 if (im < 0 || im >= HUF_ENCSIZE ||
483 iM < 0 || iM >= HUF_ENCSIZE ||
485 return AVERROR_INVALIDDATA;
487 bytestream2_skip(gb, 4);
490 td->freq = av_malloc_array(HUF_ENCSIZE, sizeof(*td->freq));
492 td->he = av_calloc(HUF_ENCSIZE, sizeof(*td->he));
493 if (!td->freq || !td->he) {
494 ret = AVERROR(ENOMEM);
498 memset(td->freq, 0, sizeof(*td->freq) * HUF_ENCSIZE);
499 if ((ret = huf_unpack_enc_table(gb, im, iM, td->freq)) < 0)
502 if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
503 ret = AVERROR_INVALIDDATA;
507 if ((ret = huf_build_dec_table(s, td, im, iM)) < 0)
509 return huf_decode(&td->vlc, gb, nBits, td->run_sym, dst_size, dst);
512 static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
517 int ai = ls + (hi & 1) + (hi >> 1);
519 int16_t bs = ai - hi;
526 #define A_OFFSET (1 << (NBITS - 1))
527 #define MOD_MASK ((1 << NBITS) - 1)
529 static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
533 int bb = (m - (d >> 1)) & MOD_MASK;
534 int aa = (d + bb - A_OFFSET) & MOD_MASK;
539 static void wav_decode(uint16_t *in, int nx, int ox,
540 int ny, int oy, uint16_t mx)
542 int w14 = (mx < (1 << 14));
543 int n = (nx > ny) ? ny : nx;
556 uint16_t *ey = in + oy * (ny - p2);
557 uint16_t i00, i01, i10, i11;
563 for (; py <= ey; py += oy2) {
565 uint16_t *ex = py + ox * (nx - p2);
567 for (; px <= ex; px += ox2) {
568 uint16_t *p01 = px + ox1;
569 uint16_t *p10 = px + oy1;
570 uint16_t *p11 = p10 + ox1;
573 wdec14(*px, *p10, &i00, &i10);
574 wdec14(*p01, *p11, &i01, &i11);
575 wdec14(i00, i01, px, p01);
576 wdec14(i10, i11, p10, p11);
578 wdec16(*px, *p10, &i00, &i10);
579 wdec16(*p01, *p11, &i01, &i11);
580 wdec16(i00, i01, px, p01);
581 wdec16(i10, i11, p10, p11);
586 uint16_t *p10 = px + oy1;
589 wdec14(*px, *p10, &i00, p10);
591 wdec16(*px, *p10, &i00, p10);
599 uint16_t *ex = py + ox * (nx - p2);
601 for (; px <= ex; px += ox2) {
602 uint16_t *p01 = px + ox1;
605 wdec14(*px, *p01, &i00, p01);
607 wdec16(*px, *p01, &i00, p01);
618 static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
619 int dsize, EXRThreadData *td)
622 uint16_t maxval, min_non_zero, max_non_zero;
624 uint16_t *tmp = (uint16_t *)td->tmp;
628 int pixel_half_size;/* 1 for half, 2 for float and uint32 */
633 td->bitmap = av_malloc(BITMAP_SIZE);
635 td->lut = av_malloc(1 << 17);
636 if (!td->bitmap || !td->lut) {
637 av_freep(&td->bitmap);
639 return AVERROR(ENOMEM);
642 bytestream2_init(&gb, src, ssize);
643 min_non_zero = bytestream2_get_le16(&gb);
644 max_non_zero = bytestream2_get_le16(&gb);
646 if (max_non_zero >= BITMAP_SIZE)
647 return AVERROR_INVALIDDATA;
649 memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
650 if (min_non_zero <= max_non_zero)
651 bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
652 max_non_zero - min_non_zero + 1);
653 memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
655 maxval = reverse_lut(td->bitmap, td->lut);
657 ret = huf_uncompress(s, td, &gb, tmp, dsize / sizeof(uint16_t));
662 for (i = 0; i < s->nb_channels; i++) {
663 channel = &s->channels[i];
665 if (channel->pixel_type == EXR_HALF)
670 for (j = 0; j < pixel_half_size; j++)
671 wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize,
672 td->xsize * pixel_half_size, maxval);
673 ptr += td->xsize * td->ysize * pixel_half_size;
676 apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
678 out = (uint16_t *)td->uncompressed_data;
679 for (i = 0; i < td->ysize; i++) {
681 for (j = 0; j < s->nb_channels; j++) {
682 channel = &s->channels[j];
683 if (channel->pixel_type == EXR_HALF)
688 in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size;
689 tmp_offset += pixel_half_size;
692 s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size);
694 memcpy(out, in, td->xsize * 2 * pixel_half_size);
696 out += td->xsize * pixel_half_size;
703 static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
704 int compressed_size, int uncompressed_size,
707 unsigned long dest_len, expected_len = 0;
708 const uint8_t *in = td->tmp;
712 for (i = 0; i < s->nb_channels; i++) {
713 if (s->channels[i].pixel_type == EXR_FLOAT) {
714 expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */
715 } else if (s->channels[i].pixel_type == EXR_HALF) {
716 expected_len += (td->xsize * td->ysize * 2);
718 expected_len += (td->xsize * td->ysize * 4);
722 dest_len = expected_len;
724 if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
725 return AVERROR_INVALIDDATA;
726 } else if (dest_len != expected_len) {
727 return AVERROR_INVALIDDATA;
730 out = td->uncompressed_data;
731 for (i = 0; i < td->ysize; i++)
732 for (c = 0; c < s->nb_channels; c++) {
733 EXRChannel *channel = &s->channels[c];
734 const uint8_t *ptr[4];
737 switch (channel->pixel_type) {
740 ptr[1] = ptr[0] + td->xsize;
741 ptr[2] = ptr[1] + td->xsize;
742 in = ptr[2] + td->xsize;
744 for (j = 0; j < td->xsize; ++j) {
745 uint32_t diff = ((unsigned)*(ptr[0]++) << 24) |
746 (*(ptr[1]++) << 16) |
749 bytestream_put_le32(&out, pixel);
754 ptr[1] = ptr[0] + td->xsize;
755 in = ptr[1] + td->xsize;
756 for (j = 0; j < td->xsize; j++) {
757 uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
760 bytestream_put_le16(&out, pixel);
765 ptr[1] = ptr[0] + s->xdelta;
766 ptr[2] = ptr[1] + s->xdelta;
767 ptr[3] = ptr[2] + s->xdelta;
768 in = ptr[3] + s->xdelta;
770 for (j = 0; j < s->xdelta; ++j) {
771 uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) |
772 (*(ptr[1]++) << 16) |
773 (*(ptr[2]++) << 8 ) |
776 bytestream_put_le32(&out, pixel);
780 return AVERROR_INVALIDDATA;
787 static void unpack_14(const uint8_t b[14], uint16_t s[16])
789 unsigned short shift = (b[ 2] >> 2) & 15;
790 unsigned short bias = (0x20 << shift);
793 s[ 0] = (b[0] << 8) | b[1];
795 s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
796 s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
797 s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias;
799 s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias;
800 s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
801 s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
802 s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias;
804 s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias;
805 s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
806 s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
807 s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias;
809 s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias;
810 s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
811 s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
812 s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias;
814 for (i = 0; i < 16; ++i) {
822 static void unpack_3(const uint8_t b[3], uint16_t s[16])
826 s[0] = (b[0] << 8) | b[1];
833 for (i = 1; i < 16; i++)
838 static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
839 int uncompressed_size, EXRThreadData *td) {
840 const int8_t *sr = src;
841 int stay_to_uncompress = compressed_size;
842 int nb_b44_block_w, nb_b44_block_h;
843 int index_tl_x, index_tl_y, index_out, index_tmp;
844 uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */
846 int target_channel_offset = 0;
848 /* calc B44 block count */
849 nb_b44_block_w = td->xsize / 4;
850 if ((td->xsize % 4) != 0)
853 nb_b44_block_h = td->ysize / 4;
854 if ((td->ysize % 4) != 0)
857 for (c = 0; c < s->nb_channels; c++) {
858 if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
859 for (iY = 0; iY < nb_b44_block_h; iY++) {
860 for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */
861 if (stay_to_uncompress < 3) {
862 av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress);
863 return AVERROR_INVALIDDATA;
866 if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */
867 unpack_3(sr, tmp_buffer);
869 stay_to_uncompress -= 3;
870 } else {/* B44 Block */
871 if (stay_to_uncompress < 14) {
872 av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress);
873 return AVERROR_INVALIDDATA;
875 unpack_14(sr, tmp_buffer);
877 stay_to_uncompress -= 14;
880 /* copy data to uncompress buffer (B44 block can exceed target resolution)*/
884 for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) {
885 for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {
886 index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;
887 index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);
888 td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;
889 td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;
894 target_channel_offset += 2;
895 } else {/* Float or UINT 32 channel */
896 if (stay_to_uncompress < td->ysize * td->xsize * 4) {
897 av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress);
898 return AVERROR_INVALIDDATA;
901 for (y = 0; y < td->ysize; y++) {
902 index_out = target_channel_offset * td->xsize + y * td->channel_line_size;
903 memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);
906 target_channel_offset += 4;
908 stay_to_uncompress -= td->ysize * td->xsize * 4;
915 static int decode_block(AVCodecContext *avctx, void *tdata,
916 int jobnr, int threadnr)
918 EXRContext *s = avctx->priv_data;
919 AVFrame *const p = s->picture;
920 EXRThreadData *td = &s->thread_data[threadnr];
921 const uint8_t *channel_buffer[4] = { 0 };
922 const uint8_t *buf = s->buf;
923 uint64_t line_offset, uncompressed_size;
927 uint64_t tile_x, tile_y, tile_level_x, tile_level_y;
929 int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components;
930 int bxmin = 0, axmax = 0, window_xoffset = 0;
931 int window_xmin, window_xmax, window_ymin, window_ymax;
932 int data_xoffset, data_yoffset, data_window_offset, xsize, ysize;
933 int i, x, buf_size = s->buf_size;
934 int c, rgb_channel_count;
935 float one_gamma = 1.0f / s->gamma;
936 avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
939 line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
942 if (buf_size < 20 || line_offset > buf_size - 20)
943 return AVERROR_INVALIDDATA;
945 src = buf + line_offset + 20;
949 tile_x = AV_RL32(src - 20);
950 tile_y = AV_RL32(src - 16);
951 tile_level_x = AV_RL32(src - 12);
952 tile_level_y = AV_RL32(src - 8);
954 data_size = AV_RL32(src - 4);
955 if (data_size <= 0 || data_size > buf_size - line_offset - 20)
956 return AVERROR_INVALIDDATA;
958 if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */
959 avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
960 return AVERROR_PATCHWELCOME;
963 line = s->ymin + s->tile_attr.ySize * tile_y;
964 col = s->tile_attr.xSize * tile_x;
966 if (line < s->ymin || line > s->ymax ||
967 s->xmin + col < s->xmin || s->xmin + col > s->xmax)
968 return AVERROR_INVALIDDATA;
970 td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);
971 td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);
973 if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
974 return AVERROR_INVALIDDATA;
976 td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
977 uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
979 if (buf_size < 8 || line_offset > buf_size - 8)
980 return AVERROR_INVALIDDATA;
982 src = buf + line_offset + 8;
985 line = AV_RL32(src - 8);
987 if (line < s->ymin || line > s->ymax)
988 return AVERROR_INVALIDDATA;
990 data_size = AV_RL32(src - 4);
991 if (data_size <= 0 || data_size > buf_size - line_offset - 8)
992 return AVERROR_INVALIDDATA;
994 td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
995 td->xsize = s->xdelta;
997 if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
998 return AVERROR_INVALIDDATA;
1000 td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1001 uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1003 if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
1004 line_offset > buf_size - uncompressed_size)) ||
1005 (s->compression != EXR_RAW && (data_size > uncompressed_size ||
1006 line_offset > buf_size - data_size))) {
1007 return AVERROR_INVALIDDATA;
1011 window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col));
1012 window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize));
1013 window_ymin = FFMIN(avctx->height, FFMAX(0, line ));
1014 window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize));
1015 xsize = window_xmax - window_xmin;
1016 ysize = window_ymax - window_ymin;
1018 /* tile or scanline not visible skip decoding */
1019 if (xsize <= 0 || ysize <= 0)
1022 /* is the first tile or is a scanline */
1025 /* pixels to add at the left of the display window */
1026 window_xoffset = FFMAX(0, s->xmin);
1027 /* bytes to add at the left of the display window */
1028 bxmin = window_xoffset * step;
1031 /* is the last tile or is a scanline */
1032 if(col + td->xsize == s->xdelta) {
1033 window_xmax = avctx->width;
1034 /* bytes to add at the right of the display window */
1035 axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step;
1038 if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
1039 av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
1041 return AVERROR(ENOMEM);
1044 if (data_size < uncompressed_size) {
1045 av_fast_padded_malloc(&td->uncompressed_data,
1046 &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */
1048 if (!td->uncompressed_data)
1049 return AVERROR(ENOMEM);
1051 ret = AVERROR_INVALIDDATA;
1052 switch (s->compression) {
1055 ret = zip_uncompress(s, src, data_size, uncompressed_size, td);
1058 ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
1061 ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
1064 ret = rle_uncompress(s, src, data_size, uncompressed_size, td);
1068 ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
1072 av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
1075 src = td->uncompressed_data;
1078 /* offsets to crop data outside display window */
1079 data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4);
1080 data_yoffset = FFABS(FFMIN(0, line));
1081 data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset;
1084 channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset;
1085 channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
1086 channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset;
1087 rgb_channel_count = 3;
1088 } else { /* put y data in the first channel_buffer */
1089 channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
1090 rgb_channel_count = 1;
1092 if (s->channel_offsets[3] >= 0)
1093 channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset;
1095 if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1097 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1098 int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count;
1100 channel_buffer[1] = channel_buffer[0];
1101 channel_buffer[2] = channel_buffer[0];
1104 for (c = 0; c < channel_count; c++) {
1105 int plane = s->desc->comp[c].plane;
1106 ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4);
1108 for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) {
1110 union av_intfloat32 *ptr_x;
1112 src = channel_buffer[c];
1113 ptr_x = (union av_intfloat32 *)ptr;
1115 // Zero out the start if xmin is not 0
1116 memset(ptr_x, 0, bxmin);
1117 ptr_x += window_xoffset;
1119 if (s->pixel_type == EXR_FLOAT) {
1121 union av_intfloat32 t;
1122 if (trc_func && c < 3) {
1123 for (x = 0; x < xsize; x++) {
1124 t.i = bytestream_get_le32(&src);
1125 t.f = trc_func(t.f);
1129 for (x = 0; x < xsize; x++) {
1130 t.i = bytestream_get_le32(&src);
1131 if (t.f > 0.0f && c < 3) /* avoid negative values */
1132 t.f = powf(t.f, one_gamma);
1136 } else if (s->pixel_type == EXR_HALF) {
1138 if (c < 3 || !trc_func) {
1139 for (x = 0; x < xsize; x++) {
1140 *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)];
1143 for (x = 0; x < xsize; x++) {
1144 *ptr_x++ = exr_half2float(bytestream_get_le16(&src));;
1149 // Zero out the end if xmax+1 is not w
1150 memset(ptr_x, 0, axmax);
1151 channel_buffer[c] += td->channel_line_size;
1156 av_assert1(s->pixel_type == EXR_UINT);
1157 ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2);
1159 for (i = 0; i < ysize; i++, ptr += p->linesize[0]) {
1162 const uint8_t *rgb[3];
1165 for (c = 0; c < rgb_channel_count; c++) {
1166 rgb[c] = channel_buffer[c];
1169 if (channel_buffer[3])
1170 a = channel_buffer[3];
1172 ptr_x = (uint16_t *) ptr;
1174 // Zero out the start if xmin is not 0
1175 memset(ptr_x, 0, bxmin);
1176 ptr_x += window_xoffset * s->desc->nb_components;
1178 for (x = 0; x < xsize; x++) {
1179 for (c = 0; c < rgb_channel_count; c++) {
1180 *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;
1183 if (channel_buffer[3])
1184 *ptr_x++ = bytestream_get_le32(&a) >> 16;
1187 // Zero out the end if xmax+1 is not w
1188 memset(ptr_x, 0, axmax);
1190 channel_buffer[0] += td->channel_line_size;
1191 channel_buffer[1] += td->channel_line_size;
1192 channel_buffer[2] += td->channel_line_size;
1193 if (channel_buffer[3])
1194 channel_buffer[3] += td->channel_line_size;
1201 static void skip_header_chunk(EXRContext *s)
1203 GetByteContext *gb = &s->gb;
1205 while (bytestream2_get_bytes_left(gb) > 0) {
1206 if (!bytestream2_peek_byte(gb))
1209 // Process unknown variables
1210 for (int i = 0; i < 2; i++) // value_name and value_type
1211 while (bytestream2_get_byte(gb) != 0);
1213 // Skip variable length
1214 bytestream2_skip(gb, bytestream2_get_le32(gb));
1219 * Check if the variable name corresponds to its data type.
1221 * @param s the EXRContext
1222 * @param value_name name of the variable to check
1223 * @param value_type type of the variable to check
1224 * @param minimum_length minimum length of the variable data
1226 * @return bytes to read containing variable data
1227 * -1 if variable is not found
1228 * 0 if buffer ended prematurely
1230 static int check_header_variable(EXRContext *s,
1231 const char *value_name,
1232 const char *value_type,
1233 unsigned int minimum_length)
1235 GetByteContext *gb = &s->gb;
1238 if (bytestream2_get_bytes_left(gb) >= minimum_length &&
1239 !strcmp(gb->buffer, value_name)) {
1240 // found value_name, jump to value_type (null terminated strings)
1241 gb->buffer += strlen(value_name) + 1;
1242 if (!strcmp(gb->buffer, value_type)) {
1243 gb->buffer += strlen(value_type) + 1;
1244 var_size = bytestream2_get_le32(gb);
1245 // don't go read past boundaries
1246 if (var_size > bytestream2_get_bytes_left(gb))
1249 // value_type not found, reset the buffer
1250 gb->buffer -= strlen(value_name) + 1;
1251 av_log(s->avctx, AV_LOG_WARNING,
1252 "Unknown data type %s for header variable %s.\n",
1253 value_type, value_name);
1260 static int decode_header(EXRContext *s, AVFrame *frame)
1262 AVDictionary *metadata = NULL;
1263 GetByteContext *gb = &s->gb;
1264 int magic_number, version, flags;
1265 int layer_match = 0;
1267 int dup_channels = 0;
1269 s->current_channel_offset = 0;
1276 s->channel_offsets[0] = -1;
1277 s->channel_offsets[1] = -1;
1278 s->channel_offsets[2] = -1;
1279 s->channel_offsets[3] = -1;
1280 s->pixel_type = EXR_UNKNOWN;
1281 s->compression = EXR_UNKN;
1285 s->tile_attr.xSize = -1;
1286 s->tile_attr.ySize = -1;
1288 s->is_multipart = 0;
1290 s->current_part = 0;
1292 if (bytestream2_get_bytes_left(gb) < 10) {
1293 av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1294 return AVERROR_INVALIDDATA;
1297 magic_number = bytestream2_get_le32(gb);
1298 if (magic_number != 20000630) {
1299 /* As per documentation of OpenEXR, it is supposed to be
1300 * int 20000630 little-endian */
1301 av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1302 return AVERROR_INVALIDDATA;
1305 version = bytestream2_get_byte(gb);
1307 avpriv_report_missing_feature(s->avctx, "Version %d", version);
1308 return AVERROR_PATCHWELCOME;
1311 flags = bytestream2_get_le24(gb);
1316 s->is_multipart = 1;
1318 avpriv_report_missing_feature(s->avctx, "deep data");
1319 return AVERROR_PATCHWELCOME;
1323 while (bytestream2_get_bytes_left(gb) > 0) {
1326 while (s->is_multipart && s->current_part < s->selected_part &&
1327 bytestream2_get_bytes_left(gb) > 0) {
1328 if (bytestream2_peek_byte(gb)) {
1329 skip_header_chunk(s);
1331 bytestream2_skip(gb, 1);
1332 if (!bytestream2_peek_byte(gb))
1335 bytestream2_skip(gb, 1);
1339 if (!bytestream2_peek_byte(gb)) {
1340 if (!s->is_multipart)
1342 bytestream2_skip(gb, 1);
1343 if (s->current_part == s->selected_part) {
1344 while (bytestream2_get_bytes_left(gb) > 0) {
1345 if (bytestream2_peek_byte(gb)) {
1346 skip_header_chunk(s);
1348 bytestream2_skip(gb, 1);
1349 if (!bytestream2_peek_byte(gb))
1354 if (!bytestream2_peek_byte(gb))
1359 if ((var_size = check_header_variable(s, "channels",
1360 "chlist", 38)) >= 0) {
1361 GetByteContext ch_gb;
1363 ret = AVERROR_INVALIDDATA;
1367 bytestream2_init(&ch_gb, gb->buffer, var_size);
1369 while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1370 EXRChannel *channel;
1371 enum ExrPixelType current_pixel_type;
1372 int channel_index = -1;
1375 if (strcmp(s->layer, "") != 0) {
1376 if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1378 av_log(s->avctx, AV_LOG_INFO,
1379 "Channel match layer : %s.\n", ch_gb.buffer);
1380 ch_gb.buffer += strlen(s->layer);
1381 if (*ch_gb.buffer == '.')
1382 ch_gb.buffer++; /* skip dot if not given */
1385 av_log(s->avctx, AV_LOG_INFO,
1386 "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1392 if (layer_match) { /* only search channel if the layer match is valid */
1393 if (!av_strcasecmp(ch_gb.buffer, "R") ||
1394 !av_strcasecmp(ch_gb.buffer, "X") ||
1395 !av_strcasecmp(ch_gb.buffer, "U")) {
1398 } else if (!av_strcasecmp(ch_gb.buffer, "G") ||
1399 !av_strcasecmp(ch_gb.buffer, "V")) {
1402 } else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
1405 } else if (!av_strcasecmp(ch_gb.buffer, "B") ||
1406 !av_strcasecmp(ch_gb.buffer, "Z") ||
1407 !av_strcasecmp(ch_gb.buffer, "W")) {
1410 } else if (!av_strcasecmp(ch_gb.buffer, "A")) {
1413 av_log(s->avctx, AV_LOG_WARNING,
1414 "Unsupported channel %.256s.\n", ch_gb.buffer);
1418 /* skip until you get a 0 */
1419 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1420 bytestream2_get_byte(&ch_gb))
1423 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1424 av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1425 ret = AVERROR_INVALIDDATA;
1429 current_pixel_type = bytestream2_get_le32(&ch_gb);
1430 if (current_pixel_type >= EXR_UNKNOWN) {
1431 avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1432 current_pixel_type);
1433 ret = AVERROR_PATCHWELCOME;
1437 bytestream2_skip(&ch_gb, 4);
1438 xsub = bytestream2_get_le32(&ch_gb);
1439 ysub = bytestream2_get_le32(&ch_gb);
1441 if (xsub != 1 || ysub != 1) {
1442 avpriv_report_missing_feature(s->avctx,
1443 "Subsampling %dx%d",
1445 ret = AVERROR_PATCHWELCOME;
1449 if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */
1450 if (s->pixel_type != EXR_UNKNOWN &&
1451 s->pixel_type != current_pixel_type) {
1452 av_log(s->avctx, AV_LOG_ERROR,
1453 "RGB channels not of the same depth.\n");
1454 ret = AVERROR_INVALIDDATA;
1457 s->pixel_type = current_pixel_type;
1458 s->channel_offsets[channel_index] = s->current_channel_offset;
1459 } else if (channel_index >= 0) {
1460 av_log(s->avctx, AV_LOG_WARNING,
1461 "Multiple channels with index %d.\n", channel_index);
1462 if (++dup_channels > 10) {
1463 ret = AVERROR_INVALIDDATA;
1468 s->channels = av_realloc(s->channels,
1469 ++s->nb_channels * sizeof(EXRChannel));
1471 ret = AVERROR(ENOMEM);
1474 channel = &s->channels[s->nb_channels - 1];
1475 channel->pixel_type = current_pixel_type;
1476 channel->xsub = xsub;
1477 channel->ysub = ysub;
1479 if (current_pixel_type == EXR_HALF) {
1480 s->current_channel_offset += 2;
1481 } else {/* Float or UINT32 */
1482 s->current_channel_offset += 4;
1486 /* Check if all channels are set with an offset or if the channels
1487 * are causing an overflow */
1488 if (!s->is_luma) {/* if we expected to have at least 3 channels */
1489 if (FFMIN3(s->channel_offsets[0],
1490 s->channel_offsets[1],
1491 s->channel_offsets[2]) < 0) {
1492 if (s->channel_offsets[0] < 0)
1493 av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1494 if (s->channel_offsets[1] < 0)
1495 av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1496 if (s->channel_offsets[2] < 0)
1497 av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1498 ret = AVERROR_INVALIDDATA;
1503 // skip one last byte and update main gb
1504 gb->buffer = ch_gb.buffer + 1;
1506 } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1508 int xmin, ymin, xmax, ymax;
1510 ret = AVERROR_INVALIDDATA;
1514 xmin = bytestream2_get_le32(gb);
1515 ymin = bytestream2_get_le32(gb);
1516 xmax = bytestream2_get_le32(gb);
1517 ymax = bytestream2_get_le32(gb);
1519 if (xmin > xmax || ymin > ymax ||
1520 (unsigned)xmax - xmin >= INT_MAX ||
1521 (unsigned)ymax - ymin >= INT_MAX) {
1522 ret = AVERROR_INVALIDDATA;
1529 s->xdelta = (s->xmax - s->xmin) + 1;
1530 s->ydelta = (s->ymax - s->ymin) + 1;
1533 } else if ((var_size = check_header_variable(s, "displayWindow",
1534 "box2i", 34)) >= 0) {
1535 int32_t sx, sy, dx, dy;
1538 ret = AVERROR_INVALIDDATA;
1542 sx = bytestream2_get_le32(gb);
1543 sy = bytestream2_get_le32(gb);
1544 dx = bytestream2_get_le32(gb);
1545 dy = bytestream2_get_le32(gb);
1551 } else if ((var_size = check_header_variable(s, "lineOrder",
1552 "lineOrder", 25)) >= 0) {
1555 ret = AVERROR_INVALIDDATA;
1559 line_order = bytestream2_get_byte(gb);
1560 av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1561 if (line_order > 2) {
1562 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1563 ret = AVERROR_INVALIDDATA;
1568 } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1569 "float", 31)) >= 0) {
1571 ret = AVERROR_INVALIDDATA;
1575 s->sar = bytestream2_get_le32(gb);
1578 } else if ((var_size = check_header_variable(s, "compression",
1579 "compression", 29)) >= 0) {
1581 ret = AVERROR_INVALIDDATA;
1585 if (s->compression == EXR_UNKN)
1586 s->compression = bytestream2_get_byte(gb);
1588 bytestream2_skip(gb, 1);
1589 av_log(s->avctx, AV_LOG_WARNING,
1590 "Found more than one compression attribute.\n");
1594 } else if ((var_size = check_header_variable(s, "tiles",
1595 "tiledesc", 22)) >= 0) {
1599 av_log(s->avctx, AV_LOG_WARNING,
1600 "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
1602 s->tile_attr.xSize = bytestream2_get_le32(gb);
1603 s->tile_attr.ySize = bytestream2_get_le32(gb);
1605 tileLevel = bytestream2_get_byte(gb);
1606 s->tile_attr.level_mode = tileLevel & 0x0f;
1607 s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
1609 if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) {
1610 avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
1611 s->tile_attr.level_mode);
1612 ret = AVERROR_PATCHWELCOME;
1616 if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
1617 avpriv_report_missing_feature(s->avctx, "Tile level round %d",
1618 s->tile_attr.level_round);
1619 ret = AVERROR_PATCHWELCOME;
1624 } else if ((var_size = check_header_variable(s, "writer",
1625 "string", 1)) >= 0) {
1626 uint8_t key[256] = { 0 };
1628 bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1629 av_dict_set(&metadata, "writer", key, 0);
1632 } else if ((var_size = check_header_variable(s, "framesPerSecond",
1633 "rational", 33)) >= 0) {
1635 ret = AVERROR_INVALIDDATA;
1639 s->avctx->framerate.num = bytestream2_get_le32(gb);
1640 s->avctx->framerate.den = bytestream2_get_le32(gb);
1643 } else if ((var_size = check_header_variable(s, "chunkCount",
1646 s->chunk_count = bytestream2_get_le32(gb);
1649 } else if ((var_size = check_header_variable(s, "type",
1650 "string", 16)) >= 0) {
1651 uint8_t key[256] = { 0 };
1653 bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1654 if (strncmp("scanlineimage", key, var_size) &&
1655 strncmp("tiledimage", key, var_size))
1656 return AVERROR_PATCHWELCOME;
1659 } else if ((var_size = check_header_variable(s, "preview",
1660 "preview", 16)) >= 0) {
1661 uint32_t pw = bytestream2_get_le32(gb);
1662 uint32_t ph = bytestream2_get_le32(gb);
1663 int64_t psize = 4LL * pw * ph;
1665 if (psize >= bytestream2_get_bytes_left(gb))
1666 return AVERROR_INVALIDDATA;
1668 bytestream2_skip(gb, psize);
1673 // Check if there are enough bytes for a header
1674 if (bytestream2_get_bytes_left(gb) <= 9) {
1675 av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1676 ret = AVERROR_INVALIDDATA;
1680 // Process unknown variables
1682 uint8_t name[256] = { 0 };
1683 uint8_t type[256] = { 0 };
1684 uint8_t value[256] = { 0 };
1687 while (bytestream2_get_bytes_left(gb) > 0 &&
1688 bytestream2_peek_byte(gb) && i < 255) {
1689 name[i++] = bytestream2_get_byte(gb);
1692 bytestream2_skip(gb, 1);
1694 while (bytestream2_get_bytes_left(gb) > 0 &&
1695 bytestream2_peek_byte(gb) && i < 255) {
1696 type[i++] = bytestream2_get_byte(gb);
1698 bytestream2_skip(gb, 1);
1699 size = bytestream2_get_le32(gb);
1701 bytestream2_get_buffer(gb, value, FFMIN(sizeof(value) - 1, size));
1702 if (!strcmp(type, "string"))
1703 av_dict_set(&metadata, name, value, 0);
1707 if (s->compression == EXR_UNKN) {
1708 av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1709 ret = AVERROR_INVALIDDATA;
1714 if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1715 av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1716 ret = AVERROR_INVALIDDATA;
1721 if (bytestream2_get_bytes_left(gb) <= 0) {
1722 av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1723 ret = AVERROR_INVALIDDATA;
1727 frame->metadata = metadata;
1729 // aaand we are done
1730 bytestream2_skip(gb, 1);
1733 av_dict_free(&metadata);
1737 static int decode_frame(AVCodecContext *avctx, void *data,
1738 int *got_frame, AVPacket *avpkt)
1740 EXRContext *s = avctx->priv_data;
1741 GetByteContext *gb = &s->gb;
1742 ThreadFrame frame = { .f = data };
1743 AVFrame *picture = data;
1746 int i, y, ret, ymax;
1749 int nb_blocks; /* nb scanline or nb tile */
1750 uint64_t start_offset_table;
1751 uint64_t start_next_scanline;
1752 PutByteContext offset_table_writer;
1754 bytestream2_init(gb, avpkt->data, avpkt->size);
1756 if ((ret = decode_header(s, picture)) < 0)
1759 switch (s->pixel_type) {
1762 if (s->channel_offsets[3] >= 0) {
1764 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1766 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1767 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1771 avctx->pix_fmt = AV_PIX_FMT_GBRPF32;
1773 avctx->pix_fmt = AV_PIX_FMT_GRAYF32;
1778 if (s->channel_offsets[3] >= 0) {
1780 avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1782 avctx->pix_fmt = AV_PIX_FMT_YA16;
1786 avctx->pix_fmt = AV_PIX_FMT_RGB48;
1788 avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1793 av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1794 return AVERROR_INVALIDDATA;
1797 if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1798 avctx->color_trc = s->apply_trc_type;
1800 switch (s->compression) {
1804 s->scan_lines_per_block = 1;
1808 s->scan_lines_per_block = 16;
1813 s->scan_lines_per_block = 32;
1816 avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1817 return AVERROR_PATCHWELCOME;
1820 /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.
1821 * It's possible for the data window can larger or outside the display window */
1822 if (s->xmin > s->xmax || s->ymin > s->ymax ||
1823 s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {
1824 av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1825 return AVERROR_INVALIDDATA;
1828 if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1831 ff_set_sar(s->avctx, av_d2q(av_int2float(s->sar), 255));
1833 s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1835 return AVERROR_INVALIDDATA;
1837 if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1838 planes = s->desc->nb_components;
1839 out_line_size = avctx->width * 4;
1842 out_line_size = avctx->width * 2 * s->desc->nb_components;
1846 nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
1847 ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
1848 } else { /* scanline */
1849 nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1850 s->scan_lines_per_block;
1853 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1856 if (bytestream2_get_bytes_left(gb)/8 < nb_blocks)
1857 return AVERROR_INVALIDDATA;
1859 // check offset table and recreate it if need
1860 if (!s->is_tile && bytestream2_peek_le64(gb) == 0) {
1861 av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n");
1863 start_offset_table = bytestream2_tell(gb);
1864 start_next_scanline = start_offset_table + nb_blocks * 8;
1865 bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);
1867 for (y = 0; y < nb_blocks; y++) {
1868 /* write offset of prev scanline in offset table */
1869 bytestream2_put_le64(&offset_table_writer, start_next_scanline);
1871 /* get len of next scanline */
1872 bytestream2_seek(gb, start_next_scanline + 4, SEEK_SET);/* skip line number */
1873 start_next_scanline += (bytestream2_get_le32(gb) + 8);
1875 bytestream2_seek(gb, start_offset_table, SEEK_SET);
1878 // save pointer we are going to use in decode_block
1879 s->buf = avpkt->data;
1880 s->buf_size = avpkt->size;
1882 // Zero out the start if ymin is not 0
1883 for (i = 0; i < planes; i++) {
1884 ptr = picture->data[i];
1885 for (y = 0; y < FFMIN(s->ymin, s->h); y++) {
1886 memset(ptr, 0, out_line_size);
1887 ptr += picture->linesize[i];
1891 s->picture = picture;
1893 avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
1895 ymax = FFMAX(0, s->ymax + 1);
1896 // Zero out the end if ymax+1 is not h
1897 if (ymax < avctx->height)
1898 for (i = 0; i < planes; i++) {
1899 ptr = picture->data[i] + (ymax * picture->linesize[i]);
1900 for (y = ymax; y < avctx->height; y++) {
1901 memset(ptr, 0, out_line_size);
1902 ptr += picture->linesize[i];
1906 picture->pict_type = AV_PICTURE_TYPE_I;
1912 static av_cold int decode_init(AVCodecContext *avctx)
1914 EXRContext *s = avctx->priv_data;
1916 union av_intfloat32 t;
1917 float one_gamma = 1.0f / s->gamma;
1918 avpriv_trc_function trc_func = NULL;
1922 ff_exrdsp_init(&s->dsp);
1925 ff_bswapdsp_init(&s->bbdsp);
1928 trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1930 for (i = 0; i < 65536; ++i) {
1931 t = exr_half2float(i);
1932 t.f = trc_func(t.f);
1933 s->gamma_table[i] = t;
1936 if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1937 for (i = 0; i < 65536; ++i) {
1938 s->gamma_table[i] = exr_half2float(i);
1941 for (i = 0; i < 65536; ++i) {
1942 t = exr_half2float(i);
1943 /* If negative value we reuse half value */
1945 s->gamma_table[i] = t;
1947 t.f = powf(t.f, one_gamma);
1948 s->gamma_table[i] = t;
1954 // allocate thread data, used for non EXR_RAW compression types
1955 s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1956 if (!s->thread_data)
1957 return AVERROR_INVALIDDATA;
1962 static av_cold int decode_end(AVCodecContext *avctx)
1964 EXRContext *s = avctx->priv_data;
1966 for (i = 0; i < avctx->thread_count; i++) {
1967 EXRThreadData *td = &s->thread_data[i];
1968 av_freep(&td->uncompressed_data);
1970 av_freep(&td->bitmap);
1973 av_freep(&td->freq);
1974 ff_free_vlc(&td->vlc);
1977 av_freep(&s->thread_data);
1978 av_freep(&s->channels);
1983 #define OFFSET(x) offsetof(EXRContext, x)
1984 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1985 static const AVOption options[] = {
1986 { "layer", "Set the decoding layer", OFFSET(layer),
1987 AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
1988 { "part", "Set the decoding part", OFFSET(selected_part),
1989 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
1990 { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
1991 AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
1993 // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
1994 { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
1995 AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
1996 { "bt709", "BT.709", 0,
1997 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1998 { "gamma", "gamma", 0,
1999 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2000 { "gamma22", "BT.470 M", 0,
2001 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2002 { "gamma28", "BT.470 BG", 0,
2003 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2004 { "smpte170m", "SMPTE 170 M", 0,
2005 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2006 { "smpte240m", "SMPTE 240 M", 0,
2007 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2008 { "linear", "Linear", 0,
2009 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2011 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2012 { "log_sqrt", "Log square root", 0,
2013 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2014 { "iec61966_2_4", "IEC 61966-2-4", 0,
2015 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2016 { "bt1361", "BT.1361", 0,
2017 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2018 { "iec61966_2_1", "IEC 61966-2-1", 0,
2019 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2020 { "bt2020_10bit", "BT.2020 - 10 bit", 0,
2021 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2022 { "bt2020_12bit", "BT.2020 - 12 bit", 0,
2023 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2024 { "smpte2084", "SMPTE ST 2084", 0,
2025 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2026 { "smpte428_1", "SMPTE ST 428-1", 0,
2027 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2032 static const AVClass exr_class = {
2033 .class_name = "EXR",
2034 .item_name = av_default_item_name,
2036 .version = LIBAVUTIL_VERSION_INT,
2039 AVCodec ff_exr_decoder = {
2041 .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"),
2042 .type = AVMEDIA_TYPE_VIDEO,
2043 .id = AV_CODEC_ID_EXR,
2044 .priv_data_size = sizeof(EXRContext),
2045 .init = decode_init,
2046 .close = decode_end,
2047 .decode = decode_frame,
2048 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
2049 AV_CODEC_CAP_SLICE_THREADS,
2050 .priv_class = &exr_class,