1 /*
2  * OpenEXR (.exr) image decoder
3  * Copyright (c) 2009 Jimmy Christensen
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * OpenEXR decoder
25  * @author Jimmy Christensen
26  *
27  * For more information on the OpenEXR format, visit:
28  *  http://openexr.com/
29  *
30  * exr_flt2uint() and exr_halflt2uint() is credited to  Reimar Döffinger.
31  * exr_half2float() is credited to Aaftab Munshi; Dan Ginsburg, Dave Shreiner.
32  *
33  */
34 
35 #include <zconf.h>
36 #ifdef Z_HAVE_STDARG_H
37 #include <stdarg.h>
38 #endif
39 #include <zlib.h>
40 #include <float.h>
41 
42 #include "libavutil/imgutils.h"
43 #include "libavutil/opt.h"
44 #include "libavutil/intfloat.h"
45 
46 #include "avcodec.h"
47 #include "bytestream.h"
48 #include "get_bits.h"
49 #include "internal.h"
50 #include "mathops.h"
51 #include "thread.h"
52 
53 enum ExrCompr {
54     EXR_RAW,
55     EXR_RLE,
56     EXR_ZIP1,
57     EXR_ZIP16,
58     EXR_PIZ,
59     EXR_PXR24,
60     EXR_B44,
61     EXR_B44A,
62     EXR_UNKN,
63 };
64 
65 enum ExrPixelType {
66     EXR_UINT,
67     EXR_HALF,
68     EXR_FLOAT,
69     EXR_UNKNOWN,
70 };
71 
72 typedef struct EXRChannel {
73     int xsub, ysub;
74     enum ExrPixelType pixel_type;
75 } EXRChannel;
76 
77 typedef struct EXRThreadData {
78     uint8_t *uncompressed_data;
79     int uncompressed_size;
80 
81     uint8_t *tmp;
82     int tmp_size;
83 
84     uint8_t *bitmap;
85     uint16_t *lut;
86 } EXRThreadData;
87 
88 typedef struct EXRContext {
89     AVClass *class;
90     AVFrame *picture;
91     AVCodecContext *avctx;
92 
93     enum ExrCompr compression;
94     enum ExrPixelType pixel_type;
95     int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
96     const AVPixFmtDescriptor *desc;
97 
98     int w, h;
99     uint32_t xmax, xmin;
100     uint32_t ymax, ymin;
101     uint32_t xdelta, ydelta;
102     int ysize;
103 
104     uint64_t scan_line_size;
105     int scan_lines_per_block;
106 
107     GetByteContext gb;
108     const uint8_t *buf;
109     int buf_size;
110 
111     EXRChannel *channels;
112     int nb_channels;
113 
114     EXRThreadData *thread_data;
115 
116     const char *layer;
117 
118     float gamma;
119 
120     uint16_t gamma_table[65536];
121 
122 } EXRContext;
123 
124 /* -15 stored using a single precision bias of 127 */
125 #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
126 /* max exponent value in single precision that will be converted
127  * to Inf or Nan when stored as a half-float */
128 #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
129 
130 /* 255 is the max exponent biased value */
131 #define FLOAT_MAX_BIASED_EXP (0xFF << 23)
132 
133 #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
134 
135 /*
136  * Convert a half float as a uint16_t into a full float.
137  *
138  * @param hf half float as uint16_t
139  *
140  * @return float value
141  */
exr_half2float(uint16_t hf)142 static union av_intfloat32 exr_half2float(uint16_t hf)
143 {
144     unsigned int    sign = (unsigned int)(hf >> 15);
145     unsigned int    mantissa = (unsigned int)(hf & ((1 << 10) - 1));
146     unsigned int    exp = (unsigned int)(hf & HALF_FLOAT_MAX_BIASED_EXP);
147     union av_intfloat32   f;
148 
149     if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
150         // we have a half-float NaN or Inf
151         // half-float NaNs will be converted to a single precision NaN
152         // half-float Infs will be converted to a single precision Inf
153         exp = FLOAT_MAX_BIASED_EXP;
154         if (mantissa)
155             mantissa = (1 << 23) - 1;    // set all bits to indicate a NaN
156     } else if (exp == 0x0) {
157         // convert half-float zero/denorm to single precision value
158         if (mantissa) {
159             mantissa <<= 1;
160             exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
161             // check for leading 1 in denorm mantissa
162             while ((mantissa & (1 << 10))) {
163                 // for every leading 0, decrement single precision exponent by 1
164                 // and shift half-float mantissa value to the left
165                 mantissa <<= 1;
166                 exp -= (1 << 23);
167             }
168             // clamp the mantissa to 10-bits
169             mantissa &= ((1 << 10) - 1);
170             // shift left to generate single-precision mantissa of 23-bits
171             mantissa <<= 13;
172         }
173     } else {
174         // shift left to generate single-precision mantissa of 23-bits
175         mantissa <<= 13;
176         // generate single precision biased exponent value
177         exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
178     }
179 
180     f.i = (sign << 31) | exp | mantissa;
181 
182     return f;
183 }
184 
185 
186 /**
187  * Convert from 32-bit float as uint32_t to uint16_t.
188  *
189  * @param v 32-bit float
190  *
191  * @return normalized 16-bit unsigned int
192  */
exr_flt2uint(uint32_t v)193 static inline uint16_t exr_flt2uint(uint32_t v)
194 {
195     unsigned int exp = v >> 23;
196     // "HACK": negative values result in exp<  0, so clipping them to 0
197     // is also handled by this condition, avoids explicit check for sign bit.
198     if (exp <= 127 + 7 - 24) // we would shift out all bits anyway
199         return 0;
200     if (exp >= 127)
201         return 0xffff;
202     v &= 0x007fffff;
203     return (v + (1 << 23)) >> (127 + 7 - exp);
204 }
205 
206 /**
207  * Convert from 16-bit float as uint16_t to uint16_t.
208  *
209  * @param v 16-bit float
210  *
211  * @return normalized 16-bit unsigned int
212  */
exr_halflt2uint(uint16_t v)213 static inline uint16_t exr_halflt2uint(uint16_t v)
214 {
215     unsigned exp = 14 - (v >> 10);
216     if (exp >= 14) {
217         if (exp == 14)
218             return (v >> 9) & 1;
219         else
220             return (v & 0x8000) ? 0 : 0xffff;
221     }
222     v <<= 6;
223     return (v + (1 << 16)) >> (exp + 1);
224 }
225 
predictor(uint8_t * src,int size)226 static void predictor(uint8_t *src, int size)
227 {
228     uint8_t *t    = src + 1;
229     uint8_t *stop = src + size;
230 
231     while (t < stop) {
232         int d = (int) t[-1] + (int) t[0] - 128;
233         t[0] = d;
234         ++t;
235     }
236 }
237 
reorder_pixels(uint8_t * src,uint8_t * dst,int size)238 static void reorder_pixels(uint8_t *src, uint8_t *dst, int size)
239 {
240     const int8_t *t1 = src;
241     const int8_t *t2 = src + (size + 1) / 2;
242     int8_t *s        = dst;
243     int8_t *stop     = s + size;
244 
245     while (1) {
246         if (s < stop)
247             *(s++) = *(t1++);
248         else
249             break;
250 
251         if (s < stop)
252             *(s++) = *(t2++);
253         else
254             break;
255     }
256 }
257 
zip_uncompress(const uint8_t * src,int compressed_size,int uncompressed_size,EXRThreadData * td)258 static int zip_uncompress(const uint8_t *src, int compressed_size,
259                           int uncompressed_size, EXRThreadData *td)
260 {
261     unsigned long dest_len = uncompressed_size;
262 
263     if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
264         dest_len != uncompressed_size)
265         return AVERROR_INVALIDDATA;
266 
267     predictor(td->tmp, uncompressed_size);
268     reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
269 
270     return 0;
271 }
272 
rle_uncompress(const uint8_t * src,int compressed_size,int uncompressed_size,EXRThreadData * td)273 static int rle_uncompress(const uint8_t *src, int compressed_size,
274                           int uncompressed_size, EXRThreadData *td)
275 {
276     uint8_t *d      = td->tmp;
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     predictor(td->tmp, uncompressed_size);
313     reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
314 
315     return 0;
316 }
317 
318 #define USHORT_RANGE (1 << 16)
319 #define BITMAP_SIZE  (1 << 13)
320 
reverse_lut(const uint8_t * bitmap,uint16_t * lut)321 static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
322 {
323     int i, k = 0;
324 
325     for (i = 0; i < USHORT_RANGE; i++)
326         if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
327             lut[k++] = i;
328 
329     i = k - 1;
330 
331     memset(lut + k, 0, (USHORT_RANGE - k) * 2);
332 
333     return i;
334 }
335 
apply_lut(const uint16_t * lut,uint16_t * dst,int dsize)336 static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
337 {
338     int i;
339 
340     for (i = 0; i < dsize; ++i)
341         dst[i] = lut[dst[i]];
342 }
343 
344 #define HUF_ENCBITS 16  // literal (value) bit length
345 #define HUF_DECBITS 14  // decoding bit size (>= 8)
346 
347 #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1)  // encoding table size
348 #define HUF_DECSIZE (1 << HUF_DECBITS)        // decoding table size
349 #define HUF_DECMASK (HUF_DECSIZE - 1)
350 
351 typedef struct HufDec {
352     int len;
353     int lit;
354     int *p;
355 } HufDec;
356 
huf_canonical_code_table(uint64_t * hcode)357 static void huf_canonical_code_table(uint64_t *hcode)
358 {
359     uint64_t c, n[59] = { 0 };
360     int i;
361 
362     for (i = 0; i < HUF_ENCSIZE; ++i)
363         n[hcode[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 = hcode[i];
374 
375         if (l > 0)
376             hcode[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 
huf_unpack_enc_table(GetByteContext * gb,int32_t im,int32_t iM,uint64_t * hcode)385 static int huf_unpack_enc_table(GetByteContext *gb,
386                                 int32_t im, int32_t iM, uint64_t *hcode)
387 {
388     GetBitContext gbit;
389 
390     init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
391 
392     for (; im <= iM; im++) {
393         uint64_t l = hcode[im] = get_bits(&gbit, 6);
394 
395         if (l == LONG_ZEROCODE_RUN) {
396             int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
397 
398             if (im + zerun > iM + 1)
399                 return AVERROR_INVALIDDATA;
400 
401             while (zerun--)
402                 hcode[im++] = 0;
403 
404             im--;
405         } else if (l >= SHORT_ZEROCODE_RUN) {
406             int zerun = l - SHORT_ZEROCODE_RUN + 2;
407 
408             if (im + zerun > iM + 1)
409                 return AVERROR_INVALIDDATA;
410 
411             while (zerun--)
412                 hcode[im++] = 0;
413 
414             im--;
415         }
416     }
417 
418     bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
419     huf_canonical_code_table(hcode);
420 
421     return 0;
422 }
423 
huf_build_dec_table(const uint64_t * hcode,int im,int iM,HufDec * hdecod)424 static int huf_build_dec_table(const uint64_t *hcode, int im,
425                                int iM, HufDec *hdecod)
426 {
427     for (; im <= iM; im++) {
428         uint64_t c = hcode[im] >> 6;
429         int i, l = hcode[im] & 63;
430 
431         if (c >> l)
432             return AVERROR_INVALIDDATA;
433 
434         if (l > HUF_DECBITS) {
435             HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
436             if (pl->len)
437                 return AVERROR_INVALIDDATA;
438 
439             pl->lit++;
440 
441             pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
442             if (!pl->p)
443                 return AVERROR(ENOMEM);
444 
445             pl->p[pl->lit - 1] = im;
446         } else if (l) {
447             HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
448 
449             for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
450                 if (pl->len || pl->p)
451                     return AVERROR_INVALIDDATA;
452                 pl->len = l;
453                 pl->lit = im;
454             }
455         }
456     }
457 
458     return 0;
459 }
460 
461 #define get_char(c, lc, gb)                                                   \
462 {                                                                             \
463         c   = (c << 8) | bytestream2_get_byte(gb);                            \
464         lc += 8;                                                              \
465 }
466 
467 #define get_code(po, rlc, c, lc, gb, out, oe)                                 \
468 {                                                                             \
469         if (po == rlc) {                                                      \
470             if (lc < 8)                                                       \
471                 get_char(c, lc, gb);                                          \
472             lc -= 8;                                                          \
473                                                                               \
474             cs = c >> lc;                                                     \
475                                                                               \
476             if (out + cs > oe)                                                \
477                 return AVERROR_INVALIDDATA;                                   \
478                                                                               \
479             s = out[-1];                                                      \
480                                                                               \
481             while (cs-- > 0)                                                  \
482                 *out++ = s;                                                   \
483         } else if (out < oe) {                                                \
484             *out++ = po;                                                      \
485         } else {                                                              \
486             return AVERROR_INVALIDDATA;                                       \
487         }                                                                     \
488 }
489 
huf_decode(const uint64_t * hcode,const HufDec * hdecod,GetByteContext * gb,int nbits,int rlc,int no,uint16_t * out)490 static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
491                       GetByteContext *gb, int nbits,
492                       int rlc, int no, uint16_t *out)
493 {
494     uint64_t c        = 0;
495     uint16_t *outb    = out;
496     uint16_t *oe      = out + no;
497     const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
498     uint8_t cs, s;
499     int i, lc = 0;
500 
501     while (gb->buffer < ie) {
502         get_char(c, lc, gb);
503 
504         while (lc >= HUF_DECBITS) {
505             const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
506 
507             if (pl.len) {
508                 lc -= pl.len;
509                 get_code(pl.lit, rlc, c, lc, gb, out, oe);
510             } else {
511                 int j;
512 
513                 if (!pl.p)
514                     return AVERROR_INVALIDDATA;
515 
516                 for (j = 0; j < pl.lit; j++) {
517                     int l = hcode[pl.p[j]] & 63;
518 
519                     while (lc < l && bytestream2_get_bytes_left(gb) > 0)
520                         get_char(c, lc, gb);
521 
522                     if (lc >= l) {
523                         if ((hcode[pl.p[j]] >> 6) ==
524                             ((c >> (lc - l)) & ((1LL << l) - 1))) {
525                             lc -= l;
526                             get_code(pl.p[j], rlc, c, lc, gb, out, oe);
527                             break;
528                         }
529                     }
530                 }
531 
532                 if (j == pl.lit)
533                     return AVERROR_INVALIDDATA;
534             }
535         }
536     }
537 
538     i   = (8 - nbits) & 7;
539     c >>= i;
540     lc -= i;
541 
542     while (lc > 0) {
543         const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
544 
545         if (pl.len) {
546             lc -= pl.len;
547             get_code(pl.lit, rlc, c, lc, gb, out, oe);
548         } else {
549             return AVERROR_INVALIDDATA;
550         }
551     }
552 
553     if (out - outb != no)
554         return AVERROR_INVALIDDATA;
555     return 0;
556 }
557 
huf_uncompress(GetByteContext * gb,uint16_t * dst,int dst_size)558 static int huf_uncompress(GetByteContext *gb,
559                           uint16_t *dst, int dst_size)
560 {
561     int32_t src_size, im, iM;
562     uint32_t nBits;
563     uint64_t *freq;
564     HufDec *hdec;
565     int ret, i;
566 
567     src_size = bytestream2_get_le32(gb);
568     im       = bytestream2_get_le32(gb);
569     iM       = bytestream2_get_le32(gb);
570     bytestream2_skip(gb, 4);
571     nBits = bytestream2_get_le32(gb);
572     if (im < 0 || im >= HUF_ENCSIZE ||
573         iM < 0 || iM >= HUF_ENCSIZE ||
574         src_size < 0)
575         return AVERROR_INVALIDDATA;
576 
577     bytestream2_skip(gb, 4);
578 
579     freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
580     hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
581     if (!freq || !hdec) {
582         ret = AVERROR(ENOMEM);
583         goto fail;
584     }
585 
586     if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
587         goto fail;
588 
589     if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
590         ret = AVERROR_INVALIDDATA;
591         goto fail;
592     }
593 
594     if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
595         goto fail;
596     ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
597 
598 fail:
599     for (i = 0; i < HUF_DECSIZE; i++)
600         if (hdec)
601             av_freep(&hdec[i].p);
602 
603     av_free(freq);
604     av_free(hdec);
605 
606     return ret;
607 }
608 
wdec14(uint16_t l,uint16_t h,uint16_t * a,uint16_t * b)609 static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
610 {
611     int16_t ls = l;
612     int16_t hs = h;
613     int hi     = hs;
614     int ai     = ls + (hi & 1) + (hi >> 1);
615     int16_t as = ai;
616     int16_t bs = ai - hi;
617 
618     *a = as;
619     *b = bs;
620 }
621 
622 #define NBITS      16
623 #define A_OFFSET  (1 << (NBITS - 1))
624 #define MOD_MASK  ((1 << NBITS) - 1)
625 
wdec16(uint16_t l,uint16_t h,uint16_t * a,uint16_t * b)626 static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
627 {
628     int m  = l;
629     int d  = h;
630     int bb = (m - (d >> 1)) & MOD_MASK;
631     int aa = (d + bb - A_OFFSET) & MOD_MASK;
632     *b = bb;
633     *a = aa;
634 }
635 
wav_decode(uint16_t * in,int nx,int ox,int ny,int oy,uint16_t mx)636 static void wav_decode(uint16_t *in, int nx, int ox,
637                        int ny, int oy, uint16_t mx)
638 {
639     int w14 = (mx < (1 << 14));
640     int n   = (nx > ny) ? ny : nx;
641     int p   = 1;
642     int p2;
643 
644     while (p <= n)
645         p <<= 1;
646 
647     p >>= 1;
648     p2  = p;
649     p >>= 1;
650 
651     while (p >= 1) {
652         uint16_t *py = in;
653         uint16_t *ey = in + oy * (ny - p2);
654         uint16_t i00, i01, i10, i11;
655         int oy1 = oy * p;
656         int oy2 = oy * p2;
657         int ox1 = ox * p;
658         int ox2 = ox * p2;
659 
660         for (; py <= ey; py += oy2) {
661             uint16_t *px = py;
662             uint16_t *ex = py + ox * (nx - p2);
663 
664             for (; px <= ex; px += ox2) {
665                 uint16_t *p01 = px + ox1;
666                 uint16_t *p10 = px + oy1;
667                 uint16_t *p11 = p10 + ox1;
668 
669                 if (w14) {
670                     wdec14(*px, *p10, &i00, &i10);
671                     wdec14(*p01, *p11, &i01, &i11);
672                     wdec14(i00, i01, px, p01);
673                     wdec14(i10, i11, p10, p11);
674                 } else {
675                     wdec16(*px, *p10, &i00, &i10);
676                     wdec16(*p01, *p11, &i01, &i11);
677                     wdec16(i00, i01, px, p01);
678                     wdec16(i10, i11, p10, p11);
679                 }
680             }
681 
682             if (nx & p) {
683                 uint16_t *p10 = px + oy1;
684 
685                 if (w14)
686                     wdec14(*px, *p10, &i00, p10);
687                 else
688                     wdec16(*px, *p10, &i00, p10);
689 
690                 *px = i00;
691             }
692         }
693 
694         if (ny & p) {
695             uint16_t *px = py;
696             uint16_t *ex = py + ox * (nx - p2);
697 
698             for (; px <= ex; px += ox2) {
699                 uint16_t *p01 = px + ox1;
700 
701                 if (w14)
702                     wdec14(*px, *p01, &i00, p01);
703                 else
704                     wdec16(*px, *p01, &i00, p01);
705 
706                 *px = i00;
707             }
708         }
709 
710         p2  = p;
711         p >>= 1;
712     }
713 }
714 
piz_uncompress(EXRContext * s,const uint8_t * src,int ssize,int dsize,EXRThreadData * td)715 static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
716                           int dsize, EXRThreadData *td)
717 {
718     GetByteContext gb;
719     uint16_t maxval, min_non_zero, max_non_zero;
720     uint16_t *ptr;
721     uint16_t *tmp = (uint16_t *)td->tmp;
722     uint8_t *out;
723     int ret, i, j;
724 
725     if (!td->bitmap)
726         td->bitmap = av_malloc(BITMAP_SIZE);
727     if (!td->lut)
728         td->lut = av_malloc(1 << 17);
729     if (!td->bitmap || !td->lut) {
730         av_freep(&td->bitmap);
731         av_freep(&td->lut);
732         return AVERROR(ENOMEM);
733     }
734 
735     bytestream2_init(&gb, src, ssize);
736     min_non_zero = bytestream2_get_le16(&gb);
737     max_non_zero = bytestream2_get_le16(&gb);
738 
739     if (max_non_zero >= BITMAP_SIZE)
740         return AVERROR_INVALIDDATA;
741 
742     memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
743     if (min_non_zero <= max_non_zero)
744         bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
745                                max_non_zero - min_non_zero + 1);
746     memset(td->bitmap + max_non_zero, 0, BITMAP_SIZE - max_non_zero);
747 
748     maxval = reverse_lut(td->bitmap, td->lut);
749 
750     ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
751     if (ret)
752         return ret;
753 
754     ptr = tmp;
755     for (i = 0; i < s->nb_channels; i++) {
756         EXRChannel *channel = &s->channels[i];
757         int size = channel->pixel_type;
758 
759         for (j = 0; j < size; j++)
760             wav_decode(ptr + j, s->xdelta, size, s->ysize,
761                        s->xdelta * size, maxval);
762         ptr += s->xdelta * s->ysize * size;
763     }
764 
765     apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
766 
767     out = td->uncompressed_data;
768     for (i = 0; i < s->ysize; i++)
769         for (j = 0; j < s->nb_channels; j++) {
770             uint16_t *in = tmp + j * s->xdelta * s->ysize + i * s->xdelta;
771             memcpy(out, in, s->xdelta * 2);
772             out += s->xdelta * 2;
773         }
774 
775     return 0;
776 }
777 
pxr24_uncompress(EXRContext * s,const uint8_t * src,int compressed_size,int uncompressed_size,EXRThreadData * td)778 static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
779                             int compressed_size, int uncompressed_size,
780                             EXRThreadData *td)
781 {
782     unsigned long dest_len = uncompressed_size;
783     const uint8_t *in = td->tmp;
784     uint8_t *out;
785     int c, i, j;
786 
787     if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
788         dest_len != uncompressed_size)
789         return AVERROR_INVALIDDATA;
790 
791     out = td->uncompressed_data;
792     for (i = 0; i < s->ysize; i++)
793         for (c = 0; c < s->nb_channels; c++) {
794             EXRChannel *channel = &s->channels[c];
795             const uint8_t *ptr[4];
796             uint32_t pixel = 0;
797 
798             switch (channel->pixel_type) {
799             case EXR_FLOAT:
800                 ptr[0] = in;
801                 ptr[1] = ptr[0] + s->xdelta;
802                 ptr[2] = ptr[1] + s->xdelta;
803                 in     = ptr[2] + s->xdelta;
804 
805                 for (j = 0; j < s->xdelta; ++j) {
806                     uint32_t diff = (*(ptr[0]++) << 24) |
807                                     (*(ptr[1]++) << 16) |
808                                     (*(ptr[2]++) << 8);
809                     pixel += diff;
810                     bytestream_put_le32(&out, pixel);
811                 }
812                 break;
813             case EXR_HALF:
814                 ptr[0] = in;
815                 ptr[1] = ptr[0] + s->xdelta;
816                 in     = ptr[1] + s->xdelta;
817                 for (j = 0; j < s->xdelta; j++) {
818                     uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
819 
820                     pixel += diff;
821                     bytestream_put_le16(&out, pixel);
822                 }
823                 break;
824             default:
825                 return AVERROR_INVALIDDATA;
826             }
827         }
828 
829     return 0;
830 }
831 
decode_block(AVCodecContext * avctx,void * tdata,int jobnr,int threadnr)832 static int decode_block(AVCodecContext *avctx, void *tdata,
833                         int jobnr, int threadnr)
834 {
835     EXRContext *s = avctx->priv_data;
836     AVFrame *const p = s->picture;
837     EXRThreadData *td = &s->thread_data[threadnr];
838     const uint8_t *channel_buffer[4] = { 0 };
839     const uint8_t *buf = s->buf;
840     uint64_t line_offset, uncompressed_size;
841     uint32_t xdelta = s->xdelta;
842     uint16_t *ptr_x;
843     uint8_t *ptr;
844     uint32_t data_size, line;
845     const uint8_t *src;
846     int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components;
847     int bxmin = s->xmin * 2 * s->desc->nb_components;
848     int i, x, buf_size = s->buf_size;
849     int ret;
850     float one_gamma = 1.0f / s->gamma;
851 
852     line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
853     // Check if the buffer has the required bytes needed from the offset
854     if (line_offset > buf_size - 8)
855         return AVERROR_INVALIDDATA;
856 
857     src  = buf + line_offset + 8;
858     line = AV_RL32(src - 8);
859     if (line < s->ymin || line > s->ymax)
860         return AVERROR_INVALIDDATA;
861 
862     data_size = AV_RL32(src - 4);
863     if (data_size <= 0 || data_size > buf_size)
864         return AVERROR_INVALIDDATA;
865 
866     s->ysize          = FFMIN(s->scan_lines_per_block, s->ymax - line + 1);
867     uncompressed_size = s->scan_line_size * s->ysize;
868     if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
869                                  line_offset > buf_size - uncompressed_size)) ||
870         (s->compression != EXR_RAW && (data_size > uncompressed_size ||
871                                  line_offset > buf_size - data_size))) {
872         return AVERROR_INVALIDDATA;
873     }
874 
875     if (data_size < uncompressed_size) {
876         av_fast_padded_malloc(&td->uncompressed_data,
877                               &td->uncompressed_size, uncompressed_size);
878         av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
879         if (!td->uncompressed_data || !td->tmp)
880             return AVERROR(ENOMEM);
881 
882         ret = AVERROR_INVALIDDATA;
883         switch (s->compression) {
884         case EXR_ZIP1:
885         case EXR_ZIP16:
886             ret = zip_uncompress(src, data_size, uncompressed_size, td);
887             break;
888         case EXR_PIZ:
889             ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
890             break;
891         case EXR_PXR24:
892             ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
893             break;
894         case EXR_RLE:
895             ret = rle_uncompress(src, data_size, uncompressed_size, td);
896         }
897         if (ret < 0) {
898             av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
899             return ret;
900         }
901         src = td->uncompressed_data;
902     }
903 
904     channel_buffer[0] = src + xdelta * s->channel_offsets[0];
905     channel_buffer[1] = src + xdelta * s->channel_offsets[1];
906     channel_buffer[2] = src + xdelta * s->channel_offsets[2];
907     if (s->channel_offsets[3] >= 0)
908         channel_buffer[3] = src + xdelta * s->channel_offsets[3];
909 
910     ptr = p->data[0] + line * p->linesize[0];
911     for (i = 0;
912          i < s->scan_lines_per_block && line + i <= s->ymax;
913          i++, ptr += p->linesize[0]) {
914         const uint8_t *r, *g, *b;
915         const uint8_t *a = NULL;
916 
917         r = channel_buffer[0];
918         g = channel_buffer[1];
919         b = channel_buffer[2];
920         if (channel_buffer[3])
921             a = channel_buffer[3];
922 
923         ptr_x = (uint16_t *) ptr;
924 
925         // Zero out the start if xmin is not 0
926         memset(ptr_x, 0, bxmin);
927         ptr_x += s->xmin * s->desc->nb_components;
928         if (s->pixel_type == EXR_FLOAT) {
929             // 32-bit
930             for (x = 0; x < xdelta; x++) {
931                 union av_intfloat32 t;
932                 t.i = bytestream_get_le32(&r);
933                 if ( t.f > 0.0f )  /* avoid negative values */
934                     t.f = powf(t.f, one_gamma);
935                 *ptr_x++ = exr_flt2uint(t.i);
936 
937                 t.i = bytestream_get_le32(&g);
938                 if ( t.f > 0.0f )
939                     t.f = powf(t.f, one_gamma);
940                 *ptr_x++ = exr_flt2uint(t.i);
941 
942                 t.i = bytestream_get_le32(&b);
943                 if ( t.f > 0.0f )
944                     t.f = powf(t.f, one_gamma);
945                 *ptr_x++ = exr_flt2uint(t.i);
946                 if (channel_buffer[3])
947                     *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
948             }
949         } else {
950             // 16-bit
951             for (x = 0; x < xdelta; x++) {
952                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&r)];
953                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&g)];
954                 *ptr_x++ = s->gamma_table[bytestream_get_le16(&b)];
955                 if (channel_buffer[3])
956                     *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));
957             }
958         }
959 
960         // Zero out the end if xmax+1 is not w
961         memset(ptr_x, 0, axmax);
962 
963         channel_buffer[0] += s->scan_line_size;
964         channel_buffer[1] += s->scan_line_size;
965         channel_buffer[2] += s->scan_line_size;
966         if (channel_buffer[3])
967             channel_buffer[3] += s->scan_line_size;
968     }
969 
970     return 0;
971 }
972 
973 /**
974  * Check if the variable name corresponds to its data type.
975  *
976  * @param s              the EXRContext
977  * @param value_name     name of the variable to check
978  * @param value_type     type of the variable to check
979  * @param minimum_length minimum length of the variable data
980  *
981  * @return bytes to read containing variable data
982  *         -1 if variable is not found
983  *         0 if buffer ended prematurely
984  */
check_header_variable(EXRContext * s,const char * value_name,const char * value_type,unsigned int minimum_length)985 static int check_header_variable(EXRContext *s,
986                                  const char *value_name,
987                                  const char *value_type,
988                                  unsigned int minimum_length)
989 {
990     int var_size = -1;
991 
992     if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
993         !strcmp(s->gb.buffer, value_name)) {
994         // found value_name, jump to value_type (null terminated strings)
995         s->gb.buffer += strlen(value_name) + 1;
996         if (!strcmp(s->gb.buffer, value_type)) {
997             s->gb.buffer += strlen(value_type) + 1;
998             var_size = bytestream2_get_le32(&s->gb);
999             // don't go read past boundaries
1000             if (var_size > bytestream2_get_bytes_left(&s->gb))
1001                 var_size = 0;
1002         } else {
1003             // value_type not found, reset the buffer
1004             s->gb.buffer -= strlen(value_name) + 1;
1005             av_log(s->avctx, AV_LOG_WARNING,
1006                    "Unknown data type %s for header variable %s.\n",
1007                    value_type, value_name);
1008         }
1009     }
1010 
1011     return var_size;
1012 }
1013 
decode_header(EXRContext * s)1014 static int decode_header(EXRContext *s)
1015 {
1016     int current_channel_offset = 0;
1017     int magic_number, version, flags, i;
1018 
1019     if (bytestream2_get_bytes_left(&s->gb) < 10) {
1020         av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1021         return AVERROR_INVALIDDATA;
1022     }
1023 
1024     magic_number = bytestream2_get_le32(&s->gb);
1025     if (magic_number != 20000630) {
1026         /* As per documentation of OpenEXR, it is supposed to be
1027          * int 20000630 little-endian */
1028         av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1029         return AVERROR_INVALIDDATA;
1030     }
1031 
1032     version = bytestream2_get_byte(&s->gb);
1033     if (version != 2) {
1034         avpriv_report_missing_feature(s->avctx, "Version %d", version);
1035         return AVERROR_PATCHWELCOME;
1036     }
1037 
1038     flags = bytestream2_get_le24(&s->gb);
1039     if (flags & 0x02) {
1040         avpriv_report_missing_feature(s->avctx, "Tile support");
1041         return AVERROR_PATCHWELCOME;
1042     }
1043 
1044     // Parse the header
1045     while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
1046         int var_size;
1047         if ((var_size = check_header_variable(s, "channels",
1048                                               "chlist", 38)) >= 0) {
1049             GetByteContext ch_gb;
1050             if (!var_size)
1051                 return AVERROR_INVALIDDATA;
1052 
1053             bytestream2_init(&ch_gb, s->gb.buffer, var_size);
1054 
1055             while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1056                 EXRChannel *channel;
1057                 enum ExrPixelType current_pixel_type;
1058                 int channel_index = -1;
1059                 int xsub, ysub;
1060 
1061                 if (strcmp(s->layer, "") != 0) {
1062                     if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1063                         ch_gb.buffer += strlen(s->layer);
1064                         if (*ch_gb.buffer == '.')
1065                             ch_gb.buffer++;         /* skip dot if not given */
1066                         av_log(s->avctx, AV_LOG_INFO,
1067                                "Layer %s.%s matched.\n", s->layer, ch_gb.buffer);
1068                     }
1069                 }
1070 
1071                 if (!strcmp(ch_gb.buffer, "R") ||
1072                     !strcmp(ch_gb.buffer, "X") ||
1073                     !strcmp(ch_gb.buffer, "U"))
1074                     channel_index = 0;
1075                 else if (!strcmp(ch_gb.buffer, "G") ||
1076                          !strcmp(ch_gb.buffer, "Y") ||
1077                          !strcmp(ch_gb.buffer, "V"))
1078                     channel_index = 1;
1079                 else if (!strcmp(ch_gb.buffer, "B") ||
1080                          !strcmp(ch_gb.buffer, "Z") ||
1081                          !strcmp(ch_gb.buffer, "W"))
1082                     channel_index = 2;
1083                 else if (!strcmp(ch_gb.buffer, "A"))
1084                     channel_index = 3;
1085                 else
1086                     av_log(s->avctx, AV_LOG_WARNING,
1087                            "Unsupported channel %.256s.\n", ch_gb.buffer);
1088 
1089                 /* skip until you get a 0 */
1090                 while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1091                        bytestream2_get_byte(&ch_gb))
1092                     continue;
1093 
1094                 if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1095                     av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1096                     return AVERROR_INVALIDDATA;
1097                 }
1098 
1099                 current_pixel_type = bytestream2_get_le32(&ch_gb);
1100                 if (current_pixel_type >= EXR_UNKNOWN) {
1101                     avpriv_report_missing_feature(s->avctx,
1102                                                   "Pixel type %d.\n",
1103                                                   current_pixel_type);
1104                     return AVERROR_PATCHWELCOME;
1105                 }
1106 
1107                 bytestream2_skip(&ch_gb, 4);
1108                 xsub = bytestream2_get_le32(&ch_gb);
1109                 ysub = bytestream2_get_le32(&ch_gb);
1110                 if (xsub != 1 || ysub != 1) {
1111                     avpriv_report_missing_feature(s->avctx,
1112                                                   "Subsampling %dx%d",
1113                                                   xsub, ysub);
1114                     return AVERROR_PATCHWELCOME;
1115                 }
1116 
1117                 if (channel_index >= 0) {
1118                     if (s->pixel_type != EXR_UNKNOWN &&
1119                         s->pixel_type != current_pixel_type) {
1120                         av_log(s->avctx, AV_LOG_ERROR,
1121                                "RGB channels not of the same depth.\n");
1122                         return AVERROR_INVALIDDATA;
1123                     }
1124                     s->pixel_type                     = current_pixel_type;
1125                     s->channel_offsets[channel_index] = current_channel_offset;
1126                 }
1127 
1128                 s->channels = av_realloc(s->channels,
1129                                          ++s->nb_channels * sizeof(EXRChannel));
1130                 if (!s->channels)
1131                     return AVERROR(ENOMEM);
1132                 channel             = &s->channels[s->nb_channels - 1];
1133                 channel->pixel_type = current_pixel_type;
1134                 channel->xsub       = xsub;
1135                 channel->ysub       = ysub;
1136 
1137                 current_channel_offset += 1 << current_pixel_type;
1138             }
1139 
1140             /* Check if all channels are set with an offset or if the channels
1141              * are causing an overflow  */
1142             if (FFMIN3(s->channel_offsets[0],
1143                        s->channel_offsets[1],
1144                        s->channel_offsets[2]) < 0) {
1145                 if (s->channel_offsets[0] < 0)
1146                     av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1147                 if (s->channel_offsets[1] < 0)
1148                     av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1149                 if (s->channel_offsets[2] < 0)
1150                     av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1151                 return AVERROR_INVALIDDATA;
1152             }
1153 
1154             // skip one last byte and update main gb
1155             s->gb.buffer = ch_gb.buffer + 1;
1156             continue;
1157         } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1158                                                      31)) >= 0) {
1159             if (!var_size)
1160                 return AVERROR_INVALIDDATA;
1161 
1162             s->xmin   = bytestream2_get_le32(&s->gb);
1163             s->ymin   = bytestream2_get_le32(&s->gb);
1164             s->xmax   = bytestream2_get_le32(&s->gb);
1165             s->ymax   = bytestream2_get_le32(&s->gb);
1166             s->xdelta = (s->xmax - s->xmin) + 1;
1167             s->ydelta = (s->ymax - s->ymin) + 1;
1168 
1169             continue;
1170         } else if ((var_size = check_header_variable(s, "displayWindow",
1171                                                      "box2i", 34)) >= 0) {
1172             if (!var_size)
1173                 return AVERROR_INVALIDDATA;
1174 
1175             bytestream2_skip(&s->gb, 8);
1176             s->w = bytestream2_get_le32(&s->gb) + 1;
1177             s->h = bytestream2_get_le32(&s->gb) + 1;
1178 
1179             continue;
1180         } else if ((var_size = check_header_variable(s, "lineOrder",
1181                                                      "lineOrder", 25)) >= 0) {
1182             int line_order;
1183             if (!var_size)
1184                 return AVERROR_INVALIDDATA;
1185 
1186             line_order = bytestream2_get_byte(&s->gb);
1187             av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1188             if (line_order > 2) {
1189                 av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1190                 return AVERROR_INVALIDDATA;
1191             }
1192 
1193             continue;
1194         } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1195                                                      "float", 31)) >= 0) {
1196             if (!var_size)
1197                 return AVERROR_INVALIDDATA;
1198 
1199             ff_set_sar(s->avctx,
1200                        av_d2q(av_int2float(bytestream2_get_le32(&s->gb)), 255));
1201 
1202             continue;
1203         } else if ((var_size = check_header_variable(s, "compression",
1204                                                      "compression", 29)) >= 0) {
1205             if (!var_size)
1206                 return AVERROR_INVALIDDATA;
1207 
1208             if (s->compression == EXR_UNKN)
1209                 s->compression = bytestream2_get_byte(&s->gb);
1210             else
1211                 av_log(s->avctx, AV_LOG_WARNING,
1212                        "Found more than one compression attribute.\n");
1213 
1214             continue;
1215         }
1216 
1217         // Check if there are enough bytes for a header
1218         if (bytestream2_get_bytes_left(&s->gb) <= 9) {
1219             av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1220             return AVERROR_INVALIDDATA;
1221         }
1222 
1223         // Process unknown variables
1224         for (i = 0; i < 2; i++) // value_name and value_type
1225             while (bytestream2_get_byte(&s->gb) != 0);
1226 
1227         // Skip variable length
1228         bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb));
1229     }
1230 
1231     if (s->compression == EXR_UNKN) {
1232         av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1233         return AVERROR_INVALIDDATA;
1234     }
1235     s->scan_line_size = s->xdelta * current_channel_offset;
1236 
1237     if (bytestream2_get_bytes_left(&s->gb) <= 0) {
1238         av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1239         return AVERROR_INVALIDDATA;
1240     }
1241 
1242     // aaand we are done
1243     bytestream2_skip(&s->gb, 1);
1244     return 0;
1245 }
1246 
decode_frame(AVCodecContext * avctx,void * data,int * got_frame,AVPacket * avpkt)1247 static int decode_frame(AVCodecContext *avctx, void *data,
1248                         int *got_frame, AVPacket *avpkt)
1249 {
1250     EXRContext *s = avctx->priv_data;
1251     ThreadFrame frame = { .f = data };
1252     AVFrame *picture = data;
1253     uint8_t *ptr;
1254 
1255     int y, ret;
1256     int out_line_size;
1257     int scan_line_blocks;
1258 
1259     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1260 
1261     if ((ret = decode_header(s)) < 0)
1262         return ret;
1263 
1264     switch (s->pixel_type) {
1265     case EXR_FLOAT:
1266     case EXR_HALF:
1267         if (s->channel_offsets[3] >= 0)
1268             avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1269         else
1270             avctx->pix_fmt = AV_PIX_FMT_RGB48;
1271         break;
1272     case EXR_UINT:
1273         avpriv_request_sample(avctx, "32-bit unsigned int");
1274         return AVERROR_PATCHWELCOME;
1275     default:
1276         av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1277         return AVERROR_INVALIDDATA;
1278     }
1279 
1280     switch (s->compression) {
1281     case EXR_RAW:
1282     case EXR_RLE:
1283     case EXR_ZIP1:
1284         s->scan_lines_per_block = 1;
1285         break;
1286     case EXR_PXR24:
1287     case EXR_ZIP16:
1288         s->scan_lines_per_block = 16;
1289         break;
1290     case EXR_PIZ:
1291         s->scan_lines_per_block = 32;
1292         break;
1293     default:
1294         avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1295         return AVERROR_PATCHWELCOME;
1296     }
1297 
1298     /* Verify the xmin, xmax, ymin, ymax and xdelta before setting
1299      * the actual image size. */
1300     if (s->xmin > s->xmax                  ||
1301         s->ymin > s->ymax                  ||
1302         s->xdelta != s->xmax - s->xmin + 1 ||
1303         s->xmax >= s->w                    ||
1304         s->ymax >= s->h) {
1305         av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1306         return AVERROR_INVALIDDATA;
1307     }
1308 
1309     if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1310         return ret;
1311 
1312     s->desc          = av_pix_fmt_desc_get(avctx->pix_fmt);
1313     if (!s->desc)
1314         return AVERROR_INVALIDDATA;
1315     out_line_size    = avctx->width * 2 * s->desc->nb_components;
1316     scan_line_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1317                        s->scan_lines_per_block;
1318 
1319     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1320         return ret;
1321 
1322     if (bytestream2_get_bytes_left(&s->gb) < scan_line_blocks * 8)
1323         return AVERROR_INVALIDDATA;
1324 
1325     // save pointer we are going to use in decode_block
1326     s->buf      = avpkt->data;
1327     s->buf_size = avpkt->size;
1328     ptr         = picture->data[0];
1329 
1330     // Zero out the start if ymin is not 0
1331     for (y = 0; y < s->ymin; y++) {
1332         memset(ptr, 0, out_line_size);
1333         ptr += picture->linesize[0];
1334     }
1335 
1336     s->picture = picture;
1337     avctx->execute2(avctx, decode_block, s->thread_data, NULL, scan_line_blocks);
1338 
1339     // Zero out the end if ymax+1 is not h
1340     for (y = s->ymax + 1; y < avctx->height; y++) {
1341         memset(ptr, 0, out_line_size);
1342         ptr += picture->linesize[0];
1343     }
1344 
1345     picture->pict_type = AV_PICTURE_TYPE_I;
1346     *got_frame = 1;
1347 
1348     return avpkt->size;
1349 }
1350 
decode_init(AVCodecContext * avctx)1351 static av_cold int decode_init(AVCodecContext *avctx)
1352 {
1353     uint32_t i;
1354     union av_intfloat32 t;
1355     EXRContext *s = avctx->priv_data;
1356     float one_gamma = 1.0f / s->gamma;
1357 
1358     s->avctx              = avctx;
1359     s->xmin               = ~0;
1360     s->xmax               = ~0;
1361     s->ymin               = ~0;
1362     s->ymax               = ~0;
1363     s->xdelta             = ~0;
1364     s->ydelta             = ~0;
1365     s->channel_offsets[0] = -1;
1366     s->channel_offsets[1] = -1;
1367     s->channel_offsets[2] = -1;
1368     s->channel_offsets[3] = -1;
1369     s->pixel_type         = EXR_UNKNOWN;
1370     s->compression        = EXR_UNKN;
1371     s->nb_channels        = 0;
1372     s->w                  = 0;
1373     s->h                  = 0;
1374 
1375     if ( one_gamma > 0.9999f && one_gamma < 1.0001f ) {
1376         for ( i = 0; i < 65536; ++i ) {
1377             s->gamma_table[i] = exr_halflt2uint(i);
1378         }
1379     } else {
1380         for ( i = 0; i < 65536; ++i ) {
1381             t = exr_half2float(i);
1382             /* If negative value we reuse half value */
1383             if ( t.f <= 0.0f ) {
1384                 s->gamma_table[i] = exr_halflt2uint(i);
1385             } else {
1386                 t.f = powf(t.f, one_gamma);
1387                 s->gamma_table[i] = exr_flt2uint(t.i);
1388             }
1389         }
1390     }
1391 
1392     // allocate thread data, used for non EXR_RAW compreesion types
1393     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1394     if (!s->thread_data)
1395         return AVERROR_INVALIDDATA;
1396 
1397     return 0;
1398 }
1399 
decode_init_thread_copy(AVCodecContext * avctx)1400 static int decode_init_thread_copy(AVCodecContext *avctx)
1401 {    EXRContext *s = avctx->priv_data;
1402 
1403     // allocate thread data, used for non EXR_RAW compreesion types
1404     s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1405     if (!s->thread_data)
1406         return AVERROR_INVALIDDATA;
1407 
1408     return 0;
1409 }
1410 
decode_end(AVCodecContext * avctx)1411 static av_cold int decode_end(AVCodecContext *avctx)
1412 {
1413     EXRContext *s = avctx->priv_data;
1414     int i;
1415     for (i = 0; i < avctx->thread_count; i++) {
1416         EXRThreadData *td = &s->thread_data[i];
1417         av_freep(&td->uncompressed_data);
1418         av_freep(&td->tmp);
1419         av_freep(&td->bitmap);
1420         av_freep(&td->lut);
1421     }
1422 
1423     av_freep(&s->thread_data);
1424     av_freep(&s->channels);
1425 
1426     return 0;
1427 }
1428 
1429 #define OFFSET(x) offsetof(EXRContext, x)
1430 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1431 static const AVOption options[] = {
1432     { "layer", "Set the decoding layer", OFFSET(layer),
1433         AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
1434     { "gamma", "Set the float gamma value when decoding (experimental/unsupported)", OFFSET(gamma),
1435         AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
1436     { NULL },
1437 };
1438 
1439 static const AVClass exr_class = {
1440     .class_name = "EXR",
1441     .item_name  = av_default_item_name,
1442     .option     = options,
1443     .version    = LIBAVUTIL_VERSION_INT,
1444 };
1445 
1446 AVCodec ff_exr_decoder = {
1447     .name             = "exr",
1448     .long_name        = NULL_IF_CONFIG_SMALL("OpenEXR image"),
1449     .type             = AVMEDIA_TYPE_VIDEO,
1450     .id               = AV_CODEC_ID_EXR,
1451     .priv_data_size   = sizeof(EXRContext),
1452     .init             = decode_init,
1453     .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1454     .close            = decode_end,
1455     .decode           = decode_frame,
1456     .capabilities     = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS |
1457                         CODEC_CAP_SLICE_THREADS,
1458     .priv_class       = &exr_class,
1459 };
1460