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