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