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