]> git.sesse.net Git - ffmpeg/blob - libavcodec/exr.c
Merge commit '0e7772c5e4f1b31e2a3dda714ba4f89b1cca644a'
[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         for (iY = 0; iY < nbB44BlockH; iY++) {
946             for (iX = 0; iX < nbB44BlockW; iX++) {/* For each B44 block */
947                 if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
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                 } else{/* Float or UINT 32 channel */
980                     for (y = indexHgY; y < FFMIN(indexHgY + 4, td->ysize); y++) {
981                         for (x = indexHgX; x < FFMIN(indexHgX + 4, td->xsize); x++) {
982                             indexOut = target_channel_offset * td->xsize + y * td->channel_line_size + 4 * x;
983                             memcpy(&td->uncompressed_data[indexOut], sr, 4);
984                             sr += 4;
985                         }
986                     }
987                 }
988             }
989         }
990         if (s->channels[c].pixel_type == EXR_HALF) {
991             target_channel_offset += 2;
992         } else {
993             target_channel_offset += 4;
994         }
995     }
996
997     return 0;
998 }
999
1000 static int decode_block(AVCodecContext *avctx, void *tdata,
1001                         int jobnr, int threadnr)
1002 {
1003     EXRContext *s = avctx->priv_data;
1004     AVFrame *const p = s->picture;
1005     EXRThreadData *td = &s->thread_data[threadnr];
1006     const uint8_t *channel_buffer[4] = { 0 };
1007     const uint8_t *buf = s->buf;
1008     uint64_t line_offset, uncompressed_size;
1009     uint16_t *ptr_x;
1010     uint8_t *ptr;
1011     uint32_t data_size, line, col = 0;
1012     uint32_t tileX, tileY, tileLevelX, tileLevelY;
1013     const uint8_t *src;
1014     int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components; /* nb pixel to add at the right of the datawindow */
1015     int bxmin = s->xmin * 2 * s->desc->nb_components; /* nb pixel to add at the left of the datawindow */
1016     int i, x, buf_size = s->buf_size;
1017     float one_gamma = 1.0f / s->gamma;
1018     avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1019     int ret;
1020
1021     line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
1022
1023     if (s->is_tile) {
1024         if (line_offset > buf_size - 20)
1025             return AVERROR_INVALIDDATA;
1026
1027         src  = buf + line_offset + 20;
1028
1029         tileX = AV_RL32(src - 20);
1030         tileY = AV_RL32(src - 16);
1031         tileLevelX = AV_RL32(src - 12);
1032         tileLevelY = AV_RL32(src - 8);
1033
1034         data_size = AV_RL32(src - 4);
1035         if (data_size <= 0 || data_size > buf_size)
1036             return AVERROR_INVALIDDATA;
1037
1038         if (tileLevelX || tileLevelY) { /* tile level, is not the full res level */
1039             avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
1040             return AVERROR_PATCHWELCOME;
1041         }
1042
1043         line = s->tile_attr.ySize * tileY;
1044         col = s->tile_attr.xSize * tileX;
1045
1046         td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tileY * s->tile_attr.ySize);
1047         td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tileX * s->tile_attr.xSize);
1048
1049         if (col) { /* not the first tile of the line */
1050             bxmin = 0; /* doesn't add pixel at the left of the datawindow */
1051         }
1052
1053         if ((col + td->xsize) != s->xdelta)/* not the last tile of the line */
1054             axmax = 0; /* doesn't add pixel at the right of the datawindow */
1055
1056         td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1057         uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1058     } else {
1059         if (line_offset > buf_size - 8)
1060             return AVERROR_INVALIDDATA;
1061
1062         src  = buf + line_offset + 8;
1063         line = AV_RL32(src - 8);
1064
1065         if (line < s->ymin || line > s->ymax)
1066             return AVERROR_INVALIDDATA;
1067
1068         data_size = AV_RL32(src - 4);
1069         if (data_size <= 0 || data_size > buf_size)
1070             return AVERROR_INVALIDDATA;
1071
1072         td->ysize          = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
1073         td->xsize          = s->xdelta;
1074
1075         td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1076         uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1077
1078         if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
1079                                            line_offset > buf_size - uncompressed_size)) ||
1080             (s->compression != EXR_RAW && (data_size > uncompressed_size ||
1081                                            line_offset > buf_size - data_size))) {
1082             return AVERROR_INVALIDDATA;
1083         }
1084     }
1085
1086     if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
1087         av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
1088         if (!td->tmp)
1089             return AVERROR(ENOMEM);
1090     }
1091
1092     if (data_size < uncompressed_size) {
1093         av_fast_padded_malloc(&td->uncompressed_data,
1094                               &td->uncompressed_size, uncompressed_size);
1095
1096         if (!td->uncompressed_data)
1097             return AVERROR(ENOMEM);
1098
1099         ret = AVERROR_INVALIDDATA;
1100         switch (s->compression) {
1101         case EXR_ZIP1:
1102         case EXR_ZIP16:
1103             ret = zip_uncompress(src, data_size, uncompressed_size, td);
1104             break;
1105         case EXR_PIZ:
1106             ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
1107             break;
1108         case EXR_PXR24:
1109             ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
1110             break;
1111         case EXR_RLE:
1112             ret = rle_uncompress(src, data_size, uncompressed_size, td);
1113             break;
1114         case EXR_B44:
1115         case EXR_B44A:
1116             ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
1117             break;
1118         }
1119         if (ret < 0) {
1120             av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
1121             return ret;
1122         }
1123         src = td->uncompressed_data;
1124     }
1125
1126     channel_buffer[0] = src + td->xsize * s->channel_offsets[0];
1127     channel_buffer[1] = src + td->xsize * s->channel_offsets[1];
1128     channel_buffer[2] = src + td->xsize * s->channel_offsets[2];
1129     if (s->channel_offsets[3] >= 0)
1130         channel_buffer[3] = src + td->xsize * s->channel_offsets[3];
1131
1132     ptr = p->data[0] + line * p->linesize[0] + (col * s->desc->nb_components * 2);
1133
1134     for (i = 0;
1135          i < td->ysize; i++, ptr += p->linesize[0]) {
1136
1137         const uint8_t *r, *g, *b, *a;
1138
1139         r = channel_buffer[0];
1140         g = channel_buffer[1];
1141         b = channel_buffer[2];
1142         if (channel_buffer[3])
1143             a = channel_buffer[3];
1144
1145         ptr_x = (uint16_t *) ptr;
1146
1147         // Zero out the start if xmin is not 0
1148         memset(ptr_x, 0, bxmin);
1149         ptr_x += s->xmin * s->desc->nb_components;
1150
1151         if (s->pixel_type == EXR_FLOAT) {
1152             // 32-bit
1153             if (trc_func) {
1154                 for (x = 0; x < td->xsize; x++) {
1155                     union av_intfloat32 t;
1156                     t.i = bytestream_get_le32(&r);
1157                     t.f = trc_func(t.f);
1158                     *ptr_x++ = exr_flt2uint(t.i);
1159
1160                     t.i = bytestream_get_le32(&g);
1161                     t.f = trc_func(t.f);
1162                     *ptr_x++ = exr_flt2uint(t.i);
1163
1164                     t.i = bytestream_get_le32(&b);
1165                     t.f = trc_func(t.f);
1166                     *ptr_x++ = exr_flt2uint(t.i);
1167                     if (channel_buffer[3])
1168                         *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
1169                 }
1170             } else {
1171                 for (x = 0; x < td->xsize; x++) {
1172                     union av_intfloat32 t;
1173                     t.i = bytestream_get_le32(&r);
1174                     if (t.f > 0.0f)  /* avoid negative values */
1175                         t.f = powf(t.f, one_gamma);
1176                     *ptr_x++ = exr_flt2uint(t.i);
1177
1178                     t.i = bytestream_get_le32(&g);
1179                     if (t.f > 0.0f)
1180                         t.f = powf(t.f, one_gamma);
1181                     *ptr_x++ = exr_flt2uint(t.i);
1182
1183                     t.i = bytestream_get_le32(&b);
1184                     if (t.f > 0.0f)
1185                         t.f = powf(t.f, one_gamma);
1186                     *ptr_x++ = exr_flt2uint(t.i);
1187                     if (channel_buffer[3])
1188                         *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
1189                 }
1190             }
1191         } else {
1192             // 16-bit
1193             for (x = 0; x < td->xsize; x++) {
1194                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&r)];
1195                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&g)];
1196                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&b)];
1197                 if (channel_buffer[3])
1198                     *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));
1199             }
1200         }
1201
1202         // Zero out the end if xmax+1 is not w
1203         memset(ptr_x, 0, axmax);
1204
1205         channel_buffer[0] += td->channel_line_size;
1206         channel_buffer[1] += td->channel_line_size;
1207         channel_buffer[2] += td->channel_line_size;
1208         if (channel_buffer[3])
1209             channel_buffer[3] += td->channel_line_size;
1210     }
1211
1212     return 0;
1213 }
1214
1215 /**
1216  * Check if the variable name corresponds to its data type.
1217  *
1218  * @param s              the EXRContext
1219  * @param value_name     name of the variable to check
1220  * @param value_type     type of the variable to check
1221  * @param minimum_length minimum length of the variable data
1222  *
1223  * @return bytes to read containing variable data
1224  *         -1 if variable is not found
1225  *         0 if buffer ended prematurely
1226  */
1227 static int check_header_variable(EXRContext *s,
1228                                  const char *value_name,
1229                                  const char *value_type,
1230                                  unsigned int minimum_length)
1231 {
1232     int var_size = -1;
1233
1234     if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
1235         !strcmp(s->gb.buffer, value_name)) {
1236         // found value_name, jump to value_type (null terminated strings)
1237         s->gb.buffer += strlen(value_name) + 1;
1238         if (!strcmp(s->gb.buffer, value_type)) {
1239             s->gb.buffer += strlen(value_type) + 1;
1240             var_size = bytestream2_get_le32(&s->gb);
1241             // don't go read past boundaries
1242             if (var_size > bytestream2_get_bytes_left(&s->gb))
1243                 var_size = 0;
1244         } else {
1245             // value_type not found, reset the buffer
1246             s->gb.buffer -= strlen(value_name) + 1;
1247             av_log(s->avctx, AV_LOG_WARNING,
1248                    "Unknown data type %s for header variable %s.\n",
1249                    value_type, value_name);
1250         }
1251     }
1252
1253     return var_size;
1254 }
1255
1256 static int decode_header(EXRContext *s)
1257 {
1258     int magic_number, version, i, flags, sar = 0;
1259     int layer_match = 0;
1260
1261     s->current_channel_offset = 0;
1262     s->xmin               = ~0;
1263     s->xmax               = ~0;
1264     s->ymin               = ~0;
1265     s->ymax               = ~0;
1266     s->xdelta             = ~0;
1267     s->ydelta             = ~0;
1268     s->channel_offsets[0] = -1;
1269     s->channel_offsets[1] = -1;
1270     s->channel_offsets[2] = -1;
1271     s->channel_offsets[3] = -1;
1272     s->pixel_type         = EXR_UNKNOWN;
1273     s->compression        = EXR_UNKN;
1274     s->nb_channels        = 0;
1275     s->w                  = 0;
1276     s->h                  = 0;
1277     s->tile_attr.xSize    = -1;
1278     s->tile_attr.ySize    = -1;
1279     s->is_tile            = 0;
1280
1281     if (bytestream2_get_bytes_left(&s->gb) < 10) {
1282         av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1283         return AVERROR_INVALIDDATA;
1284     }
1285
1286     magic_number = bytestream2_get_le32(&s->gb);
1287     if (magic_number != 20000630) {
1288         /* As per documentation of OpenEXR, it is supposed to be
1289          * int 20000630 little-endian */
1290         av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1291         return AVERROR_INVALIDDATA;
1292     }
1293
1294     version = bytestream2_get_byte(&s->gb);
1295     if (version != 2) {
1296         avpriv_report_missing_feature(s->avctx, "Version %d", version);
1297         return AVERROR_PATCHWELCOME;
1298     }
1299
1300     flags = bytestream2_get_le24(&s->gb);
1301
1302     if (flags == 0x00)
1303         s->is_tile = 0;
1304     else if (flags & 0x02)
1305         s->is_tile = 1;
1306     else{
1307         avpriv_report_missing_feature(s->avctx, "flags %d", flags);
1308         return AVERROR_PATCHWELCOME;
1309     }
1310
1311     // Parse the header
1312     while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
1313         int var_size;
1314         if ((var_size = check_header_variable(s, "channels",
1315                                               "chlist", 38)) >= 0) {
1316             GetByteContext ch_gb;
1317             if (!var_size)
1318                 return AVERROR_INVALIDDATA;
1319
1320             bytestream2_init(&ch_gb, s->gb.buffer, var_size);
1321
1322             while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1323                 EXRChannel *channel;
1324                 enum ExrPixelType current_pixel_type;
1325                 int channel_index = -1;
1326                 int xsub, ysub;
1327
1328                 if (strcmp(s->layer, "") != 0) {
1329                     if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1330                         layer_match = 1;
1331                         av_log(s->avctx, AV_LOG_INFO,
1332                                "Channel match layer : %s.\n", ch_gb.buffer);
1333                         ch_gb.buffer += strlen(s->layer);
1334                         if (*ch_gb.buffer == '.')
1335                             ch_gb.buffer++;         /* skip dot if not given */
1336                     } else {
1337                         av_log(s->avctx, AV_LOG_INFO,
1338                                "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1339                     }
1340                 } else {
1341                     layer_match = 1;
1342                 }
1343
1344                 if (layer_match) { /* only search channel if the layer match is valid */
1345                     if (!strcmp(ch_gb.buffer, "R") ||
1346                         !strcmp(ch_gb.buffer, "X") ||
1347                         !strcmp(ch_gb.buffer, "U"))
1348                         channel_index = 0;
1349                     else if (!strcmp(ch_gb.buffer, "G") ||
1350                              !strcmp(ch_gb.buffer, "Y") ||
1351                              !strcmp(ch_gb.buffer, "V"))
1352                         channel_index = 1;
1353                     else if (!strcmp(ch_gb.buffer, "B") ||
1354                              !strcmp(ch_gb.buffer, "Z") ||
1355                              !strcmp(ch_gb.buffer, "W"))
1356                         channel_index = 2;
1357                     else if (!strcmp(ch_gb.buffer, "A"))
1358                         channel_index = 3;
1359                     else
1360                         av_log(s->avctx, AV_LOG_WARNING,
1361                                "Unsupported channel %.256s.\n", ch_gb.buffer);
1362                 }
1363
1364                 /* skip until you get a 0 */
1365                 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1366                        bytestream2_get_byte(&ch_gb))
1367                     continue;
1368
1369                 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1370                     av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1371                     return AVERROR_INVALIDDATA;
1372                 }
1373
1374                 current_pixel_type = bytestream2_get_le32(&ch_gb);
1375                 if (current_pixel_type >= EXR_UNKNOWN) {
1376                     avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1377                                                   current_pixel_type);
1378                     return AVERROR_PATCHWELCOME;
1379                 }
1380
1381                 bytestream2_skip(&ch_gb, 4);
1382                 xsub = bytestream2_get_le32(&ch_gb);
1383                 ysub = bytestream2_get_le32(&ch_gb);
1384                 if (xsub != 1 || ysub != 1) {
1385                     avpriv_report_missing_feature(s->avctx,
1386                                                   "Subsampling %dx%d",
1387                                                   xsub, ysub);
1388                     return AVERROR_PATCHWELCOME;
1389                 }
1390
1391                 if (s->channel_offsets[channel_index] == -1){/* channel have not been previously assign */
1392                     if (channel_index >= 0) {
1393                         if (s->pixel_type != EXR_UNKNOWN &&
1394                             s->pixel_type != current_pixel_type) {
1395                             av_log(s->avctx, AV_LOG_ERROR,
1396                                    "RGB channels not of the same depth.\n");
1397                             return AVERROR_INVALIDDATA;
1398                         }
1399                         s->pixel_type                     = current_pixel_type;
1400                         s->channel_offsets[channel_index] = s->current_channel_offset;
1401                     }
1402                 }
1403
1404                 s->channels = av_realloc(s->channels,
1405                                          ++s->nb_channels * sizeof(EXRChannel));
1406                 if (!s->channels)
1407                     return AVERROR(ENOMEM);
1408                 channel             = &s->channels[s->nb_channels - 1];
1409                 channel->pixel_type = current_pixel_type;
1410                 channel->xsub       = xsub;
1411                 channel->ysub       = ysub;
1412
1413                 s->current_channel_offset += 1 << current_pixel_type;
1414             }
1415
1416             /* Check if all channels are set with an offset or if the channels
1417              * are causing an overflow  */
1418             if (FFMIN3(s->channel_offsets[0],
1419                        s->channel_offsets[1],
1420                        s->channel_offsets[2]) < 0) {
1421                 if (s->channel_offsets[0] < 0)
1422                     av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1423                 if (s->channel_offsets[1] < 0)
1424                     av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1425                 if (s->channel_offsets[2] < 0)
1426                     av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1427                 return AVERROR_INVALIDDATA;
1428             }
1429
1430             // skip one last byte and update main gb
1431             s->gb.buffer = ch_gb.buffer + 1;
1432             continue;
1433         } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1434                                                      31)) >= 0) {
1435             if (!var_size)
1436                 return AVERROR_INVALIDDATA;
1437
1438             s->xmin   = bytestream2_get_le32(&s->gb);
1439             s->ymin   = bytestream2_get_le32(&s->gb);
1440             s->xmax   = bytestream2_get_le32(&s->gb);
1441             s->ymax   = bytestream2_get_le32(&s->gb);
1442             s->xdelta = (s->xmax - s->xmin) + 1;
1443             s->ydelta = (s->ymax - s->ymin) + 1;
1444
1445             continue;
1446         } else if ((var_size = check_header_variable(s, "displayWindow",
1447                                                      "box2i", 34)) >= 0) {
1448             if (!var_size)
1449                 return AVERROR_INVALIDDATA;
1450
1451             bytestream2_skip(&s->gb, 8);
1452             s->w = bytestream2_get_le32(&s->gb) + 1;
1453             s->h = bytestream2_get_le32(&s->gb) + 1;
1454
1455             continue;
1456         } else if ((var_size = check_header_variable(s, "lineOrder",
1457                                                      "lineOrder", 25)) >= 0) {
1458             int line_order;
1459             if (!var_size)
1460                 return AVERROR_INVALIDDATA;
1461
1462             line_order = bytestream2_get_byte(&s->gb);
1463             av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1464             if (line_order > 2) {
1465                 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1466                 return AVERROR_INVALIDDATA;
1467             }
1468
1469             continue;
1470         } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1471                                                      "float", 31)) >= 0) {
1472             if (!var_size)
1473                 return AVERROR_INVALIDDATA;
1474
1475             sar = bytestream2_get_le32(&s->gb);
1476
1477             continue;
1478         } else if ((var_size = check_header_variable(s, "compression",
1479                                                      "compression", 29)) >= 0) {
1480             if (!var_size)
1481                 return AVERROR_INVALIDDATA;
1482
1483             if (s->compression == EXR_UNKN)
1484                 s->compression = bytestream2_get_byte(&s->gb);
1485             else
1486                 av_log(s->avctx, AV_LOG_WARNING,
1487                        "Found more than one compression attribute.\n");
1488
1489             continue;
1490         } else if ((var_size = check_header_variable(s, "tiles",
1491                                                      "tiledesc", 22)) >= 0) {
1492             char tileLevel;
1493
1494             if (!s->is_tile)
1495                 av_log(s->avctx, AV_LOG_WARNING,
1496                        "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
1497
1498             s->tile_attr.xSize = bytestream2_get_le32(&s->gb);
1499             s->tile_attr.ySize = bytestream2_get_le32(&s->gb);
1500
1501             tileLevel = bytestream2_get_byte(&s->gb);
1502             s->tile_attr.level_mode = tileLevel & 0x0f;
1503             s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
1504
1505             if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN){
1506                 avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
1507                                               s->tile_attr.level_mode);
1508                 return AVERROR_PATCHWELCOME;
1509             }
1510
1511             if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
1512                 avpriv_report_missing_feature(s->avctx, "Tile level round %d",
1513                                               s->tile_attr.level_round);
1514                 return AVERROR_PATCHWELCOME;
1515             }
1516
1517             continue;
1518         }
1519
1520         // Check if there are enough bytes for a header
1521         if (bytestream2_get_bytes_left(&s->gb) <= 9) {
1522             av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1523             return AVERROR_INVALIDDATA;
1524         }
1525
1526         // Process unknown variables
1527         for (i = 0; i < 2; i++) // value_name and value_type
1528             while (bytestream2_get_byte(&s->gb) != 0);
1529
1530         // Skip variable length
1531         bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb));
1532     }
1533
1534     ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255));
1535
1536     if (s->compression == EXR_UNKN) {
1537         av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1538         return AVERROR_INVALIDDATA;
1539     }
1540
1541     if (s->is_tile) {
1542         if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1543             av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1544             return AVERROR_INVALIDDATA;
1545         }
1546     }
1547
1548     if (bytestream2_get_bytes_left(&s->gb) <= 0) {
1549         av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1550         return AVERROR_INVALIDDATA;
1551     }
1552
1553     // aaand we are done
1554     bytestream2_skip(&s->gb, 1);
1555     return 0;
1556 }
1557
1558 static int decode_frame(AVCodecContext *avctx, void *data,
1559                         int *got_frame, AVPacket *avpkt)
1560 {
1561     EXRContext *s = avctx->priv_data;
1562     ThreadFrame frame = { .f = data };
1563     AVFrame *picture = data;
1564     uint8_t *ptr;
1565
1566     int y, ret;
1567     int out_line_size;
1568     int nb_blocks;/* nb scanline or nb tile */
1569
1570     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1571
1572     if ((ret = decode_header(s)) < 0)
1573         return ret;
1574
1575     switch (s->pixel_type) {
1576     case EXR_FLOAT:
1577     case EXR_HALF:
1578         if (s->channel_offsets[3] >= 0)
1579             avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1580         else
1581             avctx->pix_fmt = AV_PIX_FMT_RGB48;
1582         break;
1583     case EXR_UINT:
1584         avpriv_request_sample(avctx, "32-bit unsigned int");
1585         return AVERROR_PATCHWELCOME;
1586     default:
1587         av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1588         return AVERROR_INVALIDDATA;
1589     }
1590
1591     if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1592         avctx->color_trc = s->apply_trc_type;
1593
1594     switch (s->compression) {
1595     case EXR_RAW:
1596     case EXR_RLE:
1597     case EXR_ZIP1:
1598         s->scan_lines_per_block = 1;
1599         break;
1600     case EXR_PXR24:
1601     case EXR_ZIP16:
1602         s->scan_lines_per_block = 16;
1603         break;
1604     case EXR_PIZ:
1605     case EXR_B44:
1606     case EXR_B44A:
1607         s->scan_lines_per_block = 32;
1608         break;
1609     default:
1610         avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1611         return AVERROR_PATCHWELCOME;
1612     }
1613
1614     /* Verify the xmin, xmax, ymin, ymax and xdelta before setting
1615      * the actual image size. */
1616     if (s->xmin > s->xmax                  ||
1617         s->ymin > s->ymax                  ||
1618         s->xdelta != s->xmax - s->xmin + 1 ||
1619         s->xmax >= s->w                    ||
1620         s->ymax >= s->h) {
1621         av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1622         return AVERROR_INVALIDDATA;
1623     }
1624
1625     if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1626         return ret;
1627
1628     s->desc          = av_pix_fmt_desc_get(avctx->pix_fmt);
1629     if (!s->desc)
1630         return AVERROR_INVALIDDATA;
1631     out_line_size    = avctx->width * 2 * s->desc->nb_components;
1632
1633     if (s->is_tile) {
1634         nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
1635         ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
1636     } else { /* scanline */
1637         nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1638         s->scan_lines_per_block;
1639     }
1640
1641     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1642         return ret;
1643
1644     if (bytestream2_get_bytes_left(&s->gb) < nb_blocks * 8)
1645         return AVERROR_INVALIDDATA;
1646
1647     // save pointer we are going to use in decode_block
1648     s->buf      = avpkt->data;
1649     s->buf_size = avpkt->size;
1650     ptr         = picture->data[0];
1651
1652     // Zero out the start if ymin is not 0
1653     for (y = 0; y < s->ymin; y++) {
1654         memset(ptr, 0, out_line_size);
1655         ptr += picture->linesize[0];
1656     }
1657
1658     s->picture = picture;
1659
1660     avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
1661
1662     // Zero out the end if ymax+1 is not h
1663     for (y = s->ymax + 1; y < avctx->height; y++) {
1664         memset(ptr, 0, out_line_size);
1665         ptr += picture->linesize[0];
1666     }
1667
1668     picture->pict_type = AV_PICTURE_TYPE_I;
1669     *got_frame = 1;
1670
1671     return avpkt->size;
1672 }
1673
1674 static av_cold int decode_init(AVCodecContext *avctx)
1675 {
1676     EXRContext *s = avctx->priv_data;
1677     uint32_t i;
1678     union av_intfloat32 t;
1679     float one_gamma = 1.0f / s->gamma;
1680     avpriv_trc_function trc_func = NULL;
1681
1682     s->avctx              = avctx;
1683
1684     trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1685     if (trc_func) {
1686         for (i = 0; i < 65536; ++i) {
1687             t = exr_half2float(i);
1688             t.f = trc_func(t.f);
1689             s->gamma_table[i] = exr_flt2uint(t.i);
1690         }
1691     } else {
1692         if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1693             for (i = 0; i < 65536; ++i)
1694                 s->gamma_table[i] = exr_halflt2uint(i);
1695         } else {
1696             for (i = 0; i < 65536; ++i) {
1697                 t = exr_half2float(i);
1698                 /* If negative value we reuse half value */
1699                 if (t.f <= 0.0f) {
1700                     s->gamma_table[i] = exr_halflt2uint(i);
1701                 } else {
1702                     t.f = powf(t.f, one_gamma);
1703                     s->gamma_table[i] = exr_flt2uint(t.i);
1704                 }
1705             }
1706         }
1707     }
1708
1709     // allocate thread data, used for non EXR_RAW compreesion types
1710     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1711     if (!s->thread_data)
1712         return AVERROR_INVALIDDATA;
1713
1714     return 0;
1715 }
1716
1717 #if HAVE_THREADS
1718 static int decode_init_thread_copy(AVCodecContext *avctx)
1719 {    EXRContext *s = avctx->priv_data;
1720
1721     // allocate thread data, used for non EXR_RAW compreesion types
1722     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1723     if (!s->thread_data)
1724         return AVERROR_INVALIDDATA;
1725
1726     return 0;
1727 }
1728 #endif
1729
1730 static av_cold int decode_end(AVCodecContext *avctx)
1731 {
1732     EXRContext *s = avctx->priv_data;
1733     int i;
1734     for (i = 0; i < avctx->thread_count; i++) {
1735         EXRThreadData *td = &s->thread_data[i];
1736         av_freep(&td->uncompressed_data);
1737         av_freep(&td->tmp);
1738         av_freep(&td->bitmap);
1739         av_freep(&td->lut);
1740     }
1741
1742     av_freep(&s->thread_data);
1743     av_freep(&s->channels);
1744
1745     return 0;
1746 }
1747
1748 #define OFFSET(x) offsetof(EXRContext, x)
1749 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1750 static const AVOption options[] = {
1751     { "layer", "Set the decoding layer", OFFSET(layer),
1752         AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
1753     { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
1754         AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
1755
1756     // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
1757     { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
1758         AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
1759     { "bt709",        "BT.709",           0,
1760         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 },        INT_MIN, INT_MAX, VD, "apply_trc_type"},
1761     { "gamma",        "gamma",            0,
1762         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED },  INT_MIN, INT_MAX, VD, "apply_trc_type"},
1763     { "gamma22",      "BT.470 M",         0,
1764         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 },      INT_MIN, INT_MAX, VD, "apply_trc_type"},
1765     { "gamma28",      "BT.470 BG",        0,
1766         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 },      INT_MIN, INT_MAX, VD, "apply_trc_type"},
1767     { "smpte170m",    "SMPTE 170 M",      0,
1768         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1769     { "smpte240m",    "SMPTE 240 M",      0,
1770         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1771     { "linear",       "Linear",           0,
1772         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR },       INT_MIN, INT_MAX, VD, "apply_trc_type"},
1773     { "log",          "Log",              0,
1774         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG },          INT_MIN, INT_MAX, VD, "apply_trc_type"},
1775     { "log_sqrt",     "Log square root",  0,
1776         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT },     INT_MIN, INT_MAX, VD, "apply_trc_type"},
1777     { "iec61966_2_4", "IEC 61966-2-4",    0,
1778         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1779     { "bt1361",       "BT.1361",          0,
1780         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG },   INT_MIN, INT_MAX, VD, "apply_trc_type"},
1781     { "iec61966_2_1", "IEC 61966-2-1",    0,
1782         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1783     { "bt2020_10bit", "BT.2020 - 10 bit", 0,
1784         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1785     { "bt2020_12bit", "BT.2020 - 12 bit", 0,
1786         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1787     { "smpte2084",    "SMPTE ST 2084",    0,
1788         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 },  INT_MIN, INT_MAX, VD, "apply_trc_type"},
1789     { "smpte428_1",   "SMPTE ST 428-1",   0,
1790         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1791
1792     { NULL },
1793 };
1794
1795 static const AVClass exr_class = {
1796     .class_name = "EXR",
1797     .item_name  = av_default_item_name,
1798     .option     = options,
1799     .version    = LIBAVUTIL_VERSION_INT,
1800 };
1801
1802 AVCodec ff_exr_decoder = {
1803     .name             = "exr",
1804     .long_name        = NULL_IF_CONFIG_SMALL("OpenEXR image"),
1805     .type             = AVMEDIA_TYPE_VIDEO,
1806     .id               = AV_CODEC_ID_EXR,
1807     .priv_data_size   = sizeof(EXRContext),
1808     .init             = decode_init,
1809     .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1810     .close            = decode_end,
1811     .decode           = decode_frame,
1812     .capabilities     = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
1813                         AV_CODEC_CAP_SLICE_THREADS,
1814     .priv_class       = &exr_class,
1815 };