OSDN Git Service

avcodec/snow: Initialize spatial_decomposition_count to a valid value
[android-x86/external-ffmpeg.git] / libavcodec / exr.c
1 /*
2  * OpenEXR (.exr) image decoder
3  * Copyright (c) 2009 Jimmy Christensen
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * OpenEXR decoder
25  * @author Jimmy Christensen
26  *
27  * For more information on the OpenEXR format, visit:
28  *  http://openexr.com/
29  *
30  * exr_flt2uint() and exr_halflt2uint() is credited to Reimar Döffinger.
31  * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner.
32  */
33
34 #include <float.h>
35 #include <zlib.h>
36
37 #include "libavutil/imgutils.h"
38 #include "libavutil/intfloat.h"
39 #include "libavutil/opt.h"
40
41 #include "avcodec.h"
42 #include "bytestream.h"
43 #include "get_bits.h"
44 #include "internal.h"
45 #include "mathops.h"
46 #include "thread.h"
47
48 enum ExrCompr {
49     EXR_RAW,
50     EXR_RLE,
51     EXR_ZIP1,
52     EXR_ZIP16,
53     EXR_PIZ,
54     EXR_PXR24,
55     EXR_B44,
56     EXR_B44A,
57     EXR_UNKN,
58 };
59
60 enum ExrPixelType {
61     EXR_UINT,
62     EXR_HALF,
63     EXR_FLOAT,
64     EXR_UNKNOWN,
65 };
66
67 typedef struct EXRChannel {
68     int xsub, ysub;
69     enum ExrPixelType pixel_type;
70 } EXRChannel;
71
72 typedef struct EXRThreadData {
73     uint8_t *uncompressed_data;
74     int uncompressed_size;
75
76     uint8_t *tmp;
77     int tmp_size;
78
79     uint8_t *bitmap;
80     uint16_t *lut;
81 } EXRThreadData;
82
83 typedef struct EXRContext {
84     AVClass *class;
85     AVFrame *picture;
86     AVCodecContext *avctx;
87
88     enum ExrCompr compression;
89     enum ExrPixelType pixel_type;
90     int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
91     const AVPixFmtDescriptor *desc;
92
93     int w, h;
94     uint32_t xmax, xmin;
95     uint32_t ymax, ymin;
96     uint32_t xdelta, ydelta;
97     int ysize;
98
99     uint64_t scan_line_size;
100     int scan_lines_per_block;
101
102     GetByteContext gb;
103     const uint8_t *buf;
104     int buf_size;
105
106     EXRChannel *channels;
107     int nb_channels;
108
109     EXRThreadData *thread_data;
110
111     const char *layer;
112
113     float gamma;
114     uint16_t gamma_table[65536];
115 } EXRContext;
116
117 /* -15 stored using a single precision bias of 127 */
118 #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
119
120 /* max exponent value in single precision that will be converted
121  * to Inf or Nan when stored as a half-float */
122 #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
123
124 /* 255 is the max exponent biased value */
125 #define FLOAT_MAX_BIASED_EXP (0xFF << 23)
126
127 #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
128
129 /**
130  * Convert a half float as a uint16_t into a full float.
131  *
132  * @param hf half float as uint16_t
133  *
134  * @return float value
135  */
136 static union av_intfloat32 exr_half2float(uint16_t hf)
137 {
138     unsigned int sign = (unsigned int) (hf >> 15);
139     unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
140     unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
141     union av_intfloat32 f;
142
143     if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
144         // we have a half-float NaN or Inf
145         // half-float NaNs will be converted to a single precision NaN
146         // half-float Infs will be converted to a single precision Inf
147         exp = FLOAT_MAX_BIASED_EXP;
148         if (mantissa)
149             mantissa = (1 << 23) - 1;    // set all bits to indicate a NaN
150     } else if (exp == 0x0) {
151         // convert half-float zero/denorm to single precision value
152         if (mantissa) {
153             mantissa <<= 1;
154             exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
155             // check for leading 1 in denorm mantissa
156             while ((mantissa & (1 << 10))) {
157                 // for every leading 0, decrement single precision exponent by 1
158                 // and shift half-float mantissa value to the left
159                 mantissa <<= 1;
160                 exp -= (1 << 23);
161             }
162             // clamp the mantissa to 10-bits
163             mantissa &= ((1 << 10) - 1);
164             // shift left to generate single-precision mantissa of 23-bits
165             mantissa <<= 13;
166         }
167     } else {
168         // shift left to generate single-precision mantissa of 23-bits
169         mantissa <<= 13;
170         // generate single precision biased exponent value
171         exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
172     }
173
174     f.i = (sign << 31) | exp | mantissa;
175
176     return f;
177 }
178
179
180 /**
181  * Convert from 32-bit float as uint32_t to uint16_t.
182  *
183  * @param v 32-bit float
184  *
185  * @return normalized 16-bit unsigned int
186  */
187 static inline uint16_t exr_flt2uint(uint32_t v)
188 {
189     unsigned int exp = v >> 23;
190     // "HACK": negative values result in exp<  0, so clipping them to 0
191     // is also handled by this condition, avoids explicit check for sign bit.
192     if (exp <= 127 + 7 - 24) // we would shift out all bits anyway
193         return 0;
194     if (exp >= 127)
195         return 0xffff;
196     v &= 0x007fffff;
197     return (v + (1 << 23)) >> (127 + 7 - exp);
198 }
199
200 /**
201  * Convert from 16-bit float as uint16_t to uint16_t.
202  *
203  * @param v 16-bit float
204  *
205  * @return normalized 16-bit unsigned int
206  */
207 static inline uint16_t exr_halflt2uint(uint16_t v)
208 {
209     unsigned exp = 14 - (v >> 10);
210     if (exp >= 14) {
211         if (exp == 14)
212             return (v >> 9) & 1;
213         else
214             return (v & 0x8000) ? 0 : 0xffff;
215     }
216     v <<= 6;
217     return (v + (1 << 16)) >> (exp + 1);
218 }
219
220 static void predictor(uint8_t *src, int size)
221 {
222     uint8_t *t    = src + 1;
223     uint8_t *stop = src + size;
224
225     while (t < stop) {
226         int d = (int) t[-1] + (int) t[0] - 128;
227         t[0] = d;
228         ++t;
229     }
230 }
231
232 static void reorder_pixels(uint8_t *src, uint8_t *dst, int size)
233 {
234     const int8_t *t1 = src;
235     const int8_t *t2 = src + (size + 1) / 2;
236     int8_t *s        = dst;
237     int8_t *stop     = s + size;
238
239     while (1) {
240         if (s < stop)
241             *(s++) = *(t1++);
242         else
243             break;
244
245         if (s < stop)
246             *(s++) = *(t2++);
247         else
248             break;
249     }
250 }
251
252 static int zip_uncompress(const uint8_t *src, int compressed_size,
253                           int uncompressed_size, EXRThreadData *td)
254 {
255     unsigned long dest_len = uncompressed_size;
256
257     if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
258         dest_len != uncompressed_size)
259         return AVERROR_INVALIDDATA;
260
261     predictor(td->tmp, uncompressed_size);
262     reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
263
264     return 0;
265 }
266
267 static int rle_uncompress(const uint8_t *src, int compressed_size,
268                           int uncompressed_size, EXRThreadData *td)
269 {
270     uint8_t *d      = td->tmp;
271     const int8_t *s = src;
272     int ssize       = compressed_size;
273     int dsize       = uncompressed_size;
274     uint8_t *dend   = d + dsize;
275     int count;
276
277     while (ssize > 0) {
278         count = *s++;
279
280         if (count < 0) {
281             count = -count;
282
283             if ((dsize -= count) < 0 ||
284                 (ssize -= count + 1) < 0)
285                 return AVERROR_INVALIDDATA;
286
287             while (count--)
288                 *d++ = *s++;
289         } else {
290             count++;
291
292             if ((dsize -= count) < 0 ||
293                 (ssize -= 2) < 0)
294                 return AVERROR_INVALIDDATA;
295
296             while (count--)
297                 *d++ = *s;
298
299             s++;
300         }
301     }
302
303     if (dend != d)
304         return AVERROR_INVALIDDATA;
305
306     predictor(td->tmp, uncompressed_size);
307     reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
308
309     return 0;
310 }
311
312 #define USHORT_RANGE (1 << 16)
313 #define BITMAP_SIZE  (1 << 13)
314
315 static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
316 {
317     int i, k = 0;
318
319     for (i = 0; i < USHORT_RANGE; i++)
320         if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
321             lut[k++] = i;
322
323     i = k - 1;
324
325     memset(lut + k * 2, 0, (USHORT_RANGE - k) * 2);
326
327     return i;
328 }
329
330 static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
331 {
332     int i;
333
334     for (i = 0; i < dsize; ++i)
335         dst[i] = lut[dst[i]];
336 }
337
338 #define HUF_ENCBITS 16  // literal (value) bit length
339 #define HUF_DECBITS 14  // decoding bit size (>= 8)
340
341 #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1)  // encoding table size
342 #define HUF_DECSIZE (1 << HUF_DECBITS)        // decoding table size
343 #define HUF_DECMASK (HUF_DECSIZE - 1)
344
345 typedef struct HufDec {
346     int len;
347     int lit;
348     int *p;
349 } HufDec;
350
351 static void huf_canonical_code_table(uint64_t *hcode)
352 {
353     uint64_t c, n[59] = { 0 };
354     int i;
355
356     for (i = 0; i < HUF_ENCSIZE; ++i)
357         n[hcode[i]] += 1;
358
359     c = 0;
360     for (i = 58; i > 0; --i) {
361         uint64_t nc = ((c + n[i]) >> 1);
362         n[i] = c;
363         c    = nc;
364     }
365
366     for (i = 0; i < HUF_ENCSIZE; ++i) {
367         int l = hcode[i];
368
369         if (l > 0)
370             hcode[i] = l | (n[l]++ << 6);
371     }
372 }
373
374 #define SHORT_ZEROCODE_RUN  59
375 #define LONG_ZEROCODE_RUN   63
376 #define SHORTEST_LONG_RUN   (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
377 #define LONGEST_LONG_RUN    (255 + SHORTEST_LONG_RUN)
378
379 static int huf_unpack_enc_table(GetByteContext *gb,
380                                 int32_t im, int32_t iM, uint64_t *hcode)
381 {
382     GetBitContext gbit;
383     int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
384     if (ret < 0)
385         return ret;
386
387     for (; im <= iM; im++) {
388         uint64_t l = hcode[im] = get_bits(&gbit, 6);
389
390         if (l == LONG_ZEROCODE_RUN) {
391             int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
392
393             if (im + zerun > iM + 1)
394                 return AVERROR_INVALIDDATA;
395
396             while (zerun--)
397                 hcode[im++] = 0;
398
399             im--;
400         } else if (l >= SHORT_ZEROCODE_RUN) {
401             int zerun = l - SHORT_ZEROCODE_RUN + 2;
402
403             if (im + zerun > iM + 1)
404                 return AVERROR_INVALIDDATA;
405
406             while (zerun--)
407                 hcode[im++] = 0;
408
409             im--;
410         }
411     }
412
413     bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
414     huf_canonical_code_table(hcode);
415
416     return 0;
417 }
418
419 static int huf_build_dec_table(const uint64_t *hcode, int im,
420                                int iM, HufDec *hdecod)
421 {
422     for (; im <= iM; im++) {
423         uint64_t c = hcode[im] >> 6;
424         int i, l = hcode[im] & 63;
425
426         if (c >> l)
427             return AVERROR_INVALIDDATA;
428
429         if (l > HUF_DECBITS) {
430             HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
431             if (pl->len)
432                 return AVERROR_INVALIDDATA;
433
434             pl->lit++;
435
436             pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
437             if (!pl->p)
438                 return AVERROR(ENOMEM);
439
440             pl->p[pl->lit - 1] = im;
441         } else if (l) {
442             HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
443
444             for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
445                 if (pl->len || pl->p)
446                     return AVERROR_INVALIDDATA;
447                 pl->len = l;
448                 pl->lit = im;
449             }
450         }
451     }
452
453     return 0;
454 }
455
456 #define get_char(c, lc, gb)                                                   \
457 {                                                                             \
458         c   = (c << 8) | bytestream2_get_byte(gb);                            \
459         lc += 8;                                                              \
460 }
461
462 #define get_code(po, rlc, c, lc, gb, out, oe)                                 \
463 {                                                                             \
464         if (po == rlc) {                                                      \
465             if (lc < 8)                                                       \
466                 get_char(c, lc, gb);                                          \
467             lc -= 8;                                                          \
468                                                                               \
469             cs = c >> lc;                                                     \
470                                                                               \
471             if (out + cs > oe)                                                \
472                 return AVERROR_INVALIDDATA;                                   \
473                                                                               \
474             s = out[-1];                                                      \
475                                                                               \
476             while (cs-- > 0)                                                  \
477                 *out++ = s;                                                   \
478         } else if (out < oe) {                                                \
479             *out++ = po;                                                      \
480         } else {                                                              \
481             return AVERROR_INVALIDDATA;                                       \
482         }                                                                     \
483 }
484
485 static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
486                       GetByteContext *gb, int nbits,
487                       int rlc, int no, uint16_t *out)
488 {
489     uint64_t c        = 0;
490     uint16_t *outb    = out;
491     uint16_t *oe      = out + no;
492     const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
493     uint8_t cs, s;
494     int i, lc = 0;
495
496     while (gb->buffer < ie) {
497         get_char(c, lc, gb);
498
499         while (lc >= HUF_DECBITS) {
500             const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
501
502             if (pl.len) {
503                 lc -= pl.len;
504                 get_code(pl.lit, rlc, c, lc, gb, out, oe);
505             } else {
506                 int j;
507
508                 if (!pl.p)
509                     return AVERROR_INVALIDDATA;
510
511                 for (j = 0; j < pl.lit; j++) {
512                     int l = hcode[pl.p[j]] & 63;
513
514                     while (lc < l && bytestream2_get_bytes_left(gb) > 0)
515                         get_char(c, lc, gb);
516
517                     if (lc >= l) {
518                         if ((hcode[pl.p[j]] >> 6) ==
519                             ((c >> (lc - l)) & ((1LL << l) - 1))) {
520                             lc -= l;
521                             get_code(pl.p[j], rlc, c, lc, gb, out, oe);
522                             break;
523                         }
524                     }
525                 }
526
527                 if (j == pl.lit)
528                     return AVERROR_INVALIDDATA;
529             }
530         }
531     }
532
533     i   = (8 - nbits) & 7;
534     c >>= i;
535     lc -= i;
536
537     while (lc > 0) {
538         const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
539
540         if (pl.len) {
541             lc -= pl.len;
542             get_code(pl.lit, rlc, c, lc, gb, out, oe);
543         } else {
544             return AVERROR_INVALIDDATA;
545         }
546     }
547
548     if (out - outb != no)
549         return AVERROR_INVALIDDATA;
550     return 0;
551 }
552
553 static int huf_uncompress(GetByteContext *gb,
554                           uint16_t *dst, int dst_size)
555 {
556     int32_t src_size, im, iM;
557     uint32_t nBits;
558     uint64_t *freq;
559     HufDec *hdec;
560     int ret, i;
561
562     src_size = bytestream2_get_le32(gb);
563     im       = bytestream2_get_le32(gb);
564     iM       = bytestream2_get_le32(gb);
565     bytestream2_skip(gb, 4);
566     nBits = bytestream2_get_le32(gb);
567     if (im < 0 || im >= HUF_ENCSIZE ||
568         iM < 0 || iM >= HUF_ENCSIZE ||
569         src_size < 0)
570         return AVERROR_INVALIDDATA;
571
572     bytestream2_skip(gb, 4);
573
574     freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
575     hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
576     if (!freq || !hdec) {
577         ret = AVERROR(ENOMEM);
578         goto fail;
579     }
580
581     if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
582         goto fail;
583
584     if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
585         ret = AVERROR_INVALIDDATA;
586         goto fail;
587     }
588
589     if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
590         goto fail;
591     ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
592
593 fail:
594     for (i = 0; i < HUF_DECSIZE; i++)
595         if (hdec)
596             av_freep(&hdec[i].p);
597
598     av_free(freq);
599     av_free(hdec);
600
601     return ret;
602 }
603
604 static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
605 {
606     int16_t ls = l;
607     int16_t hs = h;
608     int hi     = hs;
609     int ai     = ls + (hi & 1) + (hi >> 1);
610     int16_t as = ai;
611     int16_t bs = ai - hi;
612
613     *a = as;
614     *b = bs;
615 }
616
617 #define NBITS      16
618 #define A_OFFSET  (1 << (NBITS - 1))
619 #define MOD_MASK  ((1 << NBITS) - 1)
620
621 static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
622 {
623     int m  = l;
624     int d  = h;
625     int bb = (m - (d >> 1)) & MOD_MASK;
626     int aa = (d + bb - A_OFFSET) & MOD_MASK;
627     *b = bb;
628     *a = aa;
629 }
630
631 static void wav_decode(uint16_t *in, int nx, int ox,
632                        int ny, int oy, uint16_t mx)
633 {
634     int w14 = (mx < (1 << 14));
635     int n   = (nx > ny) ? ny : nx;
636     int p   = 1;
637     int p2;
638
639     while (p <= n)
640         p <<= 1;
641
642     p >>= 1;
643     p2  = p;
644     p >>= 1;
645
646     while (p >= 1) {
647         uint16_t *py = in;
648         uint16_t *ey = in + oy * (ny - p2);
649         uint16_t i00, i01, i10, i11;
650         int oy1 = oy * p;
651         int oy2 = oy * p2;
652         int ox1 = ox * p;
653         int ox2 = ox * p2;
654
655         for (; py <= ey; py += oy2) {
656             uint16_t *px = py;
657             uint16_t *ex = py + ox * (nx - p2);
658
659             for (; px <= ex; px += ox2) {
660                 uint16_t *p01 = px + ox1;
661                 uint16_t *p10 = px + oy1;
662                 uint16_t *p11 = p10 + ox1;
663
664                 if (w14) {
665                     wdec14(*px, *p10, &i00, &i10);
666                     wdec14(*p01, *p11, &i01, &i11);
667                     wdec14(i00, i01, px, p01);
668                     wdec14(i10, i11, p10, p11);
669                 } else {
670                     wdec16(*px, *p10, &i00, &i10);
671                     wdec16(*p01, *p11, &i01, &i11);
672                     wdec16(i00, i01, px, p01);
673                     wdec16(i10, i11, p10, p11);
674                 }
675             }
676
677             if (nx & p) {
678                 uint16_t *p10 = px + oy1;
679
680                 if (w14)
681                     wdec14(*px, *p10, &i00, p10);
682                 else
683                     wdec16(*px, *p10, &i00, p10);
684
685                 *px = i00;
686             }
687         }
688
689         if (ny & p) {
690             uint16_t *px = py;
691             uint16_t *ex = py + ox * (nx - p2);
692
693             for (; px <= ex; px += ox2) {
694                 uint16_t *p01 = px + ox1;
695
696                 if (w14)
697                     wdec14(*px, *p01, &i00, p01);
698                 else
699                     wdec16(*px, *p01, &i00, p01);
700
701                 *px = i00;
702             }
703         }
704
705         p2  = p;
706         p >>= 1;
707     }
708 }
709
710 static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
711                           int dsize, EXRThreadData *td)
712 {
713     GetByteContext gb;
714     uint16_t maxval, min_non_zero, max_non_zero;
715     uint16_t *ptr;
716     uint16_t *tmp = (uint16_t *)td->tmp;
717     uint8_t *out;
718     int ret, i, j;
719
720     if (!td->bitmap)
721         td->bitmap = av_malloc(BITMAP_SIZE);
722     if (!td->lut)
723         td->lut = av_malloc(1 << 17);
724     if (!td->bitmap || !td->lut) {
725         av_freep(&td->bitmap);
726         av_freep(&td->lut);
727         return AVERROR(ENOMEM);
728     }
729
730     bytestream2_init(&gb, src, ssize);
731     min_non_zero = bytestream2_get_le16(&gb);
732     max_non_zero = bytestream2_get_le16(&gb);
733
734     if (max_non_zero >= BITMAP_SIZE)
735         return AVERROR_INVALIDDATA;
736
737     memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
738     if (min_non_zero <= max_non_zero)
739         bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
740                                max_non_zero - min_non_zero + 1);
741     memset(td->bitmap + max_non_zero, 0, BITMAP_SIZE - max_non_zero);
742
743     maxval = reverse_lut(td->bitmap, td->lut);
744
745     ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
746     if (ret)
747         return ret;
748
749     ptr = tmp;
750     for (i = 0; i < s->nb_channels; i++) {
751         EXRChannel *channel = &s->channels[i];
752         int size = channel->pixel_type;
753
754         for (j = 0; j < size; j++)
755             wav_decode(ptr + j, s->xdelta, size, s->ysize,
756                        s->xdelta * size, maxval);
757         ptr += s->xdelta * s->ysize * size;
758     }
759
760     apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
761
762     out = td->uncompressed_data;
763     for (i = 0; i < s->ysize; i++)
764         for (j = 0; j < s->nb_channels; j++) {
765             uint16_t *in = tmp + j * s->xdelta * s->ysize + i * s->xdelta;
766             memcpy(out, in, s->xdelta * 2);
767             out += s->xdelta * 2;
768         }
769
770     return 0;
771 }
772
773 static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
774                             int compressed_size, int uncompressed_size,
775                             EXRThreadData *td)
776 {
777     unsigned long dest_len = uncompressed_size;
778     const uint8_t *in = td->tmp;
779     uint8_t *out;
780     int c, i, j;
781
782     if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
783         dest_len != uncompressed_size)
784         return AVERROR_INVALIDDATA;
785
786     out = td->uncompressed_data;
787     for (i = 0; i < s->ysize; i++)
788         for (c = 0; c < s->nb_channels; c++) {
789             EXRChannel *channel = &s->channels[c];
790             const uint8_t *ptr[4];
791             uint32_t pixel = 0;
792
793             switch (channel->pixel_type) {
794             case EXR_FLOAT:
795                 ptr[0] = in;
796                 ptr[1] = ptr[0] + s->xdelta;
797                 ptr[2] = ptr[1] + s->xdelta;
798                 in     = ptr[2] + s->xdelta;
799
800                 for (j = 0; j < s->xdelta; ++j) {
801                     uint32_t diff = (*(ptr[0]++) << 24) |
802                                     (*(ptr[1]++) << 16) |
803                                     (*(ptr[2]++) << 8);
804                     pixel += diff;
805                     bytestream_put_le32(&out, pixel);
806                 }
807                 break;
808             case EXR_HALF:
809                 ptr[0] = in;
810                 ptr[1] = ptr[0] + s->xdelta;
811                 in     = ptr[1] + s->xdelta;
812                 for (j = 0; j < s->xdelta; j++) {
813                     uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
814
815                     pixel += diff;
816                     bytestream_put_le16(&out, pixel);
817                 }
818                 break;
819             default:
820                 return AVERROR_INVALIDDATA;
821             }
822         }
823
824     return 0;
825 }
826
827 static int decode_block(AVCodecContext *avctx, void *tdata,
828                         int jobnr, int threadnr)
829 {
830     EXRContext *s = avctx->priv_data;
831     AVFrame *const p = s->picture;
832     EXRThreadData *td = &s->thread_data[threadnr];
833     const uint8_t *channel_buffer[4] = { 0 };
834     const uint8_t *buf = s->buf;
835     uint64_t line_offset, uncompressed_size;
836     uint32_t xdelta = s->xdelta;
837     uint16_t *ptr_x;
838     uint8_t *ptr;
839     uint32_t data_size, line;
840     const uint8_t *src;
841     int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components;
842     int bxmin = s->xmin * 2 * s->desc->nb_components;
843     int i, x, buf_size = s->buf_size;
844     float one_gamma = 1.0f / s->gamma;
845     int ret;
846
847     line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
848     // Check if the buffer has the required bytes needed from the offset
849     if (line_offset > buf_size - 8)
850         return AVERROR_INVALIDDATA;
851
852     src  = buf + line_offset + 8;
853     line = AV_RL32(src - 8);
854     if (line < s->ymin || line > s->ymax)
855         return AVERROR_INVALIDDATA;
856
857     data_size = AV_RL32(src - 4);
858     if (data_size <= 0 || data_size > buf_size)
859         return AVERROR_INVALIDDATA;
860
861     s->ysize          = FFMIN(s->scan_lines_per_block, s->ymax - line + 1);
862     uncompressed_size = s->scan_line_size * s->ysize;
863     if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
864                                  line_offset > buf_size - uncompressed_size)) ||
865         (s->compression != EXR_RAW && (data_size > uncompressed_size ||
866                                  line_offset > buf_size - data_size))) {
867         return AVERROR_INVALIDDATA;
868     }
869
870     if (data_size < uncompressed_size) {
871         av_fast_padded_malloc(&td->uncompressed_data,
872                               &td->uncompressed_size, uncompressed_size);
873         av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
874         if (!td->uncompressed_data || !td->tmp)
875             return AVERROR(ENOMEM);
876
877         ret = AVERROR_INVALIDDATA;
878         switch (s->compression) {
879         case EXR_ZIP1:
880         case EXR_ZIP16:
881             ret = zip_uncompress(src, data_size, uncompressed_size, td);
882             break;
883         case EXR_PIZ:
884             ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
885             break;
886         case EXR_PXR24:
887             ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
888             break;
889         case EXR_RLE:
890             ret = rle_uncompress(src, data_size, uncompressed_size, td);
891         }
892         if (ret < 0) {
893             av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
894             return ret;
895         }
896         src = td->uncompressed_data;
897     }
898
899     channel_buffer[0] = src + xdelta * s->channel_offsets[0];
900     channel_buffer[1] = src + xdelta * s->channel_offsets[1];
901     channel_buffer[2] = src + xdelta * s->channel_offsets[2];
902     if (s->channel_offsets[3] >= 0)
903         channel_buffer[3] = src + xdelta * s->channel_offsets[3];
904
905     ptr = p->data[0] + line * p->linesize[0];
906     for (i = 0;
907          i < s->scan_lines_per_block && line + i <= s->ymax;
908          i++, ptr += p->linesize[0]) {
909         const uint8_t *r, *g, *b, *a;
910
911         r = channel_buffer[0];
912         g = channel_buffer[1];
913         b = channel_buffer[2];
914         if (channel_buffer[3])
915             a = channel_buffer[3];
916
917         ptr_x = (uint16_t *) ptr;
918
919         // Zero out the start if xmin is not 0
920         memset(ptr_x, 0, bxmin);
921         ptr_x += s->xmin * s->desc->nb_components;
922         if (s->pixel_type == EXR_FLOAT) {
923             // 32-bit
924             for (x = 0; x < xdelta; x++) {
925                 union av_intfloat32 t;
926                 t.i = bytestream_get_le32(&r);
927                 if (t.f > 0.0f)  /* avoid negative values */
928                     t.f = powf(t.f, one_gamma);
929                 *ptr_x++ = exr_flt2uint(t.i);
930
931                 t.i = bytestream_get_le32(&g);
932                 if (t.f > 0.0f)
933                     t.f = powf(t.f, one_gamma);
934                 *ptr_x++ = exr_flt2uint(t.i);
935
936                 t.i = bytestream_get_le32(&b);
937                 if (t.f > 0.0f)
938                     t.f = powf(t.f, one_gamma);
939                 *ptr_x++ = exr_flt2uint(t.i);
940                 if (channel_buffer[3])
941                     *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
942             }
943         } else {
944             // 16-bit
945             for (x = 0; x < xdelta; x++) {
946                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&r)];
947                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&g)];
948                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&b)];
949                 if (channel_buffer[3])
950                     *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));
951             }
952         }
953
954         // Zero out the end if xmax+1 is not w
955         memset(ptr_x, 0, axmax);
956
957         channel_buffer[0] += s->scan_line_size;
958         channel_buffer[1] += s->scan_line_size;
959         channel_buffer[2] += s->scan_line_size;
960         if (channel_buffer[3])
961             channel_buffer[3] += s->scan_line_size;
962     }
963
964     return 0;
965 }
966
967 /**
968  * Check if the variable name corresponds to its data type.
969  *
970  * @param s              the EXRContext
971  * @param value_name     name of the variable to check
972  * @param value_type     type of the variable to check
973  * @param minimum_length minimum length of the variable data
974  *
975  * @return bytes to read containing variable data
976  *         -1 if variable is not found
977  *         0 if buffer ended prematurely
978  */
979 static int check_header_variable(EXRContext *s,
980                                  const char *value_name,
981                                  const char *value_type,
982                                  unsigned int minimum_length)
983 {
984     int var_size = -1;
985
986     if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
987         !strcmp(s->gb.buffer, value_name)) {
988         // found value_name, jump to value_type (null terminated strings)
989         s->gb.buffer += strlen(value_name) + 1;
990         if (!strcmp(s->gb.buffer, value_type)) {
991             s->gb.buffer += strlen(value_type) + 1;
992             var_size = bytestream2_get_le32(&s->gb);
993             // don't go read past boundaries
994             if (var_size > bytestream2_get_bytes_left(&s->gb))
995                 var_size = 0;
996         } else {
997             // value_type not found, reset the buffer
998             s->gb.buffer -= strlen(value_name) + 1;
999             av_log(s->avctx, AV_LOG_WARNING,
1000                    "Unknown data type %s for header variable %s.\n",
1001                    value_type, value_name);
1002         }
1003     }
1004
1005     return var_size;
1006 }
1007
1008 static int decode_header(EXRContext *s)
1009 {
1010     int current_channel_offset = 0;
1011     int magic_number, version, flags, i;
1012
1013     if (bytestream2_get_bytes_left(&s->gb) < 10) {
1014         av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1015         return AVERROR_INVALIDDATA;
1016     }
1017
1018     magic_number = bytestream2_get_le32(&s->gb);
1019     if (magic_number != 20000630) {
1020         /* As per documentation of OpenEXR, it is supposed to be
1021          * int 20000630 little-endian */
1022         av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1023         return AVERROR_INVALIDDATA;
1024     }
1025
1026     version = bytestream2_get_byte(&s->gb);
1027     if (version != 2) {
1028         avpriv_report_missing_feature(s->avctx, "Version %d", version);
1029         return AVERROR_PATCHWELCOME;
1030     }
1031
1032     flags = bytestream2_get_le24(&s->gb);
1033     if (flags & 0x02) {
1034         avpriv_report_missing_feature(s->avctx, "Tile support");
1035         return AVERROR_PATCHWELCOME;
1036     }
1037
1038     // Parse the header
1039     while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
1040         int var_size;
1041         if ((var_size = check_header_variable(s, "channels",
1042                                               "chlist", 38)) >= 0) {
1043             GetByteContext ch_gb;
1044             if (!var_size)
1045                 return AVERROR_INVALIDDATA;
1046
1047             bytestream2_init(&ch_gb, s->gb.buffer, var_size);
1048
1049             while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1050                 EXRChannel *channel;
1051                 enum ExrPixelType current_pixel_type;
1052                 int channel_index = -1;
1053                 int xsub, ysub;
1054
1055                 if (strcmp(s->layer, "") != 0) {
1056                     if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1057                         ch_gb.buffer += strlen(s->layer);
1058                         if (*ch_gb.buffer == '.')
1059                             ch_gb.buffer++;         /* skip dot if not given */
1060                         av_log(s->avctx, AV_LOG_INFO,
1061                                "Layer %s.%s matched.\n", s->layer, ch_gb.buffer);
1062                     }
1063                 }
1064
1065                 if (!strcmp(ch_gb.buffer, "R") ||
1066                     !strcmp(ch_gb.buffer, "X") ||
1067                     !strcmp(ch_gb.buffer, "U"))
1068                     channel_index = 0;
1069                 else if (!strcmp(ch_gb.buffer, "G") ||
1070                          !strcmp(ch_gb.buffer, "Y") ||
1071                          !strcmp(ch_gb.buffer, "V"))
1072                     channel_index = 1;
1073                 else if (!strcmp(ch_gb.buffer, "B") ||
1074                          !strcmp(ch_gb.buffer, "Z") ||
1075                          !strcmp(ch_gb.buffer, "W"))
1076                     channel_index = 2;
1077                 else if (!strcmp(ch_gb.buffer, "A"))
1078                     channel_index = 3;
1079                 else
1080                     av_log(s->avctx, AV_LOG_WARNING,
1081                            "Unsupported channel %.256s.\n", ch_gb.buffer);
1082
1083                 /* skip until you get a 0 */
1084                 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1085                        bytestream2_get_byte(&ch_gb))
1086                     continue;
1087
1088                 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1089                     av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1090                     return AVERROR_INVALIDDATA;
1091                 }
1092
1093                 current_pixel_type = bytestream2_get_le32(&ch_gb);
1094                 if (current_pixel_type >= EXR_UNKNOWN) {
1095                     avpriv_report_missing_feature(s->avctx,
1096                                                   "Pixel type %d.\n",
1097                                                   current_pixel_type);
1098                     return AVERROR_PATCHWELCOME;
1099                 }
1100
1101                 bytestream2_skip(&ch_gb, 4);
1102                 xsub = bytestream2_get_le32(&ch_gb);
1103                 ysub = bytestream2_get_le32(&ch_gb);
1104                 if (xsub != 1 || ysub != 1) {
1105                     avpriv_report_missing_feature(s->avctx,
1106                                                   "Subsampling %dx%d",
1107                                                   xsub, ysub);
1108                     return AVERROR_PATCHWELCOME;
1109                 }
1110
1111                 if (channel_index >= 0) {
1112                     if (s->pixel_type != EXR_UNKNOWN &&
1113                         s->pixel_type != current_pixel_type) {
1114                         av_log(s->avctx, AV_LOG_ERROR,
1115                                "RGB channels not of the same depth.\n");
1116                         return AVERROR_INVALIDDATA;
1117                     }
1118                     s->pixel_type                     = current_pixel_type;
1119                     s->channel_offsets[channel_index] = current_channel_offset;
1120                 }
1121
1122                 s->channels = av_realloc(s->channels,
1123                                          ++s->nb_channels * sizeof(EXRChannel));
1124                 if (!s->channels)
1125                     return AVERROR(ENOMEM);
1126                 channel             = &s->channels[s->nb_channels - 1];
1127                 channel->pixel_type = current_pixel_type;
1128                 channel->xsub       = xsub;
1129                 channel->ysub       = ysub;
1130
1131                 current_channel_offset += 1 << current_pixel_type;
1132             }
1133
1134             /* Check if all channels are set with an offset or if the channels
1135              * are causing an overflow  */
1136             if (FFMIN3(s->channel_offsets[0],
1137                        s->channel_offsets[1],
1138                        s->channel_offsets[2]) < 0) {
1139                 if (s->channel_offsets[0] < 0)
1140                     av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1141                 if (s->channel_offsets[1] < 0)
1142                     av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1143                 if (s->channel_offsets[2] < 0)
1144                     av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1145                 return AVERROR_INVALIDDATA;
1146             }
1147
1148             // skip one last byte and update main gb
1149             s->gb.buffer = ch_gb.buffer + 1;
1150             continue;
1151         } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1152                                                      31)) >= 0) {
1153             if (!var_size)
1154                 return AVERROR_INVALIDDATA;
1155
1156             s->xmin   = bytestream2_get_le32(&s->gb);
1157             s->ymin   = bytestream2_get_le32(&s->gb);
1158             s->xmax   = bytestream2_get_le32(&s->gb);
1159             s->ymax   = bytestream2_get_le32(&s->gb);
1160             s->xdelta = (s->xmax - s->xmin) + 1;
1161             s->ydelta = (s->ymax - s->ymin) + 1;
1162
1163             continue;
1164         } else if ((var_size = check_header_variable(s, "displayWindow",
1165                                                      "box2i", 34)) >= 0) {
1166             if (!var_size)
1167                 return AVERROR_INVALIDDATA;
1168
1169             bytestream2_skip(&s->gb, 8);
1170             s->w = bytestream2_get_le32(&s->gb) + 1;
1171             s->h = bytestream2_get_le32(&s->gb) + 1;
1172
1173             continue;
1174         } else if ((var_size = check_header_variable(s, "lineOrder",
1175                                                      "lineOrder", 25)) >= 0) {
1176             int line_order;
1177             if (!var_size)
1178                 return AVERROR_INVALIDDATA;
1179
1180             line_order = bytestream2_get_byte(&s->gb);
1181             av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1182             if (line_order > 2) {
1183                 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1184                 return AVERROR_INVALIDDATA;
1185             }
1186
1187             continue;
1188         } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1189                                                      "float", 31)) >= 0) {
1190             if (!var_size)
1191                 return AVERROR_INVALIDDATA;
1192
1193             ff_set_sar(s->avctx,
1194                        av_d2q(av_int2float(bytestream2_get_le32(&s->gb)), 255));
1195
1196             continue;
1197         } else if ((var_size = check_header_variable(s, "compression",
1198                                                      "compression", 29)) >= 0) {
1199             if (!var_size)
1200                 return AVERROR_INVALIDDATA;
1201
1202             if (s->compression == EXR_UNKN)
1203                 s->compression = bytestream2_get_byte(&s->gb);
1204             else
1205                 av_log(s->avctx, AV_LOG_WARNING,
1206                        "Found more than one compression attribute.\n");
1207
1208             continue;
1209         }
1210
1211         // Check if there are enough bytes for a header
1212         if (bytestream2_get_bytes_left(&s->gb) <= 9) {
1213             av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1214             return AVERROR_INVALIDDATA;
1215         }
1216
1217         // Process unknown variables
1218         for (i = 0; i < 2; i++) // value_name and value_type
1219             while (bytestream2_get_byte(&s->gb) != 0);
1220
1221         // Skip variable length
1222         bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb));
1223     }
1224
1225     if (s->compression == EXR_UNKN) {
1226         av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1227         return AVERROR_INVALIDDATA;
1228     }
1229     s->scan_line_size = s->xdelta * current_channel_offset;
1230
1231     if (bytestream2_get_bytes_left(&s->gb) <= 0) {
1232         av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1233         return AVERROR_INVALIDDATA;
1234     }
1235
1236     // aaand we are done
1237     bytestream2_skip(&s->gb, 1);
1238     return 0;
1239 }
1240
1241 static int decode_frame(AVCodecContext *avctx, void *data,
1242                         int *got_frame, AVPacket *avpkt)
1243 {
1244     EXRContext *s = avctx->priv_data;
1245     ThreadFrame frame = { .f = data };
1246     AVFrame *picture = data;
1247     uint8_t *ptr;
1248
1249     int y, ret;
1250     int out_line_size;
1251     int scan_line_blocks;
1252
1253     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1254
1255     if ((ret = decode_header(s)) < 0)
1256         return ret;
1257
1258     switch (s->pixel_type) {
1259     case EXR_FLOAT:
1260     case EXR_HALF:
1261         if (s->channel_offsets[3] >= 0)
1262             avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1263         else
1264             avctx->pix_fmt = AV_PIX_FMT_RGB48;
1265         break;
1266     case EXR_UINT:
1267         avpriv_request_sample(avctx, "32-bit unsigned int");
1268         return AVERROR_PATCHWELCOME;
1269     default:
1270         av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1271         return AVERROR_INVALIDDATA;
1272     }
1273
1274     switch (s->compression) {
1275     case EXR_RAW:
1276     case EXR_RLE:
1277     case EXR_ZIP1:
1278         s->scan_lines_per_block = 1;
1279         break;
1280     case EXR_PXR24:
1281     case EXR_ZIP16:
1282         s->scan_lines_per_block = 16;
1283         break;
1284     case EXR_PIZ:
1285         s->scan_lines_per_block = 32;
1286         break;
1287     default:
1288         avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1289         return AVERROR_PATCHWELCOME;
1290     }
1291
1292     /* Verify the xmin, xmax, ymin, ymax and xdelta before setting
1293      * the actual image size. */
1294     if (s->xmin > s->xmax                  ||
1295         s->ymin > s->ymax                  ||
1296         s->xdelta != s->xmax - s->xmin + 1 ||
1297         s->xmax >= s->w                    ||
1298         s->ymax >= s->h) {
1299         av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1300         return AVERROR_INVALIDDATA;
1301     }
1302
1303     if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1304         return ret;
1305
1306     s->desc          = av_pix_fmt_desc_get(avctx->pix_fmt);
1307     if (!s->desc)
1308         return AVERROR_INVALIDDATA;
1309     out_line_size    = avctx->width * 2 * s->desc->nb_components;
1310     scan_line_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1311                        s->scan_lines_per_block;
1312
1313     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1314         return ret;
1315
1316     if (bytestream2_get_bytes_left(&s->gb) < scan_line_blocks * 8)
1317         return AVERROR_INVALIDDATA;
1318
1319     // save pointer we are going to use in decode_block
1320     s->buf      = avpkt->data;
1321     s->buf_size = avpkt->size;
1322     ptr         = picture->data[0];
1323
1324     // Zero out the start if ymin is not 0
1325     for (y = 0; y < s->ymin; y++) {
1326         memset(ptr, 0, out_line_size);
1327         ptr += picture->linesize[0];
1328     }
1329
1330     s->picture = picture;
1331     avctx->execute2(avctx, decode_block, s->thread_data, NULL, scan_line_blocks);
1332
1333     // Zero out the end if ymax+1 is not h
1334     for (y = s->ymax + 1; y < avctx->height; y++) {
1335         memset(ptr, 0, out_line_size);
1336         ptr += picture->linesize[0];
1337     }
1338
1339     picture->pict_type = AV_PICTURE_TYPE_I;
1340     *got_frame = 1;
1341
1342     return avpkt->size;
1343 }
1344
1345 static av_cold int decode_init(AVCodecContext *avctx)
1346 {
1347     EXRContext *s = avctx->priv_data;
1348     uint32_t i;
1349     union av_intfloat32 t;
1350     float one_gamma = 1.0f / s->gamma;
1351
1352     s->avctx              = avctx;
1353     s->xmin               = ~0;
1354     s->xmax               = ~0;
1355     s->ymin               = ~0;
1356     s->ymax               = ~0;
1357     s->xdelta             = ~0;
1358     s->ydelta             = ~0;
1359     s->channel_offsets[0] = -1;
1360     s->channel_offsets[1] = -1;
1361     s->channel_offsets[2] = -1;
1362     s->channel_offsets[3] = -1;
1363     s->pixel_type         = EXR_UNKNOWN;
1364     s->compression        = EXR_UNKN;
1365     s->nb_channels        = 0;
1366     s->w                  = 0;
1367     s->h                  = 0;
1368
1369     if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1370         for (i = 0; i < 65536; ++i)
1371             s->gamma_table[i] = exr_halflt2uint(i);
1372     } else {
1373         for (i = 0; i < 65536; ++i) {
1374             t = exr_half2float(i);
1375             /* If negative value we reuse half value */
1376             if (t.f <= 0.0f) {
1377                 s->gamma_table[i] = exr_halflt2uint(i);
1378             } else {
1379                 t.f = powf(t.f, one_gamma);
1380                 s->gamma_table[i] = exr_flt2uint(t.i);
1381             }
1382         }
1383     }
1384
1385     // allocate thread data, used for non EXR_RAW compreesion types
1386     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1387     if (!s->thread_data)
1388         return AVERROR_INVALIDDATA;
1389
1390     return 0;
1391 }
1392
1393 static int decode_init_thread_copy(AVCodecContext *avctx)
1394 {    EXRContext *s = avctx->priv_data;
1395
1396     // allocate thread data, used for non EXR_RAW compreesion types
1397     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1398     if (!s->thread_data)
1399         return AVERROR_INVALIDDATA;
1400
1401     return 0;
1402 }
1403
1404 static av_cold int decode_end(AVCodecContext *avctx)
1405 {
1406     EXRContext *s = avctx->priv_data;
1407     int i;
1408     for (i = 0; i < avctx->thread_count; i++) {
1409         EXRThreadData *td = &s->thread_data[i];
1410         av_freep(&td->uncompressed_data);
1411         av_freep(&td->tmp);
1412         av_freep(&td->bitmap);
1413         av_freep(&td->lut);
1414     }
1415
1416     av_freep(&s->thread_data);
1417     av_freep(&s->channels);
1418
1419     return 0;
1420 }
1421
1422 #define OFFSET(x) offsetof(EXRContext, x)
1423 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1424 static const AVOption options[] = {
1425     { "layer", "Set the decoding layer", OFFSET(layer),
1426         AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
1427     { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
1428         AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
1429     { NULL },
1430 };
1431
1432 static const AVClass exr_class = {
1433     .class_name = "EXR",
1434     .item_name  = av_default_item_name,
1435     .option     = options,
1436     .version    = LIBAVUTIL_VERSION_INT,
1437 };
1438
1439 AVCodec ff_exr_decoder = {
1440     .name             = "exr",
1441     .long_name        = NULL_IF_CONFIG_SMALL("OpenEXR image"),
1442     .type             = AVMEDIA_TYPE_VIDEO,
1443     .id               = AV_CODEC_ID_EXR,
1444     .priv_data_size   = sizeof(EXRContext),
1445     .init             = decode_init,
1446     .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1447     .close            = decode_end,
1448     .decode           = decode_frame,
1449     .capabilities     = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS |
1450                         CODEC_CAP_SLICE_THREADS,
1451     .priv_class       = &exr_class,
1452 };