GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/exr.c Lines: 784 983 79.8 %
Date: 2020-07-13 04:22:34 Branches: 433 625 69.3 %

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_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner.
34
 */
35
36
#include <float.h>
37
#include <zlib.h>
38
39
#include "libavutil/avassert.h"
40
#include "libavutil/common.h"
41
#include "libavutil/imgutils.h"
42
#include "libavutil/intfloat.h"
43
#include "libavutil/avstring.h"
44
#include "libavutil/opt.h"
45
#include "libavutil/color_utils.h"
46
47
#include "avcodec.h"
48
#include "bytestream.h"
49
50
#if HAVE_BIGENDIAN
51
#include "bswapdsp.h"
52
#endif
53
54
#include "exrdsp.h"
55
#include "get_bits.h"
56
#include "internal.h"
57
#include "mathops.h"
58
#include "thread.h"
59
60
enum ExrCompr {
61
    EXR_RAW,
62
    EXR_RLE,
63
    EXR_ZIP1,
64
    EXR_ZIP16,
65
    EXR_PIZ,
66
    EXR_PXR24,
67
    EXR_B44,
68
    EXR_B44A,
69
    EXR_DWA,
70
    EXR_DWB,
71
    EXR_UNKN,
72
};
73
74
enum ExrPixelType {
75
    EXR_UINT,
76
    EXR_HALF,
77
    EXR_FLOAT,
78
    EXR_UNKNOWN,
79
};
80
81
enum ExrTileLevelMode {
82
    EXR_TILE_LEVEL_ONE,
83
    EXR_TILE_LEVEL_MIPMAP,
84
    EXR_TILE_LEVEL_RIPMAP,
85
    EXR_TILE_LEVEL_UNKNOWN,
86
};
87
88
enum ExrTileLevelRound {
89
    EXR_TILE_ROUND_UP,
90
    EXR_TILE_ROUND_DOWN,
91
    EXR_TILE_ROUND_UNKNOWN,
92
};
93
94
typedef struct EXRChannel {
95
    int xsub, ysub;
96
    enum ExrPixelType pixel_type;
97
} EXRChannel;
98
99
typedef struct EXRTileAttribute {
100
    int32_t xSize;
101
    int32_t ySize;
102
    enum ExrTileLevelMode level_mode;
103
    enum ExrTileLevelRound level_round;
104
} EXRTileAttribute;
105
106
typedef struct EXRThreadData {
107
    uint8_t *uncompressed_data;
108
    int uncompressed_size;
109
110
    uint8_t *tmp;
111
    int tmp_size;
112
113
    uint8_t *bitmap;
114
    uint16_t *lut;
115
116
    int ysize, xsize;
117
118
    int channel_line_size;
119
} EXRThreadData;
120
121
typedef struct EXRContext {
122
    AVClass *class;
123
    AVFrame *picture;
124
    AVCodecContext *avctx;
125
    ExrDSPContext dsp;
126
127
#if HAVE_BIGENDIAN
128
    BswapDSPContext bbdsp;
129
#endif
130
131
    enum ExrCompr compression;
132
    enum ExrPixelType pixel_type;
133
    int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
134
    const AVPixFmtDescriptor *desc;
135
136
    int w, h;
137
    uint32_t xmax, xmin;
138
    uint32_t ymax, ymin;
139
    uint32_t xdelta, ydelta;
140
141
    int scan_lines_per_block;
142
143
    EXRTileAttribute tile_attr; /* header data attribute of tile */
144
    int is_tile; /* 0 if scanline, 1 if tile */
145
146
    int is_luma;/* 1 if there is an Y plane */
147
148
    GetByteContext gb;
149
    const uint8_t *buf;
150
    int buf_size;
151
152
    EXRChannel *channels;
153
    int nb_channels;
154
    int current_channel_offset;
155
156
    EXRThreadData *thread_data;
157
158
    const char *layer;
159
160
    enum AVColorTransferCharacteristic apply_trc_type;
161
    float gamma;
162
    union av_intfloat32 gamma_table[65536];
163
} EXRContext;
164
165
/* -15 stored using a single precision bias of 127 */
166
#define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000
167
168
/* max exponent value in single precision that will be converted
169
 * to Inf or Nan when stored as a half-float */
170
#define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000
171
172
/* 255 is the max exponent biased value */
173
#define FLOAT_MAX_BIASED_EXP (0xFF << 23)
174
175
#define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10)
176
177
/**
178
 * Convert a half float as a uint16_t into a full float.
179
 *
180
 * @param hf half float as uint16_t
181
 *
182
 * @return float value
183
 */
184
11898966
static union av_intfloat32 exr_half2float(uint16_t hf)
185
{
186
11898966
    unsigned int sign = (unsigned int) (hf >> 15);
187
11898966
    unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1));
188
11898966
    unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP);
189
    union av_intfloat32 f;
190
191
11898966
    if (exp == HALF_FLOAT_MAX_BIASED_EXP) {
192
        // we have a half-float NaN or Inf
193
        // half-float NaNs will be converted to a single precision NaN
194
        // half-float Infs will be converted to a single precision Inf
195
258048
        exp = FLOAT_MAX_BIASED_EXP;
196
258048
        if (mantissa)
197
257796
            mantissa = (1 << 23) - 1;    // set all bits to indicate a NaN
198
11640918
    } else if (exp == 0x0) {
199
        // convert half-float zero/denorm to single precision value
200
548266
        if (mantissa) {
201
265528
            mantissa <<= 1;
202
265528
            exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
203
            // check for leading 1 in denorm mantissa
204
523324
            while ((mantissa & (1 << 10))) {
205
                // for every leading 0, decrement single precision exponent by 1
206
                // and shift half-float mantissa value to the left
207
257796
                mantissa <<= 1;
208
257796
                exp -= (1 << 23);
209
            }
210
            // clamp the mantissa to 10 bits
211
265528
            mantissa &= ((1 << 10) - 1);
212
            // shift left to generate single-precision mantissa of 23 bits
213
265528
            mantissa <<= 13;
214
        }
215
    } else {
216
        // shift left to generate single-precision mantissa of 23 bits
217
11092652
        mantissa <<= 13;
218
        // generate single precision biased exponent value
219
11092652
        exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP;
220
    }
221
222
11898966
    f.i = (sign << 31) | exp | mantissa;
223
224
11898966
    return f;
225
}
226
227
1504
static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
228
                          int uncompressed_size, EXRThreadData *td)
229
{
230
1504
    unsigned long dest_len = uncompressed_size;
231
232
1504
    if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK ||
233
1504
        dest_len != uncompressed_size)
234
        return AVERROR_INVALIDDATA;
235
236
    av_assert1(uncompressed_size % 2 == 0);
237
238
1504
    s->dsp.predictor(td->tmp, uncompressed_size);
239
1504
    s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
240
241
1504
    return 0;
242
}
243
244
1386
static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size,
245
                          int uncompressed_size, EXRThreadData *td)
246
{
247
1386
    uint8_t *d      = td->tmp;
248
1386
    const int8_t *s = src;
249
1386
    int ssize       = compressed_size;
250
1386
    int dsize       = uncompressed_size;
251
1386
    uint8_t *dend   = d + dsize;
252
    int count;
253
254
378128
    while (ssize > 0) {
255
376742
        count = *s++;
256
257
376742
        if (count < 0) {
258
186494
            count = -count;
259
260
186494
            if ((dsize -= count) < 0 ||
261
186494
                (ssize -= count + 1) < 0)
262
                return AVERROR_INVALIDDATA;
263
264
3463010
            while (count--)
265
3276516
                *d++ = *s++;
266
        } else {
267
190248
            count++;
268
269
190248
            if ((dsize -= count) < 0 ||
270
190248
                (ssize -= 2) < 0)
271
                return AVERROR_INVALIDDATA;
272
273
3270228
            while (count--)
274
3079980
                *d++ = *s;
275
276
190248
            s++;
277
        }
278
    }
279
280
1386
    if (dend != d)
281
        return AVERROR_INVALIDDATA;
282
283
    av_assert1(uncompressed_size % 2 == 0);
284
285
1386
    ctx->dsp.predictor(td->tmp, uncompressed_size);
286
1386
    ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size);
287
288
1386
    return 0;
289
}
290
291
#define USHORT_RANGE (1 << 16)
292
#define BITMAP_SIZE  (1 << 13)
293
294
48
static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut)
295
{
296
48
    int i, k = 0;
297
298
3145776
    for (i = 0; i < USHORT_RANGE; i++)
299

3145728
        if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
300
5798
            lut[k++] = i;
301
302
48
    i = k - 1;
303
304
48
    memset(lut + k, 0, (USHORT_RANGE - k) * 2);
305
306
48
    return i;
307
}
308
309
48
static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize)
310
{
311
    int i;
312
313
1472148
    for (i = 0; i < dsize; ++i)
314
1472100
        dst[i] = lut[dst[i]];
315
48
}
316
317
#define HUF_ENCBITS 16  // literal (value) bit length
318
#define HUF_DECBITS 14  // decoding bit size (>= 8)
319
320
#define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1)  // encoding table size
321
#define HUF_DECSIZE (1 << HUF_DECBITS)        // decoding table size
322
#define HUF_DECMASK (HUF_DECSIZE - 1)
323
324
typedef struct HufDec {
325
    int len;
326
    int lit;
327
    int *p;
328
} HufDec;
329
330
48
static void huf_canonical_code_table(uint64_t *hcode)
331
{
332
48
    uint64_t c, n[59] = { 0 };
333
    int i;
334
335
3145824
    for (i = 0; i < HUF_ENCSIZE; ++i)
336
3145776
        n[hcode[i]] += 1;
337
338
48
    c = 0;
339
2832
    for (i = 58; i > 0; --i) {
340
2784
        uint64_t nc = ((c + n[i]) >> 1);
341
2784
        n[i] = c;
342
2784
        c    = nc;
343
    }
344
345
3145824
    for (i = 0; i < HUF_ENCSIZE; ++i) {
346
3145776
        int l = hcode[i];
347
348
3145776
        if (l > 0)
349
3404
            hcode[i] = l | (n[l]++ << 6);
350
    }
351
48
}
352
353
#define SHORT_ZEROCODE_RUN  59
354
#define LONG_ZEROCODE_RUN   63
355
#define SHORTEST_LONG_RUN   (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN)
356
#define LONGEST_LONG_RUN    (255 + SHORTEST_LONG_RUN)
357
358
48
static int huf_unpack_enc_table(GetByteContext *gb,
359
                                int32_t im, int32_t iM, uint64_t *hcode)
360
{
361
    GetBitContext gbit;
362
48
    int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb));
363
48
    if (ret < 0)
364
        return ret;
365
366
16678
    for (; im <= iM; im++) {
367
16630
        uint64_t l = hcode[im] = get_bits(&gbit, 6);
368
369
16630
        if (l == LONG_ZEROCODE_RUN) {
370
12358
            int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN;
371
372
12358
            if (im + zerun > iM + 1)
373
                return AVERROR_INVALIDDATA;
374
375
3152920
            while (zerun--)
376
3140562
                hcode[im++] = 0;
377
378
12358
            im--;
379
4272
        } else if (l >= SHORT_ZEROCODE_RUN) {
380
458
            int zerun = l - SHORT_ZEROCODE_RUN + 2;
381
382
458
            if (im + zerun > iM + 1)
383
                return AVERROR_INVALIDDATA;
384
385
1858
            while (zerun--)
386
1400
                hcode[im++] = 0;
387
388
458
            im--;
389
        }
390
    }
391
392
48
    bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8);
393
48
    huf_canonical_code_table(hcode);
394
395
48
    return 0;
396
}
397
398
48
static int huf_build_dec_table(const uint64_t *hcode, int im,
399
                               int iM, HufDec *hdecod)
400
{
401
3145824
    for (; im <= iM; im++) {
402
3145776
        uint64_t c = hcode[im] >> 6;
403
3145776
        int i, l = hcode[im] & 63;
404
405
3145776
        if (c >> l)
406
            return AVERROR_INVALIDDATA;
407
408
3145776
        if (l > HUF_DECBITS) {
409
            HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
410
            if (pl->len)
411
                return AVERROR_INVALIDDATA;
412
413
            pl->lit++;
414
415
            pl->p = av_realloc(pl->p, pl->lit * sizeof(int));
416
            if (!pl->p)
417
                return AVERROR(ENOMEM);
418
419
            pl->p[pl->lit - 1] = im;
420
3145776
        } else if (l) {
421
3404
            HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
422
423
789836
            for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
424

786432
                if (pl->len || pl->p)
425
                    return AVERROR_INVALIDDATA;
426
786432
                pl->len = l;
427
786432
                pl->lit = im;
428
            }
429
        }
430
    }
431
432
48
    return 0;
433
}
434
435
#define get_char(c, lc, gb)                                                   \
436
{                                                                             \
437
        c   = (c << 8) | bytestream2_get_byte(gb);                            \
438
        lc += 8;                                                              \
439
}
440
441
#define get_code(po, rlc, c, lc, gb, out, oe, outb)                           \
442
{                                                                             \
443
        if (po == rlc) {                                                      \
444
            if (lc < 8)                                                       \
445
                get_char(c, lc, gb);                                          \
446
            lc -= 8;                                                          \
447
                                                                              \
448
            cs = c >> lc;                                                     \
449
                                                                              \
450
            if (out + cs > oe || out == outb)                                 \
451
                return AVERROR_INVALIDDATA;                                   \
452
                                                                              \
453
            s = out[-1];                                                      \
454
                                                                              \
455
            while (cs-- > 0)                                                  \
456
                *out++ = s;                                                   \
457
        } else if (out < oe) {                                                \
458
            *out++ = po;                                                      \
459
        } else {                                                              \
460
            return AVERROR_INVALIDDATA;                                       \
461
        }                                                                     \
462
}
463
464
48
static int huf_decode(const uint64_t *hcode, const HufDec *hdecod,
465
                      GetByteContext *gb, int nbits,
466
                      int rlc, int no, uint16_t *out)
467
{
468
48
    uint64_t c        = 0;
469
48
    uint16_t *outb    = out;
470
48
    uint16_t *oe      = out + no;
471
48
    const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size
472
    uint8_t cs;
473
    uint16_t s;
474
48
    int i, lc = 0;
475
476
76904
    while (gb->buffer < ie) {
477
76856
        get_char(c, lc, gb);
478
479
385156
        while (lc >= HUF_DECBITS) {
480
308300
            const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
481
482
308300
            if (pl.len) {
483
308300
                lc -= pl.len;
484



1477504
                get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
485
            } else {
486
                int j;
487
488
                if (!pl.p)
489
                    return AVERROR_INVALIDDATA;
490
491
                for (j = 0; j < pl.lit; j++) {
492
                    int l = hcode[pl.p[j]] & 63;
493
494
                    while (lc < l && bytestream2_get_bytes_left(gb) > 0)
495
                        get_char(c, lc, gb);
496
497
                    if (lc >= l) {
498
                        if ((hcode[pl.p[j]] >> 6) ==
499
                            ((c >> (lc - l)) & ((1LL << l) - 1))) {
500
                            lc -= l;
501
                            get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb);
502
                            break;
503
                        }
504
                    }
505
                }
506
507
                if (j == pl.lit)
508
                    return AVERROR_INVALIDDATA;
509
            }
510
        }
511
    }
512
513
48
    i   = (8 - nbits) & 7;
514
48
    c >>= i;
515
48
    lc -= i;
516
517
124
    while (lc > 0) {
518
76
        const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
519
520

76
        if (pl.len && lc >= pl.len) {
521
76
            lc -= pl.len;
522



520
            get_code(pl.lit, rlc, c, lc, gb, out, oe, outb);
523
        } else {
524
            return AVERROR_INVALIDDATA;
525
        }
526
    }
527
528
48
    if (out - outb != no)
529
        return AVERROR_INVALIDDATA;
530
48
    return 0;
531
}
532
533
48
static int huf_uncompress(GetByteContext *gb,
534
                          uint16_t *dst, int dst_size)
535
{
536
    int32_t src_size, im, iM;
537
    uint32_t nBits;
538
    uint64_t *freq;
539
    HufDec *hdec;
540
    int ret, i;
541
542
48
    src_size = bytestream2_get_le32(gb);
543
48
    im       = bytestream2_get_le32(gb);
544
48
    iM       = bytestream2_get_le32(gb);
545
48
    bytestream2_skip(gb, 4);
546
48
    nBits = bytestream2_get_le32(gb);
547

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

48
        iM < 0 || iM >= HUF_ENCSIZE ||
549
        src_size < 0)
550
        return AVERROR_INVALIDDATA;
551
552
48
    bytestream2_skip(gb, 4);
553
554
48
    freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq));
555
48
    hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec));
556

48
    if (!freq || !hdec) {
557
        ret = AVERROR(ENOMEM);
558
        goto fail;
559
    }
560
561
48
    if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0)
562
        goto fail;
563
564
48
    if (nBits > 8 * bytestream2_get_bytes_left(gb)) {
565
        ret = AVERROR_INVALIDDATA;
566
        goto fail;
567
    }
568
569
48
    if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0)
570
        goto fail;
571
48
    ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst);
572
573
48
fail:
574
786480
    for (i = 0; i < HUF_DECSIZE; i++)
575
786432
        if (hdec)
576
786432
            av_freep(&hdec[i].p);
577
578
48
    av_free(freq);
579
48
    av_free(hdec);
580
581
48
    return ret;
582
}
583
584
1958562
static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
585
{
586
1958562
    int16_t ls = l;
587
1958562
    int16_t hs = h;
588
1958562
    int hi     = hs;
589
1958562
    int ai     = ls + (hi & 1) + (hi >> 1);
590
1958562
    int16_t as = ai;
591
1958562
    int16_t bs = ai - hi;
592
593
1958562
    *a = as;
594
1958562
    *b = bs;
595
1958562
}
596
597
#define NBITS      16
598
#define A_OFFSET  (1 << (NBITS - 1))
599
#define MOD_MASK  ((1 << NBITS) - 1)
600
601
static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b)
602
{
603
    int m  = l;
604
    int d  = h;
605
    int bb = (m - (d >> 1)) & MOD_MASK;
606
    int aa = (d + bb - A_OFFSET) & MOD_MASK;
607
    *b = bb;
608
    *a = aa;
609
}
610
611
150
static void wav_decode(uint16_t *in, int nx, int ox,
612
                       int ny, int oy, uint16_t mx)
613
{
614
150
    int w14 = (mx < (1 << 14));
615
150
    int n   = (nx > ny) ? ny : nx;
616
150
    int p   = 1;
617
    int p2;
618
619
1008
    while (p <= n)
620
858
        p <<= 1;
621
622
150
    p >>= 1;
623
150
    p2  = p;
624
150
    p >>= 1;
625
626
858
    while (p >= 1) {
627
708
        uint16_t *py = in;
628
708
        uint16_t *ey = in + oy * (ny - p2);
629
        uint16_t i00, i01, i10, i11;
630
708
        int oy1 = oy * p;
631
708
        int oy2 = oy * p2;
632
708
        int ox1 = ox * p;
633
708
        int ox2 = ox * p2;
634
635
4914
        for (; py <= ey; py += oy2) {
636
4206
            uint16_t *px = py;
637
4206
            uint16_t *ex = py + ox * (nx - p2);
638
639
493602
            for (; px <= ex; px += ox2) {
640
489396
                uint16_t *p01 = px + ox1;
641
489396
                uint16_t *p10 = px + oy1;
642
489396
                uint16_t *p11 = p10 + ox1;
643
644
489396
                if (w14) {
645
489396
                    wdec14(*px, *p10, &i00, &i10);
646
489396
                    wdec14(*p01, *p11, &i01, &i11);
647
489396
                    wdec14(i00, i01, px, p01);
648
489396
                    wdec14(i10, i11, p10, p11);
649
                } else {
650
                    wdec16(*px, *p10, &i00, &i10);
651
                    wdec16(*p01, *p11, &i01, &i11);
652
                    wdec16(i00, i01, px, p01);
653
                    wdec16(i10, i11, p10, p11);
654
                }
655
            }
656
657
4206
            if (nx & p) {
658
216
                uint16_t *p10 = px + oy1;
659
660
216
                if (w14)
661
216
                    wdec14(*px, *p10, &i00, p10);
662
                else
663
                    wdec16(*px, *p10, &i00, p10);
664
665
216
                *px = i00;
666
            }
667
        }
668
669
708
        if (ny & p) {
670
30
            uint16_t *px = py;
671
30
            uint16_t *ex = py + ox * (nx - p2);
672
673
792
            for (; px <= ex; px += ox2) {
674
762
                uint16_t *p01 = px + ox1;
675
676
762
                if (w14)
677
762
                    wdec14(*px, *p01, &i00, p01);
678
                else
679
                    wdec16(*px, *p01, &i00, p01);
680
681
762
                *px = i00;
682
            }
683
        }
684
685
708
        p2  = p;
686
708
        p >>= 1;
687
    }
688
150
}
689
690
48
static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize,
691
                          int dsize, EXRThreadData *td)
692
{
693
    GetByteContext gb;
694
    uint16_t maxval, min_non_zero, max_non_zero;
695
    uint16_t *ptr;
696
48
    uint16_t *tmp = (uint16_t *)td->tmp;
697
    uint16_t *out;
698
    uint16_t *in;
699
    int ret, i, j;
700
    int pixel_half_size;/* 1 for half, 2 for float and uint32 */
701
    EXRChannel *channel;
702
    int tmp_offset;
703
704
48
    if (!td->bitmap)
705
10
        td->bitmap = av_malloc(BITMAP_SIZE);
706
48
    if (!td->lut)
707
10
        td->lut = av_malloc(1 << 17);
708

48
    if (!td->bitmap || !td->lut) {
709
        av_freep(&td->bitmap);
710
        av_freep(&td->lut);
711
        return AVERROR(ENOMEM);
712
    }
713
714
48
    bytestream2_init(&gb, src, ssize);
715
48
    min_non_zero = bytestream2_get_le16(&gb);
716
48
    max_non_zero = bytestream2_get_le16(&gb);
717
718
48
    if (max_non_zero >= BITMAP_SIZE)
719
        return AVERROR_INVALIDDATA;
720
721
48
    memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE));
722
48
    if (min_non_zero <= max_non_zero)
723
48
        bytestream2_get_buffer(&gb, td->bitmap + min_non_zero,
724
48
                               max_non_zero - min_non_zero + 1);
725
48
    memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1);
726
727
48
    maxval = reverse_lut(td->bitmap, td->lut);
728
729
48
    ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t));
730
48
    if (ret)
731
        return ret;
732
733
48
    ptr = tmp;
734
192
    for (i = 0; i < s->nb_channels; i++) {
735
144
        channel = &s->channels[i];
736
737
144
        if (channel->pixel_type == EXR_HALF)
738
138
            pixel_half_size = 1;
739
        else
740
6
            pixel_half_size = 2;
741
742
294
        for (j = 0; j < pixel_half_size; j++)
743
150
            wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize,
744
150
                       td->xsize * pixel_half_size, maxval);
745
144
        ptr += td->xsize * td->ysize * pixel_half_size;
746
    }
747
748
48
    apply_lut(td->lut, tmp, dsize / sizeof(uint16_t));
749
750
48
    out = (uint16_t *)td->uncompressed_data;
751
1446
    for (i = 0; i < td->ysize; i++) {
752
1398
        tmp_offset = 0;
753
5592
        for (j = 0; j < s->nb_channels; j++) {
754
4194
            channel = &s->channels[j];
755
4194
            if (channel->pixel_type == EXR_HALF)
756
4002
                pixel_half_size = 1;
757
            else
758
192
                pixel_half_size = 2;
759
760
4194
            in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size;
761
4194
            tmp_offset += pixel_half_size;
762
763
#if HAVE_BIGENDIAN
764
            s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size);
765
#else
766
4194
            memcpy(out, in, td->xsize * 2 * pixel_half_size);
767
#endif
768
4194
            out += td->xsize * pixel_half_size;
769
        }
770
    }
771
772
48
    return 0;
773
}
774
775
122
static int pxr24_uncompress(EXRContext *s, const uint8_t *src,
776
                            int compressed_size, int uncompressed_size,
777
                            EXRThreadData *td)
778
{
779
122
    unsigned long dest_len, expected_len = 0;
780
122
    const uint8_t *in = td->tmp;
781
    uint8_t *out;
782
    int c, i, j;
783
784
558
    for (i = 0; i < s->nb_channels; i++) {
785
436
        if (s->channels[i].pixel_type == EXR_FLOAT) {
786
62
            expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */
787
374
        } else if (s->channels[i].pixel_type == EXR_HALF) {
788
362
            expected_len += (td->xsize * td->ysize * 2);
789
        } else {//UINT 32
790
12
            expected_len += (td->xsize * td->ysize * 4);
791
        }
792
    }
793
794
122
    dest_len = expected_len;
795
796
122
    if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) {
797
        return AVERROR_INVALIDDATA;
798
122
    } else if (dest_len != expected_len) {
799
        return AVERROR_INVALIDDATA;
800
    }
801
802
122
    out = td->uncompressed_data;
803
1900
    for (i = 0; i < td->ysize; i++)
804
7678
        for (c = 0; c < s->nb_channels; c++) {
805
5900
            EXRChannel *channel = &s->channels[c];
806
            const uint8_t *ptr[4];
807
5900
            uint32_t pixel = 0;
808
809

5900
            switch (channel->pixel_type) {
810
496
            case EXR_FLOAT:
811
496
                ptr[0] = in;
812
496
                ptr[1] = ptr[0] + td->xsize;
813
496
                ptr[2] = ptr[1] + td->xsize;
814
496
                in     = ptr[2] + td->xsize;
815
816
6448
                for (j = 0; j < td->xsize; ++j) {
817
5952
                    uint32_t diff = ((unsigned)*(ptr[0]++) << 24) |
818
5952
                                    (*(ptr[1]++) << 16) |
819
5952
                                    (*(ptr[2]++) << 8);
820
5952
                    pixel += diff;
821
5952
                    bytestream_put_le32(&out, pixel);
822
                }
823
496
                break;
824
5302
            case EXR_HALF:
825
5302
                ptr[0] = in;
826
5302
                ptr[1] = ptr[0] + td->xsize;
827
5302
                in     = ptr[1] + td->xsize;
828
3851380
                for (j = 0; j < td->xsize; j++) {
829
3846078
                    uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++);
830
831
3846078
                    pixel += diff;
832
3846078
                    bytestream_put_le16(&out, pixel);
833
                }
834
5302
                break;
835
102
            case EXR_UINT:
836
102
                ptr[0] = in;
837
102
                ptr[1] = ptr[0] + s->xdelta;
838
102
                ptr[2] = ptr[1] + s->xdelta;
839
102
                ptr[3] = ptr[2] + s->xdelta;
840
102
                in     = ptr[3] + s->xdelta;
841
842
1380
                for (j = 0; j < s->xdelta; ++j) {
843
1278
                    uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) |
844
1278
                    (*(ptr[1]++) << 16) |
845
1278
                    (*(ptr[2]++) << 8 ) |
846
1278
                    (*(ptr[3]++));
847
1278
                    pixel += diff;
848
1278
                    bytestream_put_le32(&out, pixel);
849
                }
850
102
                break;
851
            default:
852
                return AVERROR_INVALIDDATA;
853
            }
854
        }
855
856
122
    return 0;
857
}
858
859
118558
static void unpack_14(const uint8_t b[14], uint16_t s[16])
860
{
861
118558
    unsigned short shift = (b[ 2] >> 2) & 15;
862
118558
    unsigned short bias = (0x20 << shift);
863
    int i;
864
865
118558
    s[ 0] = (b[0] << 8) | b[1];
866
867
118558
    s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;
868
118558
    s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;
869
118558
    s[12] = s[ 8] +   ((b[ 4]                       & 0x3f) << shift) - bias;
870
871
118558
    s[ 1] = s[ 0] +   ((b[ 5] >> 2)                         << shift) - bias;
872
118558
    s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;
873
118558
    s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;
874
118558
    s[13] = s[12] +   ((b[ 7]                       & 0x3f) << shift) - bias;
875
876
118558
    s[ 2] = s[ 1] +   ((b[ 8] >> 2)                         << shift) - bias;
877
118558
    s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;
878
118558
    s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;
879
118558
    s[14] = s[13] +   ((b[10]                       & 0x3f) << shift) - bias;
880
881
118558
    s[ 3] = s[ 2] +   ((b[11] >> 2)                         << shift) - bias;
882
118558
    s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;
883
118558
    s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;
884
118558
    s[15] = s[14] +   ((b[13]                       & 0x3f) << shift) - bias;
885
886
2015486
    for (i = 0; i < 16; ++i) {
887
1896928
        if (s[i] & 0x8000)
888
1884694
            s[i] &= 0x7fff;
889
        else
890
12234
            s[i] = ~s[i];
891
    }
892
118558
}
893
894
212
static void unpack_3(const uint8_t b[3], uint16_t s[16])
895
{
896
    int i;
897
898
212
    s[0] = (b[0] << 8) | b[1];
899
900
212
    if (s[0] & 0x8000)
901
210
        s[0] &= 0x7fff;
902
    else
903
2
        s[0] = ~s[0];
904
905
3392
    for (i = 1; i < 16; i++)
906
3180
        s[i] = s[0];
907
212
}
908
909
910
46
static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,
911
                          int uncompressed_size, EXRThreadData *td) {
912
46
    const int8_t *sr = src;
913
46
    int stay_to_uncompress = compressed_size;
914
    int nb_b44_block_w, nb_b44_block_h;
915
    int index_tl_x, index_tl_y, index_out, index_tmp;
916
    uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */
917
    int c, iY, iX, y, x;
918
46
    int target_channel_offset = 0;
919
920
    /* calc B44 block count */
921
46
    nb_b44_block_w = td->xsize / 4;
922
46
    if ((td->xsize % 4) != 0)
923
26
        nb_b44_block_w++;
924
925
46
    nb_b44_block_h = td->ysize / 4;
926
46
    if ((td->ysize % 4) != 0)
927
12
        nb_b44_block_h++;
928
929
312
    for (c = 0; c < s->nb_channels; c++) {
930
266
        if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */
931
918
            for (iY = 0; iY < nb_b44_block_h; iY++) {
932
119518
                for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */
933
118770
                    if (stay_to_uncompress < 3) {
934
                        av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress);
935
                        return AVERROR_INVALIDDATA;
936
                    }
937
938
118770
                    if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */
939
212
                        unpack_3(sr, tmp_buffer);
940
212
                        sr += 3;
941
212
                        stay_to_uncompress -= 3;
942
                    }  else {/* B44 Block */
943
118558
                        if (stay_to_uncompress < 14) {
944
                            av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress);
945
                            return AVERROR_INVALIDDATA;
946
                        }
947
118558
                        unpack_14(sr, tmp_buffer);
948
118558
                        sr += 14;
949
118558
                        stay_to_uncompress -= 14;
950
                    }
951
952
                    /* copy data to uncompress buffer (B44 block can exceed target resolution)*/
953
118770
                    index_tl_x = iX * 4;
954
118770
                    index_tl_y = iY * 4;
955
956

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

2360726
                        for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {
958
1887974
                            index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;
959
1887974
                            index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);
960
1887974
                            td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;
961
1887974
                            td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;
962
                        }
963
                    }
964
                }
965
            }
966
170
            target_channel_offset += 2;
967
        } else {/* Float or UINT 32 channel */
968
96
            if (stay_to_uncompress < td->ysize * td->xsize * 4) {
969
                av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress);
970
                return AVERROR_INVALIDDATA;
971
            }
972
973
896
            for (y = 0; y < td->ysize; y++) {
974
800
                index_out = target_channel_offset * td->xsize + y * td->channel_line_size;
975
800
                memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);
976
800
                sr += td->xsize * 4;
977
            }
978
96
            target_channel_offset += 4;
979
980
96
            stay_to_uncompress -= td->ysize * td->xsize * 4;
981
        }
982
    }
983
984
46
    return 0;
985
}
986
987
4526
static int decode_block(AVCodecContext *avctx, void *tdata,
988
                        int jobnr, int threadnr)
989
{
990
4526
    EXRContext *s = avctx->priv_data;
991
4526
    AVFrame *const p = s->picture;
992
4526
    EXRThreadData *td = &s->thread_data[threadnr];
993
4526
    const uint8_t *channel_buffer[4] = { 0 };
994
4526
    const uint8_t *buf = s->buf;
995
    uint64_t line_offset, uncompressed_size;
996
    uint8_t *ptr;
997
    uint32_t data_size;
998
4526
    uint64_t line, col = 0;
999
    uint64_t tile_x, tile_y, tile_level_x, tile_level_y;
1000
    const uint8_t *src;
1001
4526
    int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components;
1002
4526
    int axmax = (avctx->width - (s->xmax + 1)) * step; /* nb pixel to add at the right of the datawindow */
1003
4526
    int bxmin = s->xmin * step; /* nb pixel to add at the left of the datawindow */
1004
4526
    int i, x, buf_size = s->buf_size;
1005
    int c, rgb_channel_count;
1006
4526
    float one_gamma = 1.0f / s->gamma;
1007
4526
    avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);
1008
    int ret;
1009
1010
4526
    line_offset = AV_RL64(s->gb.buffer + jobnr * 8);
1011
1012
4526
    if (s->is_tile) {
1013

52
        if (buf_size < 20 || line_offset > buf_size - 20)
1014
            return AVERROR_INVALIDDATA;
1015
1016
52
        src  = buf + line_offset + 20;
1017
1018
52
        tile_x = AV_RL32(src - 20);
1019
52
        tile_y = AV_RL32(src - 16);
1020
52
        tile_level_x = AV_RL32(src - 12);
1021
52
        tile_level_y = AV_RL32(src - 8);
1022
1023
52
        data_size = AV_RL32(src - 4);
1024

52
        if (data_size <= 0 || data_size > buf_size - line_offset - 20)
1025
            return AVERROR_INVALIDDATA;
1026
1027

52
        if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */
1028
            avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");
1029
            return AVERROR_PATCHWELCOME;
1030
        }
1031
1032

52
        if (s->xmin || s->ymin) {
1033
            avpriv_report_missing_feature(s->avctx, "Tiles with xmin/ymin");
1034
            return AVERROR_PATCHWELCOME;
1035
        }
1036
1037
52
        line = s->tile_attr.ySize * tile_y;
1038
52
        col = s->tile_attr.xSize * tile_x;
1039
1040

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

52
            col  < s->xmin || col  > s->xmax)
1042
            return AVERROR_INVALIDDATA;
1043
1044
52
        td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);
1045
52
        td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);
1046
1047
52
        if (col) { /* not the first tile of the line */
1048
12
            bxmin = 0; /* doesn't add pixel at the left of the datawindow */
1049
        }
1050
1051
52
        if ((col + td->xsize) != s->xdelta)/* not the last tile of the line */
1052
12
            axmax = 0; /* doesn't add pixel at the right of the datawindow */
1053
1054
52
        td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1055
52
        uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1056
    } else {
1057

4474
        if (buf_size < 8 || line_offset > buf_size - 8)
1058
            return AVERROR_INVALIDDATA;
1059
1060
4474
        src  = buf + line_offset + 8;
1061
4474
        line = AV_RL32(src - 8);
1062
1063

4474
        if (line < s->ymin || line > s->ymax)
1064
            return AVERROR_INVALIDDATA;
1065
1066
4474
        data_size = AV_RL32(src - 4);
1067

4474
        if (data_size <= 0 || data_size > buf_size - line_offset - 8)
1068
            return AVERROR_INVALIDDATA;
1069
1070
4474
        td->ysize          = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */
1071
4474
        td->xsize          = s->xdelta;
1072
1073
4474
        td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */
1074
4474
        uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */
1075
1076

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

4474
            (s->compression != EXR_RAW && (data_size > uncompressed_size ||
1079
3084
                                           line_offset > buf_size - data_size))) {
1080
            return AVERROR_INVALIDDATA;
1081
        }
1082
    }
1083
1084

4526
    if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */
1085
3132
        av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);
1086
3132
        if (!td->tmp)
1087
            return AVERROR(ENOMEM);
1088
    }
1089
1090
4526
    if (data_size < uncompressed_size) {
1091
3106
        av_fast_padded_malloc(&td->uncompressed_data,
1092
3106
                              &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */
1093
1094
3106
        if (!td->uncompressed_data)
1095
            return AVERROR(ENOMEM);
1096
1097
3106
        ret = AVERROR_INVALIDDATA;
1098

3106
        switch (s->compression) {
1099
1504
        case EXR_ZIP1:
1100
        case EXR_ZIP16:
1101
1504
            ret = zip_uncompress(s, src, data_size, uncompressed_size, td);
1102
1504
            break;
1103
48
        case EXR_PIZ:
1104
48
            ret = piz_uncompress(s, src, data_size, uncompressed_size, td);
1105
48
            break;
1106
122
        case EXR_PXR24:
1107
122
            ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);
1108
122
            break;
1109
1386
        case EXR_RLE:
1110
1386
            ret = rle_uncompress(s, src, data_size, uncompressed_size, td);
1111
1386
            break;
1112
46
        case EXR_B44:
1113
        case EXR_B44A:
1114
46
            ret = b44_uncompress(s, src, data_size, uncompressed_size, td);
1115
46
            break;
1116
        }
1117
3106
        if (ret < 0) {
1118
            av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");
1119
            return ret;
1120
        }
1121
3106
        src = td->uncompressed_data;
1122
    }
1123
1124
4526
    if (!s->is_luma) {
1125
4522
        channel_buffer[0] = src + td->xsize * s->channel_offsets[0];
1126
4522
        channel_buffer[1] = src + td->xsize * s->channel_offsets[1];
1127
4522
        channel_buffer[2] = src + td->xsize * s->channel_offsets[2];
1128
4522
        rgb_channel_count = 3;
1129
    } else { /* put y data in the first channel_buffer */
1130
4
        channel_buffer[0] = src + td->xsize * s->channel_offsets[1];
1131
4
        rgb_channel_count = 1;
1132
    }
1133
4526
    if (s->channel_offsets[3] >= 0)
1134
4242
        channel_buffer[3] = src + td->xsize * s->channel_offsets[3];
1135
1136
4526
    if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {
1137
1138
        /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1139
4522
        int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count;
1140
4522
        if (s->is_luma) {
1141
4
            channel_buffer[1] = channel_buffer[0];
1142
4
            channel_buffer[2] = channel_buffer[0];
1143
        }
1144
1145
22322
        for (c = 0; c < channel_count; c++) {
1146
17800
            int plane = s->desc->comp[c].plane;
1147
17800
            ptr = p->data[plane] + line * p->linesize[plane] + (col * 4);
1148
1149
55586
            for (i = 0; i < td->ysize; i++, ptr += p->linesize[plane]) {
1150
                const uint8_t *src;
1151
                union av_intfloat32 *ptr_x;
1152
1153
37786
                src = channel_buffer[c];
1154
37786
                ptr_x = (union av_intfloat32 *)ptr;
1155
1156
                // Zero out the start if xmin is not 0
1157
37786
                memset(ptr_x, 0, bxmin);
1158
37786
                ptr_x += s->xmin;
1159
1160
37786
                if (s->pixel_type == EXR_FLOAT) {
1161
                    // 32-bit
1162
                    union av_intfloat32 t;
1163

3836
                    if (trc_func && c < 3) {
1164
                        for (x = 0; x < td->xsize; x++) {
1165
                            t.i = bytestream_get_le32(&src);
1166
                            t.f = trc_func(t.f);
1167
                            *ptr_x++ = t;
1168
                        }
1169
                    } else {
1170
145652
                        for (x = 0; x < td->xsize; x++) {
1171
141816
                            t.i = bytestream_get_le32(&src);
1172

141816
                            if (t.f > 0.0f && c < 3)  /* avoid negative values */
1173
136236
                                t.f = powf(t.f, one_gamma);
1174
141816
                            *ptr_x++ = t;
1175
                        }
1176
                    }
1177
33950
                } else if (s->pixel_type == EXR_HALF) {
1178
                    // 16-bit
1179
33950
                    if (c < 3) {
1180
16256366
                        for (x = 0; x < td->xsize; x++) {
1181
16228482
                            *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)];
1182
                        }
1183
                    } else {
1184
3647496
                        for (x = 0; x < td->xsize; x++) {
1185
3641430
                            *ptr_x++ = exr_half2float(bytestream_get_le16(&src));;
1186
                        }
1187
                    }
1188
                }
1189
1190
                // Zero out the end if xmax+1 is not w
1191
37786
                memset(ptr_x, 0, axmax);
1192
37786
                channel_buffer[c] += td->channel_line_size;
1193
            }
1194
        }
1195
    } else {
1196
1197
        av_assert1(s->pixel_type == EXR_UINT);
1198
4
        ptr = p->data[0] + line * p->linesize[0] + (col * s->desc->nb_components * 2);
1199
1200
36
        for (i = 0; i < td->ysize; i++, ptr += p->linesize[0]) {
1201
1202
            const uint8_t * a;
1203
            const uint8_t *rgb[3];
1204
            uint16_t *ptr_x;
1205
1206
128
            for (c = 0; c < rgb_channel_count; c++) {
1207
96
                rgb[c] = channel_buffer[c];
1208
            }
1209
1210
32
            if (channel_buffer[3])
1211
                a = channel_buffer[3];
1212
1213
32
            ptr_x = (uint16_t *) ptr;
1214
1215
            // Zero out the start if xmin is not 0
1216
32
            memset(ptr_x, 0, bxmin);
1217
32
            ptr_x += s->xmin * s->desc->nb_components;
1218
1219
416
            for (x = 0; x < td->xsize; x++) {
1220
1536
                for (c = 0; c < rgb_channel_count; c++) {
1221
1152
                    *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;
1222
                }
1223
1224
384
                if (channel_buffer[3])
1225
                    *ptr_x++ = bytestream_get_le32(&a) >> 16;
1226
            }
1227
1228
            // Zero out the end if xmax+1 is not w
1229
32
            memset(ptr_x, 0, axmax);
1230
1231
32
            channel_buffer[0] += td->channel_line_size;
1232
32
            channel_buffer[1] += td->channel_line_size;
1233
32
            channel_buffer[2] += td->channel_line_size;
1234
32
            if (channel_buffer[3])
1235
                channel_buffer[3] += td->channel_line_size;
1236
        }
1237
    }
1238
1239
4526
    return 0;
1240
}
1241
1242
/**
1243
 * Check if the variable name corresponds to its data type.
1244
 *
1245
 * @param s              the EXRContext
1246
 * @param value_name     name of the variable to check
1247
 * @param value_type     type of the variable to check
1248
 * @param minimum_length minimum length of the variable data
1249
 *
1250
 * @return bytes to read containing variable data
1251
 *         -1 if variable is not found
1252
 *         0 if buffer ended prematurely
1253
 */
1254
13522
static int check_header_variable(EXRContext *s,
1255
                                 const char *value_name,
1256
                                 const char *value_type,
1257
                                 unsigned int minimum_length)
1258
{
1259
13522
    int var_size = -1;
1260
1261
13522
    if (bytestream2_get_bytes_left(&s->gb) >= minimum_length &&
1262
13522
        !strcmp(s->gb.buffer, value_name)) {
1263
        // found value_name, jump to value_type (null terminated strings)
1264
808
        s->gb.buffer += strlen(value_name) + 1;
1265
808
        if (!strcmp(s->gb.buffer, value_type)) {
1266
808
            s->gb.buffer += strlen(value_type) + 1;
1267
808
            var_size = bytestream2_get_le32(&s->gb);
1268
            // don't go read past boundaries
1269
808
            if (var_size > bytestream2_get_bytes_left(&s->gb))
1270
                var_size = 0;
1271
        } else {
1272
            // value_type not found, reset the buffer
1273
            s->gb.buffer -= strlen(value_name) + 1;
1274
            av_log(s->avctx, AV_LOG_WARNING,
1275
                   "Unknown data type %s for header variable %s.\n",
1276
                   value_type, value_name);
1277
        }
1278
    }
1279
1280
13522
    return var_size;
1281
}
1282
1283
126
static int decode_header(EXRContext *s, AVFrame *frame)
1284
{
1285
126
    AVDictionary *metadata = NULL;
1286
126
    int magic_number, version, i, flags, sar = 0;
1287
126
    int layer_match = 0;
1288
    int ret;
1289
126
    int dup_channels = 0;
1290
1291
126
    s->current_channel_offset = 0;
1292
126
    s->xmin               = ~0;
1293
126
    s->xmax               = ~0;
1294
126
    s->ymin               = ~0;
1295
126
    s->ymax               = ~0;
1296
126
    s->xdelta             = ~0;
1297
126
    s->ydelta             = ~0;
1298
126
    s->channel_offsets[0] = -1;
1299
126
    s->channel_offsets[1] = -1;
1300
126
    s->channel_offsets[2] = -1;
1301
126
    s->channel_offsets[3] = -1;
1302
126
    s->pixel_type         = EXR_UNKNOWN;
1303
126
    s->compression        = EXR_UNKN;
1304
126
    s->nb_channels        = 0;
1305
126
    s->w                  = 0;
1306
126
    s->h                  = 0;
1307
126
    s->tile_attr.xSize    = -1;
1308
126
    s->tile_attr.ySize    = -1;
1309
126
    s->is_tile            = 0;
1310
126
    s->is_luma            = 0;
1311
1312
126
    if (bytestream2_get_bytes_left(&s->gb) < 10) {
1313
        av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");
1314
        return AVERROR_INVALIDDATA;
1315
    }
1316
1317
126
    magic_number = bytestream2_get_le32(&s->gb);
1318
126
    if (magic_number != 20000630) {
1319
        /* As per documentation of OpenEXR, it is supposed to be
1320
         * int 20000630 little-endian */
1321
        av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number);
1322
        return AVERROR_INVALIDDATA;
1323
    }
1324
1325
126
    version = bytestream2_get_byte(&s->gb);
1326
126
    if (version != 2) {
1327
        avpriv_report_missing_feature(s->avctx, "Version %d", version);
1328
        return AVERROR_PATCHWELCOME;
1329
    }
1330
1331
126
    flags = bytestream2_get_le24(&s->gb);
1332
1333
126
    if (flags & 0x02)
1334
36
        s->is_tile = 1;
1335
126
    if (flags & 0x08) {
1336
        avpriv_report_missing_feature(s->avctx, "deep data");
1337
        return AVERROR_PATCHWELCOME;
1338
    }
1339
126
    if (flags & 0x10) {
1340
        avpriv_report_missing_feature(s->avctx, "multipart");
1341
        return AVERROR_PATCHWELCOME;
1342
    }
1343
1344
    // Parse the header
1345

2246
    while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) {
1346
        int var_size;
1347
2120
        if ((var_size = check_header_variable(s, "channels",
1348
                                              "chlist", 38)) >= 0) {
1349
            GetByteContext ch_gb;
1350
126
            if (!var_size) {
1351
                ret = AVERROR_INVALIDDATA;
1352
                goto fail;
1353
            }
1354
1355
126
            bytestream2_init(&ch_gb, s->gb.buffer, var_size);
1356
1357
826
            while (bytestream2_get_bytes_left(&ch_gb) >= 19) {
1358
                EXRChannel *channel;
1359
                enum ExrPixelType current_pixel_type;
1360
700
                int channel_index = -1;
1361
                int xsub, ysub;
1362
1363
700
                if (strcmp(s->layer, "") != 0) {
1364
260
                    if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) {
1365
144
                        layer_match = 1;
1366
144
                        av_log(s->avctx, AV_LOG_INFO,
1367
                               "Channel match layer : %s.\n", ch_gb.buffer);
1368
144
                        ch_gb.buffer += strlen(s->layer);
1369
144
                        if (*ch_gb.buffer == '.')
1370
144
                            ch_gb.buffer++;         /* skip dot if not given */
1371
                    } else {
1372
116
                        layer_match = 0;
1373
116
                        av_log(s->avctx, AV_LOG_INFO,
1374
                               "Channel doesn't match layer : %s.\n", ch_gb.buffer);
1375
                    }
1376
                } else {
1377
440
                    layer_match = 1;
1378
                }
1379
1380
700
                if (layer_match) { /* only search channel if the layer match is valid */
1381

1046
                    if (!av_strcasecmp(ch_gb.buffer, "R") ||
1382
924
                        !av_strcasecmp(ch_gb.buffer, "X") ||
1383
462
                        !av_strcasecmp(ch_gb.buffer, "U")) {
1384
122
                        channel_index = 0;
1385
122
                        s->is_luma = 0;
1386

802
                    } else if (!av_strcasecmp(ch_gb.buffer, "G") ||
1387
340
                               !av_strcasecmp(ch_gb.buffer, "V")) {
1388
122
                        channel_index = 1;
1389
122
                        s->is_luma = 0;
1390
340
                    } else if (!av_strcasecmp(ch_gb.buffer, "Y")) {
1391
4
                        channel_index = 1;
1392
4
                        s->is_luma = 1;
1393

550
                    } else if (!av_strcasecmp(ch_gb.buffer, "B") ||
1394
428
                               !av_strcasecmp(ch_gb.buffer, "Z") ||
1395
214
                               !av_strcasecmp(ch_gb.buffer, "W")) {
1396
122
                        channel_index = 2;
1397
122
                        s->is_luma = 0;
1398
214
                    } else if (!av_strcasecmp(ch_gb.buffer, "A")) {
1399
56
                        channel_index = 3;
1400
                    } else {
1401
158
                        av_log(s->avctx, AV_LOG_WARNING,
1402
                               "Unsupported channel %.256s.\n", ch_gb.buffer);
1403
                    }
1404
                }
1405
1406
                /* skip until you get a 0 */
1407

7856
                while (bytestream2_get_bytes_left(&ch_gb) > 0 &&
1408
3928
                       bytestream2_get_byte(&ch_gb))
1409
3228
                    continue;
1410
1411
700
                if (bytestream2_get_bytes_left(&ch_gb) < 4) {
1412
                    av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n");
1413
                    ret = AVERROR_INVALIDDATA;
1414
                    goto fail;
1415
                }
1416
1417
700
                current_pixel_type = bytestream2_get_le32(&ch_gb);
1418
700
                if (current_pixel_type >= EXR_UNKNOWN) {
1419
                    avpriv_report_missing_feature(s->avctx, "Pixel type %d",
1420
                                                  current_pixel_type);
1421
                    ret = AVERROR_PATCHWELCOME;
1422
                    goto fail;
1423
                }
1424
1425
700
                bytestream2_skip(&ch_gb, 4);
1426
700
                xsub = bytestream2_get_le32(&ch_gb);
1427
700
                ysub = bytestream2_get_le32(&ch_gb);
1428
1429

700
                if (xsub != 1 || ysub != 1) {
1430
                    avpriv_report_missing_feature(s->avctx,
1431
                                                  "Subsampling %dx%d",
1432
                                                  xsub, ysub);
1433
                    ret = AVERROR_PATCHWELCOME;
1434
                    goto fail;
1435
                }
1436
1437

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

36
        if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) {
1627
            av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n");
1628
            ret = AVERROR_INVALIDDATA;
1629
            goto fail;
1630
        }
1631
    }
1632
1633
126
    if (bytestream2_get_bytes_left(&s->gb) <= 0) {
1634
        av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n");
1635
        ret = AVERROR_INVALIDDATA;
1636
        goto fail;
1637
    }
1638
1639
126
    frame->metadata = metadata;
1640
1641
    // aaand we are done
1642
126
    bytestream2_skip(&s->gb, 1);
1643
126
    return 0;
1644
fail:
1645
    av_dict_free(&metadata);
1646
    return ret;
1647
}
1648
1649
126
static int decode_frame(AVCodecContext *avctx, void *data,
1650
                        int *got_frame, AVPacket *avpkt)
1651
{
1652
126
    EXRContext *s = avctx->priv_data;
1653
126
    ThreadFrame frame = { .f = data };
1654
126
    AVFrame *picture = data;
1655
    uint8_t *ptr;
1656
1657
    int i, y, ret;
1658
    int planes;
1659
    int out_line_size;
1660
    int nb_blocks;   /* nb scanline or nb tile */
1661
    uint64_t start_offset_table;
1662
    uint64_t start_next_scanline;
1663
    PutByteContext offset_table_writer;
1664
1665
126
    bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1666
1667
126
    if ((ret = decode_header(s, picture)) < 0)
1668
        return ret;
1669
1670
126
    switch (s->pixel_type) {
1671
122
    case EXR_FLOAT:
1672
    case EXR_HALF:
1673
122
        if (s->channel_offsets[3] >= 0) {
1674
56
            if (!s->is_luma) {
1675
56
                avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1676
            } else {
1677
                /* todo: change this when a floating point pixel format with luma with alpha is implemented */
1678
                avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;
1679
            }
1680
        } else {
1681
66
            if (!s->is_luma) {
1682
62
                avctx->pix_fmt = AV_PIX_FMT_GBRPF32;
1683
            } else {
1684
4
                avctx->pix_fmt = AV_PIX_FMT_GRAYF32;
1685
            }
1686
        }
1687
122
        break;
1688
4
    case EXR_UINT:
1689
4
        if (s->channel_offsets[3] >= 0) {
1690
            if (!s->is_luma) {
1691
                avctx->pix_fmt = AV_PIX_FMT_RGBA64;
1692
            } else {
1693
                avctx->pix_fmt = AV_PIX_FMT_YA16;
1694
            }
1695
        } else {
1696
4
            if (!s->is_luma) {
1697
4
                avctx->pix_fmt = AV_PIX_FMT_RGB48;
1698
            } else {
1699
                avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1700
            }
1701
        }
1702
4
        break;
1703
    default:
1704
        av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n");
1705
        return AVERROR_INVALIDDATA;
1706
    }
1707
1708
126
    if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)
1709
        avctx->color_trc = s->apply_trc_type;
1710
1711

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

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

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