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