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