GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/pngdec.c Lines: 614 1085 56.6 %
Date: 2020-07-11 02:49:52 Branches: 390 798 48.9 %

Line Branch Exec Source
1
/*
2
 * PNG image format
3
 * Copyright (c) 2003 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
//#define DEBUG
23
24
#include "libavutil/avassert.h"
25
#include "libavutil/bprint.h"
26
#include "libavutil/crc.h"
27
#include "libavutil/imgutils.h"
28
#include "libavutil/intreadwrite.h"
29
#include "libavutil/stereo3d.h"
30
#include "libavutil/mastering_display_metadata.h"
31
32
#include "avcodec.h"
33
#include "bytestream.h"
34
#include "internal.h"
35
#include "apng.h"
36
#include "png.h"
37
#include "pngdsp.h"
38
#include "thread.h"
39
40
#include <zlib.h>
41
42
enum PNGHeaderState {
43
    PNG_IHDR = 1 << 0,
44
    PNG_PLTE = 1 << 1,
45
};
46
47
enum PNGImageState {
48
    PNG_IDAT     = 1 << 0,
49
    PNG_ALLIMAGE = 1 << 1,
50
};
51
52
typedef struct PNGDecContext {
53
    PNGDSPContext dsp;
54
    AVCodecContext *avctx;
55
56
    GetByteContext gb;
57
    ThreadFrame previous_picture;
58
    ThreadFrame last_picture;
59
    ThreadFrame picture;
60
61
    enum PNGHeaderState hdr_state;
62
    enum PNGImageState pic_state;
63
    int width, height;
64
    int cur_w, cur_h;
65
    int last_w, last_h;
66
    int x_offset, y_offset;
67
    int last_x_offset, last_y_offset;
68
    uint8_t dispose_op, blend_op;
69
    uint8_t last_dispose_op;
70
    int bit_depth;
71
    int color_type;
72
    int compression_type;
73
    int interlace_type;
74
    int filter_type;
75
    int channels;
76
    int bits_per_pixel;
77
    int bpp;
78
    int has_trns;
79
    uint8_t transparent_color_be[6];
80
81
    uint8_t *image_buf;
82
    int image_linesize;
83
    uint32_t palette[256];
84
    uint8_t *crow_buf;
85
    uint8_t *last_row;
86
    unsigned int last_row_size;
87
    uint8_t *tmp_row;
88
    unsigned int tmp_row_size;
89
    uint8_t *buffer;
90
    int buffer_size;
91
    int pass;
92
    int crow_size; /* compressed row size (include filter type) */
93
    int row_size; /* decompressed row size */
94
    int pass_row_size; /* decompress row size of the current pass */
95
    int y;
96
    z_stream zstream;
97
} PNGDecContext;
98
99
/* Mask to determine which pixels are valid in a pass */
100
static const uint8_t png_pass_mask[NB_PASSES] = {
101
    0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
102
};
103
104
/* Mask to determine which y pixels can be written in a pass */
105
static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
106
    0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
107
};
108
109
/* Mask to determine which pixels to overwrite while displaying */
110
static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
111
    0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
112
};
113
114
/* NOTE: we try to construct a good looking image at each pass. width
115
 * is the original image width. We also do pixel format conversion at
116
 * this stage */
117
1408
static void png_put_interlaced_row(uint8_t *dst, int width,
118
                                   int bits_per_pixel, int pass,
119
                                   int color_type, const uint8_t *src)
120
{
121
    int x, mask, dsp_mask, j, src_x, b, bpp;
122
    uint8_t *d;
123
    const uint8_t *s;
124
125
1408
    mask     = png_pass_mask[pass];
126
1408
    dsp_mask = png_pass_dsp_mask[pass];
127
128

1408
    switch (bits_per_pixel) {
129
    case 1:
130
        src_x = 0;
131
        for (x = 0; x < width; x++) {
132
            j = (x & 7);
133
            if ((dsp_mask << j) & 0x80) {
134
                b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
135
                dst[x >> 3] &= 0xFF7F>>j;
136
                dst[x >> 3] |= b << (7 - j);
137
            }
138
            if ((mask << j) & 0x80)
139
                src_x++;
140
        }
141
        break;
142
    case 2:
143
        src_x = 0;
144
        for (x = 0; x < width; x++) {
145
            int j2 = 2 * (x & 3);
146
            j = (x & 7);
147
            if ((dsp_mask << j) & 0x80) {
148
                b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
149
                dst[x >> 2] &= 0xFF3F>>j2;
150
                dst[x >> 2] |= b << (6 - j2);
151
            }
152
            if ((mask << j) & 0x80)
153
                src_x++;
154
        }
155
        break;
156
    case 4:
157
        src_x = 0;
158
        for (x = 0; x < width; x++) {
159
            int j2 = 4*(x&1);
160
            j = (x & 7);
161
            if ((dsp_mask << j) & 0x80) {
162
                b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
163
                dst[x >> 1] &= 0xFF0F>>j2;
164
                dst[x >> 1] |= b << (4 - j2);
165
            }
166
            if ((mask << j) & 0x80)
167
                src_x++;
168
        }
169
        break;
170
1408
    default:
171
1408
        bpp = bits_per_pixel >> 3;
172
1408
        d   = dst;
173
1408
        s   = src;
174
181632
            for (x = 0; x < width; x++) {
175
180224
                j = x & 7;
176
180224
                if ((dsp_mask << j) & 0x80) {
177
131072
                    memcpy(d, s, bpp);
178
                }
179
180224
                d += bpp;
180
180224
                if ((mask << j) & 0x80)
181
61440
                    s += bpp;
182
            }
183
1408
        break;
184
    }
185
1408
}
186
187
13000
void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
188
                                 int w, int bpp)
189
{
190
    int i;
191
4820674
    for (i = 0; i < w; i++) {
192
        int a, b, c, p, pa, pb, pc;
193
194
4807674
        a = dst[i - bpp];
195
4807674
        b = top[i];
196
4807674
        c = top[i - bpp];
197
198
4807674
        p  = b - c;
199
4807674
        pc = a - c;
200
201
4807674
        pa = abs(p);
202
4807674
        pb = abs(pc);
203
4807674
        pc = abs(p + pc);
204
205

4807674
        if (pa <= pb && pa <= pc)
206
2726778
            p = a;
207
2080896
        else if (pb <= pc)
208
1790946
            p = b;
209
        else
210
289950
            p = c;
211
4807674
        dst[i] = p + src[i];
212
    }
213
13000
}
214
215
#define UNROLL1(bpp, op)                                                      \
216
    {                                                                         \
217
        r = dst[0];                                                           \
218
        if (bpp >= 2)                                                         \
219
            g = dst[1];                                                       \
220
        if (bpp >= 3)                                                         \
221
            b = dst[2];                                                       \
222
        if (bpp >= 4)                                                         \
223
            a = dst[3];                                                       \
224
        for (; i <= size - bpp; i += bpp) {                                   \
225
            dst[i + 0] = r = op(r, src[i + 0], last[i + 0]);                  \
226
            if (bpp == 1)                                                     \
227
                continue;                                                     \
228
            dst[i + 1] = g = op(g, src[i + 1], last[i + 1]);                  \
229
            if (bpp == 2)                                                     \
230
                continue;                                                     \
231
            dst[i + 2] = b = op(b, src[i + 2], last[i + 2]);                  \
232
            if (bpp == 3)                                                     \
233
                continue;                                                     \
234
            dst[i + 3] = a = op(a, src[i + 3], last[i + 3]);                  \
235
        }                                                                     \
236
    }
237
238
#define UNROLL_FILTER(op)                                                     \
239
    if (bpp == 1) {                                                           \
240
        UNROLL1(1, op)                                                        \
241
    } else if (bpp == 2) {                                                    \
242
        UNROLL1(2, op)                                                        \
243
    } else if (bpp == 3) {                                                    \
244
        UNROLL1(3, op)                                                        \
245
    } else if (bpp == 4) {                                                    \
246
        UNROLL1(4, op)                                                        \
247
    }                                                                         \
248
    for (; i < size; i++) {                                                   \
249
        dst[i] = op(dst[i - bpp], src[i], last[i]);                           \
250
    }
251
252
/* NOTE: 'dst' can be equal to 'last' */
253
94072
static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
254
                           uint8_t *src, uint8_t *last, int size, int bpp)
255
{
256
    int i, p, r, g, b, a;
257
258

94072
    switch (filter_type) {
259
77546
    case PNG_FILTER_VALUE_NONE:
260
77546
        memcpy(dst, src, size);
261
77546
        break;
262
2304
    case PNG_FILTER_VALUE_SUB:
263
10819
        for (i = 0; i < bpp; i++)
264
8515
            dst[i] = src[i];
265
2304
        if (bpp == 4) {
266
1573
            p = *(int *)dst;
267
272180
            for (; i < size; i += bpp) {
268
270607
                unsigned s = *(int *)(src + i);
269
270607
                p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
270
270607
                *(int *)(dst + i) = p;
271
            }
272
        } else {
273
#define OP_SUB(x, s, l) ((x) + (s))
274




210220
            UNROLL_FILTER(OP_SUB);
275
        }
276
2304
        break;
277
6751
    case PNG_FILTER_VALUE_UP:
278
6751
        dsp->add_bytes_l2(dst, src, last, size);
279
6751
        break;
280
805
    case PNG_FILTER_VALUE_AVG:
281
3532
        for (i = 0; i < bpp; i++) {
282
2727
            p      = (last[i] >> 1);
283
2727
            dst[i] = p + src[i];
284
        }
285
#define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
286




161268
        UNROLL_FILTER(OP_AVG);
287
805
        break;
288
6666
    case PNG_FILTER_VALUE_PAETH:
289
28992
        for (i = 0; i < bpp; i++) {
290
22326
            p      = last[i];
291
22326
            dst[i] = p + src[i];
292
        }
293

6666
        if (bpp > 2 && size > 4) {
294
            /* would write off the end of the array if we let it process
295
             * the last pixel with bpp=3 */
296
6596
            int w = (bpp & 3) ? size - 3 : size;
297
298
6596
            if (w > i) {
299
6596
                dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
300
6596
                i = w;
301
            }
302
        }
303
6666
        ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
304
6666
        break;
305
    }
306
94072
}
307
308
/* This used to be called "deloco" in FFmpeg
309
 * and is actually an inverse reversible colorspace transformation */
310
#define YUV2RGB(NAME, TYPE) \
311
static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
312
{ \
313
    int i; \
314
    for (i = 0; i < size; i += 3 + alpha) { \
315
        int g = dst [i + 1]; \
316
        dst[i + 0] += g; \
317
        dst[i + 2] += g; \
318
    } \
319
}
320
321
YUV2RGB(rgb8, uint8_t)
322
YUV2RGB(rgb16, uint16_t)
323
324
404
static int percent_missing(PNGDecContext *s)
325
{
326
404
    if (s->interlace_type) {
327
1
        return 100 - 100 * s->pass / (NB_PASSES - 1);
328
    } else {
329
403
        return 100 - 100 * s->y / s->cur_h;
330
    }
331
}
332
333
/* process exactly one decompressed row */
334
94072
static void png_handle_row(PNGDecContext *s)
335
{
336
    uint8_t *ptr, *last_row;
337
    int got_line;
338
339
94072
    if (!s->interlace_type) {
340
93592
        ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
341
93592
        if (s->y == 0)
342
448
            last_row = s->last_row;
343
        else
344
93144
            last_row = ptr - s->image_linesize;
345
346
93592
        png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
347
                       last_row, s->row_size, s->bpp);
348
        /* loco lags by 1 row so that it doesn't interfere with top prediction */
349

93592
        if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
350
            if (s->bit_depth == 16) {
351
                deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
352
                             s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
353
            } else {
354
                deloco_rgb8(ptr - s->image_linesize, s->row_size,
355
                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
356
            }
357
        }
358
93592
        s->y++;
359
93592
        if (s->y == s->cur_h) {
360
448
            s->pic_state |= PNG_ALLIMAGE;
361
448
            if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
362
                if (s->bit_depth == 16) {
363
                    deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
364
                                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
365
                } else {
366
                    deloco_rgb8(ptr, s->row_size,
367
                                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
368
                }
369
            }
370
        }
371
    } else {
372
480
        got_line = 0;
373
        for (;;) {
374
2270
            ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
375
2270
            if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
376
                /* if we already read one row, it is time to stop to
377
                 * wait for the next one */
378
958
                if (got_line)
379
478
                    break;
380
480
                png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
381
                               s->last_row, s->pass_row_size, s->bpp);
382
480
                FFSWAP(uint8_t *, s->last_row, s->tmp_row);
383
480
                FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
384
480
                got_line = 1;
385
            }
386
1792
            if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
387
1408
                png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
388
1408
                                       s->color_type, s->last_row);
389
            }
390
1792
            s->y++;
391
1792
            if (s->y == s->cur_h) {
392
14
                memset(s->last_row, 0, s->row_size);
393
                for (;;) {
394
14
                    if (s->pass == NB_PASSES - 1) {
395
2
                        s->pic_state |= PNG_ALLIMAGE;
396
2
                        goto the_end;
397
                    } else {
398
12
                        s->pass++;
399
12
                        s->y = 0;
400
12
                        s->pass_row_size = ff_png_pass_row_size(s->pass,
401
                                                                s->bits_per_pixel,
402
                                                                s->cur_w);
403
12
                        s->crow_size = s->pass_row_size + 1;
404
12
                        if (s->pass_row_size != 0)
405
12
                            break;
406
                        /* skip pass if empty row */
407
                    }
408
                }
409
            }
410
        }
411
94072
the_end:;
412
    }
413
94072
}
414
415
15613
static int png_decode_idat(PNGDecContext *s, int length)
416
{
417
    int ret;
418
15613
    s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
419
15613
    s->zstream.next_in  = s->gb.buffer;
420
15613
    bytestream2_skip(&s->gb, length);
421
422
    /* decode one line if possible */
423
124825
    while (s->zstream.avail_in > 0) {
424
109212
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
425

109212
        if (ret != Z_OK && ret != Z_STREAM_END) {
426
            av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
427
            return AVERROR_EXTERNAL;
428
        }
429
109212
        if (s->zstream.avail_out == 0) {
430
94072
            if (!(s->pic_state & PNG_ALLIMAGE)) {
431
94072
                png_handle_row(s);
432
            }
433
94072
            s->zstream.avail_out = s->crow_size;
434
94072
            s->zstream.next_out  = s->crow_buf;
435
        }
436

109212
        if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
437
            av_log(s->avctx, AV_LOG_WARNING,
438
                   "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
439
            return 0;
440
        }
441
    }
442
15613
    return 0;
443
}
444
445
1
static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
446
                       const uint8_t *data_end)
447
{
448
    z_stream zstream;
449
    unsigned char *buf;
450
    unsigned buf_size;
451
    int ret;
452
453
1
    zstream.zalloc = ff_png_zalloc;
454
1
    zstream.zfree  = ff_png_zfree;
455
1
    zstream.opaque = NULL;
456
1
    if (inflateInit(&zstream) != Z_OK)
457
        return AVERROR_EXTERNAL;
458
1
    zstream.next_in  = data;
459
1
    zstream.avail_in = data_end - data;
460
1
    av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
461
462
3
    while (zstream.avail_in > 0) {
463
3
        av_bprint_get_buffer(bp, 2, &buf, &buf_size);
464
3
        if (buf_size < 2) {
465
            ret = AVERROR(ENOMEM);
466
            goto fail;
467
        }
468
3
        zstream.next_out  = buf;
469
3
        zstream.avail_out = buf_size - 1;
470
3
        ret = inflate(&zstream, Z_PARTIAL_FLUSH);
471

3
        if (ret != Z_OK && ret != Z_STREAM_END) {
472
            ret = AVERROR_EXTERNAL;
473
            goto fail;
474
        }
475
3
        bp->len += zstream.next_out - buf;
476
3
        if (ret == Z_STREAM_END)
477
1
            break;
478
    }
479
1
    inflateEnd(&zstream);
480
1
    bp->str[bp->len] = 0;
481
1
    return 0;
482
483
fail:
484
    inflateEnd(&zstream);
485
    av_bprint_finalize(bp, NULL);
486
    return ret;
487
}
488
489
226
static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
490
{
491
226
    size_t extra = 0, i;
492
    uint8_t *out, *q;
493
494
3938
    for (i = 0; i < size_in; i++)
495
3712
        extra += in[i] >= 0x80;
496

226
    if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
497
        return NULL;
498
226
    q = out = av_malloc(size_in + extra + 1);
499
226
    if (!out)
500
        return NULL;
501
3938
    for (i = 0; i < size_in; i++) {
502
3712
        if (in[i] >= 0x80) {
503
            *(q++) = 0xC0 | (in[i] >> 6);
504
            *(q++) = 0x80 | (in[i] & 0x3F);
505
        } else {
506
3712
            *(q++) = in[i];
507
        }
508
    }
509
226
    *(q++) = 0;
510
226
    return out;
511
}
512
513
113
static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
514
                             AVDictionary **dict)
515
{
516
    int ret, method;
517
113
    const uint8_t *data        = s->gb.buffer;
518
113
    const uint8_t *data_end    = data + length;
519
113
    const uint8_t *keyword     = data;
520
113
    const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
521
113
    uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
522
    unsigned text_len;
523
    AVBPrint bp;
524
525
113
    if (!keyword_end)
526
        return AVERROR_INVALIDDATA;
527
113
    data = keyword_end + 1;
528
529
113
    if (compressed) {
530
        if (data == data_end)
531
            return AVERROR_INVALIDDATA;
532
        method = *(data++);
533
        if (method)
534
            return AVERROR_INVALIDDATA;
535
        if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
536
            return ret;
537
        text_len = bp.len;
538
        ret = av_bprint_finalize(&bp, (char **)&text);
539
        if (ret < 0)
540
            return ret;
541
    } else {
542
113
        text = (uint8_t *)data;
543
113
        text_len = data_end - text;
544
    }
545
546
113
    kw_utf8  = iso88591_to_utf8(keyword, keyword_end - keyword);
547
113
    txt_utf8 = iso88591_to_utf8(text, text_len);
548
113
    if (text != data)
549
        av_free(text);
550

113
    if (!(kw_utf8 && txt_utf8)) {
551
        av_free(kw_utf8);
552
        av_free(txt_utf8);
553
        return AVERROR(ENOMEM);
554
    }
555
556
113
    av_dict_set(dict, kw_utf8, txt_utf8,
557
                AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
558
113
    return 0;
559
}
560
561
359
static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
562
                             uint32_t length)
563
{
564
359
    if (length != 13)
565
        return AVERROR_INVALIDDATA;
566
567
359
    if (s->pic_state & PNG_IDAT) {
568
        av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
569
        return AVERROR_INVALIDDATA;
570
    }
571
572
359
    if (s->hdr_state & PNG_IHDR) {
573
        av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
574
        return AVERROR_INVALIDDATA;
575
    }
576
577
359
    s->width  = s->cur_w = bytestream2_get_be32(&s->gb);
578
359
    s->height = s->cur_h = bytestream2_get_be32(&s->gb);
579
359
    if (av_image_check_size(s->width, s->height, 0, avctx)) {
580
        s->cur_w = s->cur_h = s->width = s->height = 0;
581
        av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
582
        return AVERROR_INVALIDDATA;
583
    }
584
359
    s->bit_depth        = bytestream2_get_byte(&s->gb);
585

359
    if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
586

359
        s->bit_depth != 8 && s->bit_depth != 16) {
587
        av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
588
        goto error;
589
    }
590
359
    s->color_type       = bytestream2_get_byte(&s->gb);
591
359
    s->compression_type = bytestream2_get_byte(&s->gb);
592
359
    if (s->compression_type) {
593
        av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
594
        goto error;
595
    }
596
359
    s->filter_type      = bytestream2_get_byte(&s->gb);
597
359
    s->interlace_type   = bytestream2_get_byte(&s->gb);
598
359
    bytestream2_skip(&s->gb, 4); /* crc */
599
359
    s->hdr_state |= PNG_IHDR;
600
359
    if (avctx->debug & FF_DEBUG_PICT_INFO)
601
        av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
602
                "compression_type=%d filter_type=%d interlace_type=%d\n",
603
                s->width, s->height, s->bit_depth, s->color_type,
604
                s->compression_type, s->filter_type, s->interlace_type);
605
606
359
    return 0;
607
error:
608
    s->cur_w = s->cur_h = s->width = s->height = 0;
609
    s->bit_depth = 8;
610
    return AVERROR_INVALIDDATA;
611
}
612
613
333
static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
614
{
615
333
    if (s->pic_state & PNG_IDAT) {
616
        av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
617
        return AVERROR_INVALIDDATA;
618
    }
619
333
    avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
620
333
    avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
621

333
    if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
622
        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
623
333
    bytestream2_skip(&s->gb, 1); /* unit specifier */
624
333
    bytestream2_skip(&s->gb, 4); /* crc */
625
626
333
    return 0;
627
}
628
629
15613
static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
630
                             uint32_t length, AVFrame *p)
631
{
632
    int ret;
633
15613
    size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
634
635
15613
    if (!(s->hdr_state & PNG_IHDR)) {
636
        av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
637
        return AVERROR_INVALIDDATA;
638
    }
639
15613
    if (!(s->pic_state & PNG_IDAT)) {
640
        /* init image info */
641
450
        ret = ff_set_dimensions(avctx, s->width, s->height);
642
450
        if (ret < 0)
643
            return ret;
644
645
450
        s->channels       = ff_png_get_nb_channels(s->color_type);
646
450
        s->bits_per_pixel = s->bit_depth * s->channels;
647
450
        s->bpp            = (s->bits_per_pixel + 7) >> 3;
648
450
        s->row_size       = (s->cur_w * s->bits_per_pixel + 7) >> 3;
649
650

450
        if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
651
410
                s->color_type == PNG_COLOR_TYPE_RGB) {
652
309
            avctx->pix_fmt = AV_PIX_FMT_RGB24;
653

141
        } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
654
101
                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
655
54
            avctx->pix_fmt = AV_PIX_FMT_RGBA;
656

87
        } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
657
47
                s->color_type == PNG_COLOR_TYPE_GRAY) {
658
4
            avctx->pix_fmt = AV_PIX_FMT_GRAY8;
659
83
        } else if (s->bit_depth == 16 &&
660
40
                s->color_type == PNG_COLOR_TYPE_GRAY) {
661
16
            avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
662
67
        } else if (s->bit_depth == 16 &&
663
24
                s->color_type == PNG_COLOR_TYPE_RGB) {
664
18
            avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
665
49
        } else if (s->bit_depth == 16 &&
666
6
                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
667
4
            avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
668


45
        } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
669
41
                s->color_type == PNG_COLOR_TYPE_PALETTE) {
670
41
            avctx->pix_fmt = AV_PIX_FMT_PAL8;
671

4
        } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
672
            avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
673
4
        } else if (s->bit_depth == 8 &&
674
2
                s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
675
2
            avctx->pix_fmt = AV_PIX_FMT_YA8;
676
2
        } else if (s->bit_depth == 16 &&
677
2
                s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
678
2
            avctx->pix_fmt = AV_PIX_FMT_YA16BE;
679
        } else {
680
            avpriv_report_missing_feature(avctx,
681
                                          "Bit depth %d color type %d",
682
                                          s->bit_depth, s->color_type);
683
            return AVERROR_PATCHWELCOME;
684
        }
685
686

450
        if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
687

2
            switch (avctx->pix_fmt) {
688
2
            case AV_PIX_FMT_RGB24:
689
2
                avctx->pix_fmt = AV_PIX_FMT_RGBA;
690
2
                break;
691
692
            case AV_PIX_FMT_RGB48BE:
693
                avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
694
                break;
695
696
            case AV_PIX_FMT_GRAY8:
697
                avctx->pix_fmt = AV_PIX_FMT_YA8;
698
                break;
699
700
            case AV_PIX_FMT_GRAY16BE:
701
                avctx->pix_fmt = AV_PIX_FMT_YA16BE;
702
                break;
703
704
            default:
705
                avpriv_request_sample(avctx, "bit depth %d "
706
                        "and color type %d with TRNS",
707
                        s->bit_depth, s->color_type);
708
                return AVERROR_INVALIDDATA;
709
            }
710
711
2
            s->bpp += byte_depth;
712
        }
713
714
450
        if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
715
            return ret;
716

450
        if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
717
101
            ff_thread_release_buffer(avctx, &s->previous_picture);
718
101
            if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
719
                return ret;
720
        }
721
450
        p->pict_type        = AV_PICTURE_TYPE_I;
722
450
        p->key_frame        = 1;
723
450
        p->interlaced_frame = !!s->interlace_type;
724
725
450
        ff_thread_finish_setup(avctx);
726
727
        /* compute the compressed row size */
728
450
        if (!s->interlace_type) {
729
448
            s->crow_size = s->row_size + 1;
730
        } else {
731
2
            s->pass          = 0;
732
2
            s->pass_row_size = ff_png_pass_row_size(s->pass,
733
                    s->bits_per_pixel,
734
                    s->cur_w);
735
2
            s->crow_size = s->pass_row_size + 1;
736
        }
737
        ff_dlog(avctx, "row_size=%d crow_size =%d\n",
738
                s->row_size, s->crow_size);
739
450
        s->image_buf      = p->data[0];
740
450
        s->image_linesize = p->linesize[0];
741
        /* copy the palette if needed */
742
450
        if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
743
41
            memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
744
        /* empty row is used if differencing to the first row */
745
450
        av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
746
450
        if (!s->last_row)
747
            return AVERROR_INVALIDDATA;
748
450
        if (s->interlace_type ||
749
448
                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
750
60
            av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
751
60
            if (!s->tmp_row)
752
                return AVERROR_INVALIDDATA;
753
        }
754
        /* compressed row */
755
450
        av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
756
450
        if (!s->buffer)
757
            return AVERROR(ENOMEM);
758
759
        /* we want crow_buf+1 to be 16-byte aligned */
760
450
        s->crow_buf          = s->buffer + 15;
761
450
        s->zstream.avail_out = s->crow_size;
762
450
        s->zstream.next_out  = s->crow_buf;
763
    }
764
765
15613
    s->pic_state |= PNG_IDAT;
766
767
    /* set image to non-transparent bpp while decompressing */
768

15613
    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
769
12
        s->bpp -= byte_depth;
770
771
15613
    ret = png_decode_idat(s, length);
772
773

15613
    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
774
12
        s->bpp += byte_depth;
775
776
15613
    if (ret < 0)
777
        return ret;
778
779
15613
    bytestream2_skip(&s->gb, 4); /* crc */
780
781
15613
    return 0;
782
}
783
784
2
static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
785
                             uint32_t length)
786
{
787
    int n, i, r, g, b;
788
789

2
    if ((length % 3) != 0 || length > 256 * 3)
790
        return AVERROR_INVALIDDATA;
791
    /* read the palette */
792
2
    n = length / 3;
793
474
    for (i = 0; i < n; i++) {
794
472
        r = bytestream2_get_byte(&s->gb);
795
472
        g = bytestream2_get_byte(&s->gb);
796
472
        b = bytestream2_get_byte(&s->gb);
797
472
        s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
798
    }
799
42
    for (; i < 256; i++)
800
40
        s->palette[i] = (0xFFU << 24);
801
2
    s->hdr_state |= PNG_PLTE;
802
2
    bytestream2_skip(&s->gb, 4);     /* crc */
803
804
2
    return 0;
805
}
806
807
4
static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
808
                             uint32_t length)
809
{
810
    int v, i;
811
812
4
    if (!(s->hdr_state & PNG_IHDR)) {
813
        av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
814
        return AVERROR_INVALIDDATA;
815
    }
816
817
4
    if (s->pic_state & PNG_IDAT) {
818
        av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
819
        return AVERROR_INVALIDDATA;
820
    }
821
822
4
    if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
823

2
        if (length > 256 || !(s->hdr_state & PNG_PLTE))
824
            return AVERROR_INVALIDDATA;
825
826
36
        for (i = 0; i < length; i++) {
827
34
            unsigned v = bytestream2_get_byte(&s->gb);
828
34
            s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
829
        }
830

2
    } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
831

2
        if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
832

2
            (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
833
2
            s->bit_depth == 1)
834
            return AVERROR_INVALIDDATA;
835
836
8
        for (i = 0; i < length / 2; i++) {
837
            /* only use the least significant bits */
838
6
            v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
839
840
6
            if (s->bit_depth > 8)
841
                AV_WB16(&s->transparent_color_be[2 * i], v);
842
            else
843
6
                s->transparent_color_be[i] = v;
844
        }
845
    } else {
846
        return AVERROR_INVALIDDATA;
847
    }
848
849
4
    bytestream2_skip(&s->gb, 4); /* crc */
850
4
    s->has_trns = 1;
851
852
4
    return 0;
853
}
854
855
1
static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
856
{
857
1
    int ret, cnt = 0;
858
    uint8_t *data, profile_name[82];
859
    AVBPrint bp;
860
    AVFrameSideData *sd;
861
862

22
    while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
863
1
    if (cnt > 80) {
864
        av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
865
        return AVERROR_INVALIDDATA;
866
    }
867
868
1
    length = FFMAX(length - cnt, 0);
869
870
1
    if (bytestream2_get_byte(&s->gb) != 0) {
871
        av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
872
        return AVERROR_INVALIDDATA;
873
    }
874
875
1
    length = FFMAX(length - 1, 0);
876
877
1
    if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
878
        return ret;
879
880
1
    ret = av_bprint_finalize(&bp, (char **)&data);
881
1
    if (ret < 0)
882
        return ret;
883
884
1
    sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
885
1
    if (!sd) {
886
        av_free(data);
887
        return AVERROR(ENOMEM);
888
    }
889
890
1
    av_dict_set(&sd->metadata, "name", profile_name, 0);
891
1
    memcpy(sd->data, data, bp.len);
892
1
    av_free(data);
893
894
    /* ICC compressed data and CRC */
895
1
    bytestream2_skip(&s->gb, length + 4);
896
897
1
    return 0;
898
}
899
900
static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
901
{
902
    if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
903
        int i, j, k;
904
        uint8_t *pd = p->data[0];
905
        for (j = 0; j < s->height; j++) {
906
            i = s->width / 8;
907
            for (k = 7; k >= 1; k--)
908
                if ((s->width&7) >= k)
909
                    pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
910
            for (i--; i >= 0; i--) {
911
                pd[8*i + 7]=  pd[i]     & 1;
912
                pd[8*i + 6]= (pd[i]>>1) & 1;
913
                pd[8*i + 5]= (pd[i]>>2) & 1;
914
                pd[8*i + 4]= (pd[i]>>3) & 1;
915
                pd[8*i + 3]= (pd[i]>>4) & 1;
916
                pd[8*i + 2]= (pd[i]>>5) & 1;
917
                pd[8*i + 1]= (pd[i]>>6) & 1;
918
                pd[8*i + 0]=  pd[i]>>7;
919
            }
920
            pd += s->image_linesize;
921
        }
922
    } else if (s->bits_per_pixel == 2) {
923
        int i, j;
924
        uint8_t *pd = p->data[0];
925
        for (j = 0; j < s->height; j++) {
926
            i = s->width / 4;
927
            if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
928
                if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
929
                if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
930
                if ((s->width&3) >= 1) pd[4*i + 0]=  pd[i] >> 6;
931
                for (i--; i >= 0; i--) {
932
                    pd[4*i + 3]=  pd[i]     & 3;
933
                    pd[4*i + 2]= (pd[i]>>2) & 3;
934
                    pd[4*i + 1]= (pd[i]>>4) & 3;
935
                    pd[4*i + 0]=  pd[i]>>6;
936
                }
937
            } else {
938
                if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
939
                if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
940
                if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6     )*0x55;
941
                for (i--; i >= 0; i--) {
942
                    pd[4*i + 3]= ( pd[i]     & 3)*0x55;
943
                    pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
944
                    pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
945
                    pd[4*i + 0]= ( pd[i]>>6     )*0x55;
946
                }
947
            }
948
            pd += s->image_linesize;
949
        }
950
    } else if (s->bits_per_pixel == 4) {
951
        int i, j;
952
        uint8_t *pd = p->data[0];
953
        for (j = 0; j < s->height; j++) {
954
            i = s->width/2;
955
            if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
956
                if (s->width&1) pd[2*i+0]= pd[i]>>4;
957
                for (i--; i >= 0; i--) {
958
                    pd[2*i + 1] = pd[i] & 15;
959
                    pd[2*i + 0] = pd[i] >> 4;
960
                }
961
            } else {
962
                if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
963
                for (i--; i >= 0; i--) {
964
                    pd[2*i + 1] = (pd[i] & 15) * 0x11;
965
                    pd[2*i + 0] = (pd[i] >> 4) * 0x11;
966
                }
967
            }
968
            pd += s->image_linesize;
969
        }
970
    }
971
}
972
973
101
static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
974
                             uint32_t length)
975
{
976
    uint32_t sequence_number;
977
    int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
978
979
101
    if (length != 26)
980
        return AVERROR_INVALIDDATA;
981
982
101
    if (!(s->hdr_state & PNG_IHDR)) {
983
        av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
984
        return AVERROR_INVALIDDATA;
985
    }
986
987
101
    if (s->pic_state & PNG_IDAT) {
988
        av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
989
        return AVERROR_INVALIDDATA;
990
    }
991
992
101
    s->last_w = s->cur_w;
993
101
    s->last_h = s->cur_h;
994
101
    s->last_x_offset = s->x_offset;
995
101
    s->last_y_offset = s->y_offset;
996
101
    s->last_dispose_op = s->dispose_op;
997
998
101
    sequence_number = bytestream2_get_be32(&s->gb);
999
101
    cur_w           = bytestream2_get_be32(&s->gb);
1000
101
    cur_h           = bytestream2_get_be32(&s->gb);
1001
101
    x_offset        = bytestream2_get_be32(&s->gb);
1002
101
    y_offset        = bytestream2_get_be32(&s->gb);
1003
101
    bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
1004
101
    dispose_op      = bytestream2_get_byte(&s->gb);
1005
101
    blend_op        = bytestream2_get_byte(&s->gb);
1006
101
    bytestream2_skip(&s->gb, 4); /* crc */
1007
1008
101
    if (sequence_number == 0 &&
1009
9
        (cur_w != s->width ||
1010

9
         cur_h != s->height ||
1011
9
         x_offset != 0 ||
1012
101
         y_offset != 0) ||
1013

101
        cur_w <= 0 || cur_h <= 0 ||
1014
101
        x_offset < 0 || y_offset < 0 ||
1015

101
        cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1016
            return AVERROR_INVALIDDATA;
1017
1018

101
    if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1019
        av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1020
        return AVERROR_INVALIDDATA;
1021
    }
1022
1023

101
    if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
1024
        dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1025
        // No previous frame to revert to for the first frame
1026
        // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1027
        dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1028
    }
1029
1030

101
    if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1031
            avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1032
            avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1033
            avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1034
            avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1035
            avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1036
            avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1037
        )) {
1038
        // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1039
        blend_op = APNG_BLEND_OP_SOURCE;
1040
    }
1041
1042
101
    s->cur_w      = cur_w;
1043
101
    s->cur_h      = cur_h;
1044
101
    s->x_offset   = x_offset;
1045
101
    s->y_offset   = y_offset;
1046
101
    s->dispose_op = dispose_op;
1047
101
    s->blend_op   = blend_op;
1048
1049
101
    return 0;
1050
}
1051
1052
static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1053
{
1054
    int i, j;
1055
    uint8_t *pd      = p->data[0];
1056
    uint8_t *pd_last = s->last_picture.f->data[0];
1057
    int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1058
1059
    ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1060
    for (j = 0; j < s->height; j++) {
1061
        for (i = 0; i < ls; i++)
1062
            pd[i] += pd_last[i];
1063
        pd      += s->image_linesize;
1064
        pd_last += s->image_linesize;
1065
    }
1066
}
1067
1068
// divide by 255 and round to nearest
1069
// apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1070
#define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1071
1072
39
static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1073
                               AVFrame *p)
1074
{
1075
    size_t x, y;
1076
    uint8_t *buffer;
1077
1078
39
    if (s->blend_op == APNG_BLEND_OP_OVER &&
1079
39
        avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1080
39
        avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
1081
39
        avctx->pix_fmt != AV_PIX_FMT_PAL8) {
1082
        avpriv_request_sample(avctx, "Blending with pixel format %s",
1083
                              av_get_pix_fmt_name(avctx->pix_fmt));
1084
        return AVERROR_PATCHWELCOME;
1085
    }
1086
1087
39
    buffer = av_malloc_array(s->image_linesize, s->height);
1088
39
    if (!buffer)
1089
        return AVERROR(ENOMEM);
1090
1091
1092
    // Do the disposal operation specified by the last frame on the frame
1093
39
    if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
1094
39
        ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1095
39
        memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
1096
1097
39
        if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
1098
            for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
1099
                memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1100
1101
39
        memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
1102
39
        ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1103
    } else {
1104
        ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
1105
        memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
1106
    }
1107
1108
    // Perform blending
1109
39
    if (s->blend_op == APNG_BLEND_OP_SOURCE) {
1110
        for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1111
            size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
1112
            memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
1113
        }
1114
    } else { // APNG_BLEND_OP_OVER
1115
1918
        for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1116
1879
            uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
1117
1879
            uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
1118
143095
            for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1119
                size_t b;
1120
                uint8_t foreground_alpha, background_alpha, output_alpha;
1121
                uint8_t output[10];
1122
1123
                // Since we might be blending alpha onto alpha, we use the following equations:
1124
                // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1125
                // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1126
1127

141216
                switch (avctx->pix_fmt) {
1128
                case AV_PIX_FMT_RGBA:
1129
                    foreground_alpha = foreground[3];
1130
                    background_alpha = background[3];
1131
                    break;
1132
1133
                case AV_PIX_FMT_GRAY8A:
1134
                    foreground_alpha = foreground[1];
1135
                    background_alpha = background[1];
1136
                    break;
1137
1138
141216
                case AV_PIX_FMT_PAL8:
1139
141216
                    foreground_alpha = s->palette[foreground[0]] >> 24;
1140
141216
                    background_alpha = s->palette[background[0]] >> 24;
1141
141216
                    break;
1142
                }
1143
1144
141216
                if (foreground_alpha == 0)
1145
141216
                    continue;
1146
1147
19634
                if (foreground_alpha == 255) {
1148
19634
                    memcpy(background, foreground, s->bpp);
1149
19634
                    continue;
1150
                }
1151
1152
                if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1153
                    // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1154
                    avpriv_request_sample(avctx, "Alpha blending palette samples");
1155
                    background[0] = foreground[0];
1156
                    continue;
1157
                }
1158
1159
                output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1160
1161
                av_assert0(s->bpp <= 10);
1162
1163
                for (b = 0; b < s->bpp - 1; ++b) {
1164
                    if (output_alpha == 0) {
1165
                        output[b] = 0;
1166
                    } else if (background_alpha == 255) {
1167
                        output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1168
                    } else {
1169
                        output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1170
                    }
1171
                }
1172
                output[b] = output_alpha;
1173
                memcpy(background, output, s->bpp);
1174
            }
1175
        }
1176
    }
1177
1178
    // Copy blended buffer into the frame and free
1179
39
    memcpy(p->data[0], buffer, s->image_linesize * s->height);
1180
39
    av_free(buffer);
1181
1182
39
    return 0;
1183
}
1184
1185
460
static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1186
                               AVFrame *p, AVPacket *avpkt)
1187
{
1188
460
    const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1189
460
    AVDictionary **metadatap = NULL;
1190
    uint32_t tag, length;
1191
460
    int decode_next_dat = 0;
1192
    int i, ret;
1193
1194
    for (;;) {
1195
17171
        length = bytestream2_get_bytes_left(&s->gb);
1196
17171
        if (length <= 0) {
1197
1198
156
            if (avctx->codec_id == AV_CODEC_ID_PNG &&
1199
46
                avctx->skip_frame == AVDISCARD_ALL) {
1200
46
                return 0;
1201
            }
1202
1203

110
            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1204
110
                if (!(s->pic_state & PNG_IDAT))
1205
9
                    return 0;
1206
                else
1207
101
                    goto exit_loop;
1208
            }
1209
            av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1210
            if (   s->pic_state & PNG_ALLIMAGE
1211
                && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1212
                goto exit_loop;
1213
            ret = AVERROR_INVALIDDATA;
1214
            goto fail;
1215
        }
1216
1217
17015
        length = bytestream2_get_be32(&s->gb);
1218

17015
        if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1219
1
            av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1220
1
            ret = AVERROR_INVALIDDATA;
1221
1
            goto fail;
1222
        }
1223
17014
        if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_IGNORE_ERR)) {
1224
            uint32_t crc_sig = AV_RB32(s->gb.buffer + length + 4);
1225
            uint32_t crc_cal = ~av_crc(crc_tab, UINT32_MAX, s->gb.buffer, length + 4);
1226
            if (crc_sig ^ crc_cal) {
1227
                av_log(avctx, AV_LOG_ERROR, "CRC mismatch in chunk");
1228
                if (avctx->err_recognition & AV_EF_EXPLODE) {
1229
                    av_log(avctx, AV_LOG_ERROR, ", quitting\n");
1230
                    ret = AVERROR_INVALIDDATA;
1231
                    goto fail;
1232
                }
1233
                av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1234
                bytestream2_skip(&s->gb, 4); /* tag */
1235
                goto skip_tag;
1236
            }
1237
        }
1238
17014
        tag = bytestream2_get_le32(&s->gb);
1239
17014
        if (avctx->debug & FF_DEBUG_STARTCODE)
1240
            av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1241
                   av_fourcc2str(tag), length);
1242
1243
17014
        if (avctx->codec_id == AV_CODEC_ID_PNG &&
1244
13611
            avctx->skip_frame == AVDISCARD_ALL) {
1245
794
            switch(tag) {
1246
692
            case MKTAG('I', 'H', 'D', 'R'):
1247
            case MKTAG('p', 'H', 'Y', 's'):
1248
            case MKTAG('t', 'E', 'X', 't'):
1249
            case MKTAG('I', 'D', 'A', 'T'):
1250
            case MKTAG('t', 'R', 'N', 'S'):
1251
692
                break;
1252
102
            default:
1253
102
                goto skip_tag;
1254
            }
1255
16220
        }
1256
1257
16912
        metadatap = &p->metadata;
1258



16912
        switch (tag) {
1259
359
        case MKTAG('I', 'H', 'D', 'R'):
1260
359
            if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1261
                goto fail;
1262
359
            break;
1263
333
        case MKTAG('p', 'H', 'Y', 's'):
1264
333
            if ((ret = decode_phys_chunk(avctx, s)) < 0)
1265
                goto fail;
1266
333
            break;
1267
101
        case MKTAG('f', 'c', 'T', 'L'):
1268
101
            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1269
                goto skip_tag;
1270
101
            if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1271
                goto fail;
1272
101
            decode_next_dat = 1;
1273
101
            break;
1274
2966
        case MKTAG('f', 'd', 'A', 'T'):
1275
2966
            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1276
                goto skip_tag;
1277

2966
            if (!decode_next_dat || length < 4) {
1278
                ret = AVERROR_INVALIDDATA;
1279
                goto fail;
1280
            }
1281
2966
            bytestream2_get_be32(&s->gb);
1282
2966
            length -= 4;
1283
            /* fallthrough */
1284
15613
        case MKTAG('I', 'D', 'A', 'T'):
1285

15613
            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1286
                goto skip_tag;
1287
15613
            if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1288
                goto fail;
1289
15613
            break;
1290
2
        case MKTAG('P', 'L', 'T', 'E'):
1291
2
            if (decode_plte_chunk(avctx, s, length) < 0)
1292
                goto skip_tag;
1293
2
            break;
1294
4
        case MKTAG('t', 'R', 'N', 'S'):
1295
4
            if (decode_trns_chunk(avctx, s, length) < 0)
1296
                goto skip_tag;
1297
4
            break;
1298
113
        case MKTAG('t', 'E', 'X', 't'):
1299
113
            if (decode_text_chunk(s, length, 0, metadatap) < 0)
1300
                av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1301
113
            bytestream2_skip(&s->gb, length + 4);
1302
113
            break;
1303
        case MKTAG('z', 'T', 'X', 't'):
1304
            if (decode_text_chunk(s, length, 1, metadatap) < 0)
1305
                av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1306
            bytestream2_skip(&s->gb, length + 4);
1307
            break;
1308
        case MKTAG('s', 'T', 'E', 'R'): {
1309
            int mode = bytestream2_get_byte(&s->gb);
1310
            AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
1311
            if (!stereo3d) {
1312
                ret = AVERROR(ENOMEM);
1313
                goto fail;
1314
            }
1315
1316
            if (mode == 0 || mode == 1) {
1317
                stereo3d->type  = AV_STEREO3D_SIDEBYSIDE;
1318
                stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1319
            } else {
1320
                 av_log(avctx, AV_LOG_WARNING,
1321
                        "Unknown value in sTER chunk (%d)\n", mode);
1322
            }
1323
            bytestream2_skip(&s->gb, 4); /* crc */
1324
            break;
1325
        }
1326
1
        case MKTAG('i', 'C', 'C', 'P'): {
1327
1
            if ((ret = decode_iccp_chunk(s, length, p)) < 0)
1328
                goto fail;
1329
1
            break;
1330
        }
1331
1
        case MKTAG('c', 'H', 'R', 'M'): {
1332
1
            AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(p);
1333
1
            if (!mdm) {
1334
                ret = AVERROR(ENOMEM);
1335
                goto fail;
1336
            }
1337
1338
1
            mdm->white_point[0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1339
1
            mdm->white_point[1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1340
1341
            /* RGB Primaries */
1342
4
            for (i = 0; i < 3; i++) {
1343
3
                mdm->display_primaries[i][0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1344
3
                mdm->display_primaries[i][1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1345
            }
1346
1347
1
            mdm->has_primaries = 1;
1348
1
            bytestream2_skip(&s->gb, 4); /* crc */
1349
1
            break;
1350
        }
1351
13
        case MKTAG('g', 'A', 'M', 'A'): {
1352
            AVBPrint bp;
1353
            char *gamma_str;
1354
13
            int num = bytestream2_get_be32(&s->gb);
1355
1356
13
            av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1357
13
            av_bprintf(&bp, "%i/%i", num, 100000);
1358
13
            ret = av_bprint_finalize(&bp, &gamma_str);
1359
13
            if (ret < 0)
1360
                return ret;
1361
1362
13
            av_dict_set(&p->metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1363
1364
13
            bytestream2_skip(&s->gb, 4); /* crc */
1365
13
            break;
1366
        }
1367
303
        case MKTAG('I', 'E', 'N', 'D'):
1368
303
            if (!(s->pic_state & PNG_ALLIMAGE))
1369
                av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1370
303
            if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1371
                ret = AVERROR_INVALIDDATA;
1372
                goto fail;
1373
            }
1374
303
            bytestream2_skip(&s->gb, 4); /* crc */
1375
303
            goto exit_loop;
1376
        default:
1377
            /* skip tag */
1378
171
skip_tag:
1379
171
            bytestream2_skip(&s->gb, length + 4);
1380
171
            break;
1381
        }
1382
    }
1383
404
exit_loop:
1384
1385
404
    if (avctx->codec_id == AV_CODEC_ID_PNG &&
1386
303
        avctx->skip_frame == AVDISCARD_ALL) {
1387
        return 0;
1388
    }
1389
1390
404
    if (percent_missing(s) > avctx->discard_damaged_percentage)
1391
        return AVERROR_INVALIDDATA;
1392
1393
404
    if (s->bits_per_pixel <= 4)
1394
        handle_small_bpp(s, p);
1395
1396
    /* apply transparency if needed */
1397

404
    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1398
1
        size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1399
1
        size_t raw_bpp = s->bpp - byte_depth;
1400
        unsigned x, y;
1401
1402
1
        av_assert0(s->bit_depth > 1);
1403
1404
331
        for (y = 0; y < s->height; ++y) {
1405
330
            uint8_t *row = &s->image_buf[s->image_linesize * y];
1406
1407

330
            if (s->bpp == 2 && byte_depth == 1) {
1408
                uint8_t *pixel = &row[2 * s->width - 1];
1409
                uint8_t *rowp  = &row[1 * s->width - 1];
1410
                int tcolor = s->transparent_color_be[0];
1411
                for (x = s->width; x > 0; --x) {
1412
                    *pixel-- = *rowp == tcolor ? 0 : 0xff;
1413
                    *pixel-- = *rowp--;
1414
                }
1415

660
            } else if (s->bpp == 4 && byte_depth == 1) {
1416
330
                uint8_t *pixel = &row[4 * s->width - 1];
1417
330
                uint8_t *rowp  = &row[3 * s->width - 1];
1418
330
                int tcolor = AV_RL24(s->transparent_color_be);
1419
109230
                for (x = s->width; x > 0; --x) {
1420
108900
                    *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1421
108900
                    *pixel-- = *rowp--;
1422
108900
                    *pixel-- = *rowp--;
1423
108900
                    *pixel-- = *rowp--;
1424
                }
1425
            } else {
1426
                /* since we're updating in-place, we have to go from right to left */
1427
                for (x = s->width; x > 0; --x) {
1428
                    uint8_t *pixel = &row[s->bpp * (x - 1)];
1429
                    memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1430
1431
                    if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1432
                        memset(&pixel[raw_bpp], 0, byte_depth);
1433
                    } else {
1434
                        memset(&pixel[raw_bpp], 0xff, byte_depth);
1435
                    }
1436
                }
1437
            }
1438
        }
1439
    }
1440
1441
    /* handle P-frames only if a predecessor frame is available */
1442
404
    if (s->last_picture.f->data[0]) {
1443

350
        if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1444
39
            && s->last_picture.f->width == p->width
1445
39
            && s->last_picture.f->height== p->height
1446
39
            && s->last_picture.f->format== p->format
1447
         ) {
1448
39
            if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1449
                handle_p_frame_png(s, p);
1450
39
            else if (CONFIG_APNG_DECODER &&
1451
39
                     s->previous_picture.f->width == p->width  &&
1452
39
                     s->previous_picture.f->height== p->height &&
1453
39
                     s->previous_picture.f->format== p->format &&
1454

78
                     avctx->codec_id == AV_CODEC_ID_APNG &&
1455
39
                     (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1456
                goto fail;
1457
        }
1458
    }
1459
404
    ff_thread_report_progress(&s->picture, INT_MAX, 0);
1460
404
    ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1461
1462
404
    return 0;
1463
1464
1
fail:
1465
1
    ff_thread_report_progress(&s->picture, INT_MAX, 0);
1466
1
    ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1467
1
    return ret;
1468
}
1469
1470
#if CONFIG_PNG_DECODER
1471
350
static int decode_frame_png(AVCodecContext *avctx,
1472
                        void *data, int *got_frame,
1473
                        AVPacket *avpkt)
1474
{
1475
350
    PNGDecContext *const s = avctx->priv_data;
1476
350
    const uint8_t *buf     = avpkt->data;
1477
350
    int buf_size           = avpkt->size;
1478
    AVFrame *p;
1479
    int64_t sig;
1480
    int ret;
1481
1482
350
    ff_thread_release_buffer(avctx, &s->last_picture);
1483
350
    FFSWAP(ThreadFrame, s->picture, s->last_picture);
1484
350
    p = s->picture.f;
1485
1486
350
    bytestream2_init(&s->gb, buf, buf_size);
1487
1488
    /* check signature */
1489
350
    sig = bytestream2_get_be64(&s->gb);
1490

350
    if (sig != PNGSIG &&
1491
        sig != MNGSIG) {
1492
        av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1493
        return AVERROR_INVALIDDATA;
1494
    }
1495
1496
350
    s->y = s->has_trns = 0;
1497
350
    s->hdr_state = 0;
1498
350
    s->pic_state = 0;
1499
1500
    /* init the zlib */
1501
350
    s->zstream.zalloc = ff_png_zalloc;
1502
350
    s->zstream.zfree  = ff_png_zfree;
1503
350
    s->zstream.opaque = NULL;
1504
350
    ret = inflateInit(&s->zstream);
1505
350
    if (ret != Z_OK) {
1506
        av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1507
        return AVERROR_EXTERNAL;
1508
    }
1509
1510
350
    if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1511
1
        goto the_end;
1512
1513
349
    if (avctx->skip_frame == AVDISCARD_ALL) {
1514
46
        *got_frame = 0;
1515
46
        ret = bytestream2_tell(&s->gb);
1516
46
        goto the_end;
1517
    }
1518
1519
303
    if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1520
        goto the_end;
1521
1522
303
    *got_frame = 1;
1523
1524
303
    ret = bytestream2_tell(&s->gb);
1525
350
the_end:
1526
350
    inflateEnd(&s->zstream);
1527
350
    s->crow_buf = NULL;
1528
350
    return ret;
1529
}
1530
#endif
1531
1532
#if CONFIG_APNG_DECODER
1533
101
static int decode_frame_apng(AVCodecContext *avctx,
1534
                        void *data, int *got_frame,
1535
                        AVPacket *avpkt)
1536
{
1537
101
    PNGDecContext *const s = avctx->priv_data;
1538
    int ret;
1539
    AVFrame *p;
1540
1541
101
    ff_thread_release_buffer(avctx, &s->last_picture);
1542
101
    FFSWAP(ThreadFrame, s->picture, s->last_picture);
1543
101
    p = s->picture.f;
1544
1545
101
    if (!(s->hdr_state & PNG_IHDR)) {
1546
9
        if (!avctx->extradata_size)
1547
            return AVERROR_INVALIDDATA;
1548
1549
        /* only init fields, there is no zlib use in extradata */
1550
9
        s->zstream.zalloc = ff_png_zalloc;
1551
9
        s->zstream.zfree  = ff_png_zfree;
1552
1553
9
        bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1554
9
        if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1555
            goto end;
1556
    }
1557
1558
    /* reset state for a new frame */
1559
101
    if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1560
        av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1561
        ret = AVERROR_EXTERNAL;
1562
        goto end;
1563
    }
1564
101
    s->y = 0;
1565
101
    s->pic_state = 0;
1566
101
    bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1567
101
    if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1568
        goto end;
1569
1570
101
    if (!(s->pic_state & PNG_ALLIMAGE))
1571
        av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1572
101
    if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1573
        ret = AVERROR_INVALIDDATA;
1574
        goto end;
1575
    }
1576
101
    if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1577
        goto end;
1578
1579
101
    *got_frame = 1;
1580
101
    ret = bytestream2_tell(&s->gb);
1581
1582
101
end:
1583
101
    inflateEnd(&s->zstream);
1584
101
    return ret;
1585
}
1586
#endif
1587
1588
#if CONFIG_LSCR_DECODER
1589
static int decode_frame_lscr(AVCodecContext *avctx,
1590
                             void *data, int *got_frame,
1591
                             AVPacket *avpkt)
1592
{
1593
    PNGDecContext *const s = avctx->priv_data;
1594
    GetByteContext *gb = &s->gb;
1595
    AVFrame *frame = data;
1596
    int ret, nb_blocks, offset = 0;
1597
1598
    if (avpkt->size < 2)
1599
        return AVERROR_INVALIDDATA;
1600
1601
    bytestream2_init(gb, avpkt->data, avpkt->size);
1602
1603
    if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1604
        return ret;
1605
1606
    nb_blocks = bytestream2_get_le16(gb);
1607
    if (bytestream2_get_bytes_left(gb) < 2 + nb_blocks * (12 + 8))
1608
        return AVERROR_INVALIDDATA;
1609
1610
    if (s->last_picture.f->data[0]) {
1611
        ret = av_frame_copy(frame, s->last_picture.f);
1612
        if (ret < 0)
1613
            return ret;
1614
    }
1615
1616
    for (int b = 0; b < nb_blocks; b++) {
1617
        int x, y, x2, y2, w, h, left;
1618
        uint32_t csize, size;
1619
1620
        s->zstream.zalloc = ff_png_zalloc;
1621
        s->zstream.zfree  = ff_png_zfree;
1622
        s->zstream.opaque = NULL;
1623
1624
        if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1625
            av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1626
            ret = AVERROR_EXTERNAL;
1627
            goto end;
1628
        }
1629
1630
        bytestream2_seek(gb, 2 + b * 12, SEEK_SET);
1631
1632
        x = bytestream2_get_le16(gb);
1633
        y = bytestream2_get_le16(gb);
1634
        x2 = bytestream2_get_le16(gb);
1635
        y2 = bytestream2_get_le16(gb);
1636
        s->width  = s->cur_w = w = x2-x;
1637
        s->height = s->cur_h = h = y2-y;
1638
1639
        if (w <= 0 || x < 0 || x >= avctx->width || w + x > avctx->width ||
1640
            h <= 0 || y < 0 || y >= avctx->height || h + y > avctx->height) {
1641
            ret = AVERROR_INVALIDDATA;
1642
            goto end;
1643
        }
1644
1645
        size = bytestream2_get_le32(gb);
1646
1647
        frame->key_frame = (nb_blocks == 1) &&
1648
                           (w == avctx->width) &&
1649
                           (h == avctx->height) &&
1650
                           (x == 0) && (y == 0);
1651
1652
        bytestream2_seek(gb, 2 + nb_blocks * 12 + offset, SEEK_SET);
1653
        csize = bytestream2_get_be32(gb);
1654
        if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1655
            ret = AVERROR_INVALIDDATA;
1656
            goto end;
1657
        }
1658
1659
        offset += size;
1660
        left = size;
1661
1662
        s->y                 = 0;
1663
        s->row_size          = w * 3;
1664
1665
        av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
1666
        if (!s->buffer) {
1667
            ret = AVERROR(ENOMEM);
1668
            goto end;
1669
        }
1670
1671
        av_fast_padded_malloc(&s->last_row, &s->last_row_size, s->row_size);
1672
        if (!s->last_row) {
1673
            ret = AVERROR(ENOMEM);
1674
            goto end;
1675
        }
1676
1677
        s->crow_size         = w * 3 + 1;
1678
        s->crow_buf          = s->buffer + 15;
1679
        s->zstream.avail_out = s->crow_size;
1680
        s->zstream.next_out  = s->crow_buf;
1681
        s->image_buf         = frame->data[0] + (avctx->height - y - 1) * frame->linesize[0] + x * 3;
1682
        s->image_linesize    =-frame->linesize[0];
1683
        s->bpp               = 3;
1684
        s->pic_state         = 0;
1685
1686
        while (left > 16) {
1687
            ret = png_decode_idat(s, csize);
1688
            if (ret < 0)
1689
                goto end;
1690
            left -= csize + 16;
1691
            if (left > 16) {
1692
                bytestream2_skip(gb, 4);
1693
                csize = bytestream2_get_be32(gb);
1694
                if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1695
                    ret = AVERROR_INVALIDDATA;
1696
                    goto end;
1697
                }
1698
            }
1699
        }
1700
1701
        inflateEnd(&s->zstream);
1702
    }
1703
1704
    frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1705
1706
    av_frame_unref(s->last_picture.f);
1707
    if ((ret = av_frame_ref(s->last_picture.f, frame)) < 0)
1708
        return ret;
1709
1710
    *got_frame = 1;
1711
end:
1712
    inflateEnd(&s->zstream);
1713
1714
    if (ret < 0)
1715
        return ret;
1716
    return avpkt->size;
1717
}
1718
1719
static void decode_flush(AVCodecContext *avctx)
1720
{
1721
    PNGDecContext *s = avctx->priv_data;
1722
1723
    av_frame_unref(s->last_picture.f);
1724
}
1725
1726
#endif
1727
1728
#if HAVE_THREADS
1729
static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1730
{
1731
    PNGDecContext *psrc = src->priv_data;
1732
    PNGDecContext *pdst = dst->priv_data;
1733
    int ret;
1734
1735
    if (dst == src)
1736
        return 0;
1737
1738
    ff_thread_release_buffer(dst, &pdst->picture);
1739
    if (psrc->picture.f->data[0] &&
1740
        (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1741
        return ret;
1742
    if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1743
        pdst->width             = psrc->width;
1744
        pdst->height            = psrc->height;
1745
        pdst->bit_depth         = psrc->bit_depth;
1746
        pdst->color_type        = psrc->color_type;
1747
        pdst->compression_type  = psrc->compression_type;
1748
        pdst->interlace_type    = psrc->interlace_type;
1749
        pdst->filter_type       = psrc->filter_type;
1750
        pdst->cur_w = psrc->cur_w;
1751
        pdst->cur_h = psrc->cur_h;
1752
        pdst->x_offset = psrc->x_offset;
1753
        pdst->y_offset = psrc->y_offset;
1754
        pdst->has_trns = psrc->has_trns;
1755
        memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1756
1757
        pdst->dispose_op = psrc->dispose_op;
1758
1759
        memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1760
1761
        pdst->hdr_state |= psrc->hdr_state;
1762
1763
        ff_thread_release_buffer(dst, &pdst->last_picture);
1764
        if (psrc->last_picture.f->data[0] &&
1765
            (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
1766
            return ret;
1767
1768
        ff_thread_release_buffer(dst, &pdst->previous_picture);
1769
        if (psrc->previous_picture.f->data[0] &&
1770
            (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
1771
            return ret;
1772
    }
1773
1774
    return 0;
1775
}
1776
#endif
1777
1778
132
static av_cold int png_dec_init(AVCodecContext *avctx)
1779
{
1780
132
    PNGDecContext *s = avctx->priv_data;
1781
1782
132
    avctx->color_range = AVCOL_RANGE_JPEG;
1783
1784
132
    if (avctx->codec_id == AV_CODEC_ID_LSCR)
1785
        avctx->pix_fmt = AV_PIX_FMT_BGR24;
1786
1787
132
    s->avctx = avctx;
1788
132
    s->previous_picture.f = av_frame_alloc();
1789
132
    s->last_picture.f = av_frame_alloc();
1790
132
    s->picture.f = av_frame_alloc();
1791

132
    if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1792
        av_frame_free(&s->previous_picture.f);
1793
        av_frame_free(&s->last_picture.f);
1794
        av_frame_free(&s->picture.f);
1795
        return AVERROR(ENOMEM);
1796
    }
1797
1798
132
    ff_pngdsp_init(&s->dsp);
1799
1800
132
    return 0;
1801
}
1802
1803
132
static av_cold int png_dec_end(AVCodecContext *avctx)
1804
{
1805
132
    PNGDecContext *s = avctx->priv_data;
1806
1807
132
    ff_thread_release_buffer(avctx, &s->previous_picture);
1808
132
    av_frame_free(&s->previous_picture.f);
1809
132
    ff_thread_release_buffer(avctx, &s->last_picture);
1810
132
    av_frame_free(&s->last_picture.f);
1811
132
    ff_thread_release_buffer(avctx, &s->picture);
1812
132
    av_frame_free(&s->picture.f);
1813
132
    av_freep(&s->buffer);
1814
132
    s->buffer_size = 0;
1815
132
    av_freep(&s->last_row);
1816
132
    s->last_row_size = 0;
1817
132
    av_freep(&s->tmp_row);
1818
132
    s->tmp_row_size = 0;
1819
1820
132
    return 0;
1821
}
1822
1823
#if CONFIG_APNG_DECODER
1824
AVCodec ff_apng_decoder = {
1825
    .name           = "apng",
1826
    .long_name      = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1827
    .type           = AVMEDIA_TYPE_VIDEO,
1828
    .id             = AV_CODEC_ID_APNG,
1829
    .priv_data_size = sizeof(PNGDecContext),
1830
    .init           = png_dec_init,
1831
    .close          = png_dec_end,
1832
    .decode         = decode_frame_apng,
1833
    .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1834
    .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1835
    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
1836
                      FF_CODEC_CAP_ALLOCATE_PROGRESS,
1837
};
1838
#endif
1839
1840
#if CONFIG_PNG_DECODER
1841
AVCodec ff_png_decoder = {
1842
    .name           = "png",
1843
    .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1844
    .type           = AVMEDIA_TYPE_VIDEO,
1845
    .id             = AV_CODEC_ID_PNG,
1846
    .priv_data_size = sizeof(PNGDecContext),
1847
    .init           = png_dec_init,
1848
    .close          = png_dec_end,
1849
    .decode         = decode_frame_png,
1850
    .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1851
    .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1852
    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1853
                      FF_CODEC_CAP_ALLOCATE_PROGRESS,
1854
};
1855
#endif
1856
1857
#if CONFIG_LSCR_DECODER
1858
AVCodec ff_lscr_decoder = {
1859
    .name           = "lscr",
1860
    .long_name      = NULL_IF_CONFIG_SMALL("LEAD Screen Capture"),
1861
    .type           = AVMEDIA_TYPE_VIDEO,
1862
    .id             = AV_CODEC_ID_LSCR,
1863
    .priv_data_size = sizeof(PNGDecContext),
1864
    .init           = png_dec_init,
1865
    .close          = png_dec_end,
1866
    .decode         = decode_frame_lscr,
1867
    .flush          = decode_flush,
1868
    .capabilities   = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1869
    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1870
                      FF_CODEC_CAP_ALLOCATE_PROGRESS,
1871
};
1872
#endif