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)
428 if (td->run_sym == -1) {
429 avpriv_request_sample(s->avctx, "No place for run symbol");
430 return AVERROR_PATCHWELCOME;
433 td->he[j].sym = td->run_sym;
434 td->he[j].len = td->freq[iM] & 63;
435 if (td->he[j].len > 32) {
436 avpriv_request_sample(s->avctx, "Too big code length");
437 return AVERROR_PATCHWELCOME;
439 td->he[j].code = td->freq[iM] >> 6;
442 ff_free_vlc(&td->vlc);
443 return ff_init_vlc_sparse(&td->vlc, 12, j,
444 &td->he[0].len, sizeof(td->he[0]), sizeof(td->he[0].len),
445 &td->he[0].code, sizeof(td->he[0]), sizeof(td->he[0].code),
446 &td->he[0].sym, sizeof(td->he[0]), sizeof(td->he[0].sym), 0);
449 static int huf_decode(VLC *vlc, GetByteContext *gb, int nbits, int run_sym,
450 int no, uint16_t *out)
455 init_get_bits(&gbit, gb->buffer, nbits);
456 while (get_bits_left(&gbit) > 0 && oe < no) {
457 uint16_t x = get_vlc2(&gbit, vlc->table, 12, 2);
460 int run = get_bits(&gbit, 8);
461 uint16_t fill = out[oe - 1];
473 static int huf_uncompress(EXRContext *s,
476 uint16_t *dst, int dst_size)
478 int32_t src_size, im, iM;
482 src_size = bytestream2_get_le32(gb);
483 im = bytestream2_get_le32(gb);
484 iM = bytestream2_get_le32(gb);
485 bytestream2_skip(gb, 4);
486 nBits = bytestream2_get_le32(gb);
487 if (im < 0 || im >= HUF_ENCSIZE ||
488 iM < 0 || iM >= HUF_ENCSIZE ||
490 return AVERROR_INVALIDDATA;
492 bytestream2_skip(gb, 4);
495 td->freq = av_malloc_array(HUF_ENCSIZE, sizeof(*td->freq));
497 td->he = av_calloc(HUF_ENCSIZE, sizeof(*td->he));
498 if (!td->freq || !td->he) {
499 ret = AVERROR(ENOMEM);
503 memset(td->freq, 0, sizeof(*td->freq) * HUF_ENCSIZE);
504 if ((ret = huf_unpack_enc_table(gb, im, iM, td->freq)) < 0)
507 if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
508 ret = AVERROR_INVALIDDATA;
512 if ((ret = huf_build_dec_table(s, td, im, iM)) < 0)
514 return huf_decode(&td->vlc, gb, nBits, td->run_sym, dst_size, dst);
517 static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
522 int ai = ls + (hi & 1) + (hi >> 1);
524 int16_t bs = ai - hi;
531 #define A_OFFSET (1 << (NBITS - 1))
532 #define MOD_MASK ((1 << NBITS) - 1)
534 static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
538 int bb = (m - (d >> 1)) & MOD_MASK;
539 int aa = (d + bb - A_OFFSET) & MOD_MASK;
544 static void wav_decode(uint16_t *in, int nx, int ox,
545 int ny, int oy, uint16_t mx)
547 int w14 = (mx < (1 << 14));
548 int n = (nx > ny) ? ny : nx;
561 uint16_t *ey = in + oy * (ny - p2);
562 uint16_t i00, i01, i10, i11;
568 for (; py <= ey; py += oy2) {
570 uint16_t *ex = py + ox * (nx - p2);
572 for (; px <= ex; px += ox2) {
573 uint16_t *p01 = px + ox1;
574 uint16_t *p10 = px + oy1;
575 uint16_t *p11 = p10 + ox1;
578 wdec14(*px, *p10, &i00, &i10);
579 wdec14(*p01, *p11, &i01, &i11);
580 wdec14(i00, i01, px, p01);
581 wdec14(i10, i11, p10, p11);
583 wdec16(*px, *p10, &i00, &i10);
584 wdec16(*p01, *p11, &i01, &i11);
585 wdec16(i00, i01, px, p01);
586 wdec16(i10, i11, p10, p11);
591 uint16_t *p10 = px + oy1;
594 wdec14(*px, *p10, &i00, p10);
596 wdec16(*px, *p10, &i00, p10);
604 uint16_t *ex = py + ox * (nx - p2);
606 for (; px <= ex; px += ox2) {
607 uint16_t *p01 = px + ox1;
610 wdec14(*px, *p01, &i00, p01);
612 wdec16(*px, *p01, &i00, p01);
623 static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
624 int dsize, EXRThreadData *td)
627 uint16_t maxval, min_non_zero, max_non_zero;
629 uint16_t *tmp = (uint16_t *)td->tmp;
633 int pixel_half_size;/* 1 for half, 2 for float and uint32 */
638 td->bitmap = av_malloc(BITMAP_SIZE);
640 td->lut = av_malloc(1 << 17);
641 if (!td->bitmap || !td->lut) {
642 av_freep(&td->bitmap);
644 return AVERROR(ENOMEM);
647 bytestream2_init(&gb, src, ssize);
648 min_non_zero = bytestream2_get_le16(&gb);
649 max_non_zero = bytestream2_get_le16(&gb);
651 if (max_non_zero >= BITMAP_SIZE)
652 return AVERROR_INVALIDDATA;
654 memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
655 if (min_non_zero <= max_non_zero)
656 bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
657 max_non_zero - min_non_zero + 1);
658 memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
660 maxval = reverse_lut(td->bitmap, td->lut);
662 ret = huf_uncompress(s, td, &gb, tmp, dsize / sizeof(uint16_t));
667 for (i = 0; i < s->nb_channels; i++) {
668 channel = &s->channels[i];
670 if (channel->pixel_type == EXR_HALF)
675 for (j = 0; j < pixel_half_size; j++)
676 wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize,
677 td->xsize * pixel_half_size, maxval);
678 ptr += td->xsize * td->ysize * pixel_half_size;
681 apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
683 out = (uint16_t *)td->uncompressed_data;
684 for (i = 0; i < td->ysize; i++) {
686 for (j = 0; j < s->nb_channels; j++) {
687 channel = &s->channels[j];
688 if (channel->pixel_type == EXR_HALF)
693 in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size;
694 tmp_offset += pixel_half_size;
697 s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size);
699 memcpy(out, in, td->xsize * 2 * pixel_half_size);
701 out += td->xsize * pixel_half_size;
708 static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
709 int compressed_size, int uncompressed_size,
712 unsigned long dest_len, expected_len = 0;
713 const uint8_t *in = td->tmp;
717 for (i = 0; i < s->nb_channels; i++) {
718 if (s->channels[i].pixel_type == EXR_FLOAT) {
719 expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */
720 } else if (s->channels[i].pixel_type == EXR_HALF) {
721 expected_len += (td->xsize * td->ysize * 2);
723 expected_len += (td->xsize * td->ysize * 4);
727 dest_len = expected_len;
729 if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
730 return AVERROR_INVALIDDATA;
731 } else if (dest_len != expected_len) {
732 return AVERROR_INVALIDDATA;
735 out = td->uncompressed_data;
736 for (i = 0; i < td->ysize; i++)
737 for (c = 0; c < s->nb_channels; c++) {
738 EXRChannel *channel = &s->channels[c];
739 const uint8_t *ptr[4];
742 switch (channel->pixel_type) {
745 ptr[1] = ptr[0] + td->xsize;
746 ptr[2] = ptr[1] + td->xsize;
747 in = ptr[2] + td->xsize;
749 for (j = 0; j < td->xsize; ++j) {
750 uint32_t diff = ((unsigned)*(ptr[0]++) << 24) |
751 (*(ptr[1]++) << 16) |
754 bytestream_put_le32(&out, pixel);
759 ptr[1] = ptr[0] + td->xsize;
760 in = ptr[1] + td->xsize;
761 for (j = 0; j < td->xsize; j++) {
762 uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
765 bytestream_put_le16(&out, pixel);
770 ptr[1] = ptr[0] + s->xdelta;
771 ptr[2] = ptr[1] + s->xdelta;
772 ptr[3] = ptr[2] + s->xdelta;
773 in = ptr[3] + s->xdelta;
775 for (j = 0; j < s->xdelta; ++j) {
776 uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) |
777 (*(ptr[1]++) << 16) |
778 (*(ptr[2]++) << 8 ) |
781 bytestream_put_le32(&out, pixel);
785 return AVERROR_INVALIDDATA;
792 static void unpack_14(const uint8_t b[14], uint16_t s[16])
794 unsigned short shift = (b[ 2] >> 2) & 15;
795 unsigned short bias = (0x20 << shift);
798 s[ 0] = (b[0] << 8) | b[1];
800 s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
801 s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
802 s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias;
804 s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias;
805 s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
806 s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
807 s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias;
809 s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias;
810 s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
811 s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
812 s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias;
814 s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias;
815 s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
816 s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
817 s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias;
819 for (i = 0; i < 16; ++i) {
827 static void unpack_3(const uint8_t b[3], uint16_t s[16])
831 s[0] = (b[0] << 8) | b[1];
838 for (i = 1; i < 16; i++)
843 static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
844 int uncompressed_size, EXRThreadData *td) {
845 const int8_t *sr = src;
846 int stay_to_uncompress = compressed_size;
847 int nb_b44_block_w, nb_b44_block_h;
848 int index_tl_x, index_tl_y, index_out, index_tmp;
849 uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */
851 int target_channel_offset = 0;
853 /* calc B44 block count */
854 nb_b44_block_w = td->xsize / 4;
855 if ((td->xsize % 4) != 0)
858 nb_b44_block_h = td->ysize / 4;
859 if ((td->ysize % 4) != 0)
862 for (c = 0; c < s->nb_channels; c++) {
863 if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
864 for (iY = 0; iY < nb_b44_block_h; iY++) {
865 for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */
866 if (stay_to_uncompress < 3) {
867 av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress);
868 return AVERROR_INVALIDDATA;
871 if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */
872 unpack_3(sr, tmp_buffer);
874 stay_to_uncompress -= 3;
875 } else {/* B44 Block */
876 if (stay_to_uncompress < 14) {
877 av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress);
878 return AVERROR_INVALIDDATA;
880 unpack_14(sr, tmp_buffer);
882 stay_to_uncompress -= 14;
885 /* copy data to uncompress buffer (B44 block can exceed target resolution)*/
889 for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) {
890 for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {
891 index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;
892 index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);
893 td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;
894 td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;
899 target_channel_offset += 2;
900 } else {/* Float or UINT 32 channel */
901 if (stay_to_uncompress < td->ysize * td->xsize * 4) {
902 av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress);
903 return AVERROR_INVALIDDATA;
906 for (y = 0; y < td->ysize; y++) {
907 index_out = target_channel_offset * td->xsize + y * td->channel_line_size;
908 memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);
911 target_channel_offset += 4;
913 stay_to_uncompress -= td->ysize * td->xsize * 4;
920 static int decode_block(AVCodecContext *avctx, void *tdata,
921 int jobnr, int threadnr)
923 EXRContext *s = avctx->priv_data;
924 AVFrame *const p = s->picture;
925 EXRThreadData *td = &s->thread_data[threadnr];
926 const uint8_t *channel_buffer[4] = { 0 };
927 const uint8_t *buf = s->buf;
928 uint64_t line_offset, uncompressed_size;
932 uint64_t tile_x, tile_y, tile_level_x, tile_level_y;
934 int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components;
935 int bxmin = 0, axmax = 0, window_xoffset = 0;
936 int window_xmin, window_xmax, window_ymin, window_ymax;
937 int data_xoffset, data_yoffset, data_window_offset, xsize, ysize;
938 int i, x, buf_size = s->buf_size;
939 int c, rgb_channel_count;
940 float one_gamma = 1.0f / s->gamma;
941 avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
944 line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
947 if (buf_size < 20 || line_offset > buf_size - 20)
948 return AVERROR_INVALIDDATA;
950 src = buf + line_offset + 20;
954 tile_x = AV_RL32(src - 20);
955 tile_y = AV_RL32(src - 16);
956 tile_level_x = AV_RL32(src - 12);
957 tile_level_y = AV_RL32(src - 8);
959 data_size = AV_RL32(src - 4);
960 if (data_size <= 0 || data_size > buf_size - line_offset - 20)
961 return AVERROR_INVALIDDATA;
963 if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */
964 avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
965 return AVERROR_PATCHWELCOME;
968 line = s->ymin + s->tile_attr.ySize * tile_y;
969 col = s->tile_attr.xSize * tile_x;
971 if (line < s->ymin || line > s->ymax ||
972 s->xmin + col < s->xmin || s->xmin + col > s->xmax)
973 return AVERROR_INVALIDDATA;
975 td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);
976 td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);
978 if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
979 return AVERROR_INVALIDDATA;
981 td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
982 uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
984 if (buf_size < 8 || line_offset > buf_size - 8)
985 return AVERROR_INVALIDDATA;
987 src = buf + line_offset + 8;
990 line = AV_RL32(src - 8);
992 if (line < s->ymin || line > s->ymax)
993 return AVERROR_INVALIDDATA;
995 data_size = AV_RL32(src - 4);
996 if (data_size <= 0 || data_size > buf_size - line_offset - 8)
997 return AVERROR_INVALIDDATA;
999 td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
1000 td->xsize = s->xdelta;
1002 if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX)
1003 return AVERROR_INVALIDDATA;
1005 td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1006 uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1008 if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
1009 line_offset > buf_size - uncompressed_size)) ||
1010 (s->compression != EXR_RAW && (data_size > uncompressed_size ||
1011 line_offset > buf_size - data_size))) {
1012 return AVERROR_INVALIDDATA;
1016 window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col));
1017 window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize));
1018 window_ymin = FFMIN(avctx->height, FFMAX(0, line ));
1019 window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize));
1020 xsize = window_xmax - window_xmin;
1021 ysize = window_ymax - window_ymin;
1023 /* tile or scanline not visible skip decoding */
1024 if (xsize <= 0 || ysize <= 0)
1027 /* is the first tile or is a scanline */
1030 /* pixels to add at the left of the display window */
1031 window_xoffset = FFMAX(0, s->xmin);
1032 /* bytes to add at the left of the display window */
1033 bxmin = window_xoffset * step;
1036 /* is the last tile or is a scanline */
1037 if(col + td->xsize == s->xdelta) {
1038 window_xmax = avctx->width;
1039 /* bytes to add at the right of the display window */
1040 axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step;
1043 if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
1044 av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
1046 return AVERROR(ENOMEM);
1049 if (data_size < uncompressed_size) {
1050 av_fast_padded_malloc(&td->uncompressed_data,
1051 &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */
1053 if (!td->uncompressed_data)
1054 return AVERROR(ENOMEM);
1056 ret = AVERROR_INVALIDDATA;
1057 switch (s->compression) {
1060 ret = zip_uncompress(s, src, data_size, uncompressed_size, td);
1063 ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
1066 ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
1069 ret = rle_uncompress(s, src, data_size, uncompressed_size, td);
1073 ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
1077 av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
1080 src = td->uncompressed_data;
1083 /* offsets to crop data outside display window */
1084 data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4);
1085 data_yoffset = FFABS(FFMIN(0, line));
1086 data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset;
1089 channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset;
1090 channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
1091 channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset;
1092 rgb_channel_count = 3;
1093 } else { /* put y data in the first channel_buffer */
1094 channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset;
1095 rgb_channel_count = 1;
1097 if (s->channel_offsets[3] >= 0)
1098 channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset;
1100 if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1102 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1103 int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count;
1105 channel_buffer[1] = channel_buffer[0];
1106 channel_buffer[2] = channel_buffer[0];
1109 for (c = 0; c < channel_count; c++) {
1110 int plane = s->desc->comp[c].plane;
1111 ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4);
1113 for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) {
1115 union av_intfloat32 *ptr_x;
1117 src = channel_buffer[c];
1118 ptr_x = (union av_intfloat32 *)ptr;
1120 // Zero out the start if xmin is not 0
1121 memset(ptr_x, 0, bxmin);
1122 ptr_x += window_xoffset;
1124 if (s->pixel_type == EXR_FLOAT) {
1126 union av_intfloat32 t;
1127 if (trc_func && c < 3) {
1128 for (x = 0; x < xsize; x++) {
1129 t.i = bytestream_get_le32(&src);
1130 t.f = trc_func(t.f);
1133 } else if (one_gamma != 1.f) {
1134 for (x = 0; x < xsize; x++) {
1135 t.i = bytestream_get_le32(&src);
1136 if (t.f > 0.0f && c < 3) /* avoid negative values */
1137 t.f = powf(t.f, one_gamma);
1141 for (x = 0; x < xsize; x++) {
1142 t.i = bytestream_get_le32(&src);
1146 } else if (s->pixel_type == EXR_HALF) {
1148 if (c < 3 || !trc_func) {
1149 for (x = 0; x < xsize; x++) {
1150 *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)];
1153 for (x = 0; x < xsize; x++) {
1154 *ptr_x++ = exr_half2float(bytestream_get_le16(&src));;
1159 // Zero out the end if xmax+1 is not w
1160 memset(ptr_x, 0, axmax);
1161 channel_buffer[c] += td->channel_line_size;
1166 av_assert1(s->pixel_type == EXR_UINT);
1167 ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2);
1169 for (i = 0; i < ysize; i++, ptr += p->linesize[0]) {
1172 const uint8_t *rgb[3];
1175 for (c = 0; c < rgb_channel_count; c++) {
1176 rgb[c] = channel_buffer[c];
1179 if (channel_buffer[3])
1180 a = channel_buffer[3];
1182 ptr_x = (uint16_t *) ptr;
1184 // Zero out the start if xmin is not 0
1185 memset(ptr_x, 0, bxmin);
1186 ptr_x += window_xoffset * s->desc->nb_components;
1188 for (x = 0; x < xsize; x++) {
1189 for (c = 0; c < rgb_channel_count; c++) {
1190 *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;
1193 if (channel_buffer[3])
1194 *ptr_x++ = bytestream_get_le32(&a) >> 16;
1197 // Zero out the end if xmax+1 is not w
1198 memset(ptr_x, 0, axmax);
1200 channel_buffer[0] += td->channel_line_size;
1201 channel_buffer[1] += td->channel_line_size;
1202 channel_buffer[2] += td->channel_line_size;
1203 if (channel_buffer[3])
1204 channel_buffer[3] += td->channel_line_size;
1211 static void skip_header_chunk(EXRContext *s)
1213 GetByteContext *gb = &s->gb;
1215 while (bytestream2_get_bytes_left(gb) > 0) {
1216 if (!bytestream2_peek_byte(gb))
1219 // Process unknown variables
1220 for (int i = 0; i < 2; i++) // value_name and value_type
1221 while (bytestream2_get_byte(gb) != 0);
1223 // Skip variable length
1224 bytestream2_skip(gb, bytestream2_get_le32(gb));
1229 * Check if the variable name corresponds to its data type.
1231 * @param s the EXRContext
1232 * @param value_name name of the variable to check
1233 * @param value_type type of the variable to check
1234 * @param minimum_length minimum length of the variable data
1236 * @return bytes to read containing variable data
1237 * -1 if variable is not found
1238 * 0 if buffer ended prematurely
1240 static int check_header_variable(EXRContext *s,
1241 const char *value_name,
1242 const char *value_type,
1243 unsigned int minimum_length)
1245 GetByteContext *gb = &s->gb;
1248 if (bytestream2_get_bytes_left(gb) >= minimum_length &&
1249 !strcmp(gb->buffer, value_name)) {
1250 // found value_name, jump to value_type (null terminated strings)
1251 gb->buffer += strlen(value_name) + 1;
1252 if (!strcmp(gb->buffer, value_type)) {
1253 gb->buffer += strlen(value_type) + 1;
1254 var_size = bytestream2_get_le32(gb);
1255 // don't go read past boundaries
1256 if (var_size > bytestream2_get_bytes_left(gb))
1259 // value_type not found, reset the buffer
1260 gb->buffer -= strlen(value_name) + 1;
1261 av_log(s->avctx, AV_LOG_WARNING,
1262 "Unknown data type %s for header variable %s.\n",
1263 value_type, value_name);
1270 static int decode_header(EXRContext *s, AVFrame *frame)
1272 AVDictionary *metadata = NULL;
1273 GetByteContext *gb = &s->gb;
1274 int magic_number, version, flags;
1275 int layer_match = 0;
1277 int dup_channels = 0;
1279 s->current_channel_offset = 0;
1286 s->channel_offsets[0] = -1;
1287 s->channel_offsets[1] = -1;
1288 s->channel_offsets[2] = -1;
1289 s->channel_offsets[3] = -1;
1290 s->pixel_type = EXR_UNKNOWN;
1291 s->compression = EXR_UNKN;
1295 s->tile_attr.xSize = -1;
1296 s->tile_attr.ySize = -1;
1298 s->is_multipart = 0;
1300 s->current_part = 0;
1302 if (bytestream2_get_bytes_left(gb) < 10) {
1303 av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1304 return AVERROR_INVALIDDATA;
1307 magic_number = bytestream2_get_le32(gb);
1308 if (magic_number != 20000630) {
1309 /* As per documentation of OpenEXR, it is supposed to be
1310 * int 20000630 little-endian */
1311 av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1312 return AVERROR_INVALIDDATA;
1315 version = bytestream2_get_byte(gb);
1317 avpriv_report_missing_feature(s->avctx, "Version %d", version);
1318 return AVERROR_PATCHWELCOME;
1321 flags = bytestream2_get_le24(gb);
1326 s->is_multipart = 1;
1328 avpriv_report_missing_feature(s->avctx, "deep data");
1329 return AVERROR_PATCHWELCOME;
1333 while (bytestream2_get_bytes_left(gb) > 0) {
1336 while (s->is_multipart && s->current_part < s->selected_part &&
1337 bytestream2_get_bytes_left(gb) > 0) {
1338 if (bytestream2_peek_byte(gb)) {
1339 skip_header_chunk(s);
1341 bytestream2_skip(gb, 1);
1342 if (!bytestream2_peek_byte(gb))
1345 bytestream2_skip(gb, 1);
1349 if (!bytestream2_peek_byte(gb)) {
1350 if (!s->is_multipart)
1352 bytestream2_skip(gb, 1);
1353 if (s->current_part == s->selected_part) {
1354 while (bytestream2_get_bytes_left(gb) > 0) {
1355 if (bytestream2_peek_byte(gb)) {
1356 skip_header_chunk(s);
1358 bytestream2_skip(gb, 1);
1359 if (!bytestream2_peek_byte(gb))
1364 if (!bytestream2_peek_byte(gb))
1369 if ((var_size = check_header_variable(s, "channels",
1370 "chlist", 38)) >= 0) {
1371 GetByteContext ch_gb;
1373 ret = AVERROR_INVALIDDATA;
1377 bytestream2_init(&ch_gb, gb->buffer, var_size);
1379 while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1380 EXRChannel *channel;
1381 enum ExrPixelType current_pixel_type;
1382 int channel_index = -1;
1385 if (strcmp(s->layer, "") != 0) {
1386 if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1388 av_log(s->avctx, AV_LOG_INFO,
1389 "Channel match layer : %s.\n", ch_gb.buffer);
1390 ch_gb.buffer += strlen(s->layer);
1391 if (*ch_gb.buffer == '.')
1392 ch_gb.buffer++; /* skip dot if not given */
1395 av_log(s->avctx, AV_LOG_INFO,
1396 "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1402 if (layer_match) { /* only search channel if the layer match is valid */
1403 if (!av_strcasecmp(ch_gb.buffer, "R") ||
1404 !av_strcasecmp(ch_gb.buffer, "X") ||
1405 !av_strcasecmp(ch_gb.buffer, "U")) {
1408 } else if (!av_strcasecmp(ch_gb.buffer, "G") ||
1409 !av_strcasecmp(ch_gb.buffer, "V")) {
1412 } else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
1415 } else if (!av_strcasecmp(ch_gb.buffer, "B") ||
1416 !av_strcasecmp(ch_gb.buffer, "Z") ||
1417 !av_strcasecmp(ch_gb.buffer, "W")) {
1420 } else if (!av_strcasecmp(ch_gb.buffer, "A")) {
1423 av_log(s->avctx, AV_LOG_WARNING,
1424 "Unsupported channel %.256s.\n", ch_gb.buffer);
1428 /* skip until you get a 0 */
1429 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1430 bytestream2_get_byte(&ch_gb))
1433 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1434 av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1435 ret = AVERROR_INVALIDDATA;
1439 current_pixel_type = bytestream2_get_le32(&ch_gb);
1440 if (current_pixel_type >= EXR_UNKNOWN) {
1441 avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1442 current_pixel_type);
1443 ret = AVERROR_PATCHWELCOME;
1447 bytestream2_skip(&ch_gb, 4);
1448 xsub = bytestream2_get_le32(&ch_gb);
1449 ysub = bytestream2_get_le32(&ch_gb);
1451 if (xsub != 1 || ysub != 1) {
1452 avpriv_report_missing_feature(s->avctx,
1453 "Subsampling %dx%d",
1455 ret = AVERROR_PATCHWELCOME;
1459 if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */
1460 if (s->pixel_type != EXR_UNKNOWN &&
1461 s->pixel_type != current_pixel_type) {
1462 av_log(s->avctx, AV_LOG_ERROR,
1463 "RGB channels not of the same depth.\n");
1464 ret = AVERROR_INVALIDDATA;
1467 s->pixel_type = current_pixel_type;
1468 s->channel_offsets[channel_index] = s->current_channel_offset;
1469 } else if (channel_index >= 0) {
1470 av_log(s->avctx, AV_LOG_WARNING,
1471 "Multiple channels with index %d.\n", channel_index);
1472 if (++dup_channels > 10) {
1473 ret = AVERROR_INVALIDDATA;
1478 s->channels = av_realloc(s->channels,
1479 ++s->nb_channels * sizeof(EXRChannel));
1481 ret = AVERROR(ENOMEM);
1484 channel = &s->channels[s->nb_channels - 1];
1485 channel->pixel_type = current_pixel_type;
1486 channel->xsub = xsub;
1487 channel->ysub = ysub;
1489 if (current_pixel_type == EXR_HALF) {
1490 s->current_channel_offset += 2;
1491 } else {/* Float or UINT32 */
1492 s->current_channel_offset += 4;
1496 /* Check if all channels are set with an offset or if the channels
1497 * are causing an overflow */
1498 if (!s->is_luma) {/* if we expected to have at least 3 channels */
1499 if (FFMIN3(s->channel_offsets[0],
1500 s->channel_offsets[1],
1501 s->channel_offsets[2]) < 0) {
1502 if (s->channel_offsets[0] < 0)
1503 av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1504 if (s->channel_offsets[1] < 0)
1505 av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1506 if (s->channel_offsets[2] < 0)
1507 av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1508 ret = AVERROR_INVALIDDATA;
1513 // skip one last byte and update main gb
1514 gb->buffer = ch_gb.buffer + 1;
1516 } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1518 int xmin, ymin, xmax, ymax;
1520 ret = AVERROR_INVALIDDATA;
1524 xmin = bytestream2_get_le32(gb);
1525 ymin = bytestream2_get_le32(gb);
1526 xmax = bytestream2_get_le32(gb);
1527 ymax = bytestream2_get_le32(gb);
1529 if (xmin > xmax || ymin > ymax ||
1530 (unsigned)xmax - xmin >= INT_MAX ||
1531 (unsigned)ymax - ymin >= INT_MAX) {
1532 ret = AVERROR_INVALIDDATA;
1539 s->xdelta = (s->xmax - s->xmin) + 1;
1540 s->ydelta = (s->ymax - s->ymin) + 1;
1543 } else if ((var_size = check_header_variable(s, "displayWindow",
1544 "box2i", 34)) >= 0) {
1545 int32_t sx, sy, dx, dy;
1548 ret = AVERROR_INVALIDDATA;
1552 sx = bytestream2_get_le32(gb);
1553 sy = bytestream2_get_le32(gb);
1554 dx = bytestream2_get_le32(gb);
1555 dy = bytestream2_get_le32(gb);
1561 } else if ((var_size = check_header_variable(s, "lineOrder",
1562 "lineOrder", 25)) >= 0) {
1565 ret = AVERROR_INVALIDDATA;
1569 line_order = bytestream2_get_byte(gb);
1570 av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1571 if (line_order > 2) {
1572 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1573 ret = AVERROR_INVALIDDATA;
1578 } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1579 "float", 31)) >= 0) {
1581 ret = AVERROR_INVALIDDATA;
1585 s->sar = bytestream2_get_le32(gb);
1588 } else if ((var_size = check_header_variable(s, "compression",
1589 "compression", 29)) >= 0) {
1591 ret = AVERROR_INVALIDDATA;
1595 if (s->compression == EXR_UNKN)
1596 s->compression = bytestream2_get_byte(gb);
1598 bytestream2_skip(gb, 1);
1599 av_log(s->avctx, AV_LOG_WARNING,
1600 "Found more than one compression attribute.\n");
1604 } else if ((var_size = check_header_variable(s, "tiles",
1605 "tiledesc", 22)) >= 0) {
1609 av_log(s->avctx, AV_LOG_WARNING,
1610 "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
1612 s->tile_attr.xSize = bytestream2_get_le32(gb);
1613 s->tile_attr.ySize = bytestream2_get_le32(gb);
1615 tileLevel = bytestream2_get_byte(gb);
1616 s->tile_attr.level_mode = tileLevel & 0x0f;
1617 s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
1619 if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) {
1620 avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
1621 s->tile_attr.level_mode);
1622 ret = AVERROR_PATCHWELCOME;
1626 if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
1627 avpriv_report_missing_feature(s->avctx, "Tile level round %d",
1628 s->tile_attr.level_round);
1629 ret = AVERROR_PATCHWELCOME;
1634 } else if ((var_size = check_header_variable(s, "writer",
1635 "string", 1)) >= 0) {
1636 uint8_t key[256] = { 0 };
1638 bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1639 av_dict_set(&metadata, "writer", key, 0);
1642 } else if ((var_size = check_header_variable(s, "framesPerSecond",
1643 "rational", 33)) >= 0) {
1645 ret = AVERROR_INVALIDDATA;
1649 s->avctx->framerate.num = bytestream2_get_le32(gb);
1650 s->avctx->framerate.den = bytestream2_get_le32(gb);
1653 } else if ((var_size = check_header_variable(s, "chunkCount",
1656 s->chunk_count = bytestream2_get_le32(gb);
1659 } else if ((var_size = check_header_variable(s, "type",
1660 "string", 16)) >= 0) {
1661 uint8_t key[256] = { 0 };
1663 bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1664 if (strncmp("scanlineimage", key, var_size) &&
1665 strncmp("tiledimage", key, var_size))
1666 return AVERROR_PATCHWELCOME;
1669 } else if ((var_size = check_header_variable(s, "preview",
1670 "preview", 16)) >= 0) {
1671 uint32_t pw = bytestream2_get_le32(gb);
1672 uint32_t ph = bytestream2_get_le32(gb);
1673 int64_t psize = 4LL * pw * ph;
1675 if (psize >= bytestream2_get_bytes_left(gb))
1676 return AVERROR_INVALIDDATA;
1678 bytestream2_skip(gb, psize);
1683 // Check if there are enough bytes for a header
1684 if (bytestream2_get_bytes_left(gb) <= 9) {
1685 av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1686 ret = AVERROR_INVALIDDATA;
1690 // Process unknown variables
1692 uint8_t name[256] = { 0 };
1693 uint8_t type[256] = { 0 };
1694 uint8_t value[256] = { 0 };
1697 while (bytestream2_get_bytes_left(gb) > 0 &&
1698 bytestream2_peek_byte(gb) && i < 255) {
1699 name[i++] = bytestream2_get_byte(gb);
1702 bytestream2_skip(gb, 1);
1704 while (bytestream2_get_bytes_left(gb) > 0 &&
1705 bytestream2_peek_byte(gb) && i < 255) {
1706 type[i++] = bytestream2_get_byte(gb);
1708 bytestream2_skip(gb, 1);
1709 size = bytestream2_get_le32(gb);
1711 bytestream2_get_buffer(gb, value, FFMIN(sizeof(value) - 1, size));
1712 if (!strcmp(type, "string"))
1713 av_dict_set(&metadata, name, value, 0);
1717 if (s->compression == EXR_UNKN) {
1718 av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1719 ret = AVERROR_INVALIDDATA;
1724 if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1725 av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1726 ret = AVERROR_INVALIDDATA;
1731 if (bytestream2_get_bytes_left(gb) <= 0) {
1732 av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1733 ret = AVERROR_INVALIDDATA;
1737 frame->metadata = metadata;
1739 // aaand we are done
1740 bytestream2_skip(gb, 1);
1743 av_dict_free(&metadata);
1747 static int decode_frame(AVCodecContext *avctx, void *data,
1748 int *got_frame, AVPacket *avpkt)
1750 EXRContext *s = avctx->priv_data;
1751 GetByteContext *gb = &s->gb;
1752 ThreadFrame frame = { .f = data };
1753 AVFrame *picture = data;
1756 int i, y, ret, ymax;
1759 int nb_blocks; /* nb scanline or nb tile */
1760 uint64_t start_offset_table;
1761 uint64_t start_next_scanline;
1762 PutByteContext offset_table_writer;
1764 bytestream2_init(gb, avpkt->data, avpkt->size);
1766 if ((ret = decode_header(s, picture)) < 0)
1769 switch (s->pixel_type) {
1772 if (s->channel_offsets[3] >= 0) {
1774 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1776 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1777 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1781 avctx->pix_fmt = AV_PIX_FMT_GBRPF32;
1783 avctx->pix_fmt = AV_PIX_FMT_GRAYF32;
1788 if (s->channel_offsets[3] >= 0) {
1790 avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1792 avctx->pix_fmt = AV_PIX_FMT_YA16;
1796 avctx->pix_fmt = AV_PIX_FMT_RGB48;
1798 avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1803 av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1804 return AVERROR_INVALIDDATA;
1807 if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1808 avctx->color_trc = s->apply_trc_type;
1810 switch (s->compression) {
1814 s->scan_lines_per_block = 1;
1818 s->scan_lines_per_block = 16;
1823 s->scan_lines_per_block = 32;
1826 avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1827 return AVERROR_PATCHWELCOME;
1830 /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.
1831 * It's possible for the data window can larger or outside the display window */
1832 if (s->xmin > s->xmax || s->ymin > s->ymax ||
1833 s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {
1834 av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1835 return AVERROR_INVALIDDATA;
1838 if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1841 ff_set_sar(s->avctx, av_d2q(av_int2float(s->sar), 255));
1843 s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1845 return AVERROR_INVALIDDATA;
1847 if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1848 planes = s->desc->nb_components;
1849 out_line_size = avctx->width * 4;
1852 out_line_size = avctx->width * 2 * s->desc->nb_components;
1856 nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
1857 ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
1858 } else { /* scanline */
1859 nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1860 s->scan_lines_per_block;
1863 if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1866 if (bytestream2_get_bytes_left(gb)/8 < nb_blocks)
1867 return AVERROR_INVALIDDATA;
1869 // check offset table and recreate it if need
1870 if (!s->is_tile && bytestream2_peek_le64(gb) == 0) {
1871 av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n");
1873 start_offset_table = bytestream2_tell(gb);
1874 start_next_scanline = start_offset_table + nb_blocks * 8;
1875 bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);
1877 for (y = 0; y < nb_blocks; y++) {
1878 /* write offset of prev scanline in offset table */
1879 bytestream2_put_le64(&offset_table_writer, start_next_scanline);
1881 /* get len of next scanline */
1882 bytestream2_seek(gb, start_next_scanline + 4, SEEK_SET);/* skip line number */
1883 start_next_scanline += (bytestream2_get_le32(gb) + 8);
1885 bytestream2_seek(gb, start_offset_table, SEEK_SET);
1888 // save pointer we are going to use in decode_block
1889 s->buf = avpkt->data;
1890 s->buf_size = avpkt->size;
1892 // Zero out the start if ymin is not 0
1893 for (i = 0; i < planes; i++) {
1894 ptr = picture->data[i];
1895 for (y = 0; y < FFMIN(s->ymin, s->h); y++) {
1896 memset(ptr, 0, out_line_size);
1897 ptr += picture->linesize[i];
1901 s->picture = picture;
1903 avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
1905 ymax = FFMAX(0, s->ymax + 1);
1906 // Zero out the end if ymax+1 is not h
1907 if (ymax < avctx->height)
1908 for (i = 0; i < planes; i++) {
1909 ptr = picture->data[i] + (ymax * picture->linesize[i]);
1910 for (y = ymax; y < avctx->height; y++) {
1911 memset(ptr, 0, out_line_size);
1912 ptr += picture->linesize[i];
1916 picture->pict_type = AV_PICTURE_TYPE_I;
1922 static av_cold int decode_init(AVCodecContext *avctx)
1924 EXRContext *s = avctx->priv_data;
1926 union av_intfloat32 t;
1927 float one_gamma = 1.0f / s->gamma;
1928 avpriv_trc_function trc_func = NULL;
1932 ff_exrdsp_init(&s->dsp);
1935 ff_bswapdsp_init(&s->bbdsp);
1938 trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1940 for (i = 0; i < 65536; ++i) {
1941 t = exr_half2float(i);
1942 t.f = trc_func(t.f);
1943 s->gamma_table[i] = t;
1946 if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1947 for (i = 0; i < 65536; ++i) {
1948 s->gamma_table[i] = exr_half2float(i);
1951 for (i = 0; i < 65536; ++i) {
1952 t = exr_half2float(i);
1953 /* If negative value we reuse half value */
1955 s->gamma_table[i] = t;
1957 t.f = powf(t.f, one_gamma);
1958 s->gamma_table[i] = t;
1964 // allocate thread data, used for non EXR_RAW compression types
1965 s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1966 if (!s->thread_data)
1967 return AVERROR_INVALIDDATA;
1972 static av_cold int decode_end(AVCodecContext *avctx)
1974 EXRContext *s = avctx->priv_data;
1976 for (i = 0; i < avctx->thread_count; i++) {
1977 EXRThreadData *td = &s->thread_data[i];
1978 av_freep(&td->uncompressed_data);
1980 av_freep(&td->bitmap);
1983 av_freep(&td->freq);
1984 ff_free_vlc(&td->vlc);
1987 av_freep(&s->thread_data);
1988 av_freep(&s->channels);
1993 #define OFFSET(x) offsetof(EXRContext, x)
1994 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1995 static const AVOption options[] = {
1996 { "layer", "Set the decoding layer", OFFSET(layer),
1997 AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
1998 { "part", "Set the decoding part", OFFSET(selected_part),
1999 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
2000 { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
2001 AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
2003 // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
2004 { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
2005 AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
2006 { "bt709", "BT.709", 0,
2007 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2008 { "gamma", "gamma", 0,
2009 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2010 { "gamma22", "BT.470 M", 0,
2011 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2012 { "gamma28", "BT.470 BG", 0,
2013 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2014 { "smpte170m", "SMPTE 170 M", 0,
2015 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2016 { "smpte240m", "SMPTE 240 M", 0,
2017 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2018 { "linear", "Linear", 0,
2019 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2021 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2022 { "log_sqrt", "Log square root", 0,
2023 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2024 { "iec61966_2_4", "IEC 61966-2-4", 0,
2025 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2026 { "bt1361", "BT.1361", 0,
2027 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2028 { "iec61966_2_1", "IEC 61966-2-1", 0,
2029 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2030 { "bt2020_10bit", "BT.2020 - 10 bit", 0,
2031 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2032 { "bt2020_12bit", "BT.2020 - 12 bit", 0,
2033 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2034 { "smpte2084", "SMPTE ST 2084", 0,
2035 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2036 { "smpte428_1", "SMPTE ST 428-1", 0,
2037 AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2042 static const AVClass exr_class = {
2043 .class_name = "EXR",
2044 .item_name = av_default_item_name,
2046 .version = LIBAVUTIL_VERSION_INT,
2049 AVCodec ff_exr_decoder = {
2051 .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"),
2052 .type = AVMEDIA_TYPE_VIDEO,
2053 .id = AV_CODEC_ID_EXR,
2054 .priv_data_size = sizeof(EXRContext),
2055 .init = decode_init,
2056 .close = decode_end,
2057 .decode = decode_frame,
2058 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
2059 AV_CODEC_CAP_SLICE_THREADS,
2060 .priv_class = &exr_class,