]> git.sesse.net Git - ffmpeg/blob - libavcodec/exr.c
Merge commit '50ea93158d4c480f64069e8bd1da388486dcf4ba'
[ffmpeg] / libavcodec / exr.c
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  */
32
33 #include <zlib.h>
34
35 #include "get_bits.h"
36 #include "avcodec.h"
37 #include "bytestream.h"
38 #include "internal.h"
39 #include "mathops.h"
40 #include "thread.h"
41 #include "libavutil/imgutils.h"
42 #include "libavutil/avassert.h"
43
44 enum ExrCompr {
45     EXR_RAW   = 0,
46     EXR_RLE   = 1,
47     EXR_ZIP1  = 2,
48     EXR_ZIP16 = 3,
49     EXR_PIZ   = 4,
50     EXR_PXR24 = 5,
51     EXR_B44   = 6,
52     EXR_B44A  = 7,
53 };
54
55 enum ExrPixelType {
56     EXR_UINT,
57     EXR_HALF,
58     EXR_FLOAT
59 };
60
61 typedef struct EXRChannel {
62     int               xsub, ysub;
63     enum ExrPixelType pixel_type;
64 } EXRChannel;
65
66 typedef struct EXRThreadData {
67     uint8_t *uncompressed_data;
68     int uncompressed_size;
69
70     uint8_t *tmp;
71     int tmp_size;
72
73     uint8_t *bitmap;
74     uint16_t *lut;
75 } EXRThreadData;
76
77 typedef struct EXRContext {
78     AVFrame *picture;
79     int compr;
80     enum ExrPixelType pixel_type;
81     int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
82     const AVPixFmtDescriptor *desc;
83
84     uint32_t xmax, xmin;
85     uint32_t ymax, ymin;
86     uint32_t xdelta, ydelta;
87
88     int ysize;
89
90     uint64_t scan_line_size;
91     int scan_lines_per_block;
92
93     const uint8_t *buf, *table;
94     int buf_size;
95
96     EXRChannel *channels;
97     int nb_channels;
98
99     EXRThreadData *thread_data;
100     int thread_data_size;
101 } EXRContext;
102
103 /**
104  * Converts from 32-bit float as uint32_t to uint16_t
105  *
106  * @param v 32-bit float
107  * @return normalized 16-bit unsigned int
108  */
109 static inline uint16_t exr_flt2uint(uint32_t v)
110 {
111     unsigned int exp = v >> 23;
112     // "HACK": negative values result in exp<  0, so clipping them to 0
113     // is also handled by this condition, avoids explicit check for sign bit.
114     if (exp<= 127 + 7 - 24) // we would shift out all bits anyway
115         return 0;
116     if (exp >= 127)
117         return 0xffff;
118     v &= 0x007fffff;
119     return (v + (1 << 23)) >> (127 + 7 - exp);
120 }
121
122 /**
123  * Converts from 16-bit float as uint16_t to uint16_t
124  *
125  * @param v 16-bit float
126  * @return normalized 16-bit unsigned int
127  */
128 static inline uint16_t exr_halflt2uint(uint16_t v)
129 {
130     unsigned exp = 14 - (v >> 10);
131     if (exp >= 14) {
132         if (exp == 14) return (v >> 9) & 1;
133         else           return (v & 0x8000) ? 0 : 0xffff;
134     }
135     v <<= 6;
136     return (v + (1 << 16)) >> (exp + 1);
137 }
138
139 /**
140  * Gets the size of the header variable
141  *
142  * @param **buf the current pointer location in the header where
143  * the variable data starts
144  * @param *buf_end pointer location of the end of the buffer
145  * @return size of variable data
146  */
147 static unsigned int get_header_variable_length(const uint8_t **buf,
148                                                const uint8_t *buf_end)
149 {
150     unsigned int variable_buffer_data_size = bytestream_get_le32(buf);
151     if (variable_buffer_data_size >= buf_end - *buf)
152         return 0;
153     return variable_buffer_data_size;
154 }
155
156 /**
157  * Checks if the variable name corresponds with it's data type
158  *
159  * @param *avctx the AVCodecContext
160  * @param **buf the current pointer location in the header where
161  * the variable name starts
162  * @param *buf_end pointer location of the end of the buffer
163  * @param *value_name name of the varible to check
164  * @param *value_type type of the varible to check
165  * @param minimum_length minimum length of the variable data
166  * @param variable_buffer_data_size variable length read from the header
167  * after it's checked
168  * @return negative if variable is invalid
169  */
170 static int check_header_variable(AVCodecContext *avctx,
171                                               const uint8_t **buf,
172                                               const uint8_t *buf_end,
173                                               const char *value_name,
174                                               const char *value_type,
175                                               unsigned int minimum_length,
176                                               unsigned int *variable_buffer_data_size)
177 {
178     if (buf_end - *buf >= minimum_length && !strcmp(*buf, value_name)) {
179         *buf += strlen(value_name)+1;
180         if (!strcmp(*buf, value_type)) {
181             *buf += strlen(value_type)+1;
182             *variable_buffer_data_size = get_header_variable_length(buf, buf_end);
183             if (!*variable_buffer_data_size)
184                 av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
185             return 1;
186         }
187         *buf -= strlen(value_name)+1;
188         av_log(avctx, AV_LOG_WARNING, "Unknown data type for header variable %s\n", value_name);
189     }
190     return -1;
191 }
192
193 static void predictor(uint8_t *src, int size)
194 {
195     uint8_t *t = src + 1;
196     uint8_t *stop = src + size;
197
198     while (t < stop) {
199         int d = (int)t[-1] + (int)t[0] - 128;
200         t[0] = d;
201         ++t;
202     }
203 }
204
205 static void reorder_pixels(uint8_t *src, uint8_t *dst, int size)
206 {
207     const int8_t *t1 = src;
208     const int8_t *t2 = src + (size + 1) / 2;
209     int8_t *s = dst;
210     int8_t *stop = s + size;
211
212     while (1) {
213         if (s < stop)
214             *(s++) = *(t1++);
215         else
216             break;
217
218         if (s < stop)
219             *(s++) = *(t2++);
220         else
221             break;
222     }
223 }
224
225 static int zip_uncompress(const uint8_t *src, int compressed_size,
226                           int uncompressed_size, EXRThreadData *td)
227 {
228     unsigned long dest_len = uncompressed_size;
229
230     if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
231         dest_len != uncompressed_size)
232         return AVERROR(EINVAL);
233
234     predictor(td->tmp, uncompressed_size);
235     reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
236
237     return 0;
238 }
239
240 static int rle_uncompress(const uint8_t *src, int compressed_size,
241                           int uncompressed_size, EXRThreadData *td)
242 {
243     int8_t *d = (int8_t *)td->tmp;
244     const int8_t *s = (const int8_t *)src;
245     int ssize = compressed_size;
246     int dsize = uncompressed_size;
247     int8_t *dend = d + dsize;
248     int count;
249
250     while (ssize > 0) {
251         count = *s++;
252
253         if (count < 0) {
254             count = -count;
255
256             if ((dsize -= count    ) < 0 ||
257                 (ssize -= count + 1) < 0)
258                 return -1;
259
260             while (count--)
261                 *d++ = *s++;
262         } else {
263             count++;
264
265             if ((dsize -= count) < 0 ||
266                 (ssize -= 2    ) < 0)
267                 return -1;
268
269             while (count--)
270                 *d++ = *s;
271
272             s++;
273         }
274     }
275
276     if (dend != d)
277         return AVERROR_INVALIDDATA;
278
279     predictor(td->tmp, uncompressed_size);
280     reorder_pixels(td->tmp, td->uncompressed_data, uncompressed_size);
281
282     return 0;
283 }
284
285 #define USHORT_RANGE (1 << 16)
286 #define BITMAP_SIZE (1 << 13)
287
288 static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
289 {
290     int i, k = 0;
291
292     for (i = 0; i < USHORT_RANGE; i++) {
293         if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
294             lut[k++] = i;
295     }
296
297     i = k - 1;
298
299     memset(lut + k, 0, (USHORT_RANGE - k) * 2);
300
301     return i;
302 }
303
304 static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
305 {
306     int i;
307
308     for (i = 0; i < dsize; ++i)
309         dst[i] = lut[dst[i]];
310 }
311
312 #define HUF_ENCBITS 16  // literal (value) bit length
313 #define HUF_DECBITS 14  // decoding bit size (>= 8)
314
315 #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1)  // encoding table size
316 #define HUF_DECSIZE (1 << HUF_DECBITS)     // decoding table size
317 #define HUF_DECMASK (HUF_DECSIZE - 1)
318
319 typedef struct HufDec {
320     int len;
321     int lit;
322     int *p;
323 } HufDec;
324
325 static void huf_canonical_code_table(uint64_t *hcode)
326 {
327     uint64_t c, n[59] = { 0 };
328     int i;
329
330     for (i = 0; i < HUF_ENCSIZE; ++i)
331         n[hcode[i]] += 1;
332
333     c = 0;
334     for (i = 58; i > 0; --i) {
335         uint64_t nc = ((c + n[i]) >> 1);
336         n[i] = c;
337         c = nc;
338     }
339
340     for (i = 0; i < HUF_ENCSIZE; ++i) {
341         int l = hcode[i];
342
343         if (l > 0)
344             hcode[i] = l | (n[l]++ << 6);
345     }
346 }
347
348 #define SHORT_ZEROCODE_RUN  59
349 #define LONG_ZEROCODE_RUN   63
350 #define SHORTEST_LONG_RUN   (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
351 #define LONGEST_LONG_RUN    (255 + SHORTEST_LONG_RUN)
352
353 static int huf_unpack_enc_table(GetByteContext *gb,
354                                 int32_t im, int32_t iM, uint64_t *hcode)
355 {
356     GetBitContext gbit;
357
358     init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
359
360     for (; im <= iM; im++) {
361         uint64_t l = hcode[im] = get_bits(&gbit, 6);
362
363         if (l == LONG_ZEROCODE_RUN) {
364             int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
365
366             if (im + zerun > iM + 1)
367                 return AVERROR_INVALIDDATA;
368
369             while (zerun--)
370                 hcode[im++] = 0;
371
372             im--;
373         } else if (l >= (uint64_t) SHORT_ZEROCODE_RUN) {
374             int zerun = l - SHORT_ZEROCODE_RUN + 2;
375
376             if (im + zerun > iM + 1)
377                 return AVERROR_INVALIDDATA;
378
379             while (zerun--)
380                 hcode[im++] = 0;
381
382             im--;
383         }
384     }
385
386     bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
387     huf_canonical_code_table(hcode);
388
389     return 0;
390 }
391
392 static int huf_build_dec_table(const uint64_t *hcode, int im,
393                                int iM, HufDec *hdecod)
394 {
395     for (; im <= iM; im++) {
396         uint64_t c = hcode[im] >> 6;
397         int i, l = hcode[im] & 63;
398
399         if (c >> l)
400             return AVERROR_INVALIDDATA;
401
402         if (l > HUF_DECBITS) {
403             HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
404             if (pl->len)
405                 return AVERROR_INVALIDDATA;
406
407             pl->lit++;
408
409             pl->p = av_realloc_f(pl->p, pl->lit, sizeof(int));
410             if (!pl->p)
411                 return AVERROR(ENOMEM);
412
413             pl->p[pl->lit - 1] = im;
414         } else if (l) {
415             HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
416
417             for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
418                 if (pl->len || pl->p)
419                     return AVERROR_INVALIDDATA;
420                 pl->len = l;
421                 pl->lit = im;
422             }
423         }
424     }
425
426     return 0;
427 }
428
429 #define get_char(c, lc, gb) {                   \
430     c = (c << 8) | bytestream2_get_byte(gb);    \
431     lc += 8;                                    \
432 }
433
434 #define get_code(po, rlc, c, lc, gb, out, oe) { \
435     if (po == rlc) {                            \
436         if (lc < 8)                             \
437             get_char(c, lc, gb);                \
438         lc -= 8;                                \
439                                                 \
440         cs = c >> lc;                           \
441                                                 \
442         if (out + cs > oe)                      \
443             return AVERROR_INVALIDDATA;         \
444                                                 \
445         s = out[-1];                            \
446                                                 \
447         while (cs-- > 0)                        \
448             *out++ = s;                         \
449     } else if (out < oe) {                      \
450         *out++ = po;                            \
451     } else {                                    \
452         return AVERROR_INVALIDDATA;             \
453     }                                           \
454 }
455
456 static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
457                       GetByteContext *gb, int nbits,
458                       int rlc, int no, uint16_t *out)
459 {
460     uint64_t c = 0;
461     uint16_t *outb = out;
462     uint16_t *oe = out + no;
463     const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
464     uint8_t cs, s;
465     int i, lc = 0;
466
467     while (gb->buffer < ie) {
468         get_char(c, lc, gb);
469
470         while (lc >= HUF_DECBITS) {
471             const HufDec pl = hdecod[(c >> (lc-HUF_DECBITS)) & HUF_DECMASK];
472
473             if (pl.len) {
474                 lc -= pl.len;
475                 get_code(pl.lit, rlc, c, lc, gb, out, oe);
476             } else {
477                 int j;
478
479                 if (!pl.p)
480                     return AVERROR_INVALIDDATA;
481
482                 for (j = 0; j < pl.lit; j++) {
483                     int l = hcode[pl.p[j]] & 63;
484
485                     while (lc < l && bytestream2_get_bytes_left(gb) > 0)
486                         get_char(c, lc, gb);
487
488                     if (lc >= l) {
489                         if ((hcode[pl.p[j]] >> 6) ==
490                             ((c >> (lc - l)) & ((1LL << l) - 1))) {
491                             lc -= l;
492                             get_code(pl.p[j], rlc, c, lc, gb, out, oe);
493                             break;
494                         }
495                     }
496                 }
497
498                 if (j == pl.lit)
499                     return AVERROR_INVALIDDATA;
500             }
501         }
502     }
503
504     i = (8 - nbits) & 7;
505     c >>= i;
506     lc -= i;
507
508     while (lc > 0) {
509         const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
510
511         if (pl.len) {
512             lc -= pl.len;
513             get_code(pl.lit, rlc, c, lc, gb, out, oe);
514         } else {
515             return AVERROR_INVALIDDATA;
516         }
517     }
518
519     if (out - outb != no)
520         return AVERROR_INVALIDDATA;
521     return 0;
522 }
523
524 static int huf_uncompress(GetByteContext *gb,
525                           uint16_t *dst, int dst_size)
526 {
527     int32_t src_size, im, iM;
528     uint32_t nBits;
529     uint64_t *freq;
530     HufDec *hdec;
531     int ret, i;
532
533     src_size = bytestream2_get_le32(gb);
534     im = bytestream2_get_le32(gb);
535     iM = bytestream2_get_le32(gb);
536     bytestream2_skip(gb, 4);
537     nBits = bytestream2_get_le32(gb);
538     if (im < 0 || im >= HUF_ENCSIZE ||
539         iM < 0 || iM >= HUF_ENCSIZE ||
540         src_size < 0)
541         return AVERROR_INVALIDDATA;
542
543     bytestream2_skip(gb, 4);
544
545     freq = av_calloc(HUF_ENCSIZE, sizeof(*freq));
546     hdec = av_calloc(HUF_DECSIZE, sizeof(*hdec));
547     if (!freq || !hdec) {
548         ret = AVERROR(ENOMEM);
549         goto fail;
550     }
551
552     if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
553         goto fail;
554
555     if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
556         ret = AVERROR_INVALIDDATA;
557         goto fail;
558     }
559
560     if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
561         goto fail;
562     ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
563
564 fail:
565     for (i = 0; i < HUF_DECSIZE; i++) {
566         if (hdec)
567             av_freep(&hdec[i].p);
568     }
569
570     av_free(freq);
571     av_free(hdec);
572
573     return ret;
574 }
575
576 static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
577 {
578     int16_t ls = l;
579     int16_t hs = h;
580     int hi = hs;
581     int ai = ls + (hi & 1) + (hi >> 1);
582     int16_t as = ai;
583     int16_t bs = ai - hi;
584
585     *a = as;
586     *b = bs;
587 }
588
589 #define NBITS      16
590 #define A_OFFSET  (1 << (NBITS  - 1))
591 #define MOD_MASK  ((1 << NBITS) - 1)
592
593 static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
594 {
595     int m = l;
596     int d = h;
597     int bb = (m - (d >> 1)) & MOD_MASK;
598     int aa = (d + bb - A_OFFSET) & MOD_MASK;
599     *b = bb;
600     *a = aa;
601 }
602
603 static void wav_decode(uint16_t *in, int nx, int ox,
604                        int ny, int oy, uint16_t mx)
605 {
606     int w14 = (mx < (1 << 14));
607     int n = (nx > ny) ? ny: nx;
608     int p = 1;
609     int p2;
610
611     while (p <= n)
612         p <<= 1;
613
614     p >>= 1;
615     p2  = p;
616     p >>= 1;
617
618     while (p >= 1) {
619         uint16_t *py = in;
620         uint16_t *ey = in + oy * (ny - p2);
621         uint16_t i00, i01, i10, i11;
622         int oy1 = oy * p;
623         int oy2 = oy * p2;
624         int ox1 = ox * p;
625         int ox2 = ox * p2;
626
627         for (; py <= ey; py += oy2) {
628             uint16_t *px = py;
629             uint16_t *ex = py + ox * (nx - p2);
630
631             for (; px <= ex; px += ox2) {
632                 uint16_t *p01 = px  + ox1;
633                 uint16_t *p10 = px  + oy1;
634                 uint16_t *p11 = p10 + ox1;
635
636                 if (w14) {
637                     wdec14(*px,  *p10, &i00, &i10);
638                     wdec14(*p01, *p11, &i01, &i11);
639                     wdec14(i00, i01, px,  p01);
640                     wdec14(i10, i11, p10, p11);
641                 } else {
642                     wdec16(*px,  *p10, &i00, &i10);
643                     wdec16(*p01, *p11, &i01, &i11);
644                     wdec16(i00, i01, px,  p01);
645                     wdec16(i10, i11, p10, p11);
646                 }
647             }
648
649             if (nx & p) {
650                 uint16_t *p10 = px + oy1;
651
652                 if (w14)
653                     wdec14(*px, *p10, &i00, p10);
654                 else
655                     wdec16(*px, *p10, &i00, p10);
656
657                 *px = i00;
658             }
659         }
660
661         if (ny & p) {
662             uint16_t *px = py;
663             uint16_t *ex = py + ox * (nx - p2);
664
665             for (; px <= ex; px += ox2) {
666                 uint16_t *p01 = px + ox1;
667
668                 if (w14)
669                     wdec14(*px, *p01, &i00, p01);
670                 else
671                     wdec16(*px, *p01, &i00, p01);
672
673                 *px = i00;
674             }
675         }
676
677         p2 = p;
678         p >>= 1;
679     }
680 }
681
682 static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize, int dsize, EXRThreadData *td)
683 {
684     GetByteContext gb;
685     uint16_t maxval, min_non_zero, max_non_zero;
686     uint16_t *ptr, *tmp = (uint16_t *)td->tmp;
687     int8_t *out;
688     int ret, i, j;
689
690     if (!td->bitmap)
691         td->bitmap = av_malloc(BITMAP_SIZE);
692     if (!td->lut)
693         td->lut = av_malloc(1 << 17);
694     if (!td->bitmap || !td->lut)
695         return AVERROR(ENOMEM);
696
697     bytestream2_init(&gb, src, ssize);
698     min_non_zero = bytestream2_get_le16(&gb);
699     max_non_zero = bytestream2_get_le16(&gb);
700
701     if (max_non_zero >= BITMAP_SIZE)
702         return AVERROR_INVALIDDATA;
703
704     memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
705     if (min_non_zero <= max_non_zero)
706         bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
707                                max_non_zero - min_non_zero + 1);
708     memset(td->bitmap + max_non_zero, 0, BITMAP_SIZE - max_non_zero);
709
710     maxval = reverse_lut(td->bitmap, td->lut);
711
712     ret = huf_uncompress(&gb, tmp, dsize / sizeof(int16_t));
713     if (ret)
714         return ret;
715
716     ptr = tmp;
717     for (i = 0; i < s->nb_channels; i++) {
718         EXRChannel *channel = &s->channels[i];
719         int size = channel->pixel_type;
720
721         for (j = 0; j < size; j++)
722             wav_decode(ptr + j, s->xdelta, size, s->ysize, s->xdelta * size, maxval);
723         ptr += s->xdelta * s->ysize * size;
724     }
725
726     apply_lut(td->lut, tmp, dsize / sizeof(int16_t));
727
728     out = td->uncompressed_data;
729     for (i = 0; i < s->ysize; i++) {
730         for (j = 0; j < s->nb_channels; j++) {
731             uint16_t *in = tmp + j * s->xdelta * s->ysize + i * s->xdelta;
732             memcpy(out, in, s->xdelta * 2);
733             out += s->xdelta * 2;
734         }
735     }
736
737     return 0;
738 }
739
740 static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
741                             int compressed_size, int uncompressed_size,
742                             EXRThreadData *td)
743 {
744     unsigned long dest_len = uncompressed_size;
745     const uint8_t *in = td->tmp;
746     uint8_t *out;
747     int c, i, j;
748
749     if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
750         dest_len != uncompressed_size)
751         return AVERROR(EINVAL);
752
753     out = td->uncompressed_data;
754     for (i = 0; i < s->ysize; i++) {
755         for (c = 0; c < s->nb_channels; c++) {
756             EXRChannel *channel = &s->channels[c];
757             const uint8_t *ptr[4];
758             uint32_t pixel = 0;
759
760             switch (channel->pixel_type) {
761             case EXR_FLOAT:
762                 ptr[0] = in;
763                 ptr[1] = ptr[0] + s->xdelta;
764                 ptr[2] = ptr[1] + s->xdelta;
765                 in = ptr[2] + s->xdelta;
766
767                 for (j = 0; j < s->xdelta; ++j) {
768                     uint32_t diff = (*(ptr[0]++) << 24) |
769                                     (*(ptr[1]++) << 16) |
770                                     (*(ptr[2]++) <<  8);
771                     pixel += diff;
772                     bytestream_put_le32(&out, pixel);
773                 }
774                 break;
775             case EXR_HALF:
776                 ptr[0] = in;
777                 ptr[1] = ptr[0] + s->xdelta;
778                 in = ptr[1] + s->xdelta;
779                 for (j = 0; j < s->xdelta; j++) {
780                     uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
781
782                     pixel += diff;
783                     bytestream_put_le16(&out, pixel);
784                 }
785                 break;
786             default:
787                 av_assert1(0);
788             }
789         }
790     }
791
792     return 0;
793 }
794
795 static int decode_block(AVCodecContext *avctx, void *tdata,
796                         int jobnr, int threadnr)
797 {
798     EXRContext *s = avctx->priv_data;
799     AVFrame *const p = s->picture;
800     EXRThreadData *td = &s->thread_data[threadnr];
801     const uint8_t *channel_buffer[4] = { 0 };
802     const uint8_t *buf = s->buf;
803     uint64_t line_offset, uncompressed_size;
804     uint32_t xdelta = s->xdelta;
805     uint16_t *ptr_x;
806     uint8_t *ptr;
807     int32_t data_size, line;
808     const uint8_t *src;
809     int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components;
810     int bxmin = s->xmin * 2 * s->desc->nb_components;
811     int i, x, buf_size = s->buf_size;
812     int av_unused ret;
813
814     line_offset = AV_RL64(s->table + jobnr * 8);
815     // Check if the buffer has the required bytes needed from the offset
816     if (line_offset > buf_size - 8)
817         return AVERROR_INVALIDDATA;
818
819     src = buf + line_offset + 8;
820     line = AV_RL32(src - 8);
821     if (line < s->ymin || line > s->ymax)
822         return AVERROR_INVALIDDATA;
823
824     data_size = AV_RL32(src - 4);
825     if (data_size <= 0 || data_size > buf_size)
826         return AVERROR_INVALIDDATA;
827
828     s->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1);
829     uncompressed_size = s->scan_line_size * s->ysize;
830     if ((s->compr == EXR_RAW && (data_size != uncompressed_size ||
831                                  line_offset > buf_size - uncompressed_size)) ||
832         (s->compr != EXR_RAW && (data_size > uncompressed_size ||
833                                  line_offset > buf_size - data_size))) {
834         return AVERROR_INVALIDDATA;
835     }
836
837     if (data_size < uncompressed_size) {
838         av_fast_padded_malloc(&td->uncompressed_data, &td->uncompressed_size, uncompressed_size);
839         av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
840         if (!td->uncompressed_data || !td->tmp)
841             return AVERROR(ENOMEM);
842
843         switch (s->compr) {
844         case EXR_ZIP1:
845         case EXR_ZIP16:
846             ret = zip_uncompress(src, data_size, uncompressed_size, td);
847             break;
848         case EXR_PIZ:
849             ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
850             break;
851         case EXR_PXR24:
852             ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
853             break;
854         case EXR_RLE:
855             ret = rle_uncompress(src, data_size, uncompressed_size, td);
856         }
857
858         src = td->uncompressed_data;
859     }
860
861     channel_buffer[0] = src + xdelta * s->channel_offsets[0];
862     channel_buffer[1] = src + xdelta * s->channel_offsets[1];
863     channel_buffer[2] = src + xdelta * s->channel_offsets[2];
864     if (s->channel_offsets[3] >= 0)
865         channel_buffer[3] = src + xdelta * s->channel_offsets[3];
866
867     ptr = p->data[0] + line * p->linesize[0];
868     for (i = 0; i < s->scan_lines_per_block && line + i <= s->ymax; i++, ptr += p->linesize[0]) {
869         const uint8_t *r, *g, *b, *a;
870
871         r = channel_buffer[0];
872         g = channel_buffer[1];
873         b = channel_buffer[2];
874         if (channel_buffer[3])
875             a = channel_buffer[3];
876
877         ptr_x = (uint16_t *)ptr;
878
879         // Zero out the start if xmin is not 0
880         memset(ptr_x, 0, bxmin);
881         ptr_x += s->xmin * s->desc->nb_components;
882         if (s->pixel_type == EXR_FLOAT) {
883             // 32-bit
884             for (x = 0; x < xdelta; x++) {
885                 *ptr_x++ = exr_flt2uint(bytestream_get_le32(&r));
886                 *ptr_x++ = exr_flt2uint(bytestream_get_le32(&g));
887                 *ptr_x++ = exr_flt2uint(bytestream_get_le32(&b));
888                 if (channel_buffer[3])
889                     *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
890             }
891         } else {
892             // 16-bit
893             for (x = 0; x < xdelta; x++) {
894                 *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&r));
895                 *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&g));
896                 *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&b));
897                 if (channel_buffer[3])
898                     *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));
899             }
900         }
901
902         // Zero out the end if xmax+1 is not w
903         memset(ptr_x, 0, axmax);
904
905         channel_buffer[0] += s->scan_line_size;
906         channel_buffer[1] += s->scan_line_size;
907         channel_buffer[2] += s->scan_line_size;
908         if (channel_buffer[3])
909             channel_buffer[3] += s->scan_line_size;
910     }
911
912     return 0;
913 }
914
915 static int decode_frame(AVCodecContext *avctx,
916                         void *data,
917                         int *got_frame,
918                         AVPacket *avpkt)
919 {
920     const uint8_t *buf      = avpkt->data;
921     unsigned int   buf_size = avpkt->size;
922     const uint8_t *buf_end  = buf + buf_size;
923
924     EXRContext *const s = avctx->priv_data;
925     ThreadFrame frame = { .f = data };
926     AVFrame *picture  = data;
927     uint8_t *ptr;
928
929     int i, y, magic_number, version, flags, ret;
930     int w = 0;
931     int h = 0;
932
933     int out_line_size;
934     int scan_line_blocks;
935
936     unsigned int current_channel_offset = 0;
937
938     s->xmin = ~0;
939     s->xmax = ~0;
940     s->ymin = ~0;
941     s->ymax = ~0;
942     s->xdelta = ~0;
943     s->ydelta = ~0;
944     s->channel_offsets[0] = -1;
945     s->channel_offsets[1] = -1;
946     s->channel_offsets[2] = -1;
947     s->channel_offsets[3] = -1;
948     s->pixel_type = -1;
949     s->nb_channels = 0;
950     s->compr = -1;
951     s->buf = buf;
952     s->buf_size = buf_size;
953
954     if (buf_size < 10) {
955         av_log(avctx, AV_LOG_ERROR, "Too short header to parse\n");
956         return AVERROR_INVALIDDATA;
957     }
958
959     magic_number = bytestream_get_le32(&buf);
960     if (magic_number != 20000630) { // As per documentation of OpenEXR it's supposed to be int 20000630 little-endian
961         av_log(avctx, AV_LOG_ERROR, "Wrong magic number %d\n", magic_number);
962         return AVERROR_INVALIDDATA;
963     }
964
965     version = bytestream_get_byte(&buf);
966     if (version != 2) {
967         avpriv_report_missing_feature(avctx, "Version %d", version);
968         return AVERROR_PATCHWELCOME;
969     }
970
971     flags = bytestream_get_le24(&buf);
972     if (flags & 0x2) {
973         avpriv_report_missing_feature(avctx, "Tile support");
974         return AVERROR_PATCHWELCOME;
975     }
976
977     // Parse the header
978     while (buf < buf_end && buf[0]) {
979         unsigned int variable_buffer_data_size;
980         // Process the channel list
981         if (check_header_variable(avctx, &buf, buf_end, "channels", "chlist", 38, &variable_buffer_data_size) >= 0) {
982             const uint8_t *channel_list_end;
983             if (!variable_buffer_data_size)
984                 return AVERROR_INVALIDDATA;
985
986             channel_list_end = buf + variable_buffer_data_size;
987             while (channel_list_end - buf >= 19) {
988                 EXRChannel *channel;
989                 enum ExrPixelType current_pixel_type;
990                 int channel_index = -1;
991                 int xsub, ysub;
992
993                 if (!strcmp(buf, "R"))
994                     channel_index = 0;
995                 else if (!strcmp(buf, "G"))
996                     channel_index = 1;
997                 else if (!strcmp(buf, "B"))
998                     channel_index = 2;
999                 else if (!strcmp(buf, "A"))
1000                     channel_index = 3;
1001                 else
1002                     av_log(avctx, AV_LOG_WARNING, "Unsupported channel %.256s\n", buf);
1003
1004                 while (bytestream_get_byte(&buf) && buf < channel_list_end)
1005                     continue; /* skip */
1006
1007                 if (channel_list_end - * &buf < 4) {
1008                     av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
1009                     return AVERROR_INVALIDDATA;
1010                 }
1011
1012                 current_pixel_type = bytestream_get_le32(&buf);
1013                 if (current_pixel_type > 2) {
1014                     av_log(avctx, AV_LOG_ERROR, "Unknown pixel type\n");
1015                     return AVERROR_INVALIDDATA;
1016                 }
1017
1018                 buf += 4;
1019                 xsub = bytestream_get_le32(&buf);
1020                 ysub = bytestream_get_le32(&buf);
1021                 if (xsub != 1 || ysub != 1) {
1022                     avpriv_report_missing_feature(avctx, "Subsampling %dx%d", xsub, ysub);
1023                     return AVERROR_PATCHWELCOME;
1024                 }
1025
1026                 if (channel_index >= 0) {
1027                     if (s->pixel_type != -1 && s->pixel_type != current_pixel_type) {
1028                         av_log(avctx, AV_LOG_ERROR, "RGB channels not of the same depth\n");
1029                         return AVERROR_INVALIDDATA;
1030                     }
1031                     s->pixel_type = current_pixel_type;
1032                     s->channel_offsets[channel_index] = current_channel_offset;
1033                 }
1034
1035                 s->channels = av_realloc_f(s->channels, ++s->nb_channels, sizeof(EXRChannel));
1036                 if (!s->channels)
1037                     return AVERROR(ENOMEM);
1038                 channel = &s->channels[s->nb_channels - 1];
1039                 channel->pixel_type = current_pixel_type;
1040                 channel->xsub = xsub;
1041                 channel->ysub = ysub;
1042
1043                 current_channel_offset += 1 << current_pixel_type;
1044             }
1045
1046             /* Check if all channels are set with an offset or if the channels
1047              * are causing an overflow  */
1048
1049             if (FFMIN3(s->channel_offsets[0],
1050                        s->channel_offsets[1],
1051                        s->channel_offsets[2]) < 0) {
1052                 if (s->channel_offsets[0] < 0)
1053                     av_log(avctx, AV_LOG_ERROR, "Missing red channel\n");
1054                 if (s->channel_offsets[1] < 0)
1055                     av_log(avctx, AV_LOG_ERROR, "Missing green channel\n");
1056                 if (s->channel_offsets[2] < 0)
1057                     av_log(avctx, AV_LOG_ERROR, "Missing blue channel\n");
1058                 return AVERROR_INVALIDDATA;
1059             }
1060
1061             buf = channel_list_end;
1062             continue;
1063         } else if (check_header_variable(avctx, &buf, buf_end, "dataWindow", "box2i", 31, &variable_buffer_data_size) >= 0) {
1064             if (!variable_buffer_data_size)
1065                 return AVERROR_INVALIDDATA;
1066
1067             s->xmin = AV_RL32(buf);
1068             s->ymin = AV_RL32(buf + 4);
1069             s->xmax = AV_RL32(buf + 8);
1070             s->ymax = AV_RL32(buf + 12);
1071             s->xdelta = (s->xmax - s->xmin) + 1;
1072             s->ydelta = (s->ymax - s->ymin) + 1;
1073
1074             buf += variable_buffer_data_size;
1075             continue;
1076         } else if (check_header_variable(avctx, &buf, buf_end, "displayWindow", "box2i", 34, &variable_buffer_data_size) >= 0) {
1077             if (!variable_buffer_data_size)
1078                 return AVERROR_INVALIDDATA;
1079
1080             w = AV_RL32(buf + 8) + 1;
1081             h = AV_RL32(buf + 12) + 1;
1082
1083             buf += variable_buffer_data_size;
1084             continue;
1085         } else if (check_header_variable(avctx, &buf, buf_end, "lineOrder", "lineOrder", 25, &variable_buffer_data_size) >= 0) {
1086             if (!variable_buffer_data_size)
1087                 return AVERROR_INVALIDDATA;
1088
1089             av_log(avctx, AV_LOG_DEBUG, "line order : %d\n", *buf);
1090             if (*buf > 2) {
1091                 av_log(avctx, AV_LOG_ERROR, "Unknown line order\n");
1092                 return AVERROR_INVALIDDATA;
1093             }
1094
1095             buf += variable_buffer_data_size;
1096             continue;
1097         } else if (check_header_variable(avctx, &buf, buf_end, "pixelAspectRatio", "float", 31, &variable_buffer_data_size) >= 0) {
1098             if (!variable_buffer_data_size)
1099                 return AVERROR_INVALIDDATA;
1100
1101             avctx->sample_aspect_ratio = av_d2q(av_int2float(AV_RL32(buf)), 255);
1102
1103             buf += variable_buffer_data_size;
1104             continue;
1105         } else if (check_header_variable(avctx, &buf, buf_end, "compression", "compression", 29, &variable_buffer_data_size) >= 0) {
1106             if (!variable_buffer_data_size)
1107                 return AVERROR_INVALIDDATA;
1108
1109             if (s->compr == -1)
1110                 s->compr = *buf;
1111             else
1112                 av_log(avctx, AV_LOG_WARNING, "Found more than one compression attribute\n");
1113
1114             buf += variable_buffer_data_size;
1115             continue;
1116         }
1117
1118         // Check if there is enough bytes for a header
1119         if (buf_end - buf <= 9) {
1120             av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
1121             return AVERROR_INVALIDDATA;
1122         }
1123
1124         // Process unknown variables
1125         for (i = 0; i < 2; i++) {
1126             // Skip variable name/type
1127             while (++buf < buf_end)
1128                 if (buf[0] == 0x0)
1129                     break;
1130         }
1131         buf++;
1132         // Skip variable length
1133         if (buf_end - buf >= 5) {
1134             variable_buffer_data_size = get_header_variable_length(&buf, buf_end);
1135             if (!variable_buffer_data_size) {
1136                 av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
1137                 return AVERROR_INVALIDDATA;
1138             }
1139             buf += variable_buffer_data_size;
1140         }
1141     }
1142
1143     if (s->compr == -1) {
1144         av_log(avctx, AV_LOG_ERROR, "Missing compression attribute\n");
1145         return AVERROR_INVALIDDATA;
1146     }
1147
1148     if (buf >= buf_end) {
1149         av_log(avctx, AV_LOG_ERROR, "Incomplete frame\n");
1150         return AVERROR_INVALIDDATA;
1151     }
1152     buf++;
1153
1154     switch (s->pixel_type) {
1155     case EXR_FLOAT:
1156     case EXR_HALF:
1157         if (s->channel_offsets[3] >= 0)
1158             avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1159         else
1160             avctx->pix_fmt = AV_PIX_FMT_RGB48;
1161         break;
1162     case EXR_UINT:
1163         avpriv_request_sample(avctx, "32-bit unsigned int");
1164         return AVERROR_PATCHWELCOME;
1165     default:
1166         av_log(avctx, AV_LOG_ERROR, "Missing channel list\n");
1167         return AVERROR_INVALIDDATA;
1168     }
1169
1170     switch (s->compr) {
1171     case EXR_RAW:
1172     case EXR_RLE:
1173     case EXR_ZIP1:
1174         s->scan_lines_per_block = 1;
1175         break;
1176     case EXR_PXR24:
1177     case EXR_ZIP16:
1178         s->scan_lines_per_block = 16;
1179         break;
1180     case EXR_PIZ:
1181         s->scan_lines_per_block = 32;
1182         break;
1183     default:
1184         avpriv_report_missing_feature(avctx, "Compression %d", s->compr);
1185         return AVERROR_PATCHWELCOME;
1186     }
1187
1188     // Verify the xmin, xmax, ymin, ymax and xdelta before setting the actual image size
1189     if (s->xmin > s->xmax ||
1190         s->ymin > s->ymax ||
1191         s->xdelta != s->xmax - s->xmin + 1 ||
1192         s->xmax >= w || s->ymax >= h) {
1193         av_log(avctx, AV_LOG_ERROR, "Wrong sizing or missing size information\n");
1194         return AVERROR_INVALIDDATA;
1195     }
1196
1197     if ((ret = ff_set_dimensions(avctx, w, h)) < 0)
1198         return ret;
1199
1200     s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1201     out_line_size = avctx->width * 2 * s->desc->nb_components;
1202     s->scan_line_size = s->xdelta * current_channel_offset;
1203     scan_line_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block;
1204
1205     if (s->compr != EXR_RAW) {
1206         size_t thread_data_size, prev_size;
1207         EXRThreadData *m;
1208
1209         prev_size = s->thread_data_size;
1210         if (av_size_mult(avctx->thread_count, sizeof(EXRThreadData), &thread_data_size))
1211             return AVERROR(EINVAL);
1212
1213         m = av_fast_realloc(s->thread_data, &s->thread_data_size, thread_data_size);
1214         if (!m)
1215             return AVERROR(ENOMEM);
1216         s->thread_data = m;
1217         memset(s->thread_data + prev_size, 0, s->thread_data_size - prev_size);
1218     }
1219
1220     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1221         return ret;
1222
1223     if (buf_end - buf < scan_line_blocks * 8)
1224         return AVERROR_INVALIDDATA;
1225     s->table = buf;
1226     ptr = picture->data[0];
1227
1228     // Zero out the start if ymin is not 0
1229     for (y = 0; y < s->ymin; y++) {
1230         memset(ptr, 0, out_line_size);
1231         ptr += picture->linesize[0];
1232     }
1233
1234     s->picture = picture;
1235     avctx->execute2(avctx, decode_block, s->thread_data, NULL, scan_line_blocks);
1236
1237     // Zero out the end if ymax+1 is not h
1238     for (y = s->ymax + 1; y < avctx->height; y++) {
1239         memset(ptr, 0, out_line_size);
1240         ptr += picture->linesize[0];
1241     }
1242
1243     picture->pict_type = AV_PICTURE_TYPE_I;
1244     *got_frame = 1;
1245
1246     return buf_size;
1247 }
1248
1249 static av_cold int decode_end(AVCodecContext *avctx)
1250 {
1251     EXRContext *s = avctx->priv_data;
1252     int i;
1253
1254     for (i = 0; i < s->thread_data_size / sizeof(EXRThreadData); i++) {
1255         EXRThreadData *td = &s->thread_data[i];
1256         av_freep(&td->uncompressed_data);
1257         av_freep(&td->tmp);
1258         av_freep(&td->bitmap);
1259         av_freep(&td->lut);
1260     }
1261
1262     av_freep(&s->thread_data);
1263     s->thread_data_size = 0;
1264     av_freep(&s->channels);
1265
1266     return 0;
1267 }
1268
1269 AVCodec ff_exr_decoder = {
1270     .name               = "exr",
1271     .long_name          = NULL_IF_CONFIG_SMALL("OpenEXR image"),
1272     .type               = AVMEDIA_TYPE_VIDEO,
1273     .id                 = AV_CODEC_ID_EXR,
1274     .priv_data_size     = sizeof(EXRContext),
1275     .close              = decode_end,
1276     .decode             = decode_frame,
1277     .capabilities       = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS | CODEC_CAP_SLICE_THREADS,
1278 };