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