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