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