OSDN Git Service

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