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