GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/exr.c Lines: 759 982 77.3 %
Date: 2020-04-04 00:26:16 Branches: 418 618 67.6 %

Line Branch Exec Source
1
/*
2
 * OpenEXR (.exr) image decoder
3
 * Copyright (c) 2006 Industrial Light & Magic, a division of Lucas Digital Ltd. LLC
4
 * Copyright (c) 2009 Jimmy Christensen
5
 *
6
 * B44/B44A, Tile, UINT32 added by Jokyo Images support by CNC - French National Center for Cinema
7
 *
8
 * This file is part of FFmpeg.
9
 *
10
 * FFmpeg is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * FFmpeg is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with FFmpeg; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 */
24
25
/**
26
 * @file
27
 * OpenEXR decoder
28
 * @author Jimmy Christensen
29
 *
30
 * For more information on the OpenEXR format, visit:
31
 *  http://openexr.com/
32
 *
33
 * exr_flt2uint() and exr_halflt2uint() is credited to Reimar Döffinger.
34
 * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner.
35
 */
36
37
#include <float.h>
38
#include <zlib.h>
39
40
#include "libavutil/avassert.h"
41
#include "libavutil/common.h"
42
#include "libavutil/imgutils.h"
43
#include "libavutil/intfloat.h"
44
#include "libavutil/avstring.h"
45
#include "libavutil/opt.h"
46
#include "libavutil/color_utils.h"
47
48
#include "avcodec.h"
49
#include "bytestream.h"
50
51
#if HAVE_BIGENDIAN
52
#include "bswapdsp.h"
53
#endif
54
55
#include "exrdsp.h"
56
#include "get_bits.h"
57
#include "internal.h"
58
#include "mathops.h"
59
#include "thread.h"
60
61
enum ExrCompr {
62
    EXR_RAW,
63
    EXR_RLE,
64
    EXR_ZIP1,
65
    EXR_ZIP16,
66
    EXR_PIZ,
67
    EXR_PXR24,
68
    EXR_B44,
69
    EXR_B44A,
70
    EXR_DWA,
71
    EXR_DWB,
72
    EXR_UNKN,
73
};
74
75
enum ExrPixelType {
76
    EXR_UINT,
77
    EXR_HALF,
78
    EXR_FLOAT,
79
    EXR_UNKNOWN,
80
};
81
82
enum ExrTileLevelMode {
83
    EXR_TILE_LEVEL_ONE,
84
    EXR_TILE_LEVEL_MIPMAP,
85
    EXR_TILE_LEVEL_RIPMAP,
86
    EXR_TILE_LEVEL_UNKNOWN,
87
};
88
89
enum ExrTileLevelRound {
90
    EXR_TILE_ROUND_UP,
91
    EXR_TILE_ROUND_DOWN,
92
    EXR_TILE_ROUND_UNKNOWN,
93
};
94
95
typedef struct EXRChannel {
96
    int xsub, ysub;
97
    enum ExrPixelType pixel_type;
98
} EXRChannel;
99
100
typedef struct EXRTileAttribute {
101
    int32_t xSize;
102
    int32_t ySize;
103
    enum ExrTileLevelMode level_mode;
104
    enum ExrTileLevelRound level_round;
105
} EXRTileAttribute;
106
107
typedef struct EXRThreadData {
108
    uint8_t *uncompressed_data;
109
    int uncompressed_size;
110
111
    uint8_t *tmp;
112
    int tmp_size;
113
114
    uint8_t *bitmap;
115
    uint16_t *lut;
116
117
    int ysize, xsize;
118
119
    int channel_line_size;
120
} EXRThreadData;
121
122
typedef struct EXRContext {
123
    AVClass *class;
124
    AVFrame *picture;
125
    AVCodecContext *avctx;
126
    ExrDSPContext dsp;
127
128
#if HAVE_BIGENDIAN
129
    BswapDSPContext bbdsp;
130
#endif
131
132
    enum ExrCompr compression;
133
    enum ExrPixelType pixel_type;
134
    int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
135
    const AVPixFmtDescriptor *desc;
136
137
    int w, h;
138
    uint32_t xmax, xmin;
139
    uint32_t ymax, ymin;
140
    uint32_t xdelta, ydelta;
141
142
    int scan_lines_per_block;
143
144
    EXRTileAttribute tile_attr; /* header data attribute of tile */
145
    int is_tile; /* 0 if scanline, 1 if tile */
146
147
    int is_luma;/* 1 if there is an Y plane */
148
149
    GetByteContext gb;
150
    const uint8_t *buf;
151
    int buf_size;
152
153
    EXRChannel *channels;
154
    int nb_channels;
155
    int current_channel_offset;
156
157
    EXRThreadData *thread_data;
158
159
    const char *layer;
160
161
    enum AVColorTransferCharacteristic apply_trc_type;
162
    float gamma;
163
    uint16_t gamma_table[65536];
164
} EXRContext;
165
166
/* -15 stored using a single precision bias of 127 */
167
#define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
168
169
/* max exponent value in single precision that will be converted
170
 * to Inf or Nan when stored as a half-float */
171
#define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
172
173
/* 255 is the max exponent biased value */
174
#define FLOAT_MAX_BIASED_EXP (0xFF << 23)
175
176
#define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
177
178
/**
179
 * Convert a half float as a uint16_t into a full float.
180
 *
181
 * @param hf half float as uint16_t
182
 *
183
 * @return float value
184
 */
185
static union av_intfloat32 exr_half2float(uint16_t hf)
186
{
187
    unsigned int sign = (unsigned int) (hf >> 15);
188
    unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
189
    unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
190
    union av_intfloat32 f;
191
192
    if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
193
        // we have a half-float NaN or Inf
194
        // half-float NaNs will be converted to a single precision NaN
195
        // half-float Infs will be converted to a single precision Inf
196
        exp = FLOAT_MAX_BIASED_EXP;
197
        if (mantissa)
198
            mantissa = (1 << 23) - 1;    // set all bits to indicate a NaN
199
    } else if (exp == 0x0) {
200
        // convert half-float zero/denorm to single precision value
201
        if (mantissa) {
202
            mantissa <<= 1;
203
            exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
204
            // check for leading 1 in denorm mantissa
205
            while ((mantissa & (1 << 10))) {
206
                // for every leading 0, decrement single precision exponent by 1
207
                // and shift half-float mantissa value to the left
208
                mantissa <<= 1;
209
                exp -= (1 << 23);
210
            }
211
            // clamp the mantissa to 10 bits
212
            mantissa &= ((1 << 10) - 1);
213
            // shift left to generate single-precision mantissa of 23 bits
214
            mantissa <<= 13;
215
        }
216
    } else {
217
        // shift left to generate single-precision mantissa of 23 bits
218
        mantissa <<= 13;
219
        // generate single precision biased exponent value
220
        exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
221
    }
222
223
    f.i = (sign << 31) | exp | mantissa;
224
225
    return f;
226
}
227
228
229
/**
230
 * Convert from 32-bit float as uint32_t to uint16_t.
231
 *
232
 * @param v 32-bit float
233
 *
234
 * @return normalized 16-bit unsigned int
235
 */
236
141816
static inline uint16_t exr_flt2uint(int32_t v)
237
{
238
141816
    int32_t exp = v >> 23;
239
    // "HACK": negative values result in exp<  0, so clipping them to 0
240
    // is also handled by this condition, avoids explicit check for sign bit.
241
141816
    if (exp <= 127 + 7 - 24) // we would shift out all bits anyway
242
4830
        return 0;
243
136986
    if (exp >= 127)
244
3156
        return 0xffff;
245
133830
    v &= 0x007fffff;
246
133830
    return (v + (1 << 23)) >> (127 + 7 - exp);
247
}
248
249
/**
250
 * Convert from 16-bit float as uint16_t to uint16_t.
251
 *
252
 * @param v 16-bit float
253
 *
254
 * @return normalized 16-bit unsigned int
255
 */
256
11898966
static inline uint16_t exr_halflt2uint(uint16_t v)
257
{
258
11898966
    unsigned exp = 14 - (v >> 10);
259
11898966
    if (exp >= 14) {
260
10083670
        if (exp == 14)
261
416764
            return (v >> 9) & 1;
262
        else
263
9666906
            return (v & 0x8000) ? 0 : 0xffff;
264
    }
265
1815296
    v <<= 6;
266
1815296
    return (v + (1 << 16)) >> (exp + 1);
267
}
268
269
1504
static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
270
                          int uncompressed_size, EXRThreadData *td)
271
{
272
1504
    unsigned long dest_len = uncompressed_size;
273
274
1504
    if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
275
1504
        dest_len != uncompressed_size)
276
        return AVERROR_INVALIDDATA;
277
278
    av_assert1(uncompressed_size % 2 == 0);
279
280
1504
    s->dsp.predictor(td->tmp, uncompressed_size);
281
1504
    s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
282
283
1504
    return 0;
284
}
285
286
1386
static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size,
287
                          int uncompressed_size, EXRThreadData *td)
288
{
289
1386
    uint8_t *d      = td->tmp;
290
1386
    const int8_t *s = src;
291
1386
    int ssize       = compressed_size;
292
1386
    int dsize       = uncompressed_size;
293
1386
    uint8_t *dend   = d + dsize;
294
    int count;
295
296
378128
    while (ssize > 0) {
297
376742
        count = *s++;
298
299
376742
        if (count < 0) {
300
186494
            count = -count;
301
302
186494
            if ((dsize -= count) < 0 ||
303
186494
                (ssize -= count + 1) < 0)
304
                return AVERROR_INVALIDDATA;
305
306
3463010
            while (count--)
307
3276516
                *d++ = *s++;
308
        } else {
309
190248
            count++;
310
311
190248
            if ((dsize -= count) < 0 ||
312
190248
                (ssize -= 2) < 0)
313
                return AVERROR_INVALIDDATA;
314
315
3270228
            while (count--)
316
3079980
                *d++ = *s;
317
318
190248
            s++;
319
        }
320
    }
321
322
1386
    if (dend != d)
323
        return AVERROR_INVALIDDATA;
324
325
    av_assert1(uncompressed_size % 2 == 0);
326
327
1386
    ctx->dsp.predictor(td->tmp, uncompressed_size);
328
1386
    ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
329
330
1386
    return 0;
331
}
332
333
#define USHORT_RANGE (1 << 16)
334
#define BITMAP_SIZE  (1 << 13)
335
336
48
static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
337
{
338
48
    int i, k = 0;
339
340
3145776
    for (i = 0; i < USHORT_RANGE; i++)
341

3145728
        if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
342
5798
            lut[k++] = i;
343
344
48
    i = k - 1;
345
346
48
    memset(lut + k, 0, (USHORT_RANGE - k) * 2);
347
348
48
    return i;
349
}
350
351
48
static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
352
{
353
    int i;
354
355
1472148
    for (i = 0; i < dsize; ++i)
356
1472100
        dst[i] = lut[dst[i]];
357
48
}
358
359
#define HUF_ENCBITS 16  // literal (value) bit length
360
#define HUF_DECBITS 14  // decoding bit size (>= 8)
361
362
#define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1)  // encoding table size
363
#define HUF_DECSIZE (1 << HUF_DECBITS)        // decoding table size
364
#define HUF_DECMASK (HUF_DECSIZE - 1)
365
366
typedef struct HufDec {
367
    int len;
368
    int lit;
369
    int *p;
370
} HufDec;
371
372
48
static void huf_canonical_code_table(uint64_t *hcode)
373
{
374
48
    uint64_t c, n[59] = { 0 };
375
    int i;
376
377
3145824
    for (i = 0; i < HUF_ENCSIZE; ++i)
378
3145776
        n[hcode[i]] += 1;
379
380
48
    c = 0;
381
2832
    for (i = 58; i > 0; --i) {
382
2784
        uint64_t nc = ((c + n[i]) >> 1);
383
2784
        n[i] = c;
384
2784
        c    = nc;
385
    }
386
387
3145824
    for (i = 0; i < HUF_ENCSIZE; ++i) {
388
3145776
        int l = hcode[i];
389
390
3145776
        if (l > 0)
391
3404
            hcode[i] = l | (n[l]++ << 6);
392
    }
393
48
}
394
395
#define SHORT_ZEROCODE_RUN  59
396
#define LONG_ZEROCODE_RUN   63
397
#define SHORTEST_LONG_RUN   (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
398
#define LONGEST_LONG_RUN    (255 + SHORTEST_LONG_RUN)
399
400
48
static int huf_unpack_enc_table(GetByteContext *gb,
401
                                int32_t im, int32_t iM, uint64_t *hcode)
402
{
403
    GetBitContext gbit;
404
48
    int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
405
48
    if (ret < 0)
406
        return ret;
407
408
16678
    for (; im <= iM; im++) {
409
16630
        uint64_t l = hcode[im] = get_bits(&gbit, 6);
410
411
16630
        if (l == LONG_ZEROCODE_RUN) {
412
12358
            int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
413
414
12358
            if (im + zerun > iM + 1)
415
                return AVERROR_INVALIDDATA;
416
417
3152920
            while (zerun--)
418
3140562
                hcode[im++] = 0;
419
420
12358
            im--;
421
4272
        } else if (l >= SHORT_ZEROCODE_RUN) {
422
458
            int zerun = l - SHORT_ZEROCODE_RUN + 2;
423
424
458
            if (im + zerun > iM + 1)
425
                return AVERROR_INVALIDDATA;
426
427
1858
            while (zerun--)
428
1400
                hcode[im++] = 0;
429
430
458
            im--;
431
        }
432
    }
433
434
48
    bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
435
48
    huf_canonical_code_table(hcode);
436
437
48
    return 0;
438
}
439
440
48
static int huf_build_dec_table(const uint64_t *hcode, int im,
441
                               int iM, HufDec *hdecod)
442
{
443
3145824
    for (; im <= iM; im++) {
444
3145776
        uint64_t c = hcode[im] >> 6;
445
3145776
        int i, l = hcode[im] & 63;
446
447
3145776
        if (c >> l)
448
            return AVERROR_INVALIDDATA;
449
450
3145776
        if (l > HUF_DECBITS) {
451
            HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
452
            if (pl->len)
453
                return AVERROR_INVALIDDATA;
454
455
            pl->lit++;
456
457
            pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
458
            if (!pl->p)
459
                return AVERROR(ENOMEM);
460
461
            pl->p[pl->lit - 1] = im;
462
3145776
        } else if (l) {
463
3404
            HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
464
465
789836
            for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
466

786432
                if (pl->len || pl->p)
467
                    return AVERROR_INVALIDDATA;
468
786432
                pl->len = l;
469
786432
                pl->lit = im;
470
            }
471
        }
472
    }
473
474
48
    return 0;
475
}
476
477
#define get_char(c, lc, gb)                                                   \
478
{                                                                             \
479
        c   = (c << 8) | bytestream2_get_byte(gb);                            \
480
        lc += 8;                                                              \
481
}
482
483
#define get_code(po, rlc, c, lc, gb, out, oe, outb)                           \
484
{                                                                             \
485
        if (po == rlc) {                                                      \
486
            if (lc < 8)                                                       \
487
                get_char(c, lc, gb);                                          \
488
            lc -= 8;                                                          \
489
                                                                              \
490
            cs = c >> lc;                                                     \
491
                                                                              \
492
            if (out + cs > oe || out == outb)                                 \
493
                return AVERROR_INVALIDDATA;                                   \
494
                                                                              \
495
            s = out[-1];                                                      \
496
                                                                              \
497
            while (cs-- > 0)                                                  \
498
                *out++ = s;                                                   \
499
        } else if (out < oe) {                                                \
500
            *out++ = po;                                                      \
501
        } else {                                                              \
502
            return AVERROR_INVALIDDATA;                                       \
503
        }                                                                     \
504
}
505
506
48
static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
507
                      GetByteContext *gb, int nbits,
508
                      int rlc, int no, uint16_t *out)
509
{
510
48
    uint64_t c        = 0;
511
48
    uint16_t *outb    = out;
512
48
    uint16_t *oe      = out + no;
513
48
    const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
514
    uint8_t cs;
515
    uint16_t s;
516
48
    int i, lc = 0;
517
518
76904
    while (gb->buffer < ie) {
519
76856
        get_char(c, lc, gb);
520
521
385156
        while (lc >= HUF_DECBITS) {
522
308300
            const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
523
524
308300
            if (pl.len) {
525
308300
                lc -= pl.len;
526



1477504
                get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
527
            } else {
528
                int j;
529
530
                if (!pl.p)
531
                    return AVERROR_INVALIDDATA;
532
533
                for (j = 0; j < pl.lit; j++) {
534
                    int l = hcode[pl.p[j]] & 63;
535
536
                    while (lc < l && bytestream2_get_bytes_left(gb) > 0)
537
                        get_char(c, lc, gb);
538
539
                    if (lc >= l) {
540
                        if ((hcode[pl.p[j]] >> 6) ==
541
                            ((c >> (lc - l)) & ((1LL << l) - 1))) {
542
                            lc -= l;
543
                            get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb);
544
                            break;
545
                        }
546
                    }
547
                }
548
549
                if (j == pl.lit)
550
                    return AVERROR_INVALIDDATA;
551
            }
552
        }
553
    }
554
555
48
    i   = (8 - nbits) & 7;
556
48
    c >>= i;
557
48
    lc -= i;
558
559
124
    while (lc > 0) {
560
76
        const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
561
562

76
        if (pl.len && lc >= pl.len) {
563
76
            lc -= pl.len;
564



520
            get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
565
        } else {
566
            return AVERROR_INVALIDDATA;
567
        }
568
    }
569
570
48
    if (out - outb != no)
571
        return AVERROR_INVALIDDATA;
572
48
    return 0;
573
}
574
575
48
static int huf_uncompress(GetByteContext *gb,
576
                          uint16_t *dst, int dst_size)
577
{
578
    int32_t src_size, im, iM;
579
    uint32_t nBits;
580
    uint64_t *freq;
581
    HufDec *hdec;
582
    int ret, i;
583
584
48
    src_size = bytestream2_get_le32(gb);
585
48
    im       = bytestream2_get_le32(gb);
586
48
    iM       = bytestream2_get_le32(gb);
587
48
    bytestream2_skip(gb, 4);
588
48
    nBits = bytestream2_get_le32(gb);
589

48
    if (im < 0 || im >= HUF_ENCSIZE ||
590

48
        iM < 0 || iM >= HUF_ENCSIZE ||
591
        src_size < 0)
592
        return AVERROR_INVALIDDATA;
593
594
48
    bytestream2_skip(gb, 4);
595
596
48
    freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
597
48
    hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
598

48
    if (!freq || !hdec) {
599
        ret = AVERROR(ENOMEM);
600
        goto fail;
601
    }
602
603
48
    if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
604
        goto fail;
605
606
48
    if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
607
        ret = AVERROR_INVALIDDATA;
608
        goto fail;
609
    }
610
611
48
    if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
612
        goto fail;
613
48
    ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
614
615
48
fail:
616
786480
    for (i = 0; i < HUF_DECSIZE; i++)
617
786432
        if (hdec)
618
786432
            av_freep(&hdec[i].p);
619
620
48
    av_free(freq);
621
48
    av_free(hdec);
622
623
48
    return ret;
624
}
625
626
1958562
static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
627
{
628
1958562
    int16_t ls = l;
629
1958562
    int16_t hs = h;
630
1958562
    int hi     = hs;
631
1958562
    int ai     = ls + (hi & 1) + (hi >> 1);
632
1958562
    int16_t as = ai;
633
1958562
    int16_t bs = ai - hi;
634
635
1958562
    *a = as;
636
1958562
    *b = bs;
637
1958562
}
638
639
#define NBITS      16
640
#define A_OFFSET  (1 << (NBITS - 1))
641
#define MOD_MASK  ((1 << NBITS) - 1)
642
643
static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
644
{
645
    int m  = l;
646
    int d  = h;
647
    int bb = (m - (d >> 1)) & MOD_MASK;
648
    int aa = (d + bb - A_OFFSET) & MOD_MASK;
649
    *b = bb;
650
    *a = aa;
651
}
652
653
150
static void wav_decode(uint16_t *in, int nx, int ox,
654
                       int ny, int oy, uint16_t mx)
655
{
656
150
    int w14 = (mx < (1 << 14));
657
150
    int n   = (nx > ny) ? ny : nx;
658
150
    int p   = 1;
659
    int p2;
660
661
1008
    while (p <= n)
662
858
        p <<= 1;
663
664
150
    p >>= 1;
665
150
    p2  = p;
666
150
    p >>= 1;
667
668
858
    while (p >= 1) {
669
708
        uint16_t *py = in;
670
708
        uint16_t *ey = in + oy * (ny - p2);
671
        uint16_t i00, i01, i10, i11;
672
708
        int oy1 = oy * p;
673
708
        int oy2 = oy * p2;
674
708
        int ox1 = ox * p;
675
708
        int ox2 = ox * p2;
676
677
4914
        for (; py <= ey; py += oy2) {
678
4206
            uint16_t *px = py;
679
4206
            uint16_t *ex = py + ox * (nx - p2);
680
681
493602
            for (; px <= ex; px += ox2) {
682
489396
                uint16_t *p01 = px + ox1;
683
489396
                uint16_t *p10 = px + oy1;
684
489396
                uint16_t *p11 = p10 + ox1;
685
686
489396
                if (w14) {
687
489396
                    wdec14(*px, *p10, &i00, &i10);
688
489396
                    wdec14(*p01, *p11, &i01, &i11);
689
489396
                    wdec14(i00, i01, px, p01);
690
489396
                    wdec14(i10, i11, p10, p11);
691
                } else {
692
                    wdec16(*px, *p10, &i00, &i10);
693
                    wdec16(*p01, *p11, &i01, &i11);
694
                    wdec16(i00, i01, px, p01);
695
                    wdec16(i10, i11, p10, p11);
696
                }
697
            }
698
699
4206
            if (nx & p) {
700
216
                uint16_t *p10 = px + oy1;
701
702
216
                if (w14)
703
216
                    wdec14(*px, *p10, &i00, p10);
704
                else
705
                    wdec16(*px, *p10, &i00, p10);
706
707
216
                *px = i00;
708
            }
709
        }
710
711
708
        if (ny & p) {
712
30
            uint16_t *px = py;
713
30
            uint16_t *ex = py + ox * (nx - p2);
714
715
792
            for (; px <= ex; px += ox2) {
716
762
                uint16_t *p01 = px + ox1;
717
718
762
                if (w14)
719
762
                    wdec14(*px, *p01, &i00, p01);
720
                else
721
                    wdec16(*px, *p01, &i00, p01);
722
723
762
                *px = i00;
724
            }
725
        }
726
727
708
        p2  = p;
728
708
        p >>= 1;
729
    }
730
150
}
731
732
48
static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
733
                          int dsize, EXRThreadData *td)
734
{
735
    GetByteContext gb;
736
    uint16_t maxval, min_non_zero, max_non_zero;
737
    uint16_t *ptr;
738
48
    uint16_t *tmp = (uint16_t *)td->tmp;
739
    uint16_t *out;
740
    uint16_t *in;
741
    int ret, i, j;
742
    int pixel_half_size;/* 1 for half, 2 for float and uint32 */
743
    EXRChannel *channel;
744
    int tmp_offset;
745
746
48
    if (!td->bitmap)
747
10
        td->bitmap = av_malloc(BITMAP_SIZE);
748
48
    if (!td->lut)
749
10
        td->lut = av_malloc(1 << 17);
750

48
    if (!td->bitmap || !td->lut) {
751
        av_freep(&td->bitmap);
752
        av_freep(&td->lut);
753
        return AVERROR(ENOMEM);
754
    }
755
756
48
    bytestream2_init(&gb, src, ssize);
757
48
    min_non_zero = bytestream2_get_le16(&gb);
758
48
    max_non_zero = bytestream2_get_le16(&gb);
759
760
48
    if (max_non_zero >= BITMAP_SIZE)
761
        return AVERROR_INVALIDDATA;
762
763
48
    memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
764
48
    if (min_non_zero <= max_non_zero)
765
48
        bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
766
48
                               max_non_zero - min_non_zero + 1);
767
48
    memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
768
769
48
    maxval = reverse_lut(td->bitmap, td->lut);
770
771
48
    ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
772
48
    if (ret)
773
        return ret;
774
775
48
    ptr = tmp;
776
192
    for (i = 0; i < s->nb_channels; i++) {
777
144
        channel = &s->channels[i];
778
779
144
        if (channel->pixel_type == EXR_HALF)
780
138
            pixel_half_size = 1;
781
        else
782
6
            pixel_half_size = 2;
783
784
294
        for (j = 0; j < pixel_half_size; j++)
785
150
            wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize,
786
150
                       td->xsize * pixel_half_size, maxval);
787
144
        ptr += td->xsize * td->ysize * pixel_half_size;
788
    }
789
790
48
    apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
791
792
48
    out = (uint16_t *)td->uncompressed_data;
793
1446
    for (i = 0; i < td->ysize; i++) {
794
1398
        tmp_offset = 0;
795
5592
        for (j = 0; j < s->nb_channels; j++) {
796
4194
            channel = &s->channels[j];
797
4194
            if (channel->pixel_type == EXR_HALF)
798
4002
                pixel_half_size = 1;
799
            else
800
192
                pixel_half_size = 2;
801
802
4194
            in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size;
803
4194
            tmp_offset += pixel_half_size;
804
805
#if HAVE_BIGENDIAN
806
            s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size);
807
#else
808
4194
            memcpy(out, in, td->xsize * 2 * pixel_half_size);
809
#endif
810
4194
            out += td->xsize * pixel_half_size;
811
        }
812
    }
813
814
48
    return 0;
815
}
816
817
122
static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
818
                            int compressed_size, int uncompressed_size,
819
                            EXRThreadData *td)
820
{
821
122
    unsigned long dest_len, expected_len = 0;
822
122
    const uint8_t *in = td->tmp;
823
    uint8_t *out;
824
    int c, i, j;
825
826
558
    for (i = 0; i < s->nb_channels; i++) {
827
436
        if (s->channels[i].pixel_type == EXR_FLOAT) {
828
62
            expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */
829
374
        } else if (s->channels[i].pixel_type == EXR_HALF) {
830
362
            expected_len += (td->xsize * td->ysize * 2);
831
        } else {//UINT 32
832
12
            expected_len += (td->xsize * td->ysize * 4);
833
        }
834
    }
835
836
122
    dest_len = expected_len;
837
838
122
    if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
839
        return AVERROR_INVALIDDATA;
840
122
    } else if (dest_len != expected_len) {
841
        return AVERROR_INVALIDDATA;
842
    }
843
844
122
    out = td->uncompressed_data;
845
1900
    for (i = 0; i < td->ysize; i++)
846
7678
        for (c = 0; c < s->nb_channels; c++) {
847
5900
            EXRChannel *channel = &s->channels[c];
848
            const uint8_t *ptr[4];
849
5900
            uint32_t pixel = 0;
850
851

5900
            switch (channel->pixel_type) {
852
496
            case EXR_FLOAT:
853
496
                ptr[0] = in;
854
496
                ptr[1] = ptr[0] + td->xsize;
855
496
                ptr[2] = ptr[1] + td->xsize;
856
496
                in     = ptr[2] + td->xsize;
857
858
6448
                for (j = 0; j < td->xsize; ++j) {
859
5952
                    uint32_t diff = ((unsigned)*(ptr[0]++) << 24) |
860
5952
                                    (*(ptr[1]++) << 16) |
861
5952
                                    (*(ptr[2]++) << 8);
862
5952
                    pixel += diff;
863
5952
                    bytestream_put_le32(&out, pixel);
864
                }
865
496
                break;
866
5302
            case EXR_HALF:
867
5302
                ptr[0] = in;
868
5302
                ptr[1] = ptr[0] + td->xsize;
869
5302
                in     = ptr[1] + td->xsize;
870
3851380
                for (j = 0; j < td->xsize; j++) {
871
3846078
                    uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
872
873
3846078
                    pixel += diff;
874
3846078
                    bytestream_put_le16(&out, pixel);
875
                }
876
5302
                break;
877
102
            case EXR_UINT:
878
102
                ptr[0] = in;
879
102
                ptr[1] = ptr[0] + s->xdelta;
880
102
                ptr[2] = ptr[1] + s->xdelta;
881
102
                ptr[3] = ptr[2] + s->xdelta;
882
102
                in     = ptr[3] + s->xdelta;
883
884
1380
                for (j = 0; j < s->xdelta; ++j) {
885
1278
                    uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) |
886
1278
                    (*(ptr[1]++) << 16) |
887
1278
                    (*(ptr[2]++) << 8 ) |
888
1278
                    (*(ptr[3]++));
889
1278
                    pixel += diff;
890
1278
                    bytestream_put_le32(&out, pixel);
891
                }
892
102
                break;
893
            default:
894
                return AVERROR_INVALIDDATA;
895
            }
896
        }
897
898
122
    return 0;
899
}
900
901
118558
static void unpack_14(const uint8_t b[14], uint16_t s[16])
902
{
903
118558
    unsigned short shift = (b[ 2] >> 2) & 15;
904
118558
    unsigned short bias = (0x20 << shift);
905
    int i;
906
907
118558
    s[ 0] = (b[0] << 8) | b[1];
908
909
118558
    s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
910
118558
    s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
911
118558
    s[12] = s[ 8] +   ((b[ 4]                       & 0x3f) << shift) - bias;
912
913
118558
    s[ 1] = s[ 0] +   ((b[ 5] >> 2)                         << shift) - bias;
914
118558
    s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
915
118558
    s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
916
118558
    s[13] = s[12] +   ((b[ 7]                       & 0x3f) << shift) - bias;
917
918
118558
    s[ 2] = s[ 1] +   ((b[ 8] >> 2)                         << shift) - bias;
919
118558
    s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
920
118558
    s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
921
118558
    s[14] = s[13] +   ((b[10]                       & 0x3f) << shift) - bias;
922
923
118558
    s[ 3] = s[ 2] +   ((b[11] >> 2)                         << shift) - bias;
924
118558
    s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
925
118558
    s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
926
118558
    s[15] = s[14] +   ((b[13]                       & 0x3f) << shift) - bias;
927
928
2015486
    for (i = 0; i < 16; ++i) {
929
1896928
        if (s[i] & 0x8000)
930
1884694
            s[i] &= 0x7fff;
931
        else
932
12234
            s[i] = ~s[i];
933
    }
934
118558
}
935
936
212
static void unpack_3(const uint8_t b[3], uint16_t s[16])
937
{
938
    int i;
939
940
212
    s[0] = (b[0] << 8) | b[1];
941
942
212
    if (s[0] & 0x8000)
943
210
        s[0] &= 0x7fff;
944
    else
945
2
        s[0] = ~s[0];
946
947
3392
    for (i = 1; i < 16; i++)
948
3180
        s[i] = s[0];
949
212
}
950
951
952
46
static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
953
                          int uncompressed_size, EXRThreadData *td) {
954
46
    const int8_t *sr = src;
955
46
    int stay_to_uncompress = compressed_size;
956
    int nb_b44_block_w, nb_b44_block_h;
957
    int index_tl_x, index_tl_y, index_out, index_tmp;
958
    uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */
959
    int c, iY, iX, y, x;
960
46
    int target_channel_offset = 0;
961
962
    /* calc B44 block count */
963
46
    nb_b44_block_w = td->xsize / 4;
964
46
    if ((td->xsize % 4) != 0)
965
26
        nb_b44_block_w++;
966
967
46
    nb_b44_block_h = td->ysize / 4;
968
46
    if ((td->ysize % 4) != 0)
969
12
        nb_b44_block_h++;
970
971
312
    for (c = 0; c < s->nb_channels; c++) {
972
266
        if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
973
918
            for (iY = 0; iY < nb_b44_block_h; iY++) {
974
119518
                for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */
975
118770
                    if (stay_to_uncompress < 3) {
976
                        av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress);
977
                        return AVERROR_INVALIDDATA;
978
                    }
979
980
118770
                    if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */
981
212
                        unpack_3(sr, tmp_buffer);
982
212
                        sr += 3;
983
212
                        stay_to_uncompress -= 3;
984
                    }  else {/* B44 Block */
985
118558
                        if (stay_to_uncompress < 14) {
986
                            av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress);
987
                            return AVERROR_INVALIDDATA;
988
                        }
989
118558
                        unpack_14(sr, tmp_buffer);
990
118558
                        sr += 14;
991
118558
                        stay_to_uncompress -= 14;
992
                    }
993
994
                    /* copy data to uncompress buffer (B44 block can exceed target resolution)*/
995
118770
                    index_tl_x = iX * 4;
996
118770
                    index_tl_y = iY * 4;
997
998

591522
                    for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) {
999

2360726
                        for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {
1000
1887974
                            index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;
1001
1887974
                            index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);
1002
1887974
                            td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;
1003
1887974
                            td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;
1004
                        }
1005
                    }
1006
                }
1007
            }
1008
170
            target_channel_offset += 2;
1009
        } else {/* Float or UINT 32 channel */
1010
96
            if (stay_to_uncompress < td->ysize * td->xsize * 4) {
1011
                av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress);
1012
                return AVERROR_INVALIDDATA;
1013
            }
1014
1015
896
            for (y = 0; y < td->ysize; y++) {
1016
800
                index_out = target_channel_offset * td->xsize + y * td->channel_line_size;
1017
800
                memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);
1018
800
                sr += td->xsize * 4;
1019
            }
1020
96
            target_channel_offset += 4;
1021
1022
96
            stay_to_uncompress -= td->ysize * td->xsize * 4;
1023
        }
1024
    }
1025
1026
46
    return 0;
1027
}
1028
1029
4526
static int decode_block(AVCodecContext *avctx, void *tdata,
1030
                        int jobnr, int threadnr)
1031
{
1032
4526
    EXRContext *s = avctx->priv_data;
1033
4526
    AVFrame *const p = s->picture;
1034
4526
    EXRThreadData *td = &s->thread_data[threadnr];
1035
4526
    const uint8_t *channel_buffer[4] = { 0 };
1036
4526
    const uint8_t *buf = s->buf;
1037
    uint64_t line_offset, uncompressed_size;
1038
    uint16_t *ptr_x;
1039
    uint8_t *ptr;
1040
    uint32_t data_size;
1041
4526
    uint64_t line, col = 0;
1042
    uint64_t tile_x, tile_y, tile_level_x, tile_level_y;
1043
    const uint8_t *src;
1044
4526
    int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components; /* nb pixel to add at the right of the datawindow */
1045
4526
    int bxmin = s->xmin * 2 * s->desc->nb_components; /* nb pixel to add at the left of the datawindow */
1046
4526
    int i, x, buf_size = s->buf_size;
1047
    int c, rgb_channel_count;
1048
4526
    float one_gamma = 1.0f / s->gamma;
1049
4526
    avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1050
    int ret;
1051
1052
4526
    line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
1053
1054
4526
    if (s->is_tile) {
1055

52
        if (buf_size < 20 || line_offset > buf_size - 20)
1056
            return AVERROR_INVALIDDATA;
1057
1058
52
        src  = buf + line_offset + 20;
1059
1060
52
        tile_x = AV_RL32(src - 20);
1061
52
        tile_y = AV_RL32(src - 16);
1062
52
        tile_level_x = AV_RL32(src - 12);
1063
52
        tile_level_y = AV_RL32(src - 8);
1064
1065
52
        data_size = AV_RL32(src - 4);
1066

52
        if (data_size <= 0 || data_size > buf_size - line_offset - 20)
1067
            return AVERROR_INVALIDDATA;
1068
1069

52
        if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */
1070
            avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
1071
            return AVERROR_PATCHWELCOME;
1072
        }
1073
1074

52
        if (s->xmin || s->ymin) {
1075
            avpriv_report_missing_feature(s->avctx, "Tiles with xmin/ymin");
1076
            return AVERROR_PATCHWELCOME;
1077
        }
1078
1079
52
        line = s->tile_attr.ySize * tile_y;
1080
52
        col = s->tile_attr.xSize * tile_x;
1081
1082

52
        if (line < s->ymin || line > s->ymax ||
1083

52
            col  < s->xmin || col  > s->xmax)
1084
            return AVERROR_INVALIDDATA;
1085
1086
52
        td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);
1087
52
        td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);
1088
1089
52
        if (col) { /* not the first tile of the line */
1090
12
            bxmin = 0; /* doesn't add pixel at the left of the datawindow */
1091
        }
1092
1093
52
        if ((col + td->xsize) != s->xdelta)/* not the last tile of the line */
1094
12
            axmax = 0; /* doesn't add pixel at the right of the datawindow */
1095
1096
52
        td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1097
52
        uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1098
    } else {
1099

4474
        if (buf_size < 8 || line_offset > buf_size - 8)
1100
            return AVERROR_INVALIDDATA;
1101
1102
4474
        src  = buf + line_offset + 8;
1103
4474
        line = AV_RL32(src - 8);
1104
1105

4474
        if (line < s->ymin || line > s->ymax)
1106
            return AVERROR_INVALIDDATA;
1107
1108
4474
        data_size = AV_RL32(src - 4);
1109

4474
        if (data_size <= 0 || data_size > buf_size - line_offset - 8)
1110
            return AVERROR_INVALIDDATA;
1111
1112
4474
        td->ysize          = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
1113
4474
        td->xsize          = s->xdelta;
1114
1115
4474
        td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1116
4474
        uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1117
1118

4474
        if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||
1119
1390
                                           line_offset > buf_size - uncompressed_size)) ||
1120

4474
            (s->compression != EXR_RAW && (data_size > uncompressed_size ||
1121
3084
                                           line_offset > buf_size - data_size))) {
1122
            return AVERROR_INVALIDDATA;
1123
        }
1124
    }
1125
1126

4526
    if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
1127
3132
        av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
1128
3132
        if (!td->tmp)
1129
            return AVERROR(ENOMEM);
1130
    }
1131
1132
4526
    if (data_size < uncompressed_size) {
1133
3106
        av_fast_padded_malloc(&td->uncompressed_data,
1134
3106
                              &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */
1135
1136
3106
        if (!td->uncompressed_data)
1137
            return AVERROR(ENOMEM);
1138
1139
3106
        ret = AVERROR_INVALIDDATA;
1140

3106
        switch (s->compression) {
1141
1504
        case EXR_ZIP1:
1142
        case EXR_ZIP16:
1143
1504
            ret = zip_uncompress(s, src, data_size, uncompressed_size, td);
1144
1504
            break;
1145
48
        case EXR_PIZ:
1146
48
            ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
1147
48
            break;
1148
122
        case EXR_PXR24:
1149
122
            ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
1150
122
            break;
1151
1386
        case EXR_RLE:
1152
1386
            ret = rle_uncompress(s, src, data_size, uncompressed_size, td);
1153
1386
            break;
1154
46
        case EXR_B44:
1155
        case EXR_B44A:
1156
46
            ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
1157
46
            break;
1158
        }
1159
3106
        if (ret < 0) {
1160
            av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
1161
            return ret;
1162
        }
1163
3106
        src = td->uncompressed_data;
1164
    }
1165
1166
4526
    if (!s->is_luma) {
1167
4522
        channel_buffer[0] = src + td->xsize * s->channel_offsets[0];
1168
4522
        channel_buffer[1] = src + td->xsize * s->channel_offsets[1];
1169
4522
        channel_buffer[2] = src + td->xsize * s->channel_offsets[2];
1170
4522
        rgb_channel_count = 3;
1171
    } else { /* put y data in the first channel_buffer */
1172
4
        channel_buffer[0] = src + td->xsize * s->channel_offsets[1];
1173
4
        rgb_channel_count = 1;
1174
    }
1175
4526
    if (s->channel_offsets[3] >= 0)
1176
4242
        channel_buffer[3] = src + td->xsize * s->channel_offsets[3];
1177
1178
4526
    ptr = p->data[0] + line * p->linesize[0] + (col * s->desc->nb_components * 2);
1179
1180
4526
    for (i = 0;
1181
15066
         i < td->ysize; i++, ptr += p->linesize[0]) {
1182
1183
        const uint8_t * a;
1184
        const uint8_t *rgb[3];
1185
1186
42096
        for (c = 0; c < rgb_channel_count; c++) {
1187
31556
            rgb[c] = channel_buffer[c];
1188
        }
1189
1190
10540
        if (channel_buffer[3])
1191
6326
            a = channel_buffer[3];
1192
1193
10540
        ptr_x = (uint16_t *) ptr;
1194
1195
        // Zero out the start if xmin is not 0
1196
10540
        memset(ptr_x, 0, bxmin);
1197
10540
        ptr_x += s->xmin * s->desc->nb_components;
1198
1199
10540
        if (s->pixel_type == EXR_FLOAT) {
1200
            // 32-bit
1201
1192
            if (trc_func) {
1202
                for (x = 0; x < td->xsize; x++) {
1203
                    union av_intfloat32 t;
1204
1205
                    for (c = 0; c < rgb_channel_count; c++) {
1206
                        t.i = bytestream_get_le32(&rgb[c]);
1207
                        t.f = trc_func(t.f);
1208
                        *ptr_x++ = exr_flt2uint(t.i);
1209
                    }
1210
                    if (channel_buffer[3])
1211
                        *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
1212
                }
1213
            } else {
1214
47412
                for (x = 0; x < td->xsize; x++) {
1215
                    union av_intfloat32 t;
1216
                    int c;
1217
1218
184880
                    for (c = 0; c < rgb_channel_count; c++) {
1219
138660
                        t.i = bytestream_get_le32(&rgb[c]);
1220
138660
                        if (t.f > 0.0f)  /* avoid negative values */
1221
136236
                            t.f = powf(t.f, one_gamma);
1222
138660
                        *ptr_x++ = exr_flt2uint(t.i);
1223
                    }
1224
1225
46220
                    if (channel_buffer[3])
1226
3156
                        *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));
1227
                }
1228
            }
1229
9348
        } else if (s->pixel_type == EXR_HALF) {
1230
            // 16-bit
1231
5419066
            for (x = 0; x < td->xsize; x++) {
1232
                int c;
1233
21638232
                for (c = 0; c < rgb_channel_count; c++) {
1234
16228482
                    *ptr_x++ = s->gamma_table[bytestream_get_le16(&rgb[c])];
1235
                }
1236
1237
5409750
                if (channel_buffer[3])
1238
3641430
                    *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));
1239
            }
1240
32
        } else if (s->pixel_type == EXR_UINT) {
1241
416
            for (x = 0; x < td->xsize; x++) {
1242
1536
                for (c = 0; c < rgb_channel_count; c++) {
1243
1152
                    *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;
1244
                }
1245
1246
384
                if (channel_buffer[3])
1247
                    *ptr_x++ = bytestream_get_le32(&a) >> 16;
1248
            }
1249
        }
1250
1251
        // Zero out the end if xmax+1 is not w
1252
10540
        memset(ptr_x, 0, axmax);
1253
1254
10540
        channel_buffer[0] += td->channel_line_size;
1255
10540
        channel_buffer[1] += td->channel_line_size;
1256
10540
        channel_buffer[2] += td->channel_line_size;
1257
10540
        if (channel_buffer[3])
1258
6326
            channel_buffer[3] += td->channel_line_size;
1259
    }
1260
1261
4526
    return 0;
1262
}
1263
1264
/**
1265
 * Check if the variable name corresponds to its data type.
1266
 *
1267
 * @param s              the EXRContext
1268
 * @param value_name     name of the variable to check
1269
 * @param value_type     type of the variable to check
1270
 * @param minimum_length minimum length of the variable data
1271
 *
1272
 * @return bytes to read containing variable data
1273
 *         -1 if variable is not found
1274
 *         0 if buffer ended prematurely
1275
 */
1276
13522
static int check_header_variable(EXRContext *s,
1277
                                 const char *value_name,
1278
                                 const char *value_type,
1279
                                 unsigned int minimum_length)
1280
{
1281
13522
    int var_size = -1;
1282
1283
13522
    if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
1284
13522
        !strcmp(s->gb.buffer, value_name)) {
1285
        // found value_name, jump to value_type (null terminated strings)
1286
808
        s->gb.buffer += strlen(value_name) + 1;
1287
808
        if (!strcmp(s->gb.buffer, value_type)) {
1288
808
            s->gb.buffer += strlen(value_type) + 1;
1289
808
            var_size = bytestream2_get_le32(&s->gb);
1290
            // don't go read past boundaries
1291
808
            if (var_size > bytestream2_get_bytes_left(&s->gb))
1292
                var_size = 0;
1293
        } else {
1294
            // value_type not found, reset the buffer
1295
            s->gb.buffer -= strlen(value_name) + 1;
1296
            av_log(s->avctx, AV_LOG_WARNING,
1297
                   "Unknown data type %s for header variable %s.\n",
1298
                   value_type, value_name);
1299
        }
1300
    }
1301
1302
13522
    return var_size;
1303
}
1304
1305
126
static int decode_header(EXRContext *s, AVFrame *frame)
1306
{
1307
126
    AVDictionary *metadata = NULL;
1308
126
    int magic_number, version, i, flags, sar = 0;
1309
126
    int layer_match = 0;
1310
    int ret;
1311
126
    int dup_channels = 0;
1312
1313
126
    s->current_channel_offset = 0;
1314
126
    s->xmin               = ~0;
1315
126
    s->xmax               = ~0;
1316
126
    s->ymin               = ~0;
1317
126
    s->ymax               = ~0;
1318
126
    s->xdelta             = ~0;
1319
126
    s->ydelta             = ~0;
1320
126
    s->channel_offsets[0] = -1;
1321
126
    s->channel_offsets[1] = -1;
1322
126
    s->channel_offsets[2] = -1;
1323
126
    s->channel_offsets[3] = -1;
1324
126
    s->pixel_type         = EXR_UNKNOWN;
1325
126
    s->compression        = EXR_UNKN;
1326
126
    s->nb_channels        = 0;
1327
126
    s->w                  = 0;
1328
126
    s->h                  = 0;
1329
126
    s->tile_attr.xSize    = -1;
1330
126
    s->tile_attr.ySize    = -1;
1331
126
    s->is_tile            = 0;
1332
126
    s->is_luma            = 0;
1333
1334
126
    if (bytestream2_get_bytes_left(&s->gb) < 10) {
1335
        av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1336
        return AVERROR_INVALIDDATA;
1337
    }
1338
1339
126
    magic_number = bytestream2_get_le32(&s->gb);
1340
126
    if (magic_number != 20000630) {
1341
        /* As per documentation of OpenEXR, it is supposed to be
1342
         * int 20000630 little-endian */
1343
        av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1344
        return AVERROR_INVALIDDATA;
1345
    }
1346
1347
126
    version = bytestream2_get_byte(&s->gb);
1348
126
    if (version != 2) {
1349
        avpriv_report_missing_feature(s->avctx, "Version %d", version);
1350
        return AVERROR_PATCHWELCOME;
1351
    }
1352
1353
126
    flags = bytestream2_get_le24(&s->gb);
1354
1355
126
    if (flags & 0x02)
1356
36
        s->is_tile = 1;
1357
126
    if (flags & 0x08) {
1358
        avpriv_report_missing_feature(s->avctx, "deep data");
1359
        return AVERROR_PATCHWELCOME;
1360
    }
1361
126
    if (flags & 0x10) {
1362
        avpriv_report_missing_feature(s->avctx, "multipart");
1363
        return AVERROR_PATCHWELCOME;
1364
    }
1365
1366
    // Parse the header
1367

2246
    while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
1368
        int var_size;
1369
2120
        if ((var_size = check_header_variable(s, "channels",
1370
                                              "chlist", 38)) >= 0) {
1371
            GetByteContext ch_gb;
1372
126
            if (!var_size) {
1373
                ret = AVERROR_INVALIDDATA;
1374
                goto fail;
1375
            }
1376
1377
126
            bytestream2_init(&ch_gb, s->gb.buffer, var_size);
1378
1379
826
            while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1380
                EXRChannel *channel;
1381
                enum ExrPixelType current_pixel_type;
1382
700
                int channel_index = -1;
1383
                int xsub, ysub;
1384
1385
700
                if (strcmp(s->layer, "") != 0) {
1386
260
                    if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1387
144
                        layer_match = 1;
1388
144
                        av_log(s->avctx, AV_LOG_INFO,
1389
                               "Channel match layer : %s.\n", ch_gb.buffer);
1390
144
                        ch_gb.buffer += strlen(s->layer);
1391
144
                        if (*ch_gb.buffer == '.')
1392
144
                            ch_gb.buffer++;         /* skip dot if not given */
1393
                    } else {
1394
116
                        layer_match = 0;
1395
116
                        av_log(s->avctx, AV_LOG_INFO,
1396
                               "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1397
                    }
1398
                } else {
1399
440
                    layer_match = 1;
1400
                }
1401
1402
700
                if (layer_match) { /* only search channel if the layer match is valid */
1403

1046
                    if (!av_strcasecmp(ch_gb.buffer, "R") ||
1404
924
                        !av_strcasecmp(ch_gb.buffer, "X") ||
1405
462
                        !av_strcasecmp(ch_gb.buffer, "U")) {
1406
122
                        channel_index = 0;
1407
122
                        s->is_luma = 0;
1408

802
                    } else if (!av_strcasecmp(ch_gb.buffer, "G") ||
1409
340
                               !av_strcasecmp(ch_gb.buffer, "V")) {
1410
122
                        channel_index = 1;
1411
122
                        s->is_luma = 0;
1412
340
                    } else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
1413
4
                        channel_index = 1;
1414
4
                        s->is_luma = 1;
1415

550
                    } else if (!av_strcasecmp(ch_gb.buffer, "B") ||
1416
428
                               !av_strcasecmp(ch_gb.buffer, "Z") ||
1417
214
                               !av_strcasecmp(ch_gb.buffer, "W")) {
1418
122
                        channel_index = 2;
1419
122
                        s->is_luma = 0;
1420
214
                    } else if (!av_strcasecmp(ch_gb.buffer, "A")) {
1421
56
                        channel_index = 3;
1422
                    } else {
1423
158
                        av_log(s->avctx, AV_LOG_WARNING,
1424
                               "Unsupported channel %.256s.\n", ch_gb.buffer);
1425
                    }
1426
                }
1427
1428
                /* skip until you get a 0 */
1429

7856
                while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1430
3928
                       bytestream2_get_byte(&ch_gb))
1431
3228
                    continue;
1432
1433
700
                if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1434
                    av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1435
                    ret = AVERROR_INVALIDDATA;
1436
                    goto fail;
1437
                }
1438
1439
700
                current_pixel_type = bytestream2_get_le32(&ch_gb);
1440
700
                if (current_pixel_type >= EXR_UNKNOWN) {
1441
                    avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1442
                                                  current_pixel_type);
1443
                    ret = AVERROR_PATCHWELCOME;
1444
                    goto fail;
1445
                }
1446
1447
700
                bytestream2_skip(&ch_gb, 4);
1448
700
                xsub = bytestream2_get_le32(&ch_gb);
1449
700
                ysub = bytestream2_get_le32(&ch_gb);
1450
1451

700
                if (xsub != 1 || ysub != 1) {
1452
                    avpriv_report_missing_feature(s->avctx,
1453
                                                  "Subsampling %dx%d",
1454
                                                  xsub, ysub);
1455
                    ret = AVERROR_PATCHWELCOME;
1456
                    goto fail;
1457
                }
1458
1459

700
                if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */
1460
426
                    if (s->pixel_type != EXR_UNKNOWN &&
1461
300
                        s->pixel_type != current_pixel_type) {
1462
                        av_log(s->avctx, AV_LOG_ERROR,
1463
                               "RGB channels not of the same depth.\n");
1464
                        ret = AVERROR_INVALIDDATA;
1465
                        goto fail;
1466
                    }
1467
426
                    s->pixel_type                     = current_pixel_type;
1468
426
                    s->channel_offsets[channel_index] = s->current_channel_offset;
1469
274
                } else if (channel_index >= 0) {
1470
                    av_log(s->avctx, AV_LOG_WARNING,
1471
                            "Multiple channels with index %d.\n", channel_index);
1472
                    if (++dup_channels > 10) {
1473
                        ret = AVERROR_INVALIDDATA;
1474
                        goto fail;
1475
                    }
1476
                }
1477
1478
1400
                s->channels = av_realloc(s->channels,
1479
700
                                         ++s->nb_channels * sizeof(EXRChannel));
1480
700
                if (!s->channels) {
1481
                    ret = AVERROR(ENOMEM);
1482
                    goto fail;
1483
                }
1484
700
                channel             = &s->channels[s->nb_channels - 1];
1485
700
                channel->pixel_type = current_pixel_type;
1486
700
                channel->xsub       = xsub;
1487
700
                channel->ysub       = ysub;
1488
1489
700
                if (current_pixel_type == EXR_HALF) {
1490
358
                    s->current_channel_offset += 2;
1491
                } else {/* Float or UINT32 */
1492
342
                    s->current_channel_offset += 4;
1493
                }
1494
            }
1495
1496
            /* Check if all channels are set with an offset or if the channels
1497
             * are causing an overflow  */
1498
126
            if (!s->is_luma) {/* if we expected to have at least 3 channels */
1499
122
                if (FFMIN3(s->channel_offsets[0],
1500
                           s->channel_offsets[1],
1501
                           s->channel_offsets[2]) < 0) {
1502
                    if (s->channel_offsets[0] < 0)
1503
                        av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n");
1504
                    if (s->channel_offsets[1] < 0)
1505
                        av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n");
1506
                    if (s->channel_offsets[2] < 0)
1507
                        av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n");
1508
                    ret = AVERROR_INVALIDDATA;
1509
                    goto fail;
1510
                }
1511
            }
1512
1513
            // skip one last byte and update main gb
1514
126
            s->gb.buffer = ch_gb.buffer + 1;
1515
126
            continue;
1516
1994
        } else if ((var_size = check_header_variable(s, "dataWindow", "box2i",
1517
                                                     31)) >= 0) {
1518
126
            if (!var_size) {
1519
                ret = AVERROR_INVALIDDATA;
1520
                goto fail;
1521
            }
1522
1523
126
            s->xmin   = bytestream2_get_le32(&s->gb);
1524
126
            s->ymin   = bytestream2_get_le32(&s->gb);
1525
126
            s->xmax   = bytestream2_get_le32(&s->gb);
1526
126
            s->ymax   = bytestream2_get_le32(&s->gb);
1527
126
            s->xdelta = (s->xmax - s->xmin) + 1;
1528
126
            s->ydelta = (s->ymax - s->ymin) + 1;
1529
1530
126
            continue;
1531
1868
        } else if ((var_size = check_header_variable(s, "displayWindow",
1532
                                                     "box2i", 34)) >= 0) {
1533
126
            if (!var_size) {
1534
                ret = AVERROR_INVALIDDATA;
1535
                goto fail;
1536
            }
1537
1538
126
            bytestream2_skip(&s->gb, 8);
1539
126
            s->w = bytestream2_get_le32(&s->gb) + 1;
1540
126
            s->h = bytestream2_get_le32(&s->gb) + 1;
1541
1542
126
            continue;
1543
1742
        } else if ((var_size = check_header_variable(s, "lineOrder",
1544
                                                     "lineOrder", 25)) >= 0) {
1545
            int line_order;
1546
126
            if (!var_size) {
1547
                ret = AVERROR_INVALIDDATA;
1548
                goto fail;
1549
            }
1550
1551
126
            line_order = bytestream2_get_byte(&s->gb);
1552
126
            av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order);
1553
126
            if (line_order > 2) {
1554
                av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n");
1555
                ret = AVERROR_INVALIDDATA;
1556
                goto fail;
1557
            }
1558
1559
126
            continue;
1560
1616
        } else if ((var_size = check_header_variable(s, "pixelAspectRatio",
1561
                                                     "float", 31)) >= 0) {
1562
126
            if (!var_size) {
1563
                ret = AVERROR_INVALIDDATA;
1564
                goto fail;
1565
            }
1566
1567
126
            sar = bytestream2_get_le32(&s->gb);
1568
1569
126
            continue;
1570
1490
        } else if ((var_size = check_header_variable(s, "compression",
1571
                                                     "compression", 29)) >= 0) {
1572
126
            if (!var_size) {
1573
                ret = AVERROR_INVALIDDATA;
1574
                goto fail;
1575
            }
1576
1577
126
            if (s->compression == EXR_UNKN)
1578
126
                s->compression = bytestream2_get_byte(&s->gb);
1579
            else
1580
                av_log(s->avctx, AV_LOG_WARNING,
1581
                       "Found more than one compression attribute.\n");
1582
1583
126
            continue;
1584
1364
        } else if ((var_size = check_header_variable(s, "tiles",
1585
                                                     "tiledesc", 22)) >= 0) {
1586
            char tileLevel;
1587
1588
36
            if (!s->is_tile)
1589
                av_log(s->avctx, AV_LOG_WARNING,
1590
                       "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n");
1591
1592
36
            s->tile_attr.xSize = bytestream2_get_le32(&s->gb);
1593
36
            s->tile_attr.ySize = bytestream2_get_le32(&s->gb);
1594
1595
36
            tileLevel = bytestream2_get_byte(&s->gb);
1596
36
            s->tile_attr.level_mode = tileLevel & 0x0f;
1597
36
            s->tile_attr.level_round = (tileLevel >> 4) & 0x0f;
1598
1599
36
            if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) {
1600
                avpriv_report_missing_feature(s->avctx, "Tile level mode %d",
1601
                                              s->tile_attr.level_mode);
1602
                ret = AVERROR_PATCHWELCOME;
1603
                goto fail;
1604
            }
1605
1606
36
            if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) {
1607
                avpriv_report_missing_feature(s->avctx, "Tile level round %d",
1608
                                              s->tile_attr.level_round);
1609
                ret = AVERROR_PATCHWELCOME;
1610
                goto fail;
1611
            }
1612
1613
36
            continue;
1614
1328
        } else if ((var_size = check_header_variable(s, "writer",
1615
                                                     "string", 1)) >= 0) {
1616
16
            uint8_t key[256] = { 0 };
1617
1618
16
            bytestream2_get_buffer(&s->gb, key, FFMIN(sizeof(key) - 1, var_size));
1619
16
            av_dict_set(&metadata, "writer", key, 0);
1620
1621
16
            continue;
1622
        }
1623
1624
        // Check if there are enough bytes for a header
1625
1312
        if (bytestream2_get_bytes_left(&s->gb) <= 9) {
1626
            av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n");
1627
            ret = AVERROR_INVALIDDATA;
1628
            goto fail;
1629
        }
1630
1631
        // Process unknown variables
1632
3936
        for (i = 0; i < 2; i++) // value_name and value_type
1633
27594
            while (bytestream2_get_byte(&s->gb) != 0);
1634
1635
        // Skip variable length
1636
1312
        bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb));
1637
    }
1638
1639
126
    ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255));
1640
1641
126
    if (s->compression == EXR_UNKN) {
1642
        av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n");
1643
        ret = AVERROR_INVALIDDATA;
1644
        goto fail;
1645
    }
1646
1647
126
    if (s->is_tile) {
1648

36
        if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1649
            av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1650
            ret = AVERROR_INVALIDDATA;
1651
            goto fail;
1652
        }
1653
    }
1654
1655
126
    if (bytestream2_get_bytes_left(&s->gb) <= 0) {
1656
        av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1657
        ret = AVERROR_INVALIDDATA;
1658
        goto fail;
1659
    }
1660
1661
126
    frame->metadata = metadata;
1662
1663
    // aaand we are done
1664
126
    bytestream2_skip(&s->gb, 1);
1665
126
    return 0;
1666
fail:
1667
    av_dict_free(&metadata);
1668
    return ret;
1669
}
1670
1671
126
static int decode_frame(AVCodecContext *avctx, void *data,
1672
                        int *got_frame, AVPacket *avpkt)
1673
{
1674
126
    EXRContext *s = avctx->priv_data;
1675
126
    ThreadFrame frame = { .f = data };
1676
126
    AVFrame *picture = data;
1677
    uint8_t *ptr;
1678
1679
    int y, ret;
1680
    int out_line_size;
1681
    int nb_blocks;   /* nb scanline or nb tile */
1682
    uint64_t start_offset_table;
1683
    uint64_t start_next_scanline;
1684
    PutByteContext offset_table_writer;
1685
1686
126
    bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1687
1688
126
    if ((ret = decode_header(s, picture)) < 0)
1689
        return ret;
1690
1691
126
    switch (s->pixel_type) {
1692
126
    case EXR_FLOAT:
1693
    case EXR_HALF:
1694
    case EXR_UINT:
1695
126
        if (s->channel_offsets[3] >= 0) {
1696
56
            if (!s->is_luma) {
1697
56
                avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1698
            } else {
1699
                avctx->pix_fmt = AV_PIX_FMT_YA16;
1700
            }
1701
        } else {
1702
70
            if (!s->is_luma) {
1703
66
                avctx->pix_fmt = AV_PIX_FMT_RGB48;
1704
            } else {
1705
4
                avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1706
            }
1707
        }
1708
126
        break;
1709
    default:
1710
        av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1711
        return AVERROR_INVALIDDATA;
1712
    }
1713
1714
126
    if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1715
        avctx->color_trc = s->apply_trc_type;
1716
1717

126
    switch (s->compression) {
1718
40
    case EXR_RAW:
1719
    case EXR_RLE:
1720
    case EXR_ZIP1:
1721
40
        s->scan_lines_per_block = 1;
1722
40
        break;
1723
40
    case EXR_PXR24:
1724
    case EXR_ZIP16:
1725
40
        s->scan_lines_per_block = 16;
1726
40
        break;
1727
46
    case EXR_PIZ:
1728
    case EXR_B44:
1729
    case EXR_B44A:
1730
46
        s->scan_lines_per_block = 32;
1731
46
        break;
1732
    default:
1733
        avpriv_report_missing_feature(avctx, "Compression %d", s->compression);
1734
        return AVERROR_PATCHWELCOME;
1735
    }
1736
1737
    /* Verify the xmin, xmax, ymin, ymax and xdelta before setting
1738
     * the actual image size. */
1739
126
    if (s->xmin > s->xmax                  ||
1740
126
        s->ymin > s->ymax                  ||
1741
126
        s->xdelta != s->xmax - s->xmin + 1 ||
1742
126
        s->xmax >= s->w                    ||
1743
126
        s->ymax >= s->h) {
1744
        av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n");
1745
        return AVERROR_INVALIDDATA;
1746
    }
1747
1748
126
    if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)
1749
        return ret;
1750
1751
126
    s->desc          = av_pix_fmt_desc_get(avctx->pix_fmt);
1752
126
    if (!s->desc)
1753
        return AVERROR_INVALIDDATA;
1754
126
    out_line_size    = avctx->width * 2 * s->desc->nb_components;
1755
1756
126
    if (s->is_tile) {
1757
36
        nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *
1758
36
        ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);
1759
    } else { /* scanline */
1760
90
        nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /
1761
90
        s->scan_lines_per_block;
1762
    }
1763
1764
126
    if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
1765
        return ret;
1766
1767
126
    if (bytestream2_get_bytes_left(&s->gb) < nb_blocks * 8)
1768
        return AVERROR_INVALIDDATA;
1769
1770
    // check offset table and recreate it if need
1771

126
    if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) {
1772
1
        av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n");
1773
1774
1
        start_offset_table = bytestream2_tell(&s->gb);
1775
1
        start_next_scanline = start_offset_table + nb_blocks * 8;
1776
1
        bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);
1777
1778
9
        for (y = 0; y < nb_blocks; y++) {
1779
            /* write offset of prev scanline in offset table */
1780
8
            bytestream2_put_le64(&offset_table_writer, start_next_scanline);
1781
1782
            /* get len of next scanline */
1783
8
            bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */
1784
8
            start_next_scanline += (bytestream2_get_le32(&s->gb) + 8);
1785
        }
1786
1
        bytestream2_seek(&s->gb, start_offset_table, SEEK_SET);
1787
    }
1788
1789
    // save pointer we are going to use in decode_block
1790
126
    s->buf      = avpkt->data;
1791
126
    s->buf_size = avpkt->size;
1792
126
    ptr         = picture->data[0];
1793
1794
    // Zero out the start if ymin is not 0
1795
206
    for (y = 0; y < s->ymin; y++) {
1796
80
        memset(ptr, 0, out_line_size);
1797
80
        ptr += picture->linesize[0];
1798
    }
1799
1800
126
    s->picture = picture;
1801
1802
126
    avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);
1803
1804
    // Zero out the end if ymax+1 is not h
1805
126
    ptr = picture->data[0] + ((s->ymax+1) * picture->linesize[0]);
1806
248
    for (y = s->ymax + 1; y < avctx->height; y++) {
1807
122
        memset(ptr, 0, out_line_size);
1808
122
        ptr += picture->linesize[0];
1809
    }
1810
1811
126
    picture->pict_type = AV_PICTURE_TYPE_I;
1812
126
    *got_frame = 1;
1813
1814
126
    return avpkt->size;
1815
}
1816
1817
126
static av_cold int decode_init(AVCodecContext *avctx)
1818
{
1819
126
    EXRContext *s = avctx->priv_data;
1820
    uint32_t i;
1821
    union av_intfloat32 t;
1822
126
    float one_gamma = 1.0f / s->gamma;
1823
126
    avpriv_trc_function trc_func = NULL;
1824
1825
126
    s->avctx              = avctx;
1826
1827
126
    ff_exrdsp_init(&s->dsp);
1828
1829
#if HAVE_BIGENDIAN
1830
    ff_bswapdsp_init(&s->bbdsp);
1831
#endif
1832
1833
126
    trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1834
126
    if (trc_func) {
1835
        for (i = 0; i < 65536; ++i) {
1836
            t = exr_half2float(i);
1837
            t.f = trc_func(t.f);
1838
            s->gamma_table[i] = exr_flt2uint(t.i);
1839
        }
1840
    } else {
1841

126
        if (one_gamma > 0.9999f && one_gamma < 1.0001f) {
1842
8257662
            for (i = 0; i < 65536; ++i)
1843
8257536
                s->gamma_table[i] = exr_halflt2uint(i);
1844
        } else {
1845
            for (i = 0; i < 65536; ++i) {
1846
                t = exr_half2float(i);
1847
                /* If negative value we reuse half value */
1848
                if (t.f <= 0.0f) {
1849
                    s->gamma_table[i] = exr_halflt2uint(i);
1850
                } else {
1851
                    t.f = powf(t.f, one_gamma);
1852
                    s->gamma_table[i] = exr_flt2uint(t.i);
1853
                }
1854
            }
1855
        }
1856
    }
1857
1858
    // allocate thread data, used for non EXR_RAW compression types
1859
126
    s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1860
126
    if (!s->thread_data)
1861
        return AVERROR_INVALIDDATA;
1862
1863
126
    return 0;
1864
}
1865
1866
#if HAVE_THREADS
1867
static int decode_init_thread_copy(AVCodecContext *avctx)
1868
{
1869
    EXRContext *s = avctx->priv_data;
1870
1871
    // allocate thread data, used for non EXR_RAW compression types
1872
    s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData));
1873
    if (!s->thread_data)
1874
        return AVERROR_INVALIDDATA;
1875
1876
    return 0;
1877
}
1878
#endif
1879
1880
126
static av_cold int decode_end(AVCodecContext *avctx)
1881
{
1882
126
    EXRContext *s = avctx->priv_data;
1883
    int i;
1884
252
    for (i = 0; i < avctx->thread_count; i++) {
1885
126
        EXRThreadData *td = &s->thread_data[i];
1886
126
        av_freep(&td->uncompressed_data);
1887
126
        av_freep(&td->tmp);
1888
126
        av_freep(&td->bitmap);
1889
126
        av_freep(&td->lut);
1890
    }
1891
1892
126
    av_freep(&s->thread_data);
1893
126
    av_freep(&s->channels);
1894
1895
126
    return 0;
1896
}
1897
1898
#define OFFSET(x) offsetof(EXRContext, x)
1899
#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1900
static const AVOption options[] = {
1901
    { "layer", "Set the decoding layer", OFFSET(layer),
1902
        AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD },
1903
    { "gamma", "Set the float gamma value when decoding", OFFSET(gamma),
1904
        AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD },
1905
1906
    // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option
1907
    { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type),
1908
        AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"},
1909
    { "bt709",        "BT.709",           0,
1910
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 },        INT_MIN, INT_MAX, VD, "apply_trc_type"},
1911
    { "gamma",        "gamma",            0,
1912
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED },  INT_MIN, INT_MAX, VD, "apply_trc_type"},
1913
    { "gamma22",      "BT.470 M",         0,
1914
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 },      INT_MIN, INT_MAX, VD, "apply_trc_type"},
1915
    { "gamma28",      "BT.470 BG",        0,
1916
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 },      INT_MIN, INT_MAX, VD, "apply_trc_type"},
1917
    { "smpte170m",    "SMPTE 170 M",      0,
1918
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1919
    { "smpte240m",    "SMPTE 240 M",      0,
1920
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1921
    { "linear",       "Linear",           0,
1922
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR },       INT_MIN, INT_MAX, VD, "apply_trc_type"},
1923
    { "log",          "Log",              0,
1924
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG },          INT_MIN, INT_MAX, VD, "apply_trc_type"},
1925
    { "log_sqrt",     "Log square root",  0,
1926
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT },     INT_MIN, INT_MAX, VD, "apply_trc_type"},
1927
    { "iec61966_2_4", "IEC 61966-2-4",    0,
1928
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1929
    { "bt1361",       "BT.1361",          0,
1930
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG },   INT_MIN, INT_MAX, VD, "apply_trc_type"},
1931
    { "iec61966_2_1", "IEC 61966-2-1",    0,
1932
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1933
    { "bt2020_10bit", "BT.2020 - 10 bit", 0,
1934
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1935
    { "bt2020_12bit", "BT.2020 - 12 bit", 0,
1936
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 },    INT_MIN, INT_MAX, VD, "apply_trc_type"},
1937
    { "smpte2084",    "SMPTE ST 2084",    0,
1938
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 },  INT_MIN, INT_MAX, VD, "apply_trc_type"},
1939
    { "smpte428_1",   "SMPTE ST 428-1",   0,
1940
        AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"},
1941
1942
    { NULL },
1943
};
1944
1945
static const AVClass exr_class = {
1946
    .class_name = "EXR",
1947
    .item_name  = av_default_item_name,
1948
    .option     = options,
1949
    .version    = LIBAVUTIL_VERSION_INT,
1950
};
1951
1952
AVCodec ff_exr_decoder = {
1953
    .name             = "exr",
1954
    .long_name        = NULL_IF_CONFIG_SMALL("OpenEXR image"),
1955
    .type             = AVMEDIA_TYPE_VIDEO,
1956
    .id               = AV_CODEC_ID_EXR,
1957
    .priv_data_size   = sizeof(EXRContext),
1958
    .init             = decode_init,
1959
    .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1960
    .close            = decode_end,
1961
    .decode           = decode_frame,
1962
    .capabilities     = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
1963
                        AV_CODEC_CAP_SLICE_THREADS,
1964
    .priv_class       = &exr_class,
1965
};