GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/pngdec.c Lines: 613 1070 57.3 %
Date: 2020-04-02 05:41:20 Branches: 389 790 49.2 %

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/imgutils.h"
27
#include "libavutil/intreadwrite.h"
28
#include "libavutil/stereo3d.h"
29
#include "libavutil/mastering_display_metadata.h"
30
31
#include "avcodec.h"
32
#include "bytestream.h"
33
#include "internal.h"
34
#include "apng.h"
35
#include "png.h"
36
#include "pngdsp.h"
37
#include "thread.h"
38
39
#include <zlib.h>
40
41
enum PNGHeaderState {
42
    PNG_IHDR = 1 << 0,
43
    PNG_PLTE = 1 << 1,
44
};
45
46
enum PNGImageState {
47
    PNG_IDAT     = 1 << 0,
48
    PNG_ALLIMAGE = 1 << 1,
49
};
50
51
typedef struct PNGDecContext {
52
    PNGDSPContext dsp;
53
    AVCodecContext *avctx;
54
55
    GetByteContext gb;
56
    ThreadFrame previous_picture;
57
    ThreadFrame last_picture;
58
    ThreadFrame picture;
59
60
    enum PNGHeaderState hdr_state;
61
    enum PNGImageState pic_state;
62
    int width, height;
63
    int cur_w, cur_h;
64
    int last_w, last_h;
65
    int x_offset, y_offset;
66
    int last_x_offset, last_y_offset;
67
    uint8_t dispose_op, blend_op;
68
    uint8_t last_dispose_op;
69
    int bit_depth;
70
    int color_type;
71
    int compression_type;
72
    int interlace_type;
73
    int filter_type;
74
    int channels;
75
    int bits_per_pixel;
76
    int bpp;
77
    int has_trns;
78
    uint8_t transparent_color_be[6];
79
80
    uint8_t *image_buf;
81
    int image_linesize;
82
    uint32_t palette[256];
83
    uint8_t *crow_buf;
84
    uint8_t *last_row;
85
    unsigned int last_row_size;
86
    uint8_t *tmp_row;
87
    unsigned int tmp_row_size;
88
    uint8_t *buffer;
89
    int buffer_size;
90
    int pass;
91
    int crow_size; /* compressed row size (include filter type) */
92
    int row_size; /* decompressed row size */
93
    int pass_row_size; /* decompress row size of the current pass */
94
    int y;
95
    z_stream zstream;
96
} PNGDecContext;
97
98
/* Mask to determine which pixels are valid in a pass */
99
static const uint8_t png_pass_mask[NB_PASSES] = {
100
    0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
101
};
102
103
/* Mask to determine which y pixels can be written in a pass */
104
static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
105
    0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
106
};
107
108
/* Mask to determine which pixels to overwrite while displaying */
109
static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
110
    0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
111
};
112
113
/* NOTE: we try to construct a good looking image at each pass. width
114
 * is the original image width. We also do pixel format conversion at
115
 * this stage */
116
1408
static void png_put_interlaced_row(uint8_t *dst, int width,
117
                                   int bits_per_pixel, int pass,
118
                                   int color_type, const uint8_t *src)
119
{
120
    int x, mask, dsp_mask, j, src_x, b, bpp;
121
    uint8_t *d;
122
    const uint8_t *s;
123
124
1408
    mask     = png_pass_mask[pass];
125
1408
    dsp_mask = png_pass_dsp_mask[pass];
126
127

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

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

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




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




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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

9
         cur_h != s->height ||
1005
9
         x_offset != 0 ||
1006
101
         y_offset != 0) ||
1007

101
        cur_w <= 0 || cur_h <= 0 ||
1008
101
        x_offset < 0 || y_offset < 0 ||
1009

101
        cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1010
            return AVERROR_INVALIDDATA;
1011
1012

101
    if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1013
        av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1014
        return AVERROR_INVALIDDATA;
1015
    }
1016
1017

101
    if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
1018
        dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1019
        // No previous frame to revert to for the first frame
1020
        // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1021
        dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1022
    }
1023
1024

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

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

110
            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1197
110
                if (!(s->pic_state & PNG_IDAT))
1198
9
                    return 0;
1199
                else
1200
101
                    goto exit_loop;
1201
            }
1202
            av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1203
            if (   s->pic_state & PNG_ALLIMAGE
1204
                && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1205
                goto exit_loop;
1206
            ret = AVERROR_INVALIDDATA;
1207
            goto fail;
1208
        }
1209
1210
17015
        length = bytestream2_get_be32(&s->gb);
1211

17015
        if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1212
1
            av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1213
1
            ret = AVERROR_INVALIDDATA;
1214
1
            goto fail;
1215
        }
1216
17014
        tag = bytestream2_get_le32(&s->gb);
1217
17014
        if (avctx->debug & FF_DEBUG_STARTCODE)
1218
            av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1219
                   av_fourcc2str(tag), length);
1220
1221
17014
        if (avctx->codec_id == AV_CODEC_ID_PNG &&
1222
13611
            avctx->skip_frame == AVDISCARD_ALL) {
1223
794
            switch(tag) {
1224
692
            case MKTAG('I', 'H', 'D', 'R'):
1225
            case MKTAG('p', 'H', 'Y', 's'):
1226
            case MKTAG('t', 'E', 'X', 't'):
1227
            case MKTAG('I', 'D', 'A', 'T'):
1228
            case MKTAG('t', 'R', 'N', 'S'):
1229
692
                break;
1230
102
            default:
1231
102
                goto skip_tag;
1232
            }
1233
16220
        }
1234
1235
16912
        metadatap = &p->metadata;
1236



16912
        switch (tag) {
1237
359
        case MKTAG('I', 'H', 'D', 'R'):
1238
359
            if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1239
                goto fail;
1240
359
            break;
1241
333
        case MKTAG('p', 'H', 'Y', 's'):
1242
333
            if ((ret = decode_phys_chunk(avctx, s)) < 0)
1243
                goto fail;
1244
333
            break;
1245
101
        case MKTAG('f', 'c', 'T', 'L'):
1246
101
            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1247
                goto skip_tag;
1248
101
            if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1249
                goto fail;
1250
101
            decode_next_dat = 1;
1251
101
            break;
1252
2966
        case MKTAG('f', 'd', 'A', 'T'):
1253
2966
            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1254
                goto skip_tag;
1255
2966
            if (!decode_next_dat) {
1256
                ret = AVERROR_INVALIDDATA;
1257
                goto fail;
1258
            }
1259
2966
            bytestream2_get_be32(&s->gb);
1260
2966
            length -= 4;
1261
            /* fallthrough */
1262
15613
        case MKTAG('I', 'D', 'A', 'T'):
1263

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

404
    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1374
1
        size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1375
1
        size_t raw_bpp = s->bpp - byte_depth;
1376
        unsigned x, y;
1377
1378
1
        av_assert0(s->bit_depth > 1);
1379
1380
331
        for (y = 0; y < s->height; ++y) {
1381
330
            uint8_t *row = &s->image_buf[s->image_linesize * y];
1382
1383

330
            if (s->bpp == 2 && byte_depth == 1) {
1384
                uint8_t *pixel = &row[2 * s->width - 1];
1385
                uint8_t *rowp  = &row[1 * s->width - 1];
1386
                int tcolor = s->transparent_color_be[0];
1387
                for (x = s->width; x > 0; --x) {
1388
                    *pixel-- = *rowp == tcolor ? 0 : 0xff;
1389
                    *pixel-- = *rowp--;
1390
                }
1391

660
            } else if (s->bpp == 4 && byte_depth == 1) {
1392
330
                uint8_t *pixel = &row[4 * s->width - 1];
1393
330
                uint8_t *rowp  = &row[3 * s->width - 1];
1394
330
                int tcolor = AV_RL24(s->transparent_color_be);
1395
109230
                for (x = s->width; x > 0; --x) {
1396
108900
                    *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1397
108900
                    *pixel-- = *rowp--;
1398
108900
                    *pixel-- = *rowp--;
1399
108900
                    *pixel-- = *rowp--;
1400
                }
1401
            } else {
1402
                /* since we're updating in-place, we have to go from right to left */
1403
                for (x = s->width; x > 0; --x) {
1404
                    uint8_t *pixel = &row[s->bpp * (x - 1)];
1405
                    memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1406
1407
                    if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1408
                        memset(&pixel[raw_bpp], 0, byte_depth);
1409
                    } else {
1410
                        memset(&pixel[raw_bpp], 0xff, byte_depth);
1411
                    }
1412
                }
1413
            }
1414
        }
1415
    }
1416
1417
    /* handle P-frames only if a predecessor frame is available */
1418
404
    if (s->last_picture.f->data[0]) {
1419

350
        if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1420
39
            && s->last_picture.f->width == p->width
1421
39
            && s->last_picture.f->height== p->height
1422
39
            && s->last_picture.f->format== p->format
1423
         ) {
1424
39
            if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1425
                handle_p_frame_png(s, p);
1426
39
            else if (CONFIG_APNG_DECODER &&
1427
39
                     s->previous_picture.f->width == p->width  &&
1428
39
                     s->previous_picture.f->height== p->height &&
1429
39
                     s->previous_picture.f->format== p->format &&
1430

78
                     avctx->codec_id == AV_CODEC_ID_APNG &&
1431
39
                     (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1432
                goto fail;
1433
        }
1434
    }
1435
404
    ff_thread_report_progress(&s->picture, INT_MAX, 0);
1436
404
    ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1437
1438
404
    return 0;
1439
1440
1
fail:
1441
1
    ff_thread_report_progress(&s->picture, INT_MAX, 0);
1442
1
    ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1443
1
    return ret;
1444
}
1445
1446
#if CONFIG_PNG_DECODER
1447
350
static int decode_frame_png(AVCodecContext *avctx,
1448
                        void *data, int *got_frame,
1449
                        AVPacket *avpkt)
1450
{
1451
350
    PNGDecContext *const s = avctx->priv_data;
1452
350
    const uint8_t *buf     = avpkt->data;
1453
350
    int buf_size           = avpkt->size;
1454
    AVFrame *p;
1455
    int64_t sig;
1456
    int ret;
1457
1458
350
    ff_thread_release_buffer(avctx, &s->last_picture);
1459
350
    FFSWAP(ThreadFrame, s->picture, s->last_picture);
1460
350
    p = s->picture.f;
1461
1462
350
    bytestream2_init(&s->gb, buf, buf_size);
1463
1464
    /* check signature */
1465
350
    sig = bytestream2_get_be64(&s->gb);
1466

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

132
    if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1768
        av_frame_free(&s->previous_picture.f);
1769
        av_frame_free(&s->last_picture.f);
1770
        av_frame_free(&s->picture.f);
1771
        return AVERROR(ENOMEM);
1772
    }
1773
1774
132
    if (!avctx->internal->is_copy) {
1775
100
        avctx->internal->allocate_progress = 1;
1776
100
        ff_pngdsp_init(&s->dsp);
1777
    }
1778
1779
132
    return 0;
1780
}
1781
1782
132
static av_cold int png_dec_end(AVCodecContext *avctx)
1783
{
1784
132
    PNGDecContext *s = avctx->priv_data;
1785
1786
132
    ff_thread_release_buffer(avctx, &s->previous_picture);
1787
132
    av_frame_free(&s->previous_picture.f);
1788
132
    ff_thread_release_buffer(avctx, &s->last_picture);
1789
132
    av_frame_free(&s->last_picture.f);
1790
132
    ff_thread_release_buffer(avctx, &s->picture);
1791
132
    av_frame_free(&s->picture.f);
1792
132
    av_freep(&s->buffer);
1793
132
    s->buffer_size = 0;
1794
132
    av_freep(&s->last_row);
1795
132
    s->last_row_size = 0;
1796
132
    av_freep(&s->tmp_row);
1797
132
    s->tmp_row_size = 0;
1798
1799
132
    return 0;
1800
}
1801
1802
#if CONFIG_APNG_DECODER
1803
AVCodec ff_apng_decoder = {
1804
    .name           = "apng",
1805
    .long_name      = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1806
    .type           = AVMEDIA_TYPE_VIDEO,
1807
    .id             = AV_CODEC_ID_APNG,
1808
    .priv_data_size = sizeof(PNGDecContext),
1809
    .init           = png_dec_init,
1810
    .close          = png_dec_end,
1811
    .decode         = decode_frame_apng,
1812
    .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1813
    .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1814
    .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1815
    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
1816
};
1817
#endif
1818
1819
#if CONFIG_PNG_DECODER
1820
AVCodec ff_png_decoder = {
1821
    .name           = "png",
1822
    .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1823
    .type           = AVMEDIA_TYPE_VIDEO,
1824
    .id             = AV_CODEC_ID_PNG,
1825
    .priv_data_size = sizeof(PNGDecContext),
1826
    .init           = png_dec_init,
1827
    .close          = png_dec_end,
1828
    .decode         = decode_frame_png,
1829
    .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1830
    .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1831
    .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1832
    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE,
1833
};
1834
#endif
1835
1836
#if CONFIG_LSCR_DECODER
1837
AVCodec ff_lscr_decoder = {
1838
    .name           = "lscr",
1839
    .long_name      = NULL_IF_CONFIG_SMALL("LEAD Screen Capture"),
1840
    .type           = AVMEDIA_TYPE_VIDEO,
1841
    .id             = AV_CODEC_ID_LSCR,
1842
    .priv_data_size = sizeof(PNGDecContext),
1843
    .init           = png_dec_init,
1844
    .close          = png_dec_end,
1845
    .decode         = decode_frame_lscr,
1846
    .flush          = decode_flush,
1847
    .capabilities   = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1848
    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE,
1849
};
1850
#endif