]> git.sesse.net Git - ffmpeg/blob - libavcodec/exr.c
avcodec/exr: refactor GetByteContext usage
[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     GetByteContext *gb = &s->gb;
1280
1281     while (bytestream2_get_bytes_left(gb) > 0) {
1282         if (!bytestream2_peek_byte(gb))
1283             break;
1284
1285         // Process unknown variables
1286         for (int i = 0; i < 2; i++) // value_name and value_type
1287             while (bytestream2_get_byte(gb) != 0);
1288
1289         // Skip variable length
1290         bytestream2_skip(gb, bytestream2_get_le32(gb));
1291     }
1292 }
1293
1294 /**
1295  * Check if the variable name corresponds to its data type.
1296  *
1297  * @param s              the EXRContext
1298  * @param value_name     name of the variable to check
1299  * @param value_type     type of the variable to check
1300  * @param minimum_length minimum length of the variable data
1301  *
1302  * @return bytes to read containing variable data
1303  *         -1 if variable is not found
1304  *         0 if buffer ended prematurely
1305  */
1306 static int check_header_variable(EXRContext *s,
1307                                  const char *value_name,
1308                                  const char *value_type,
1309                                  unsigned int minimum_length)
1310 {
1311     GetByteContext *gb = &s->gb;
1312     int var_size = -1;
1313
1314     if (bytestream2_get_bytes_left(gb) >= minimum_length &&
1315         !strcmp(gb->buffer, value_name)) {
1316         // found value_name, jump to value_type (null terminated strings)
1317         gb->buffer += strlen(value_name) + 1;
1318         if (!strcmp(gb->buffer, value_type)) {
1319             gb->buffer += strlen(value_type) + 1;
1320             var_size = bytestream2_get_le32(gb);
1321             // don't go read past boundaries
1322             if (var_size > bytestream2_get_bytes_left(gb))
1323                 var_size = 0;
1324         } else {
1325             // value_type not found, reset the buffer
1326             gb->buffer -= strlen(value_name) + 1;
1327             av_log(s->avctx, AV_LOG_WARNING,
1328                    "Unknown data type %s for header variable %s.\n",
1329                    value_type, value_name);
1330         }
1331     }
1332
1333     return var_size;
1334 }
1335
1336 static int decode_header(EXRContext *s, AVFrame *frame)
1337 {
1338     AVDictionary *metadata = NULL;
1339     GetByteContext *gb = &s->gb;
1340     int magic_number, version, i, flags;
1341     int layer_match = 0;
1342     int ret;
1343     int dup_channels = 0;
1344
1345     s->current_channel_offset = 0;
1346     s->xmin               = ~0;
1347     s->xmax               = ~0;
1348     s->ymin               = ~0;
1349     s->ymax               = ~0;
1350     s->xdelta             = ~0;
1351     s->ydelta             = ~0;
1352     s->channel_offsets[0] = -1;
1353     s->channel_offsets[1] = -1;
1354     s->channel_offsets[2] = -1;
1355     s->channel_offsets[3] = -1;
1356     s->pixel_type         = EXR_UNKNOWN;
1357     s->compression        = EXR_UNKN;
1358     s->nb_channels        = 0;
1359     s->w                  = 0;
1360     s->h                  = 0;
1361     s->tile_attr.xSize    = -1;
1362     s->tile_attr.ySize    = -1;
1363     s->is_tile            = 0;
1364     s->is_multipart       = 0;
1365     s->is_luma            = 0;
1366     s->current_part       = 0;
1367
1368     if (bytestream2_get_bytes_left(gb) < 10) {
1369         av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1370         return AVERROR_INVALIDDATA;
1371     }
1372
1373     magic_number = bytestream2_get_le32(gb);
1374     if (magic_number != 20000630) {
1375         /* As per documentation of OpenEXR, it is supposed to be
1376          * int 20000630 little-endian */
1377         av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1378         return AVERROR_INVALIDDATA;
1379     }
1380
1381     version = bytestream2_get_byte(gb);
1382     if (version != 2) {
1383         avpriv_report_missing_feature(s->avctx, "Version %d", version);
1384         return AVERROR_PATCHWELCOME;
1385     }
1386
1387     flags = bytestream2_get_le24(gb);
1388
1389     if (flags & 0x02)
1390         s->is_tile = 1;
1391     if (flags & 0x10)
1392         s->is_multipart = 1;
1393     if (flags & 0x08) {
1394         avpriv_report_missing_feature(s->avctx, "deep data");
1395         return AVERROR_PATCHWELCOME;
1396     }
1397
1398     // Parse the header
1399     while (bytestream2_get_bytes_left(gb) > 0) {
1400         int var_size;
1401
1402         while (s->is_multipart && s->current_part < s->selected_part &&
1403                bytestream2_get_bytes_left(gb) > 0) {
1404             if (bytestream2_peek_byte(gb)) {
1405                 skip_header_chunk(s);
1406             } else {
1407                 bytestream2_skip(gb, 1);
1408                 if (!bytestream2_peek_byte(gb))
1409                     break;
1410             }
1411             bytestream2_skip(gb, 1);
1412             s->current_part++;
1413         }
1414
1415         if (!bytestream2_peek_byte(gb)) {
1416             if (!s->is_multipart)
1417                 break;
1418             bytestream2_skip(gb, 1);
1419             if (s->current_part == s->selected_part) {
1420                 while (bytestream2_get_bytes_left(gb) > 0) {
1421                     if (bytestream2_peek_byte(gb)) {
1422                         skip_header_chunk(s);
1423                     } else {
1424                         bytestream2_skip(gb, 1);
1425                         if (!bytestream2_peek_byte(gb))
1426                             break;
1427                     }
1428                 }
1429             }
1430             if (!bytestream2_peek_byte(gb))
1431                 break;
1432             s->current_part++;
1433         }
1434
1435         if ((var_size = check_header_variable(s, "channels",
1436                                               "chlist", 38)) >= 0) {
1437             GetByteContext ch_gb;
1438             if (!var_size) {
1439                 ret = AVERROR_INVALIDDATA;
1440                 goto fail;
1441             }
1442
1443             bytestream2_init(&ch_gb, gb->buffer, var_size);
1444
1445             while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1446                 EXRChannel *channel;
1447                 enum ExrPixelType current_pixel_type;
1448                 int channel_index = -1;
1449                 int xsub, ysub;
1450
1451                 if (strcmp(s->layer, "") != 0) {
1452                     if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1453                         layer_match = 1;
1454                         av_log(s->avctx, AV_LOG_INFO,
1455                                "Channel match layer : %s.\n", ch_gb.buffer);
1456                         ch_gb.buffer += strlen(s->layer);
1457                         if (*ch_gb.buffer == '.')
1458                             ch_gb.buffer++;         /* skip dot if not given */
1459                     } else {
1460                         layer_match = 0;
1461                         av_log(s->avctx, AV_LOG_INFO,
1462                                "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1463                     }
1464                 } else {
1465                     layer_match = 1;
1466                 }
1467
1468                 if (layer_match) { /* only search channel if the layer match is valid */
1469                     if (!av_strcasecmp(ch_gb.buffer, "R") ||
1470                         !av_strcasecmp(ch_gb.buffer, "X") ||
1471                         !av_strcasecmp(ch_gb.buffer, "U")) {
1472                         channel_index = 0;
1473                         s->is_luma = 0;
1474                     } else if (!av_strcasecmp(ch_gb.buffer, "G") ||
1475                                !av_strcasecmp(ch_gb.buffer, "V")) {
1476                         channel_index = 1;
1477                         s->is_luma = 0;
1478                     } else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
1479                         channel_index = 1;
1480                         s->is_luma = 1;
1481                     } else if (!av_strcasecmp(ch_gb.buffer, "B") ||
1482                                !av_strcasecmp(ch_gb.buffer, "Z") ||
1483                                !av_strcasecmp(ch_gb.buffer, "W")) {
1484                         channel_index = 2;
1485                         s->is_luma = 0;
1486                     } else if (!av_strcasecmp(ch_gb.buffer, "A")) {
1487                         channel_index = 3;
1488                     } else {
1489                         av_log(s->avctx, AV_LOG_WARNING,
1490                                "Unsupported channel %.256s.\n", ch_gb.buffer);
1491                     }
1492                 }
1493
1494                 /* skip until you get a 0 */
1495                 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1496                        bytestream2_get_byte(&ch_gb))
1497                     continue;
1498
1499                 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1500                     av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1501                     ret = AVERROR_INVALIDDATA;
1502                     goto fail;
1503                 }
1504
1505                 current_pixel_type = bytestream2_get_le32(&ch_gb);
1506                 if (current_pixel_type >= EXR_UNKNOWN) {
1507                     avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1508                                                   current_pixel_type);
1509                     ret = AVERROR_PATCHWELCOME;
1510                     goto fail;
1511                 }
1512
1513                 bytestream2_skip(&ch_gb, 4);
1514                 xsub = bytestream2_get_le32(&ch_gb);
1515                 ysub = bytestream2_get_le32(&ch_gb);
1516
1517                 if (xsub != 1 || ysub != 1) {
1518                     avpriv_report_missing_feature(s->avctx,
1519                                                   "Subsampling %dx%d",
1520                                                   xsub, ysub);
1521                     ret = AVERROR_PATCHWELCOME;
1522                     goto fail;
1523                 }
1524
1525                 if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */
1526                     if (s->pixel_type != EXR_UNKNOWN &&
1527                         s->pixel_type != current_pixel_type) {
1528                         av_log(s->avctx, AV_LOG_ERROR,
1529                                "RGB channels not of the same depth.\n");
1530                         ret = AVERROR_INVALIDDATA;
1531                         goto fail;
1532                     }
1533                     s->pixel_type                     = current_pixel_type;
1534                     s->channel_offsets[channel_index] = s->current_channel_offset;
1535                 } else if (channel_index >= 0) {
1536                     av_log(s->avctx, AV_LOG_WARNING,
1537                             "Multiple channels with index %d.\n", channel_index);
1538                     if (++dup_channels > 10) {
1539                         ret = AVERROR_INVALIDDATA;
1540                         goto fail;
1541                     }
1542                 }
1543
1544                 s->channels = av_realloc(s->channels,
1545                                          ++s->nb_channels * sizeof(EXRChannel));
1546                 if (!s->channels) {
1547                     ret = AVERROR(ENOMEM);
1548                     goto fail;
1549                 }
1550                 channel             = &s->channels[s->nb_channels - 1];
1551                 channel->pixel_type = current_pixel_type;
1552                 channel->xsub       = xsub;
1553                 channel->ysub       = ysub;
1554
1555                 if (current_pixel_type == EXR_HALF) {
1556                     s->current_channel_offset += 2;
1557                 } else {/* Float or UINT32 */
1558                     s->current_channel_offset += 4;
1559                 }
1560             }
1561
1562             /* Check if all channels are set with an offset or if the channels
1563              * are causing an overflow  */
1564             if (!s->is_luma) {/* if we expected to have at least 3 channels */
1565                 if (FFMIN3(s->channel_offsets[0],
1566                            s->channel_offsets[1],
1567                            s->channel_offsets[2]) < 0) {
1568                     if (s->channel_offsets[0] < 0)
1569                         av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1570                     if (s->channel_offsets[1] < 0)
1571                         av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1572                     if (s->channel_offsets[2] < 0)
1573                         av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1574                     ret = AVERROR_INVALIDDATA;
1575                     goto fail;
1576                 }
1577             }
1578
1579             // skip one last byte and update main gb
1580             gb->buffer = ch_gb.buffer + 1;
1581             continue;
1582         } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1583                                                      31)) >= 0) {
1584             int xmin, ymin, xmax, ymax;
1585             if (!var_size) {
1586                 ret = AVERROR_INVALIDDATA;
1587                 goto fail;
1588             }
1589
1590             xmin   = bytestream2_get_le32(gb);
1591             ymin   = bytestream2_get_le32(gb);
1592             xmax   = bytestream2_get_le32(gb);
1593             ymax   = bytestream2_get_le32(gb);
1594
1595             if (xmin > xmax || ymin > ymax ||
1596                 (unsigned)xmax - xmin >= INT_MAX ||
1597                 (unsigned)ymax - ymin >= INT_MAX) {
1598                 ret = AVERROR_INVALIDDATA;
1599                 goto fail;
1600             }
1601             s->xmin = xmin;
1602             s->xmax = xmax;
1603             s->ymin = ymin;
1604             s->ymax = ymax;
1605             s->xdelta = (s->xmax - s->xmin) + 1;
1606             s->ydelta = (s->ymax - s->ymin) + 1;
1607
1608             continue;
1609         } else if ((var_size = check_header_variable(s, "displayWindow",
1610                                                      "box2i", 34)) >= 0) {
1611             int32_t sx, sy, dx, dy;
1612
1613             if (!var_size) {
1614                 ret = AVERROR_INVALIDDATA;
1615                 goto fail;
1616             }
1617
1618             sx = bytestream2_get_le32(gb);
1619             sy = bytestream2_get_le32(gb);
1620             dx = bytestream2_get_le32(gb);
1621             dy = bytestream2_get_le32(gb);
1622
1623             s->w = dx - sx + 1;
1624             s->h = dy - sy + 1;
1625
1626             continue;
1627         } else if ((var_size = check_header_variable(s, "lineOrder",
1628                                                      "lineOrder", 25)) >= 0) {
1629             int line_order;
1630             if (!var_size) {
1631                 ret = AVERROR_INVALIDDATA;
1632                 goto fail;
1633             }
1634
1635             line_order = bytestream2_get_byte(gb);
1636             av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1637             if (line_order > 2) {
1638                 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1639                 ret = AVERROR_INVALIDDATA;
1640                 goto fail;
1641             }
1642
1643             continue;
1644         } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1645                                                      "float", 31)) >= 0) {
1646             if (!var_size) {
1647                 ret = AVERROR_INVALIDDATA;
1648                 goto fail;
1649             }
1650
1651             s->sar = bytestream2_get_le32(gb);
1652
1653             continue;
1654         } else if ((var_size = check_header_variable(s, "compression",
1655                                                      "compression", 29)) >= 0) {
1656             if (!var_size) {
1657                 ret = AVERROR_INVALIDDATA;
1658                 goto fail;
1659             }
1660
1661             if (s->compression == EXR_UNKN)
1662                 s->compression = bytestream2_get_byte(gb);
1663             else {
1664                 bytestream2_skip(gb, 1);
1665                 av_log(s->avctx, AV_LOG_WARNING,
1666                        "Found more than one compression attribute.\n");
1667             }
1668
1669             continue;
1670         } else if ((var_size = check_header_variable(s, "tiles",
1671                                                      "tiledesc", 22)) >= 0) {
1672             char tileLevel;
1673
1674             if (!s->is_tile)
1675                 av_log(s->avctx, AV_LOG_WARNING,
1676                        "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
1677
1678             s->tile_attr.xSize = bytestream2_get_le32(gb);
1679             s->tile_attr.ySize = bytestream2_get_le32(gb);
1680
1681             tileLevel = bytestream2_get_byte(gb);
1682             s->tile_attr.level_mode = tileLevel & 0x0f;
1683             s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
1684
1685             if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) {
1686                 avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
1687                                               s->tile_attr.level_mode);
1688                 ret = AVERROR_PATCHWELCOME;
1689                 goto fail;
1690             }
1691
1692             if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
1693                 avpriv_report_missing_feature(s->avctx, "Tile level round %d",
1694                                               s->tile_attr.level_round);
1695                 ret = AVERROR_PATCHWELCOME;
1696                 goto fail;
1697             }
1698
1699             continue;
1700         } else if ((var_size = check_header_variable(s, "writer",
1701                                                      "string", 1)) >= 0) {
1702             uint8_t key[256] = { 0 };
1703
1704             bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1705             av_dict_set(&metadata, "writer", key, 0);
1706
1707             continue;
1708         } else if ((var_size = check_header_variable(s, "framesPerSecond",
1709                                                      "rational", 33)) >= 0) {
1710             if (!var_size) {
1711                 ret = AVERROR_INVALIDDATA;
1712                 goto fail;
1713             }
1714
1715             s->avctx->framerate.num = bytestream2_get_le32(gb);
1716             s->avctx->framerate.den = bytestream2_get_le32(gb);
1717
1718             continue;
1719         } else if ((var_size = check_header_variable(s, "chunkCount",
1720                                                      "int", 23)) >= 0) {
1721
1722             s->chunk_count = bytestream2_get_le32(gb);
1723
1724             continue;
1725         } else if ((var_size = check_header_variable(s, "type",
1726                                                      "string", 16)) >= 0) {
1727             uint8_t key[256] = { 0 };
1728
1729             bytestream2_get_buffer(gb, key, FFMIN(sizeof(key) - 1, var_size));
1730             if (strncmp("scanlineimage", key, var_size) &&
1731                 strncmp("tiledimage", key, var_size))
1732                 return AVERROR_PATCHWELCOME;
1733
1734             continue;
1735         }
1736
1737         // Check if there are enough bytes for a header
1738         if (bytestream2_get_bytes_left(gb) <= 9) {
1739             av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1740             ret = AVERROR_INVALIDDATA;
1741             goto fail;
1742         }
1743
1744         // Process unknown variables
1745         for (i = 0; i < 2; i++) // value_name and value_type
1746             while (bytestream2_get_byte(gb) != 0);
1747
1748         // Skip variable length
1749         bytestream2_skip(gb, bytestream2_get_le32(gb));
1750     }
1751
1752     if (s->compression == EXR_UNKN) {
1753         av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1754         ret = AVERROR_INVALIDDATA;
1755         goto fail;
1756     }
1757
1758     if (s->is_tile) {
1759         if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1760             av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1761             ret = AVERROR_INVALIDDATA;
1762             goto fail;
1763         }
1764     }
1765
1766     if (bytestream2_get_bytes_left(gb) <= 0) {
1767         av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1768         ret = AVERROR_INVALIDDATA;
1769         goto fail;
1770     }
1771
1772     frame->metadata = metadata;
1773
1774     // aaand we are done
1775     bytestream2_skip(gb, 1);
1776     return 0;
1777 fail:
1778     av_dict_free(&metadata);
1779     return ret;
1780 }
1781
1782 static int decode_frame(AVCodecContext *avctx, void *data,
1783                         int *got_frame, AVPacket *avpkt)
1784 {
1785     EXRContext *s = avctx->priv_data;
1786     GetByteContext *gb = &s->gb;
1787     ThreadFrame frame = { .f = data };
1788     AVFrame *picture = data;
1789     uint8_t *ptr;
1790
1791     int i, y, ret, ymax;
1792     int planes;
1793     int out_line_size;
1794     int nb_blocks;   /* nb scanline or nb tile */
1795     uint64_t start_offset_table;
1796     uint64_t start_next_scanline;
1797     PutByteContext offset_table_writer;
1798
1799     bytestream2_init(gb, avpkt->data, avpkt->size);
1800
1801     if ((ret = decode_header(s, picture)) < 0)
1802         return ret;
1803
1804     switch (s->pixel_type) {
1805     case EXR_FLOAT:
1806     case EXR_HALF:
1807         if (s->channel_offsets[3] >= 0) {
1808             if (!s->is_luma) {
1809                 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1810             } else {
1811                 /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1812                 avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1813             }
1814         } else {
1815             if (!s->is_luma) {
1816                 avctx->pix_fmt = AV_PIX_FMT_GBRPF32;
1817             } else {
1818                 avctx->pix_fmt = AV_PIX_FMT_GRAYF32;
1819             }
1820         }
1821         break;
1822     case EXR_UINT:
1823         if (s->channel_offsets[3] >= 0) {
1824             if (!s->is_luma) {
1825                 avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1826             } else {
1827                 avctx->pix_fmt = AV_PIX_FMT_YA16;
1828             }
1829         } else {
1830             if (!s->is_luma) {
1831                 avctx->pix_fmt = AV_PIX_FMT_RGB48;
1832             } else {
1833                 avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1834             }
1835         }
1836         break;
1837     default:
1838         av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1839         return AVERROR_INVALIDDATA;
1840     }
1841
1842     if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1843         avctx->color_trc = s->apply_trc_type;
1844
1845     switch (s->compression) {
1846     case EXR_RAW:
1847     case EXR_RLE:
1848     case EXR_ZIP1:
1849         s->scan_lines_per_block = 1;
1850         break;
1851     case EXR_PXR24:
1852     case EXR_ZIP16:
1853         s->scan_lines_per_block = 16;
1854         break;
1855     case EXR_PIZ:
1856     case EXR_B44:
1857     case EXR_B44A:
1858         s->scan_lines_per_block = 32;
1859         break;
1860     default:
1861         avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1862         return AVERROR_PATCHWELCOME;
1863     }
1864
1865     /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.
1866      * It's possible for the data window can larger or outside the display window */
1867     if (s->xmin > s->xmax  || s->ymin > s->ymax ||
1868         s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {
1869         av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1870         return AVERROR_INVALIDDATA;
1871     }
1872
1873     if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1874         return ret;
1875
1876     ff_set_sar(s->avctx, av_d2q(av_int2float(s->sar), 255));
1877
1878     s->desc          = av_pix_fmt_desc_get(avctx->pix_fmt);
1879     if (!s->desc)
1880         return AVERROR_INVALIDDATA;
1881
1882     if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1883         planes           = s->desc->nb_components;
1884         out_line_size    = avctx->width * 4;
1885     } else {
1886         planes           = 1;
1887         out_line_size    = avctx->width * 2 * s->desc->nb_components;
1888     }
1889
1890     if (s->is_tile) {
1891         nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
1892         ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
1893     } else { /* scanline */
1894         nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1895         s->scan_lines_per_block;
1896     }
1897
1898     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1899         return ret;
1900
1901     if (bytestream2_get_bytes_left(gb)/8 < nb_blocks)
1902         return AVERROR_INVALIDDATA;
1903
1904     // check offset table and recreate it if need
1905     if (!s->is_tile && bytestream2_peek_le64(gb) == 0) {
1906         av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n");
1907
1908         start_offset_table = bytestream2_tell(gb);
1909         start_next_scanline = start_offset_table + nb_blocks * 8;
1910         bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);
1911
1912         for (y = 0; y < nb_blocks; y++) {
1913             /* write offset of prev scanline in offset table */
1914             bytestream2_put_le64(&offset_table_writer, start_next_scanline);
1915
1916             /* get len of next scanline */
1917             bytestream2_seek(gb, start_next_scanline + 4, SEEK_SET);/* skip line number */
1918             start_next_scanline += (bytestream2_get_le32(gb) + 8);
1919         }
1920         bytestream2_seek(gb, start_offset_table, SEEK_SET);
1921     }
1922
1923     // save pointer we are going to use in decode_block
1924     s->buf      = avpkt->data;
1925     s->buf_size = avpkt->size;
1926
1927     // Zero out the start if ymin is not 0
1928     for (i = 0; i < planes; i++) {
1929         ptr = picture->data[i];
1930         for (y = 0; y < FFMIN(s->ymin, s->h); y++) {
1931             memset(ptr, 0, out_line_size);
1932             ptr += picture->linesize[i];
1933         }
1934     }
1935
1936     s->picture = picture;
1937
1938     avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
1939
1940     ymax = FFMAX(0, s->ymax + 1);
1941     // Zero out the end if ymax+1 is not h
1942     if (ymax < avctx->height)
1943         for (i = 0; i < planes; i++) {
1944             ptr = picture->data[i] + (ymax * picture->linesize[i]);
1945             for (y = ymax; y < avctx->height; y++) {
1946                 memset(ptr, 0, out_line_size);
1947                 ptr += picture->linesize[i];
1948             }
1949         }
1950
1951     picture->pict_type = AV_PICTURE_TYPE_I;
1952     *got_frame = 1;
1953
1954     return avpkt->size;
1955 }
1956
1957 static av_cold int decode_init(AVCodecContext *avctx)
1958 {
1959     EXRContext *s = avctx->priv_data;
1960     uint32_t i;
1961     union av_intfloat32 t;
1962     float one_gamma = 1.0f / s->gamma;
1963     avpriv_trc_function trc_func = NULL;
1964
1965     s->avctx              = avctx;
1966
1967     ff_exrdsp_init(&s->dsp);
1968
1969 #if HAVE_BIGENDIAN
1970     ff_bswapdsp_init(&s->bbdsp);
1971 #endif
1972
1973     trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1974     if (trc_func) {
1975         for (i = 0; i < 65536; ++i) {
1976             t = exr_half2float(i);
1977             t.f = trc_func(t.f);
1978             s->gamma_table[i] = t;
1979         }
1980     } else {
1981         if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1982             for (i = 0; i < 65536; ++i) {
1983                 s->gamma_table[i] = exr_half2float(i);
1984             }
1985         } else {
1986             for (i = 0; i < 65536; ++i) {
1987                 t = exr_half2float(i);
1988                 /* If negative value we reuse half value */
1989                 if (t.f <= 0.0f) {
1990                     s->gamma_table[i] = t;
1991                 } else {
1992                     t.f = powf(t.f, one_gamma);
1993                     s->gamma_table[i] = t;
1994                 }
1995             }
1996         }
1997     }
1998
1999     // allocate thread data, used for non EXR_RAW compression types
2000     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
2001     if (!s->thread_data)
2002         return AVERROR_INVALIDDATA;
2003
2004     return 0;
2005 }
2006
2007 static av_cold int decode_end(AVCodecContext *avctx)
2008 {
2009     EXRContext *s = avctx->priv_data;
2010     int i;
2011     for (i = 0; i < avctx->thread_count; i++) {
2012         EXRThreadData *td = &s->thread_data[i];
2013         av_freep(&td->uncompressed_data);
2014         av_freep(&td->tmp);
2015         av_freep(&td->bitmap);
2016         av_freep(&td->lut);
2017     }
2018
2019     av_freep(&s->thread_data);
2020     av_freep(&s->channels);
2021
2022     return 0;
2023 }
2024
2025 #define OFFSET(x) offsetof(EXRContext, x)
2026 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2027 static const AVOption options[] = {
2028     { "layer", "Set the decoding layer", OFFSET(layer),
2029         AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
2030     { "part",  "Set the decoding part", OFFSET(selected_part),
2031         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VD },
2032     { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
2033         AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
2034
2035     // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
2036     { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
2037         AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
2038     { "bt709",        "BT.709",           0,
2039         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 },        INT_MIN, INT_MAX, VD, "apply_trc_type"},
2040     { "gamma",        "gamma",            0,
2041         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED },  INT_MIN, INT_MAX, VD, "apply_trc_type"},
2042     { "gamma22",      "BT.470 M",         0,
2043         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 },      INT_MIN, INT_MAX, VD, "apply_trc_type"},
2044     { "gamma28",      "BT.470 BG",        0,
2045         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 },      INT_MIN, INT_MAX, VD, "apply_trc_type"},
2046     { "smpte170m",    "SMPTE 170 M",      0,
2047         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
2048     { "smpte240m",    "SMPTE 240 M",      0,
2049         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
2050     { "linear",       "Linear",           0,
2051         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR },       INT_MIN, INT_MAX, VD, "apply_trc_type"},
2052     { "log",          "Log",              0,
2053         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG },          INT_MIN, INT_MAX, VD, "apply_trc_type"},
2054     { "log_sqrt",     "Log square root",  0,
2055         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT },     INT_MIN, INT_MAX, VD, "apply_trc_type"},
2056     { "iec61966_2_4", "IEC 61966-2-4",    0,
2057         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2058     { "bt1361",       "BT.1361",          0,
2059         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG },   INT_MIN, INT_MAX, VD, "apply_trc_type"},
2060     { "iec61966_2_1", "IEC 61966-2-1",    0,
2061         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2062     { "bt2020_10bit", "BT.2020 - 10 bit", 0,
2063         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
2064     { "bt2020_12bit", "BT.2020 - 12 bit", 0,
2065         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
2066     { "smpte2084",    "SMPTE ST 2084",    0,
2067         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 },  INT_MIN, INT_MAX, VD, "apply_trc_type"},
2068     { "smpte428_1",   "SMPTE ST 428-1",   0,
2069         AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
2070
2071     { NULL },
2072 };
2073
2074 static const AVClass exr_class = {
2075     .class_name = "EXR",
2076     .item_name  = av_default_item_name,
2077     .option     = options,
2078     .version    = LIBAVUTIL_VERSION_INT,
2079 };
2080
2081 AVCodec ff_exr_decoder = {
2082     .name             = "exr",
2083     .long_name        = NULL_IF_CONFIG_SMALL("OpenEXR image"),
2084     .type             = AVMEDIA_TYPE_VIDEO,
2085     .id               = AV_CODEC_ID_EXR,
2086     .priv_data_size   = sizeof(EXRContext),
2087     .init             = decode_init,
2088     .close            = decode_end,
2089     .decode           = decode_frame,
2090     .capabilities     = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
2091                         AV_CODEC_CAP_SLICE_THREADS,
2092     .priv_class       = &exr_class,
2093 };