xref: /third_party/ffmpeg/libavcodec/pngdec.c (revision cabdff1a)
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 "config_components.h"
25
26#include "libavutil/avassert.h"
27#include "libavutil/bprint.h"
28#include "libavutil/crc.h"
29#include "libavutil/imgutils.h"
30#include "libavutil/intreadwrite.h"
31#include "libavutil/stereo3d.h"
32#include "libavutil/mastering_display_metadata.h"
33
34#include "avcodec.h"
35#include "bytestream.h"
36#include "codec_internal.h"
37#include "internal.h"
38#include "apng.h"
39#include "png.h"
40#include "pngdsp.h"
41#include "thread.h"
42#include "threadframe.h"
43#include "zlib_wrapper.h"
44
45#include <zlib.h>
46
47enum PNGHeaderState {
48    PNG_IHDR = 1 << 0,
49    PNG_PLTE = 1 << 1,
50};
51
52enum PNGImageState {
53    PNG_IDAT     = 1 << 0,
54    PNG_ALLIMAGE = 1 << 1,
55};
56
57typedef struct PNGDecContext {
58    PNGDSPContext dsp;
59    AVCodecContext *avctx;
60
61    GetByteContext gb;
62    ThreadFrame last_picture;
63    ThreadFrame picture;
64
65    AVDictionary *frame_metadata;
66
67    uint8_t  iccp_name[82];
68    uint8_t *iccp_data;
69    size_t   iccp_data_len;
70
71    int stereo_mode;
72
73    int have_chrm;
74    uint32_t white_point[2];
75    uint32_t display_primaries[3][2];
76
77    enum PNGHeaderState hdr_state;
78    enum PNGImageState pic_state;
79    int width, height;
80    int cur_w, cur_h;
81    int x_offset, y_offset;
82    uint8_t dispose_op, blend_op;
83    int bit_depth;
84    int color_type;
85    int compression_type;
86    int interlace_type;
87    int filter_type;
88    int channels;
89    int bits_per_pixel;
90    int bpp;
91    int has_trns;
92    uint8_t transparent_color_be[6];
93
94    uint32_t palette[256];
95    uint8_t *crow_buf;
96    uint8_t *last_row;
97    unsigned int last_row_size;
98    uint8_t *tmp_row;
99    unsigned int tmp_row_size;
100    uint8_t *buffer;
101    int buffer_size;
102    int pass;
103    int crow_size; /* compressed row size (include filter type) */
104    int row_size; /* decompressed row size */
105    int pass_row_size; /* decompress row size of the current pass */
106    int y;
107    FFZStream zstream;
108} PNGDecContext;
109
110/* Mask to determine which pixels are valid in a pass */
111static const uint8_t png_pass_mask[NB_PASSES] = {
112    0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
113};
114
115/* Mask to determine which y pixels can be written in a pass */
116static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
117    0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
118};
119
120/* Mask to determine which pixels to overwrite while displaying */
121static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
122    0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
123};
124
125/* NOTE: we try to construct a good looking image at each pass. width
126 * is the original image width. We also do pixel format conversion at
127 * this stage */
128static void png_put_interlaced_row(uint8_t *dst, int width,
129                                   int bits_per_pixel, int pass,
130                                   int color_type, const uint8_t *src)
131{
132    int x, mask, dsp_mask, j, src_x, b, bpp;
133    uint8_t *d;
134    const uint8_t *s;
135
136    mask     = png_pass_mask[pass];
137    dsp_mask = png_pass_dsp_mask[pass];
138
139    switch (bits_per_pixel) {
140    case 1:
141        src_x = 0;
142        for (x = 0; x < width; x++) {
143            j = (x & 7);
144            if ((dsp_mask << j) & 0x80) {
145                b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
146                dst[x >> 3] &= 0xFF7F>>j;
147                dst[x >> 3] |= b << (7 - j);
148            }
149            if ((mask << j) & 0x80)
150                src_x++;
151        }
152        break;
153    case 2:
154        src_x = 0;
155        for (x = 0; x < width; x++) {
156            int j2 = 2 * (x & 3);
157            j = (x & 7);
158            if ((dsp_mask << j) & 0x80) {
159                b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
160                dst[x >> 2] &= 0xFF3F>>j2;
161                dst[x >> 2] |= b << (6 - j2);
162            }
163            if ((mask << j) & 0x80)
164                src_x++;
165        }
166        break;
167    case 4:
168        src_x = 0;
169        for (x = 0; x < width; x++) {
170            int j2 = 4*(x&1);
171            j = (x & 7);
172            if ((dsp_mask << j) & 0x80) {
173                b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
174                dst[x >> 1] &= 0xFF0F>>j2;
175                dst[x >> 1] |= b << (4 - j2);
176            }
177            if ((mask << j) & 0x80)
178                src_x++;
179        }
180        break;
181    default:
182        bpp = bits_per_pixel >> 3;
183        d   = dst;
184        s   = src;
185            for (x = 0; x < width; x++) {
186                j = x & 7;
187                if ((dsp_mask << j) & 0x80) {
188                    memcpy(d, s, bpp);
189                }
190                d += bpp;
191                if ((mask << j) & 0x80)
192                    s += bpp;
193            }
194        break;
195    }
196}
197
198void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
199                                 int w, int bpp)
200{
201    int i;
202    for (i = 0; i < w; i++) {
203        int a, b, c, p, pa, pb, pc;
204
205        a = dst[i - bpp];
206        b = top[i];
207        c = top[i - bpp];
208
209        p  = b - c;
210        pc = a - c;
211
212        pa = abs(p);
213        pb = abs(pc);
214        pc = abs(p + pc);
215
216        if (pa <= pb && pa <= pc)
217            p = a;
218        else if (pb <= pc)
219            p = b;
220        else
221            p = c;
222        dst[i] = p + src[i];
223    }
224}
225
226#define UNROLL1(bpp, op)                                                      \
227    {                                                                         \
228        r = dst[0];                                                           \
229        if (bpp >= 2)                                                         \
230            g = dst[1];                                                       \
231        if (bpp >= 3)                                                         \
232            b = dst[2];                                                       \
233        if (bpp >= 4)                                                         \
234            a = dst[3];                                                       \
235        for (; i <= size - bpp; i += bpp) {                                   \
236            dst[i + 0] = r = op(r, src[i + 0], last[i + 0]);                  \
237            if (bpp == 1)                                                     \
238                continue;                                                     \
239            dst[i + 1] = g = op(g, src[i + 1], last[i + 1]);                  \
240            if (bpp == 2)                                                     \
241                continue;                                                     \
242            dst[i + 2] = b = op(b, src[i + 2], last[i + 2]);                  \
243            if (bpp == 3)                                                     \
244                continue;                                                     \
245            dst[i + 3] = a = op(a, src[i + 3], last[i + 3]);                  \
246        }                                                                     \
247    }
248
249#define UNROLL_FILTER(op)                                                     \
250    if (bpp == 1) {                                                           \
251        UNROLL1(1, op)                                                        \
252    } else if (bpp == 2) {                                                    \
253        UNROLL1(2, op)                                                        \
254    } else if (bpp == 3) {                                                    \
255        UNROLL1(3, op)                                                        \
256    } else if (bpp == 4) {                                                    \
257        UNROLL1(4, op)                                                        \
258    }                                                                         \
259    for (; i < size; i++) {                                                   \
260        dst[i] = op(dst[i - bpp], src[i], last[i]);                           \
261    }
262
263/* NOTE: 'dst' can be equal to 'last' */
264void ff_png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
265                       uint8_t *src, uint8_t *last, int size, int bpp)
266{
267    int i, p, r, g, b, a;
268
269    switch (filter_type) {
270    case PNG_FILTER_VALUE_NONE:
271        memcpy(dst, src, size);
272        break;
273    case PNG_FILTER_VALUE_SUB:
274        for (i = 0; i < bpp; i++)
275            dst[i] = src[i];
276        if (bpp == 4) {
277            p = *(int *)dst;
278            for (; i < size; i += bpp) {
279                unsigned s = *(int *)(src + i);
280                p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
281                *(int *)(dst + i) = p;
282            }
283        } else {
284#define OP_SUB(x, s, l) ((x) + (s))
285            UNROLL_FILTER(OP_SUB);
286        }
287        break;
288    case PNG_FILTER_VALUE_UP:
289        dsp->add_bytes_l2(dst, src, last, size);
290        break;
291    case PNG_FILTER_VALUE_AVG:
292        for (i = 0; i < bpp; i++) {
293            p      = (last[i] >> 1);
294            dst[i] = p + src[i];
295        }
296#define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
297        UNROLL_FILTER(OP_AVG);
298        break;
299    case PNG_FILTER_VALUE_PAETH:
300        for (i = 0; i < bpp; i++) {
301            p      = last[i];
302            dst[i] = p + src[i];
303        }
304        if (bpp > 2 && size > 4) {
305            /* would write off the end of the array if we let it process
306             * the last pixel with bpp=3 */
307            int w = (bpp & 3) ? size - 3 : size;
308
309            if (w > i) {
310                dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
311                i = w;
312            }
313        }
314        ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
315        break;
316    }
317}
318
319/* This used to be called "deloco" in FFmpeg
320 * and is actually an inverse reversible colorspace transformation */
321#define YUV2RGB(NAME, TYPE) \
322static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
323{ \
324    int i; \
325    for (i = 0; i < size - 2; i += 3 + alpha) { \
326        int g = dst [i + 1]; \
327        dst[i + 0] += g; \
328        dst[i + 2] += g; \
329    } \
330}
331
332YUV2RGB(rgb8, uint8_t)
333YUV2RGB(rgb16, uint16_t)
334
335static int percent_missing(PNGDecContext *s)
336{
337    if (s->interlace_type) {
338        return 100 - 100 * s->pass / (NB_PASSES - 1);
339    } else {
340        return 100 - 100 * s->y / s->cur_h;
341    }
342}
343
344/* process exactly one decompressed row */
345static void png_handle_row(PNGDecContext *s, uint8_t *dst, ptrdiff_t dst_stride)
346{
347    uint8_t *ptr, *last_row;
348    int got_line;
349
350    if (!s->interlace_type) {
351        ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
352        if (s->y == 0)
353            last_row = s->last_row;
354        else
355            last_row = ptr - dst_stride;
356
357        ff_png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
358                          last_row, s->row_size, s->bpp);
359        /* loco lags by 1 row so that it doesn't interfere with top prediction */
360        if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
361            if (s->bit_depth == 16) {
362                deloco_rgb16((uint16_t *)(ptr - dst_stride), s->row_size / 2,
363                             s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
364            } else {
365                deloco_rgb8(ptr - dst_stride, s->row_size,
366                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
367            }
368        }
369        s->y++;
370        if (s->y == s->cur_h) {
371            s->pic_state |= PNG_ALLIMAGE;
372            if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
373                if (s->bit_depth == 16) {
374                    deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
375                                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
376                } else {
377                    deloco_rgb8(ptr, s->row_size,
378                                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
379                }
380            }
381        }
382    } else {
383        got_line = 0;
384        for (;;) {
385            ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
386            if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
387                /* if we already read one row, it is time to stop to
388                 * wait for the next one */
389                if (got_line)
390                    break;
391                ff_png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
392                                  s->last_row, s->pass_row_size, s->bpp);
393                FFSWAP(uint8_t *, s->last_row, s->tmp_row);
394                FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
395                got_line = 1;
396            }
397            if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
398                png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
399                                       s->color_type, s->last_row);
400            }
401            s->y++;
402            if (s->y == s->cur_h) {
403                memset(s->last_row, 0, s->row_size);
404                for (;;) {
405                    if (s->pass == NB_PASSES - 1) {
406                        s->pic_state |= PNG_ALLIMAGE;
407                        goto the_end;
408                    } else {
409                        s->pass++;
410                        s->y = 0;
411                        s->pass_row_size = ff_png_pass_row_size(s->pass,
412                                                                s->bits_per_pixel,
413                                                                s->cur_w);
414                        s->crow_size = s->pass_row_size + 1;
415                        if (s->pass_row_size != 0)
416                            break;
417                        /* skip pass if empty row */
418                    }
419                }
420            }
421        }
422the_end:;
423    }
424}
425
426static int png_decode_idat(PNGDecContext *s, GetByteContext *gb,
427                           uint8_t *dst, ptrdiff_t dst_stride)
428{
429    z_stream *const zstream = &s->zstream.zstream;
430    int ret;
431    zstream->avail_in = bytestream2_get_bytes_left(gb);
432    zstream->next_in  = gb->buffer;
433
434    /* decode one line if possible */
435    while (zstream->avail_in > 0) {
436        ret = inflate(zstream, Z_PARTIAL_FLUSH);
437        if (ret != Z_OK && ret != Z_STREAM_END) {
438            av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
439            return AVERROR_EXTERNAL;
440        }
441        if (zstream->avail_out == 0) {
442            if (!(s->pic_state & PNG_ALLIMAGE)) {
443                png_handle_row(s, dst, dst_stride);
444            }
445            zstream->avail_out = s->crow_size;
446            zstream->next_out  = s->crow_buf;
447        }
448        if (ret == Z_STREAM_END && zstream->avail_in > 0) {
449            av_log(s->avctx, AV_LOG_WARNING,
450                   "%d undecompressed bytes left in buffer\n", zstream->avail_in);
451            return 0;
452        }
453    }
454    return 0;
455}
456
457static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
458                       const uint8_t *data_end, void *logctx)
459{
460    FFZStream z;
461    z_stream *const zstream = &z.zstream;
462    unsigned char *buf;
463    unsigned buf_size;
464    int ret = ff_inflate_init(&z, logctx);
465    if (ret < 0)
466        return ret;
467
468    zstream->next_in  = data;
469    zstream->avail_in = data_end - data;
470    av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
471
472    while (zstream->avail_in > 0) {
473        av_bprint_get_buffer(bp, 2, &buf, &buf_size);
474        if (buf_size < 2) {
475            ret = AVERROR(ENOMEM);
476            goto fail;
477        }
478        zstream->next_out  = buf;
479        zstream->avail_out = buf_size - 1;
480        ret = inflate(zstream, Z_PARTIAL_FLUSH);
481        if (ret != Z_OK && ret != Z_STREAM_END) {
482            ret = AVERROR_EXTERNAL;
483            goto fail;
484        }
485        bp->len += zstream->next_out - buf;
486        if (ret == Z_STREAM_END)
487            break;
488    }
489    ff_inflate_end(&z);
490    bp->str[bp->len] = 0;
491    return 0;
492
493fail:
494    ff_inflate_end(&z);
495    av_bprint_finalize(bp, NULL);
496    return ret;
497}
498
499static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
500{
501    size_t extra = 0, i;
502    uint8_t *out, *q;
503
504    for (i = 0; i < size_in; i++)
505        extra += in[i] >= 0x80;
506    if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
507        return NULL;
508    q = out = av_malloc(size_in + extra + 1);
509    if (!out)
510        return NULL;
511    for (i = 0; i < size_in; i++) {
512        if (in[i] >= 0x80) {
513            *(q++) = 0xC0 | (in[i] >> 6);
514            *(q++) = 0x80 | (in[i] & 0x3F);
515        } else {
516            *(q++) = in[i];
517        }
518    }
519    *(q++) = 0;
520    return out;
521}
522
523static int decode_text_chunk(PNGDecContext *s, GetByteContext *gb, int compressed)
524{
525    int ret, method;
526    const uint8_t *data        = gb->buffer;
527    const uint8_t *data_end    = gb->buffer_end;
528    const uint8_t *keyword     = data;
529    const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
530    uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
531    unsigned text_len;
532    AVBPrint bp;
533
534    if (!keyword_end)
535        return AVERROR_INVALIDDATA;
536    data = keyword_end + 1;
537
538    if (compressed) {
539        if (data == data_end)
540            return AVERROR_INVALIDDATA;
541        method = *(data++);
542        if (method)
543            return AVERROR_INVALIDDATA;
544        if ((ret = decode_zbuf(&bp, data, data_end, s->avctx)) < 0)
545            return ret;
546        text_len = bp.len;
547        ret = av_bprint_finalize(&bp, (char **)&text);
548        if (ret < 0)
549            return ret;
550    } else {
551        text = (uint8_t *)data;
552        text_len = data_end - text;
553    }
554
555    kw_utf8  = iso88591_to_utf8(keyword, keyword_end - keyword);
556    txt_utf8 = iso88591_to_utf8(text, text_len);
557    if (text != data)
558        av_free(text);
559    if (!(kw_utf8 && txt_utf8)) {
560        av_free(kw_utf8);
561        av_free(txt_utf8);
562        return AVERROR(ENOMEM);
563    }
564
565    av_dict_set(&s->frame_metadata, kw_utf8, txt_utf8,
566                AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
567    return 0;
568}
569
570static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
571                             GetByteContext *gb)
572{
573    if (bytestream2_get_bytes_left(gb) != 13)
574        return AVERROR_INVALIDDATA;
575
576    if (s->pic_state & PNG_IDAT) {
577        av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
578        return AVERROR_INVALIDDATA;
579    }
580
581    if (s->hdr_state & PNG_IHDR) {
582        av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
583        return AVERROR_INVALIDDATA;
584    }
585
586    s->width  = s->cur_w = bytestream2_get_be32(gb);
587    s->height = s->cur_h = bytestream2_get_be32(gb);
588    if (av_image_check_size(s->width, s->height, 0, avctx)) {
589        s->cur_w = s->cur_h = s->width = s->height = 0;
590        av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
591        return AVERROR_INVALIDDATA;
592    }
593    s->bit_depth        = bytestream2_get_byte(gb);
594    if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
595        s->bit_depth != 8 && s->bit_depth != 16) {
596        av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
597        goto error;
598    }
599    s->color_type       = bytestream2_get_byte(gb);
600    s->compression_type = bytestream2_get_byte(gb);
601    if (s->compression_type) {
602        av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
603        goto error;
604    }
605    s->filter_type      = bytestream2_get_byte(gb);
606    s->interlace_type   = bytestream2_get_byte(gb);
607    s->hdr_state |= PNG_IHDR;
608    if (avctx->debug & FF_DEBUG_PICT_INFO)
609        av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
610                "compression_type=%d filter_type=%d interlace_type=%d\n",
611                s->width, s->height, s->bit_depth, s->color_type,
612                s->compression_type, s->filter_type, s->interlace_type);
613
614    return 0;
615error:
616    s->cur_w = s->cur_h = s->width = s->height = 0;
617    s->bit_depth = 8;
618    return AVERROR_INVALIDDATA;
619}
620
621static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s,
622                             GetByteContext *gb)
623{
624    if (s->pic_state & PNG_IDAT) {
625        av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
626        return AVERROR_INVALIDDATA;
627    }
628    avctx->sample_aspect_ratio.num = bytestream2_get_be32(gb);
629    avctx->sample_aspect_ratio.den = bytestream2_get_be32(gb);
630    if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
631        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
632    bytestream2_skip(gb, 1); /* unit specifier */
633
634    return 0;
635}
636
637static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
638                             GetByteContext *gb, AVFrame *p)
639{
640    int ret;
641    size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
642
643    if (!p)
644        return AVERROR_INVALIDDATA;
645    if (!(s->hdr_state & PNG_IHDR)) {
646        av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
647        return AVERROR_INVALIDDATA;
648    }
649    if (!(s->pic_state & PNG_IDAT)) {
650        /* init image info */
651        ret = ff_set_dimensions(avctx, s->width, s->height);
652        if (ret < 0)
653            return ret;
654
655        s->channels       = ff_png_get_nb_channels(s->color_type);
656        s->bits_per_pixel = s->bit_depth * s->channels;
657        s->bpp            = (s->bits_per_pixel + 7) >> 3;
658        s->row_size       = (s->cur_w * s->bits_per_pixel + 7) >> 3;
659
660        if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
661                s->color_type == PNG_COLOR_TYPE_RGB) {
662            avctx->pix_fmt = AV_PIX_FMT_RGB24;
663        } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
664                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
665            avctx->pix_fmt = AV_PIX_FMT_RGBA;
666        } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
667                s->color_type == PNG_COLOR_TYPE_GRAY) {
668            avctx->pix_fmt = AV_PIX_FMT_GRAY8;
669        } else if (s->bit_depth == 16 &&
670                s->color_type == PNG_COLOR_TYPE_GRAY) {
671            avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
672        } else if (s->bit_depth == 16 &&
673                s->color_type == PNG_COLOR_TYPE_RGB) {
674            avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
675        } else if (s->bit_depth == 16 &&
676                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
677            avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
678        } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
679                s->color_type == PNG_COLOR_TYPE_PALETTE) {
680            avctx->pix_fmt = avctx->codec_id == AV_CODEC_ID_APNG ? AV_PIX_FMT_RGBA : AV_PIX_FMT_PAL8;
681        } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
682            avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
683        } else if (s->bit_depth == 8 &&
684                s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
685            avctx->pix_fmt = AV_PIX_FMT_YA8;
686        } else if (s->bit_depth == 16 &&
687                s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
688            avctx->pix_fmt = AV_PIX_FMT_YA16BE;
689        } else {
690            avpriv_report_missing_feature(avctx,
691                                          "Bit depth %d color type %d",
692                                          s->bit_depth, s->color_type);
693            return AVERROR_PATCHWELCOME;
694        }
695
696        if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
697            switch (avctx->pix_fmt) {
698            case AV_PIX_FMT_RGB24:
699                avctx->pix_fmt = AV_PIX_FMT_RGBA;
700                break;
701
702            case AV_PIX_FMT_RGB48BE:
703                avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
704                break;
705
706            case AV_PIX_FMT_GRAY8:
707                avctx->pix_fmt = AV_PIX_FMT_YA8;
708                break;
709
710            case AV_PIX_FMT_GRAY16BE:
711                avctx->pix_fmt = AV_PIX_FMT_YA16BE;
712                break;
713
714            default:
715                avpriv_request_sample(avctx, "bit depth %d "
716                        "and color type %d with TRNS",
717                        s->bit_depth, s->color_type);
718                return AVERROR_INVALIDDATA;
719            }
720
721            s->bpp += byte_depth;
722        }
723
724        ff_thread_release_ext_buffer(avctx, &s->picture);
725        if (s->dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
726            /* We only need a buffer for the current picture. */
727            ret = ff_thread_get_buffer(avctx, p, 0);
728            if (ret < 0)
729                return ret;
730        } else if (s->dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
731            /* We need a buffer for the current picture as well as
732             * a buffer for the reference to retain. */
733            ret = ff_thread_get_ext_buffer(avctx, &s->picture,
734                                           AV_GET_BUFFER_FLAG_REF);
735            if (ret < 0)
736                return ret;
737            ret = ff_thread_get_buffer(avctx, p, 0);
738            if (ret < 0)
739                return ret;
740        } else {
741            /* The picture output this time and the reference to retain coincide. */
742            if ((ret = ff_thread_get_ext_buffer(avctx, &s->picture,
743                                                AV_GET_BUFFER_FLAG_REF)) < 0)
744                return ret;
745            ret = av_frame_ref(p, s->picture.f);
746            if (ret < 0)
747                return ret;
748        }
749
750        p->pict_type        = AV_PICTURE_TYPE_I;
751        p->key_frame        = 1;
752        p->interlaced_frame = !!s->interlace_type;
753
754        ff_thread_finish_setup(avctx);
755
756        /* compute the compressed row size */
757        if (!s->interlace_type) {
758            s->crow_size = s->row_size + 1;
759        } else {
760            s->pass          = 0;
761            s->pass_row_size = ff_png_pass_row_size(s->pass,
762                    s->bits_per_pixel,
763                    s->cur_w);
764            s->crow_size = s->pass_row_size + 1;
765        }
766        ff_dlog(avctx, "row_size=%d crow_size =%d\n",
767                s->row_size, s->crow_size);
768
769        /* copy the palette if needed */
770        if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
771            memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
772        /* empty row is used if differencing to the first row */
773        av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
774        if (!s->last_row)
775            return AVERROR_INVALIDDATA;
776        if (s->interlace_type ||
777                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
778            av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
779            if (!s->tmp_row)
780                return AVERROR_INVALIDDATA;
781        }
782        /* compressed row */
783        av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
784        if (!s->buffer)
785            return AVERROR(ENOMEM);
786
787        /* we want crow_buf+1 to be 16-byte aligned */
788        s->crow_buf          = s->buffer + 15;
789        s->zstream.zstream.avail_out = s->crow_size;
790        s->zstream.zstream.next_out  = s->crow_buf;
791    }
792
793    s->pic_state |= PNG_IDAT;
794
795    /* set image to non-transparent bpp while decompressing */
796    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
797        s->bpp -= byte_depth;
798
799    ret = png_decode_idat(s, gb, p->data[0], p->linesize[0]);
800
801    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
802        s->bpp += byte_depth;
803
804    if (ret < 0)
805        return ret;
806
807    return 0;
808}
809
810static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
811                             GetByteContext *gb)
812{
813    int length = bytestream2_get_bytes_left(gb);
814    int n, i, r, g, b;
815
816    if ((length % 3) != 0 || length > 256 * 3)
817        return AVERROR_INVALIDDATA;
818    /* read the palette */
819    n = length / 3;
820    for (i = 0; i < n; i++) {
821        r = bytestream2_get_byte(gb);
822        g = bytestream2_get_byte(gb);
823        b = bytestream2_get_byte(gb);
824        s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
825    }
826    for (; i < 256; i++)
827        s->palette[i] = (0xFFU << 24);
828    s->hdr_state |= PNG_PLTE;
829
830    return 0;
831}
832
833static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
834                             GetByteContext *gb)
835{
836    int length = bytestream2_get_bytes_left(gb);
837    int v, i;
838
839    if (!(s->hdr_state & PNG_IHDR)) {
840        av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
841        return AVERROR_INVALIDDATA;
842    }
843
844    if (s->pic_state & PNG_IDAT) {
845        av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
846        return AVERROR_INVALIDDATA;
847    }
848
849    if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
850        if (length > 256 || !(s->hdr_state & PNG_PLTE))
851            return AVERROR_INVALIDDATA;
852
853        for (i = 0; i < length; i++) {
854            unsigned v = bytestream2_get_byte(gb);
855            s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
856        }
857    } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
858        if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
859            (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
860            s->bit_depth == 1)
861            return AVERROR_INVALIDDATA;
862
863        for (i = 0; i < length / 2; i++) {
864            /* only use the least significant bits */
865            v = av_mod_uintp2(bytestream2_get_be16(gb), s->bit_depth);
866
867            if (s->bit_depth > 8)
868                AV_WB16(&s->transparent_color_be[2 * i], v);
869            else
870                s->transparent_color_be[i] = v;
871        }
872    } else {
873        return AVERROR_INVALIDDATA;
874    }
875
876    s->has_trns = 1;
877
878    return 0;
879}
880
881static int decode_iccp_chunk(PNGDecContext *s, GetByteContext *gb)
882{
883    int ret, cnt = 0;
884    AVBPrint bp;
885
886    while ((s->iccp_name[cnt++] = bytestream2_get_byte(gb)) && cnt < 81);
887    if (cnt > 80) {
888        av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
889        ret = AVERROR_INVALIDDATA;
890        goto fail;
891    }
892
893    if (bytestream2_get_byte(gb) != 0) {
894        av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
895        ret =  AVERROR_INVALIDDATA;
896        goto fail;
897    }
898
899    if ((ret = decode_zbuf(&bp, gb->buffer, gb->buffer_end, s->avctx)) < 0)
900        return ret;
901
902    av_freep(&s->iccp_data);
903    ret = av_bprint_finalize(&bp, (char **)&s->iccp_data);
904    if (ret < 0)
905        return ret;
906    s->iccp_data_len = bp.len;
907
908    return 0;
909fail:
910    s->iccp_name[0] = 0;
911    return ret;
912}
913
914static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
915{
916    if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
917        int i, j, k;
918        uint8_t *pd = p->data[0];
919        for (j = 0; j < s->height; j++) {
920            i = s->width / 8;
921            for (k = 7; k >= 1; k--)
922                if ((s->width&7) >= k)
923                    pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
924            for (i--; i >= 0; i--) {
925                pd[8*i + 7]=  pd[i]     & 1;
926                pd[8*i + 6]= (pd[i]>>1) & 1;
927                pd[8*i + 5]= (pd[i]>>2) & 1;
928                pd[8*i + 4]= (pd[i]>>3) & 1;
929                pd[8*i + 3]= (pd[i]>>4) & 1;
930                pd[8*i + 2]= (pd[i]>>5) & 1;
931                pd[8*i + 1]= (pd[i]>>6) & 1;
932                pd[8*i + 0]=  pd[i]>>7;
933            }
934            pd += p->linesize[0];
935        }
936    } else if (s->bits_per_pixel == 2) {
937        int i, j;
938        uint8_t *pd = p->data[0];
939        for (j = 0; j < s->height; j++) {
940            i = s->width / 4;
941            if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
942                if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
943                if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
944                if ((s->width&3) >= 1) pd[4*i + 0]=  pd[i] >> 6;
945                for (i--; i >= 0; i--) {
946                    pd[4*i + 3]=  pd[i]     & 3;
947                    pd[4*i + 2]= (pd[i]>>2) & 3;
948                    pd[4*i + 1]= (pd[i]>>4) & 3;
949                    pd[4*i + 0]=  pd[i]>>6;
950                }
951            } else {
952                if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
953                if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
954                if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6     )*0x55;
955                for (i--; i >= 0; i--) {
956                    pd[4*i + 3]= ( pd[i]     & 3)*0x55;
957                    pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
958                    pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
959                    pd[4*i + 0]= ( pd[i]>>6     )*0x55;
960                }
961            }
962            pd += p->linesize[0];
963        }
964    } else if (s->bits_per_pixel == 4) {
965        int i, j;
966        uint8_t *pd = p->data[0];
967        for (j = 0; j < s->height; j++) {
968            i = s->width/2;
969            if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
970                if (s->width&1) pd[2*i+0]= pd[i]>>4;
971                for (i--; i >= 0; i--) {
972                    pd[2*i + 1] = pd[i] & 15;
973                    pd[2*i + 0] = pd[i] >> 4;
974                }
975            } else {
976                if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
977                for (i--; i >= 0; i--) {
978                    pd[2*i + 1] = (pd[i] & 15) * 0x11;
979                    pd[2*i + 0] = (pd[i] >> 4) * 0x11;
980                }
981            }
982            pd += p->linesize[0];
983        }
984    }
985}
986
987static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
988                             GetByteContext *gb)
989{
990    uint32_t sequence_number;
991    int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
992
993    if (bytestream2_get_bytes_left(gb) != APNG_FCTL_CHUNK_SIZE)
994        return AVERROR_INVALIDDATA;
995
996    if (!(s->hdr_state & PNG_IHDR)) {
997        av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
998        return AVERROR_INVALIDDATA;
999    }
1000
1001    if (s->pic_state & PNG_IDAT) {
1002        av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
1003        return AVERROR_INVALIDDATA;
1004    }
1005
1006    sequence_number = bytestream2_get_be32(gb);
1007    cur_w           = bytestream2_get_be32(gb);
1008    cur_h           = bytestream2_get_be32(gb);
1009    x_offset        = bytestream2_get_be32(gb);
1010    y_offset        = bytestream2_get_be32(gb);
1011    bytestream2_skip(gb, 4); /* delay_num (2), delay_den (2) */
1012    dispose_op      = bytestream2_get_byte(gb);
1013    blend_op        = bytestream2_get_byte(gb);
1014
1015    if (sequence_number == 0 &&
1016        (cur_w != s->width ||
1017         cur_h != s->height ||
1018         x_offset != 0 ||
1019         y_offset != 0) ||
1020        cur_w <= 0 || cur_h <= 0 ||
1021        x_offset < 0 || y_offset < 0 ||
1022        cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1023            return AVERROR_INVALIDDATA;
1024
1025    if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1026        av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1027        return AVERROR_INVALIDDATA;
1028    }
1029
1030    if ((sequence_number == 0 || !s->last_picture.f) &&
1031        dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1032        // No previous frame to revert to for the first frame
1033        // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1034        dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1035    }
1036
1037    if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1038            avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1039            avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1040            avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1041            avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1042            avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1043        )) {
1044        // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1045        blend_op = APNG_BLEND_OP_SOURCE;
1046    }
1047
1048    s->cur_w      = cur_w;
1049    s->cur_h      = cur_h;
1050    s->x_offset   = x_offset;
1051    s->y_offset   = y_offset;
1052    s->dispose_op = dispose_op;
1053    s->blend_op   = blend_op;
1054
1055    return 0;
1056}
1057
1058static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1059{
1060    int i, j;
1061    uint8_t *pd      = p->data[0];
1062    uint8_t *pd_last = s->last_picture.f->data[0];
1063    int ls = av_image_get_linesize(p->format, s->width, 0);
1064
1065    ls = FFMIN(ls, s->width * s->bpp);
1066
1067    ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1068    for (j = 0; j < s->height; j++) {
1069        for (i = 0; i < ls; i++)
1070            pd[i] += pd_last[i];
1071        pd      += p->linesize[0];
1072        pd_last += s->last_picture.f->linesize[0];
1073    }
1074}
1075
1076// divide by 255 and round to nearest
1077// apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1078#define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1079
1080static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1081                               AVFrame *p)
1082{
1083    uint8_t       *dst        = p->data[0];
1084    ptrdiff_t      dst_stride = p->linesize[0];
1085    const uint8_t *src        = s->last_picture.f->data[0];
1086    ptrdiff_t      src_stride = s->last_picture.f->linesize[0];
1087    const int      bpp        = s->color_type == PNG_COLOR_TYPE_PALETTE ? 4 : s->bpp;
1088
1089    size_t x, y;
1090
1091    if (s->blend_op == APNG_BLEND_OP_OVER &&
1092        avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1093        avctx->pix_fmt != AV_PIX_FMT_GRAY8A) {
1094        avpriv_request_sample(avctx, "Blending with pixel format %s",
1095                              av_get_pix_fmt_name(avctx->pix_fmt));
1096        return AVERROR_PATCHWELCOME;
1097    }
1098
1099    ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1100
1101    // copy unchanged rectangles from the last frame
1102    for (y = 0; y < s->y_offset; y++)
1103        memcpy(dst + y * dst_stride, src + y * src_stride, p->width * bpp);
1104    for (y = s->y_offset; y < s->y_offset + s->cur_h; y++) {
1105        memcpy(dst + y * dst_stride, src + y * src_stride, s->x_offset * bpp);
1106        memcpy(dst + y * dst_stride + (s->x_offset + s->cur_w) * bpp,
1107               src + y * src_stride + (s->x_offset + s->cur_w) * bpp,
1108               (p->width - s->cur_w - s->x_offset) * bpp);
1109    }
1110    for (y = s->y_offset + s->cur_h; y < p->height; y++)
1111        memcpy(dst + y * dst_stride, src + y * src_stride, p->width * bpp);
1112
1113    if (s->blend_op == APNG_BLEND_OP_OVER) {
1114        // Perform blending
1115        for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1116            uint8_t       *foreground = dst + dst_stride * y + bpp * s->x_offset;
1117            const uint8_t *background = src + src_stride * y + bpp * s->x_offset;
1118            for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += bpp, background += 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                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
1139                if (foreground_alpha == 255)
1140                    continue;
1141
1142                if (foreground_alpha == 0) {
1143                    memcpy(foreground, background, bpp);
1144                    continue;
1145                }
1146
1147                output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1148
1149                av_assert0(bpp <= 10);
1150
1151                for (b = 0; b < bpp - 1; ++b) {
1152                    if (output_alpha == 0) {
1153                        output[b] = 0;
1154                    } else if (background_alpha == 255) {
1155                        output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1156                    } else {
1157                        output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1158                    }
1159                }
1160                output[b] = output_alpha;
1161                memcpy(foreground, output, bpp);
1162            }
1163        }
1164    }
1165
1166    return 0;
1167}
1168
1169static void apng_reset_background(PNGDecContext *s, const AVFrame *p)
1170{
1171    // need to reset a rectangle to black
1172    av_unused int ret = av_frame_copy(s->picture.f, p);
1173    const int bpp = s->color_type == PNG_COLOR_TYPE_PALETTE ? 4 : s->bpp;
1174    const ptrdiff_t dst_stride = s->picture.f->linesize[0];
1175    uint8_t *dst = s->picture.f->data[0] + s->y_offset * dst_stride + bpp * s->x_offset;
1176
1177    av_assert1(ret >= 0);
1178
1179    for (size_t y = 0; y < s->cur_h; y++) {
1180        memset(dst, 0, bpp * s->cur_w);
1181        dst += dst_stride;
1182    }
1183}
1184
1185static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1186                               AVFrame *p, const AVPacket *avpkt)
1187{
1188    const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1189    uint32_t tag, length;
1190    int decode_next_dat = 0;
1191    int i, ret;
1192
1193    for (;;) {
1194        GetByteContext gb_chunk;
1195
1196        length = bytestream2_get_bytes_left(&s->gb);
1197        if (length <= 0) {
1198
1199            if (avctx->codec_id == AV_CODEC_ID_PNG &&
1200                avctx->skip_frame == AVDISCARD_ALL) {
1201                return 0;
1202            }
1203
1204            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1205                if (!(s->pic_state & PNG_IDAT))
1206                    return 0;
1207                else
1208                    goto exit_loop;
1209            }
1210            av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1211            if (   s->pic_state & PNG_ALLIMAGE
1212                && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1213                goto exit_loop;
1214            ret = AVERROR_INVALIDDATA;
1215            goto fail;
1216        }
1217
1218        length = bytestream2_get_be32(&s->gb);
1219        if (length > 0x7fffffff || length + 8 > bytestream2_get_bytes_left(&s->gb)) {
1220            av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1221            ret = AVERROR_INVALIDDATA;
1222            goto fail;
1223        }
1224        if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_IGNORE_ERR)) {
1225            uint32_t crc_sig = AV_RB32(s->gb.buffer + length + 4);
1226            uint32_t crc_cal = ~av_crc(crc_tab, UINT32_MAX, s->gb.buffer, length + 4);
1227            if (crc_sig ^ crc_cal) {
1228                av_log(avctx, AV_LOG_ERROR, "CRC mismatch in chunk");
1229                if (avctx->err_recognition & AV_EF_EXPLODE) {
1230                    av_log(avctx, AV_LOG_ERROR, ", quitting\n");
1231                    ret = AVERROR_INVALIDDATA;
1232                    goto fail;
1233                }
1234                av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1235                bytestream2_skip(&s->gb, length + 8); /* tag */
1236                continue;
1237            }
1238        }
1239        tag = bytestream2_get_le32(&s->gb);
1240        if (avctx->debug & FF_DEBUG_STARTCODE)
1241            av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1242                   av_fourcc2str(tag), length);
1243
1244        bytestream2_init(&gb_chunk, s->gb.buffer, length);
1245        bytestream2_skip(&s->gb, length + 4);
1246
1247        if (avctx->codec_id == AV_CODEC_ID_PNG &&
1248            avctx->skip_frame == AVDISCARD_ALL) {
1249            switch(tag) {
1250            case MKTAG('I', 'H', 'D', 'R'):
1251            case MKTAG('p', 'H', 'Y', 's'):
1252            case MKTAG('t', 'E', 'X', 't'):
1253            case MKTAG('I', 'D', 'A', 'T'):
1254            case MKTAG('t', 'R', 'N', 'S'):
1255                break;
1256            default:
1257                continue;
1258            }
1259        }
1260
1261        switch (tag) {
1262        case MKTAG('I', 'H', 'D', 'R'):
1263            if ((ret = decode_ihdr_chunk(avctx, s, &gb_chunk)) < 0)
1264                goto fail;
1265            break;
1266        case MKTAG('p', 'H', 'Y', 's'):
1267            if ((ret = decode_phys_chunk(avctx, s, &gb_chunk)) < 0)
1268                goto fail;
1269            break;
1270        case MKTAG('f', 'c', 'T', 'L'):
1271            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1272                continue;
1273            if ((ret = decode_fctl_chunk(avctx, s, &gb_chunk)) < 0)
1274                goto fail;
1275            decode_next_dat = 1;
1276            break;
1277        case MKTAG('f', 'd', 'A', 'T'):
1278            if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1279                continue;
1280            if (!decode_next_dat || bytestream2_get_bytes_left(&gb_chunk) < 4) {
1281                ret = AVERROR_INVALIDDATA;
1282                goto fail;
1283            }
1284            bytestream2_get_be32(&gb_chunk);
1285            /* fallthrough */
1286        case MKTAG('I', 'D', 'A', 'T'):
1287            if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1288                continue;
1289            if ((ret = decode_idat_chunk(avctx, s, &gb_chunk, p)) < 0)
1290                goto fail;
1291            break;
1292        case MKTAG('P', 'L', 'T', 'E'):
1293            decode_plte_chunk(avctx, s, &gb_chunk);
1294            break;
1295        case MKTAG('t', 'R', 'N', 'S'):
1296            decode_trns_chunk(avctx, s, &gb_chunk);
1297            break;
1298        case MKTAG('t', 'E', 'X', 't'):
1299            if (decode_text_chunk(s, &gb_chunk, 0) < 0)
1300                av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1301            break;
1302        case MKTAG('z', 'T', 'X', 't'):
1303            if (decode_text_chunk(s, &gb_chunk, 1) < 0)
1304                av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1305            break;
1306        case MKTAG('s', 'T', 'E', 'R'): {
1307            int mode = bytestream2_get_byte(&gb_chunk);
1308
1309            if (mode == 0 || mode == 1) {
1310                s->stereo_mode = mode;
1311            } else {
1312                 av_log(avctx, AV_LOG_WARNING,
1313                        "Unknown value in sTER chunk (%d)\n", mode);
1314            }
1315            break;
1316        }
1317        case MKTAG('i', 'C', 'C', 'P'): {
1318            if ((ret = decode_iccp_chunk(s, &gb_chunk)) < 0)
1319                goto fail;
1320            break;
1321        }
1322        case MKTAG('c', 'H', 'R', 'M'): {
1323            s->have_chrm = 1;
1324
1325            s->white_point[0] = bytestream2_get_be32(&gb_chunk);
1326            s->white_point[1] = bytestream2_get_be32(&gb_chunk);
1327
1328            /* RGB Primaries */
1329            for (i = 0; i < 3; i++) {
1330                s->display_primaries[i][0] = bytestream2_get_be32(&gb_chunk);
1331                s->display_primaries[i][1] = bytestream2_get_be32(&gb_chunk);
1332            }
1333
1334            break;
1335        }
1336        case MKTAG('g', 'A', 'M', 'A'): {
1337            AVBPrint bp;
1338            char *gamma_str;
1339            int num = bytestream2_get_be32(&gb_chunk);
1340
1341            av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1342            av_bprintf(&bp, "%i/%i", num, 100000);
1343            ret = av_bprint_finalize(&bp, &gamma_str);
1344            if (ret < 0)
1345                return ret;
1346
1347            av_dict_set(&s->frame_metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1348
1349            break;
1350        }
1351        case MKTAG('I', 'E', 'N', 'D'):
1352            if (!(s->pic_state & PNG_ALLIMAGE))
1353                av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1354            if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1355                ret = AVERROR_INVALIDDATA;
1356                goto fail;
1357            }
1358            goto exit_loop;
1359        }
1360    }
1361exit_loop:
1362
1363    if (!p)
1364        return AVERROR_INVALIDDATA;
1365
1366    if (avctx->codec_id == AV_CODEC_ID_PNG &&
1367        avctx->skip_frame == AVDISCARD_ALL) {
1368        return 0;
1369    }
1370
1371    if (percent_missing(s) > avctx->discard_damaged_percentage)
1372        return AVERROR_INVALIDDATA;
1373
1374    if (s->bits_per_pixel <= 4)
1375        handle_small_bpp(s, p);
1376
1377    if (s->color_type == PNG_COLOR_TYPE_PALETTE && avctx->codec_id == AV_CODEC_ID_APNG) {
1378        for (int y = 0; y < s->height; y++) {
1379            uint8_t *row = &p->data[0][p->linesize[0] * y];
1380
1381            for (int x = s->width - 1; x >= 0; x--) {
1382                const uint8_t idx = row[x];
1383
1384                row[4*x+2] =  s->palette[idx]        & 0xFF;
1385                row[4*x+1] = (s->palette[idx] >> 8 ) & 0xFF;
1386                row[4*x+0] = (s->palette[idx] >> 16) & 0xFF;
1387                row[4*x+3] =  s->palette[idx] >> 24;
1388            }
1389        }
1390    }
1391
1392    /* apply transparency if needed */
1393    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1394        size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1395        size_t raw_bpp = s->bpp - byte_depth;
1396        unsigned x, y;
1397
1398        av_assert0(s->bit_depth > 1);
1399
1400        for (y = 0; y < s->height; ++y) {
1401            uint8_t *row = &p->data[0][p->linesize[0] * y];
1402
1403            if (s->bpp == 2 && byte_depth == 1) {
1404                uint8_t *pixel = &row[2 * s->width - 1];
1405                uint8_t *rowp  = &row[1 * s->width - 1];
1406                int tcolor = s->transparent_color_be[0];
1407                for (x = s->width; x > 0; --x) {
1408                    *pixel-- = *rowp == tcolor ? 0 : 0xff;
1409                    *pixel-- = *rowp--;
1410                }
1411            } else if (s->bpp == 4 && byte_depth == 1) {
1412                uint8_t *pixel = &row[4 * s->width - 1];
1413                uint8_t *rowp  = &row[3 * s->width - 1];
1414                int tcolor = AV_RL24(s->transparent_color_be);
1415                for (x = s->width; x > 0; --x) {
1416                    *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1417                    *pixel-- = *rowp--;
1418                    *pixel-- = *rowp--;
1419                    *pixel-- = *rowp--;
1420                }
1421            } else {
1422                /* since we're updating in-place, we have to go from right to left */
1423                for (x = s->width; x > 0; --x) {
1424                    uint8_t *pixel = &row[s->bpp * (x - 1)];
1425                    memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1426
1427                    if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1428                        memset(&pixel[raw_bpp], 0, byte_depth);
1429                    } else {
1430                        memset(&pixel[raw_bpp], 0xff, byte_depth);
1431                    }
1432                }
1433            }
1434        }
1435    }
1436
1437    /* handle P-frames only if a predecessor frame is available */
1438    if (s->last_picture.f->data[0]) {
1439        if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1440            && s->last_picture.f->width == p->width
1441            && s->last_picture.f->height== p->height
1442            && s->last_picture.f->format== p->format
1443         ) {
1444            if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1445                handle_p_frame_png(s, p);
1446            else if (CONFIG_APNG_DECODER &&
1447                     avctx->codec_id == AV_CODEC_ID_APNG &&
1448                     (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1449                goto fail;
1450        }
1451    }
1452    if (CONFIG_APNG_DECODER && s->dispose_op == APNG_DISPOSE_OP_BACKGROUND)
1453        apng_reset_background(s, p);
1454
1455    ff_thread_report_progress(&s->picture, INT_MAX, 0);
1456
1457    return 0;
1458
1459fail:
1460    ff_thread_report_progress(&s->picture, INT_MAX, 0);
1461    return ret;
1462}
1463
1464static void clear_frame_metadata(PNGDecContext *s)
1465{
1466    av_freep(&s->iccp_data);
1467    s->iccp_data_len = 0;
1468    s->iccp_name[0]  = 0;
1469
1470    s->stereo_mode = -1;
1471
1472    s->have_chrm = 0;
1473
1474    av_dict_free(&s->frame_metadata);
1475}
1476
1477static int output_frame(PNGDecContext *s, AVFrame *f)
1478{
1479    int ret;
1480
1481    if (s->iccp_data) {
1482        AVFrameSideData *sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, s->iccp_data_len);
1483        if (!sd) {
1484            ret = AVERROR(ENOMEM);
1485            goto fail;
1486        }
1487        memcpy(sd->data, s->iccp_data, s->iccp_data_len);
1488
1489        av_dict_set(&sd->metadata, "name", s->iccp_name, 0);
1490    }
1491
1492    if (s->stereo_mode >= 0) {
1493        AVStereo3D *stereo3d = av_stereo3d_create_side_data(f);
1494        if (!stereo3d) {
1495            ret = AVERROR(ENOMEM);
1496            goto fail;
1497        }
1498
1499        stereo3d->type  = AV_STEREO3D_SIDEBYSIDE;
1500        stereo3d->flags = s->stereo_mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1501    }
1502
1503    if (s->have_chrm) {
1504        AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(f);
1505        if (!mdm) {
1506            ret = AVERROR(ENOMEM);
1507            goto fail;
1508        }
1509
1510        mdm->white_point[0] = av_make_q(s->white_point[0], 100000);
1511        mdm->white_point[1] = av_make_q(s->white_point[1], 100000);
1512
1513        /* RGB Primaries */
1514        for (int i = 0; i < 3; i++) {
1515            mdm->display_primaries[i][0] = av_make_q(s->display_primaries[i][0], 100000);
1516            mdm->display_primaries[i][1] = av_make_q(s->display_primaries[i][1], 100000);
1517        }
1518
1519        mdm->has_primaries = 1;
1520    }
1521
1522    FFSWAP(AVDictionary*, f->metadata, s->frame_metadata);
1523
1524    return 0;
1525fail:
1526    av_frame_unref(f);
1527    return ret;
1528}
1529
1530#if CONFIG_PNG_DECODER
1531static int decode_frame_png(AVCodecContext *avctx, AVFrame *p,
1532                            int *got_frame, AVPacket *avpkt)
1533{
1534    PNGDecContext *const s = avctx->priv_data;
1535    const uint8_t *buf     = avpkt->data;
1536    int buf_size           = avpkt->size;
1537    int64_t sig;
1538    int ret;
1539
1540    clear_frame_metadata(s);
1541
1542    bytestream2_init(&s->gb, buf, buf_size);
1543
1544    /* check signature */
1545    sig = bytestream2_get_be64(&s->gb);
1546    if (sig != PNGSIG &&
1547        sig != MNGSIG) {
1548        av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1549        return AVERROR_INVALIDDATA;
1550    }
1551
1552    s->y = s->has_trns = 0;
1553    s->hdr_state = 0;
1554    s->pic_state = 0;
1555
1556    /* Reset z_stream */
1557    ret = inflateReset(&s->zstream.zstream);
1558    if (ret != Z_OK)
1559        return AVERROR_EXTERNAL;
1560
1561    if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1562        goto the_end;
1563
1564    if (avctx->skip_frame == AVDISCARD_ALL) {
1565        *got_frame = 0;
1566        ret = bytestream2_tell(&s->gb);
1567        goto the_end;
1568    }
1569
1570    ret = output_frame(s, p);
1571    if (ret < 0)
1572        goto the_end;
1573
1574    if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1575        ff_thread_release_ext_buffer(avctx, &s->last_picture);
1576        FFSWAP(ThreadFrame, s->picture, s->last_picture);
1577    }
1578
1579    *got_frame = 1;
1580
1581    ret = bytestream2_tell(&s->gb);
1582the_end:
1583    s->crow_buf = NULL;
1584    return ret;
1585}
1586#endif
1587
1588#if CONFIG_APNG_DECODER
1589static int decode_frame_apng(AVCodecContext *avctx, AVFrame *p,
1590                             int *got_frame, AVPacket *avpkt)
1591{
1592    PNGDecContext *const s = avctx->priv_data;
1593    int ret;
1594
1595    clear_frame_metadata(s);
1596
1597    if (!(s->hdr_state & PNG_IHDR)) {
1598        if (!avctx->extradata_size)
1599            return AVERROR_INVALIDDATA;
1600
1601        if ((ret = inflateReset(&s->zstream.zstream)) != Z_OK)
1602            return AVERROR_EXTERNAL;
1603        bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1604        if ((ret = decode_frame_common(avctx, s, NULL, avpkt)) < 0)
1605            return ret;
1606    }
1607
1608    /* reset state for a new frame */
1609    if ((ret = inflateReset(&s->zstream.zstream)) != Z_OK)
1610        return AVERROR_EXTERNAL;
1611    s->y = 0;
1612    s->pic_state = 0;
1613    bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1614    if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1615        return ret;
1616
1617    if (!(s->pic_state & PNG_ALLIMAGE))
1618        av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1619    if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT)))
1620        return AVERROR_INVALIDDATA;
1621
1622    ret = output_frame(s, p);
1623    if (ret < 0)
1624        return ret;
1625
1626    if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1627        if (s->dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1628            ff_thread_release_ext_buffer(avctx, &s->picture);
1629        } else {
1630            ff_thread_release_ext_buffer(avctx, &s->last_picture);
1631            FFSWAP(ThreadFrame, s->picture, s->last_picture);
1632        }
1633    }
1634
1635    *got_frame = 1;
1636    return bytestream2_tell(&s->gb);
1637}
1638#endif
1639
1640#if HAVE_THREADS
1641static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1642{
1643    PNGDecContext *psrc = src->priv_data;
1644    PNGDecContext *pdst = dst->priv_data;
1645    ThreadFrame *src_frame = NULL;
1646    int ret;
1647
1648    if (dst == src)
1649        return 0;
1650
1651    if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1652
1653        pdst->width             = psrc->width;
1654        pdst->height            = psrc->height;
1655        pdst->bit_depth         = psrc->bit_depth;
1656        pdst->color_type        = psrc->color_type;
1657        pdst->compression_type  = psrc->compression_type;
1658        pdst->interlace_type    = psrc->interlace_type;
1659        pdst->filter_type       = psrc->filter_type;
1660        pdst->has_trns = psrc->has_trns;
1661        memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1662
1663        memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1664
1665        pdst->hdr_state |= psrc->hdr_state;
1666    }
1667
1668    src_frame = psrc->dispose_op == APNG_DISPOSE_OP_PREVIOUS ?
1669                &psrc->last_picture : &psrc->picture;
1670
1671    ff_thread_release_ext_buffer(dst, &pdst->last_picture);
1672    if (src_frame && src_frame->f->data[0]) {
1673        ret = ff_thread_ref_frame(&pdst->last_picture, src_frame);
1674        if (ret < 0)
1675            return ret;
1676    }
1677
1678    return 0;
1679}
1680#endif
1681
1682static av_cold int png_dec_init(AVCodecContext *avctx)
1683{
1684    PNGDecContext *s = avctx->priv_data;
1685
1686    avctx->color_range = AVCOL_RANGE_JPEG;
1687
1688    s->avctx = avctx;
1689    s->last_picture.f = av_frame_alloc();
1690    s->picture.f = av_frame_alloc();
1691    if (!s->last_picture.f || !s->picture.f)
1692        return AVERROR(ENOMEM);
1693
1694    ff_pngdsp_init(&s->dsp);
1695
1696    return ff_inflate_init(&s->zstream, avctx);
1697}
1698
1699static av_cold int png_dec_end(AVCodecContext *avctx)
1700{
1701    PNGDecContext *s = avctx->priv_data;
1702
1703    ff_thread_release_ext_buffer(avctx, &s->last_picture);
1704    av_frame_free(&s->last_picture.f);
1705    ff_thread_release_ext_buffer(avctx, &s->picture);
1706    av_frame_free(&s->picture.f);
1707    av_freep(&s->buffer);
1708    s->buffer_size = 0;
1709    av_freep(&s->last_row);
1710    s->last_row_size = 0;
1711    av_freep(&s->tmp_row);
1712    s->tmp_row_size = 0;
1713
1714    av_freep(&s->iccp_data);
1715    av_dict_free(&s->frame_metadata);
1716    ff_inflate_end(&s->zstream);
1717
1718    return 0;
1719}
1720
1721#if CONFIG_APNG_DECODER
1722const FFCodec ff_apng_decoder = {
1723    .p.name         = "apng",
1724    .p.long_name    = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1725    .p.type         = AVMEDIA_TYPE_VIDEO,
1726    .p.id           = AV_CODEC_ID_APNG,
1727    .priv_data_size = sizeof(PNGDecContext),
1728    .init           = png_dec_init,
1729    .close          = png_dec_end,
1730    FF_CODEC_DECODE_CB(decode_frame_apng),
1731    .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1732    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1733    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP |
1734                      FF_CODEC_CAP_ALLOCATE_PROGRESS,
1735};
1736#endif
1737
1738#if CONFIG_PNG_DECODER
1739const FFCodec ff_png_decoder = {
1740    .p.name         = "png",
1741    .p.long_name    = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1742    .p.type         = AVMEDIA_TYPE_VIDEO,
1743    .p.id           = AV_CODEC_ID_PNG,
1744    .priv_data_size = sizeof(PNGDecContext),
1745    .init           = png_dec_init,
1746    .close          = png_dec_end,
1747    FF_CODEC_DECODE_CB(decode_frame_png),
1748    .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1749    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1750    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1751                      FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
1752};
1753#endif
1754