]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngdec.c
Merge commit '4fee11ab05fc8569ef35c0ce86a60375c903eefb'
[ffmpeg] / libavcodec / pngdec.c
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/bprint.h"
25 #include "libavutil/imgutils.h"
26 #include "avcodec.h"
27 #include "bytestream.h"
28 #include "internal.h"
29 #include "apng.h"
30 #include "png.h"
31 #include "pngdsp.h"
32 #include "thread.h"
33
34 #include <zlib.h>
35
36 typedef struct PNGDecContext {
37     PNGDSPContext dsp;
38     AVCodecContext *avctx;
39
40     GetByteContext gb;
41     ThreadFrame previous_picture;
42     ThreadFrame last_picture;
43     ThreadFrame picture;
44
45     int state;
46     int width, height;
47     int cur_w, cur_h;
48     int last_w, last_h;
49     int x_offset, y_offset;
50     int last_x_offset, last_y_offset;
51     uint8_t dispose_op, blend_op;
52     uint8_t last_dispose_op;
53     int bit_depth;
54     int color_type;
55     int compression_type;
56     int interlace_type;
57     int filter_type;
58     int channels;
59     int bits_per_pixel;
60     int bpp;
61     int has_trns;
62
63     uint8_t *image_buf;
64     int image_linesize;
65     uint32_t palette[256];
66     uint8_t *crow_buf;
67     uint8_t *last_row;
68     unsigned int last_row_size;
69     uint8_t *tmp_row;
70     unsigned int tmp_row_size;
71     uint8_t *buffer;
72     int buffer_size;
73     int pass;
74     int crow_size; /* compressed row size (include filter type) */
75     int row_size; /* decompressed row size */
76     int pass_row_size; /* decompress row size of the current pass */
77     int y;
78     z_stream zstream;
79 } PNGDecContext;
80
81 /* Mask to determine which pixels are valid in a pass */
82 static const uint8_t png_pass_mask[NB_PASSES] = {
83     0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
84 };
85
86 /* Mask to determine which y pixels can be written in a pass */
87 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
88     0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
89 };
90
91 /* Mask to determine which pixels to overwrite while displaying */
92 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
93     0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
94 };
95
96 /* NOTE: we try to construct a good looking image at each pass. width
97  * is the original image width. We also do pixel format conversion at
98  * this stage */
99 static void png_put_interlaced_row(uint8_t *dst, int width,
100                                    int bits_per_pixel, int pass,
101                                    int color_type, const uint8_t *src)
102 {
103     int x, mask, dsp_mask, j, src_x, b, bpp;
104     uint8_t *d;
105     const uint8_t *s;
106
107     mask     = png_pass_mask[pass];
108     dsp_mask = png_pass_dsp_mask[pass];
109
110     switch (bits_per_pixel) {
111     case 1:
112         src_x = 0;
113         for (x = 0; x < width; x++) {
114             j = (x & 7);
115             if ((dsp_mask << j) & 0x80) {
116                 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
117                 dst[x >> 3] &= 0xFF7F>>j;
118                 dst[x >> 3] |= b << (7 - j);
119             }
120             if ((mask << j) & 0x80)
121                 src_x++;
122         }
123         break;
124     case 2:
125         src_x = 0;
126         for (x = 0; x < width; x++) {
127             int j2 = 2 * (x & 3);
128             j = (x & 7);
129             if ((dsp_mask << j) & 0x80) {
130                 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
131                 dst[x >> 2] &= 0xFF3F>>j2;
132                 dst[x >> 2] |= b << (6 - j2);
133             }
134             if ((mask << j) & 0x80)
135                 src_x++;
136         }
137         break;
138     case 4:
139         src_x = 0;
140         for (x = 0; x < width; x++) {
141             int j2 = 4*(x&1);
142             j = (x & 7);
143             if ((dsp_mask << j) & 0x80) {
144                 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
145                 dst[x >> 1] &= 0xFF0F>>j2;
146                 dst[x >> 1] |= b << (4 - j2);
147             }
148             if ((mask << j) & 0x80)
149                 src_x++;
150         }
151         break;
152     default:
153         bpp = bits_per_pixel >> 3;
154         d   = dst;
155         s   = src;
156             for (x = 0; x < width; x++) {
157                 j = x & 7;
158                 if ((dsp_mask << j) & 0x80) {
159                     memcpy(d, s, bpp);
160                 }
161                 d += bpp;
162                 if ((mask << j) & 0x80)
163                     s += bpp;
164             }
165         break;
166     }
167 }
168
169 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
170                                  int w, int bpp)
171 {
172     int i;
173     for (i = 0; i < w; i++) {
174         int a, b, c, p, pa, pb, pc;
175
176         a = dst[i - bpp];
177         b = top[i];
178         c = top[i - bpp];
179
180         p  = b - c;
181         pc = a - c;
182
183         pa = abs(p);
184         pb = abs(pc);
185         pc = abs(p + pc);
186
187         if (pa <= pb && pa <= pc)
188             p = a;
189         else if (pb <= pc)
190             p = b;
191         else
192             p = c;
193         dst[i] = p + src[i];
194     }
195 }
196
197 #define UNROLL1(bpp, op)                                                      \
198     {                                                                         \
199         r = dst[0];                                                           \
200         if (bpp >= 2)                                                         \
201             g = dst[1];                                                       \
202         if (bpp >= 3)                                                         \
203             b = dst[2];                                                       \
204         if (bpp >= 4)                                                         \
205             a = dst[3];                                                       \
206         for (; i <= size - bpp; i += bpp) {                                   \
207             dst[i + 0] = r = op(r, src[i + 0], last[i + 0]);                  \
208             if (bpp == 1)                                                     \
209                 continue;                                                     \
210             dst[i + 1] = g = op(g, src[i + 1], last[i + 1]);                  \
211             if (bpp == 2)                                                     \
212                 continue;                                                     \
213             dst[i + 2] = b = op(b, src[i + 2], last[i + 2]);                  \
214             if (bpp == 3)                                                     \
215                 continue;                                                     \
216             dst[i + 3] = a = op(a, src[i + 3], last[i + 3]);                  \
217         }                                                                     \
218     }
219
220 #define UNROLL_FILTER(op)                                                     \
221     if (bpp == 1) {                                                           \
222         UNROLL1(1, op)                                                        \
223     } else if (bpp == 2) {                                                    \
224         UNROLL1(2, op)                                                        \
225     } else if (bpp == 3) {                                                    \
226         UNROLL1(3, op)                                                        \
227     } else if (bpp == 4) {                                                    \
228         UNROLL1(4, op)                                                        \
229     }                                                                         \
230     for (; i < size; i++) {                                                   \
231         dst[i] = op(dst[i - bpp], src[i], last[i]);                           \
232     }
233
234 /* NOTE: 'dst' can be equal to 'last' */
235 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
236                            uint8_t *src, uint8_t *last, int size, int bpp)
237 {
238     int i, p, r, g, b, a;
239
240     switch (filter_type) {
241     case PNG_FILTER_VALUE_NONE:
242         memcpy(dst, src, size);
243         break;
244     case PNG_FILTER_VALUE_SUB:
245         for (i = 0; i < bpp; i++)
246             dst[i] = src[i];
247         if (bpp == 4) {
248             p = *(int *)dst;
249             for (; i < size; i += bpp) {
250                 unsigned s = *(int *)(src + i);
251                 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
252                 *(int *)(dst + i) = p;
253             }
254         } else {
255 #define OP_SUB(x, s, l) ((x) + (s))
256             UNROLL_FILTER(OP_SUB);
257         }
258         break;
259     case PNG_FILTER_VALUE_UP:
260         dsp->add_bytes_l2(dst, src, last, size);
261         break;
262     case PNG_FILTER_VALUE_AVG:
263         for (i = 0; i < bpp; i++) {
264             p      = (last[i] >> 1);
265             dst[i] = p + src[i];
266         }
267 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
268         UNROLL_FILTER(OP_AVG);
269         break;
270     case PNG_FILTER_VALUE_PAETH:
271         for (i = 0; i < bpp; i++) {
272             p      = last[i];
273             dst[i] = p + src[i];
274         }
275         if (bpp > 2 && size > 4) {
276             /* would write off the end of the array if we let it process
277              * the last pixel with bpp=3 */
278             int w = (bpp & 3) ? size - 3 : size;
279
280             if (w > i) {
281                 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
282                 i = w;
283             }
284         }
285         ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
286         break;
287     }
288 }
289
290 /* This used to be called "deloco" in FFmpeg
291  * and is actually an inverse reversible colorspace transformation */
292 #define YUV2RGB(NAME, TYPE) \
293 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
294 { \
295     int i; \
296     for (i = 0; i < size; i += 3 + alpha) { \
297         int g = dst [i + 1]; \
298         dst[i + 0] += g; \
299         dst[i + 2] += g; \
300     } \
301 }
302
303 YUV2RGB(rgb8, uint8_t)
304 YUV2RGB(rgb16, uint16_t)
305
306 /* process exactly one decompressed row */
307 static void png_handle_row(PNGDecContext *s)
308 {
309     uint8_t *ptr, *last_row;
310     int got_line;
311
312     if (!s->interlace_type) {
313         ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
314         if (s->y == 0)
315             last_row = s->last_row;
316         else
317             last_row = ptr - s->image_linesize;
318
319         png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
320                        last_row, s->row_size, s->bpp);
321         /* loco lags by 1 row so that it doesn't interfere with top prediction */
322         if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
323             if (s->bit_depth == 16) {
324                 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
325                              s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
326             } else {
327                 deloco_rgb8(ptr - s->image_linesize, s->row_size,
328                             s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
329             }
330         }
331         s->y++;
332         if (s->y == s->cur_h) {
333             s->state |= PNG_ALLIMAGE;
334             if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
335                 if (s->bit_depth == 16) {
336                     deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
337                                  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
338                 } else {
339                     deloco_rgb8(ptr, s->row_size,
340                                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
341                 }
342             }
343         }
344     } else {
345         got_line = 0;
346         for (;;) {
347             ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
348             if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
349                 /* if we already read one row, it is time to stop to
350                  * wait for the next one */
351                 if (got_line)
352                     break;
353                 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
354                                s->last_row, s->pass_row_size, s->bpp);
355                 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
356                 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
357                 got_line = 1;
358             }
359             if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
360                 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
361                                        s->color_type, s->last_row);
362             }
363             s->y++;
364             if (s->y == s->cur_h) {
365                 memset(s->last_row, 0, s->row_size);
366                 for (;;) {
367                     if (s->pass == NB_PASSES - 1) {
368                         s->state |= PNG_ALLIMAGE;
369                         goto the_end;
370                     } else {
371                         s->pass++;
372                         s->y = 0;
373                         s->pass_row_size = ff_png_pass_row_size(s->pass,
374                                                                 s->bits_per_pixel,
375                                                                 s->cur_w);
376                         s->crow_size = s->pass_row_size + 1;
377                         if (s->pass_row_size != 0)
378                             break;
379                         /* skip pass if empty row */
380                     }
381                 }
382             }
383         }
384 the_end:;
385     }
386 }
387
388 static int png_decode_idat(PNGDecContext *s, int length)
389 {
390     int ret;
391     s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
392     s->zstream.next_in  = (unsigned char *)s->gb.buffer;
393     bytestream2_skip(&s->gb, length);
394
395     /* decode one line if possible */
396     while (s->zstream.avail_in > 0) {
397         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
398         if (ret != Z_OK && ret != Z_STREAM_END) {
399             av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
400             return AVERROR_EXTERNAL;
401         }
402         if (s->zstream.avail_out == 0) {
403             if (!(s->state & PNG_ALLIMAGE)) {
404                 png_handle_row(s);
405             }
406             s->zstream.avail_out = s->crow_size;
407             s->zstream.next_out  = s->crow_buf;
408         }
409         if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
410             av_log(NULL, AV_LOG_WARNING,
411                    "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
412             return 0;
413         }
414     }
415     return 0;
416 }
417
418 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
419                        const uint8_t *data_end)
420 {
421     z_stream zstream;
422     unsigned char *buf;
423     unsigned buf_size;
424     int ret;
425
426     zstream.zalloc = ff_png_zalloc;
427     zstream.zfree  = ff_png_zfree;
428     zstream.opaque = NULL;
429     if (inflateInit(&zstream) != Z_OK)
430         return AVERROR_EXTERNAL;
431     zstream.next_in  = (unsigned char *)data;
432     zstream.avail_in = data_end - data;
433     av_bprint_init(bp, 0, -1);
434
435     while (zstream.avail_in > 0) {
436         av_bprint_get_buffer(bp, 1, &buf, &buf_size);
437         if (!buf_size) {
438             ret = AVERROR(ENOMEM);
439             goto fail;
440         }
441         zstream.next_out  = buf;
442         zstream.avail_out = buf_size;
443         ret = inflate(&zstream, Z_PARTIAL_FLUSH);
444         if (ret != Z_OK && ret != Z_STREAM_END) {
445             ret = AVERROR_EXTERNAL;
446             goto fail;
447         }
448         bp->len += zstream.next_out - buf;
449         if (ret == Z_STREAM_END)
450             break;
451     }
452     inflateEnd(&zstream);
453     bp->str[bp->len] = 0;
454     return 0;
455
456 fail:
457     inflateEnd(&zstream);
458     av_bprint_finalize(bp, NULL);
459     return ret;
460 }
461
462 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
463 {
464     size_t extra = 0, i;
465     uint8_t *out, *q;
466
467     for (i = 0; i < size_in; i++)
468         extra += in[i] >= 0x80;
469     if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
470         return NULL;
471     q = out = av_malloc(size_in + extra + 1);
472     if (!out)
473         return NULL;
474     for (i = 0; i < size_in; i++) {
475         if (in[i] >= 0x80) {
476             *(q++) = 0xC0 | (in[i] >> 6);
477             *(q++) = 0x80 | (in[i] & 0x3F);
478         } else {
479             *(q++) = in[i];
480         }
481     }
482     *(q++) = 0;
483     return out;
484 }
485
486 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
487                              AVDictionary **dict)
488 {
489     int ret, method;
490     const uint8_t *data        = s->gb.buffer;
491     const uint8_t *data_end    = data + length;
492     const uint8_t *keyword     = data;
493     const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
494     uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
495     unsigned text_len;
496     AVBPrint bp;
497
498     if (!keyword_end)
499         return AVERROR_INVALIDDATA;
500     data = keyword_end + 1;
501
502     if (compressed) {
503         if (data == data_end)
504             return AVERROR_INVALIDDATA;
505         method = *(data++);
506         if (method)
507             return AVERROR_INVALIDDATA;
508         if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
509             return ret;
510         text_len = bp.len;
511         av_bprint_finalize(&bp, (char **)&text);
512         if (!text)
513             return AVERROR(ENOMEM);
514     } else {
515         text = (uint8_t *)data;
516         text_len = data_end - text;
517     }
518
519     kw_utf8  = iso88591_to_utf8(keyword, keyword_end - keyword);
520     txt_utf8 = iso88591_to_utf8(text, text_len);
521     if (text != data)
522         av_free(text);
523     if (!(kw_utf8 && txt_utf8)) {
524         av_free(kw_utf8);
525         av_free(txt_utf8);
526         return AVERROR(ENOMEM);
527     }
528
529     av_dict_set(dict, kw_utf8, txt_utf8,
530                 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
531     return 0;
532 }
533
534 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
535                              uint32_t length)
536 {
537     if (length != 13)
538         return AVERROR_INVALIDDATA;
539
540     if (s->state & PNG_IDAT) {
541         av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
542         return AVERROR_INVALIDDATA;
543     }
544
545     if (s->state & PNG_IHDR) {
546         av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
547         return AVERROR_INVALIDDATA;
548     }
549
550     s->width  = s->cur_w = bytestream2_get_be32(&s->gb);
551     s->height = s->cur_h = bytestream2_get_be32(&s->gb);
552     if (av_image_check_size(s->width, s->height, 0, avctx)) {
553         s->cur_w = s->cur_h = s->width = s->height = 0;
554         av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
555         return AVERROR_INVALIDDATA;
556     }
557     s->bit_depth        = bytestream2_get_byte(&s->gb);
558     s->color_type       = bytestream2_get_byte(&s->gb);
559     s->compression_type = bytestream2_get_byte(&s->gb);
560     s->filter_type      = bytestream2_get_byte(&s->gb);
561     s->interlace_type   = bytestream2_get_byte(&s->gb);
562     bytestream2_skip(&s->gb, 4); /* crc */
563     s->state |= PNG_IHDR;
564     if (avctx->debug & FF_DEBUG_PICT_INFO)
565         av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
566                 "compression_type=%d filter_type=%d interlace_type=%d\n",
567                 s->width, s->height, s->bit_depth, s->color_type,
568                 s->compression_type, s->filter_type, s->interlace_type);
569
570     return 0;
571 }
572
573 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
574 {
575     if (s->state & PNG_IDAT) {
576         av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
577         return AVERROR_INVALIDDATA;
578     }
579     avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
580     avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
581     if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
582         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
583     bytestream2_skip(&s->gb, 1); /* unit specifier */
584     bytestream2_skip(&s->gb, 4); /* crc */
585
586     return 0;
587 }
588
589 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
590                              uint32_t length, AVFrame *p)
591 {
592     int ret;
593
594     if (!(s->state & PNG_IHDR)) {
595         av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
596         return AVERROR_INVALIDDATA;
597     }
598     if (!(s->state & PNG_IDAT)) {
599         /* init image info */
600         avctx->width  = s->width;
601         avctx->height = s->height;
602
603         s->channels       = ff_png_get_nb_channels(s->color_type);
604         s->bits_per_pixel = s->bit_depth * s->channels;
605         s->bpp            = (s->bits_per_pixel + 7) >> 3;
606         s->row_size       = (s->cur_w * s->bits_per_pixel + 7) >> 3;
607
608         if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
609                 s->color_type == PNG_COLOR_TYPE_RGB) {
610             avctx->pix_fmt = AV_PIX_FMT_RGB24;
611         } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
612                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
613             avctx->pix_fmt = AV_PIX_FMT_RGBA;
614         } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
615                 s->color_type == PNG_COLOR_TYPE_GRAY) {
616             avctx->pix_fmt = AV_PIX_FMT_GRAY8;
617         } else if (s->bit_depth == 16 &&
618                 s->color_type == PNG_COLOR_TYPE_GRAY) {
619             avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
620         } else if (s->bit_depth == 16 &&
621                 s->color_type == PNG_COLOR_TYPE_RGB) {
622             avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
623         } else if (s->bit_depth == 16 &&
624                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
625             avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
626         } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
627                 s->color_type == PNG_COLOR_TYPE_PALETTE) {
628             avctx->pix_fmt = AV_PIX_FMT_PAL8;
629         } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
630             avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
631         } else if (s->bit_depth == 8 &&
632                 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
633             avctx->pix_fmt = AV_PIX_FMT_YA8;
634         } else if (s->bit_depth == 16 &&
635                 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
636             avctx->pix_fmt = AV_PIX_FMT_YA16BE;
637         } else {
638             av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
639                     "and color type %d\n",
640                     s->bit_depth, s->color_type);
641             return AVERROR_INVALIDDATA;
642         }
643
644         if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
645             return ret;
646         if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
647             ff_thread_release_buffer(avctx, &s->previous_picture);
648             if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
649                 return ret;
650         }
651         ff_thread_finish_setup(avctx);
652
653         p->pict_type        = AV_PICTURE_TYPE_I;
654         p->key_frame        = 1;
655         p->interlaced_frame = !!s->interlace_type;
656
657         /* compute the compressed row size */
658         if (!s->interlace_type) {
659             s->crow_size = s->row_size + 1;
660         } else {
661             s->pass          = 0;
662             s->pass_row_size = ff_png_pass_row_size(s->pass,
663                     s->bits_per_pixel,
664                     s->cur_w);
665             s->crow_size = s->pass_row_size + 1;
666         }
667         ff_dlog(avctx, "row_size=%d crow_size =%d\n",
668                 s->row_size, s->crow_size);
669         s->image_buf      = p->data[0];
670         s->image_linesize = p->linesize[0];
671         /* copy the palette if needed */
672         if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
673             memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
674         /* empty row is used if differencing to the first row */
675         av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
676         if (!s->last_row)
677             return AVERROR_INVALIDDATA;
678         if (s->interlace_type ||
679                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
680             av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
681             if (!s->tmp_row)
682                 return AVERROR_INVALIDDATA;
683         }
684         /* compressed row */
685         av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
686         if (!s->buffer)
687             return AVERROR(ENOMEM);
688
689         /* we want crow_buf+1 to be 16-byte aligned */
690         s->crow_buf          = s->buffer + 15;
691         s->zstream.avail_out = s->crow_size;
692         s->zstream.next_out  = s->crow_buf;
693     }
694     s->state |= PNG_IDAT;
695     if ((ret = png_decode_idat(s, length)) < 0)
696         return ret;
697     bytestream2_skip(&s->gb, 4); /* crc */
698
699     return 0;
700 }
701
702 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
703                              uint32_t length)
704 {
705     int n, i, r, g, b;
706
707     if ((length % 3) != 0 || length > 256 * 3)
708         return AVERROR_INVALIDDATA;
709     /* read the palette */
710     n = length / 3;
711     for (i = 0; i < n; i++) {
712         r = bytestream2_get_byte(&s->gb);
713         g = bytestream2_get_byte(&s->gb);
714         b = bytestream2_get_byte(&s->gb);
715         s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
716     }
717     for (; i < 256; i++)
718         s->palette[i] = (0xFFU << 24);
719     s->state |= PNG_PLTE;
720     bytestream2_skip(&s->gb, 4);     /* crc */
721
722     return 0;
723 }
724
725 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
726                              uint32_t length)
727 {
728     int v, i;
729
730     /* read the transparency. XXX: Only palette mode supported */
731     if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
732             length > 256 ||
733             !(s->state & PNG_PLTE))
734         return AVERROR_INVALIDDATA;
735     for (i = 0; i < length; i++) {
736         v = bytestream2_get_byte(&s->gb);
737         s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
738     }
739     bytestream2_skip(&s->gb, 4);     /* crc */
740
741     s->has_trns = 1;
742
743     return 0;
744 }
745
746 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
747 {
748     if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
749         int i, j, k;
750         uint8_t *pd = p->data[0];
751         for (j = 0; j < s->height; j++) {
752             i = s->width / 8;
753             for (k = 7; k >= 1; k--)
754                 if ((s->width&7) >= k)
755                     pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
756             for (i--; i >= 0; i--) {
757                 pd[8*i + 7]=  pd[i]     & 1;
758                 pd[8*i + 6]= (pd[i]>>1) & 1;
759                 pd[8*i + 5]= (pd[i]>>2) & 1;
760                 pd[8*i + 4]= (pd[i]>>3) & 1;
761                 pd[8*i + 3]= (pd[i]>>4) & 1;
762                 pd[8*i + 2]= (pd[i]>>5) & 1;
763                 pd[8*i + 1]= (pd[i]>>6) & 1;
764                 pd[8*i + 0]=  pd[i]>>7;
765             }
766             pd += s->image_linesize;
767         }
768     } else if (s->bits_per_pixel == 2) {
769         int i, j;
770         uint8_t *pd = p->data[0];
771         for (j = 0; j < s->height; j++) {
772             i = s->width / 4;
773             if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
774                 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
775                 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
776                 if ((s->width&3) >= 1) pd[4*i + 0]=  pd[i] >> 6;
777                 for (i--; i >= 0; i--) {
778                     pd[4*i + 3]=  pd[i]     & 3;
779                     pd[4*i + 2]= (pd[i]>>2) & 3;
780                     pd[4*i + 1]= (pd[i]>>4) & 3;
781                     pd[4*i + 0]=  pd[i]>>6;
782                 }
783             } else {
784                 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
785                 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
786                 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6     )*0x55;
787                 for (i--; i >= 0; i--) {
788                     pd[4*i + 3]= ( pd[i]     & 3)*0x55;
789                     pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
790                     pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
791                     pd[4*i + 0]= ( pd[i]>>6     )*0x55;
792                 }
793             }
794             pd += s->image_linesize;
795         }
796     } else if (s->bits_per_pixel == 4) {
797         int i, j;
798         uint8_t *pd = p->data[0];
799         for (j = 0; j < s->height; j++) {
800             i = s->width/2;
801             if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
802                 if (s->width&1) pd[2*i+0]= pd[i]>>4;
803                 for (i--; i >= 0; i--) {
804                     pd[2*i + 1] = pd[i] & 15;
805                     pd[2*i + 0] = pd[i] >> 4;
806                 }
807             } else {
808                 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
809                 for (i--; i >= 0; i--) {
810                     pd[2*i + 1] = (pd[i] & 15) * 0x11;
811                     pd[2*i + 0] = (pd[i] >> 4) * 0x11;
812                 }
813             }
814             pd += s->image_linesize;
815         }
816     }
817 }
818
819 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
820                              uint32_t length)
821 {
822     uint32_t sequence_number;
823     int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
824
825     if (length != 26)
826         return AVERROR_INVALIDDATA;
827
828     if (!(s->state & PNG_IHDR)) {
829         av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
830         return AVERROR_INVALIDDATA;
831     }
832
833     s->last_w = s->cur_w;
834     s->last_h = s->cur_h;
835     s->last_x_offset = s->x_offset;
836     s->last_y_offset = s->y_offset;
837     s->last_dispose_op = s->dispose_op;
838
839     sequence_number = bytestream2_get_be32(&s->gb);
840     cur_w           = bytestream2_get_be32(&s->gb);
841     cur_h           = bytestream2_get_be32(&s->gb);
842     x_offset        = bytestream2_get_be32(&s->gb);
843     y_offset        = bytestream2_get_be32(&s->gb);
844     bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
845     dispose_op      = bytestream2_get_byte(&s->gb);
846     blend_op        = bytestream2_get_byte(&s->gb);
847     bytestream2_skip(&s->gb, 4); /* crc */
848
849     if (sequence_number == 0 &&
850         (cur_w != s->width ||
851          cur_h != s->height ||
852          x_offset != 0 ||
853          y_offset != 0) ||
854         cur_w <= 0 || cur_h <= 0 ||
855         x_offset < 0 || y_offset < 0 ||
856         cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
857             return AVERROR_INVALIDDATA;
858
859     if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
860         // No previous frame to revert to for the first frame
861         // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
862         dispose_op = APNG_DISPOSE_OP_BACKGROUND;
863     }
864
865     if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
866             avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
867             avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
868             avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
869             avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
870             avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
871             avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
872         )) {
873         // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
874         blend_op = APNG_BLEND_OP_SOURCE;
875     }
876
877     s->cur_w      = cur_w;
878     s->cur_h      = cur_h;
879     s->x_offset   = x_offset;
880     s->y_offset   = y_offset;
881     s->dispose_op = dispose_op;
882     s->blend_op   = blend_op;
883
884     return 0;
885 }
886
887 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
888 {
889     int i, j;
890     uint8_t *pd      = p->data[0];
891     uint8_t *pd_last = s->last_picture.f->data[0];
892     int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
893
894     ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
895     for (j = 0; j < s->height; j++) {
896         for (i = 0; i < ls; i++)
897             pd[i] += pd_last[i];
898         pd      += s->image_linesize;
899         pd_last += s->image_linesize;
900     }
901 }
902
903 // divide by 255 and round to nearest
904 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
905 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
906
907 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
908                                AVFrame *p)
909 {
910     size_t x, y;
911     uint8_t *buffer = av_malloc(s->image_linesize * s->height);
912
913     if (!buffer)
914         return AVERROR(ENOMEM);
915
916     if (s->blend_op == APNG_BLEND_OP_OVER &&
917         avctx->pix_fmt != AV_PIX_FMT_RGBA &&
918         avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
919         avctx->pix_fmt != AV_PIX_FMT_PAL8) {
920         avpriv_request_sample(avctx, "Blending with pixel format %s",
921                               av_get_pix_fmt_name(avctx->pix_fmt));
922         return AVERROR_PATCHWELCOME;
923     }
924
925     // Do the disposal operation specified by the last frame on the frame
926     if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
927         ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
928         memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
929
930         if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
931             for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
932                 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
933
934         memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
935         ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
936     } else {
937         ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
938         memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
939     }
940
941     // Perform blending
942     if (s->blend_op == APNG_BLEND_OP_SOURCE) {
943         for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
944             size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
945             memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
946         }
947     } else { // APNG_BLEND_OP_OVER
948         for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
949             uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
950             uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
951             for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
952                 size_t b;
953                 uint8_t foreground_alpha, background_alpha, output_alpha;
954                 uint8_t output[4];
955
956                 // Since we might be blending alpha onto alpha, we use the following equations:
957                 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
958                 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
959
960                 switch (avctx->pix_fmt) {
961                 case AV_PIX_FMT_RGBA:
962                     foreground_alpha = foreground[3];
963                     background_alpha = background[3];
964                     break;
965
966                 case AV_PIX_FMT_GRAY8A:
967                     foreground_alpha = foreground[1];
968                     background_alpha = background[1];
969                     break;
970
971                 case AV_PIX_FMT_PAL8:
972                     foreground_alpha = s->palette[foreground[0]] >> 24;
973                     background_alpha = s->palette[background[0]] >> 24;
974                     break;
975                 }
976
977                 if (foreground_alpha == 0)
978                     continue;
979
980                 if (foreground_alpha == 255) {
981                     memcpy(background, foreground, s->bpp);
982                     continue;
983                 }
984
985                 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
986                     // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
987                     avpriv_request_sample(avctx, "Alpha blending palette samples");
988                     background[0] = foreground[0];
989                     continue;
990                 }
991
992                 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
993
994                 for (b = 0; b < s->bpp - 1; ++b) {
995                     if (output_alpha == 0) {
996                         output[b] = 0;
997                     } else if (background_alpha == 255) {
998                         output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
999                     } else {
1000                         output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1001                     }
1002                 }
1003                 output[b] = output_alpha;
1004                 memcpy(background, output, s->bpp);
1005             }
1006         }
1007     }
1008
1009     // Copy blended buffer into the frame and free
1010     memcpy(p->data[0], buffer, s->image_linesize * s->height);
1011     av_free(buffer);
1012
1013     return 0;
1014 }
1015
1016 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1017                                AVFrame *p, AVPacket *avpkt)
1018 {
1019     AVDictionary *metadata  = NULL;
1020     uint32_t tag, length;
1021     int decode_next_dat = 0;
1022     int ret;
1023
1024     for (;;) {
1025         length = bytestream2_get_bytes_left(&s->gb);
1026         if (length <= 0) {
1027             if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1028                 if (!(s->state & PNG_IDAT))
1029                     return 0;
1030                 else
1031                     goto exit_loop;
1032             }
1033             av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1034             if (   s->state & PNG_ALLIMAGE
1035                 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1036                 goto exit_loop;
1037             ret = AVERROR_INVALIDDATA;
1038             goto fail;
1039         }
1040
1041         length = bytestream2_get_be32(&s->gb);
1042         if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1043             av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1044             ret = AVERROR_INVALIDDATA;
1045             goto fail;
1046         }
1047         tag = bytestream2_get_le32(&s->gb);
1048         if (avctx->debug & FF_DEBUG_STARTCODE)
1049             av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
1050                 (tag & 0xff),
1051                 ((tag >> 8) & 0xff),
1052                 ((tag >> 16) & 0xff),
1053                 ((tag >> 24) & 0xff), length);
1054         switch (tag) {
1055         case MKTAG('I', 'H', 'D', 'R'):
1056             if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1057                 goto fail;
1058             break;
1059         case MKTAG('p', 'H', 'Y', 's'):
1060             if ((ret = decode_phys_chunk(avctx, s)) < 0)
1061                 goto fail;
1062             break;
1063         case MKTAG('f', 'c', 'T', 'L'):
1064             if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1065                 goto skip_tag;
1066             if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1067                 goto fail;
1068             decode_next_dat = 1;
1069             break;
1070         case MKTAG('f', 'd', 'A', 'T'):
1071             if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1072                 goto skip_tag;
1073             if (!decode_next_dat) {
1074                 ret = AVERROR_INVALIDDATA;
1075                 goto fail;
1076             }
1077             bytestream2_get_be32(&s->gb);
1078             length -= 4;
1079             /* fallthrough */
1080         case MKTAG('I', 'D', 'A', 'T'):
1081             if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1082                 goto skip_tag;
1083             if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1084                 goto fail;
1085             break;
1086         case MKTAG('P', 'L', 'T', 'E'):
1087             if (decode_plte_chunk(avctx, s, length) < 0)
1088                 goto skip_tag;
1089             break;
1090         case MKTAG('t', 'R', 'N', 'S'):
1091             if (decode_trns_chunk(avctx, s, length) < 0)
1092                 goto skip_tag;
1093             break;
1094         case MKTAG('t', 'E', 'X', 't'):
1095             if (decode_text_chunk(s, length, 0, &metadata) < 0)
1096                 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1097             bytestream2_skip(&s->gb, length + 4);
1098             break;
1099         case MKTAG('z', 'T', 'X', 't'):
1100             if (decode_text_chunk(s, length, 1, &metadata) < 0)
1101                 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1102             bytestream2_skip(&s->gb, length + 4);
1103             break;
1104         case MKTAG('I', 'E', 'N', 'D'):
1105             if (!(s->state & PNG_ALLIMAGE))
1106                 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1107             if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1108                 ret = AVERROR_INVALIDDATA;
1109                 goto fail;
1110             }
1111             bytestream2_skip(&s->gb, 4); /* crc */
1112             goto exit_loop;
1113         default:
1114             /* skip tag */
1115 skip_tag:
1116             bytestream2_skip(&s->gb, length + 4);
1117             break;
1118         }
1119     }
1120 exit_loop:
1121
1122     if (s->bits_per_pixel <= 4)
1123         handle_small_bpp(s, p);
1124
1125     /* handle p-frames only if a predecessor frame is available */
1126     if (s->last_picture.f->data[0]) {
1127         if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1128             && s->last_picture.f->width == p->width
1129             && s->last_picture.f->height== p->height
1130             && s->last_picture.f->format== p->format
1131          ) {
1132             if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1133                 handle_p_frame_png(s, p);
1134             else if (CONFIG_APNG_DECODER &&
1135                      avctx->codec_id == AV_CODEC_ID_APNG &&
1136                      (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1137                 goto fail;
1138         }
1139     }
1140     ff_thread_report_progress(&s->picture, INT_MAX, 0);
1141
1142     av_frame_set_metadata(p, metadata);
1143     metadata   = NULL;
1144     return 0;
1145
1146 fail:
1147     av_dict_free(&metadata);
1148     ff_thread_report_progress(&s->picture, INT_MAX, 0);
1149     return ret;
1150 }
1151
1152 #if CONFIG_PNG_DECODER
1153 static int decode_frame_png(AVCodecContext *avctx,
1154                         void *data, int *got_frame,
1155                         AVPacket *avpkt)
1156 {
1157     PNGDecContext *const s = avctx->priv_data;
1158     const uint8_t *buf     = avpkt->data;
1159     int buf_size           = avpkt->size;
1160     AVFrame *p;
1161     int64_t sig;
1162     int ret;
1163
1164     ff_thread_release_buffer(avctx, &s->last_picture);
1165     FFSWAP(ThreadFrame, s->picture, s->last_picture);
1166     p = s->picture.f;
1167
1168     bytestream2_init(&s->gb, buf, buf_size);
1169
1170     /* check signature */
1171     sig = bytestream2_get_be64(&s->gb);
1172     if (sig != PNGSIG &&
1173         sig != MNGSIG) {
1174         av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1175         return AVERROR_INVALIDDATA;
1176     }
1177
1178     s->y = s->state = 0;
1179
1180     /* init the zlib */
1181     s->zstream.zalloc = ff_png_zalloc;
1182     s->zstream.zfree  = ff_png_zfree;
1183     s->zstream.opaque = NULL;
1184     ret = inflateInit(&s->zstream);
1185     if (ret != Z_OK) {
1186         av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1187         return AVERROR_EXTERNAL;
1188     }
1189
1190     if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1191         goto the_end;
1192
1193     if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1194         return ret;
1195
1196     *got_frame = 1;
1197
1198     ret = bytestream2_tell(&s->gb);
1199 the_end:
1200     inflateEnd(&s->zstream);
1201     s->crow_buf = NULL;
1202     return ret;
1203 }
1204 #endif
1205
1206 #if CONFIG_APNG_DECODER
1207 static int decode_frame_apng(AVCodecContext *avctx,
1208                         void *data, int *got_frame,
1209                         AVPacket *avpkt)
1210 {
1211     PNGDecContext *const s = avctx->priv_data;
1212     int ret;
1213     AVFrame *p;
1214
1215     ff_thread_release_buffer(avctx, &s->last_picture);
1216     FFSWAP(ThreadFrame, s->picture, s->last_picture);
1217     p = s->picture.f;
1218
1219     if (!(s->state & PNG_IHDR)) {
1220         if (!avctx->extradata_size)
1221             return AVERROR_INVALIDDATA;
1222
1223         /* only init fields, there is no zlib use in extradata */
1224         s->zstream.zalloc = ff_png_zalloc;
1225         s->zstream.zfree  = ff_png_zfree;
1226
1227         bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1228         if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1229             goto end;
1230     }
1231
1232     /* reset state for a new frame */
1233     if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1234         av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1235         ret = AVERROR_EXTERNAL;
1236         goto end;
1237     }
1238     s->y = 0;
1239     s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
1240     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1241     if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1242         goto end;
1243
1244     if (!(s->state & PNG_ALLIMAGE))
1245         av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1246     if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1247         ret = AVERROR_INVALIDDATA;
1248         goto end;
1249     }
1250     if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1251         goto end;
1252
1253     *got_frame = 1;
1254     ret = bytestream2_tell(&s->gb);
1255
1256 end:
1257     inflateEnd(&s->zstream);
1258     return ret;
1259 }
1260 #endif
1261
1262 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1263 {
1264     PNGDecContext *psrc = src->priv_data;
1265     PNGDecContext *pdst = dst->priv_data;
1266     int ret;
1267
1268     if (dst == src)
1269         return 0;
1270
1271     ff_thread_release_buffer(dst, &pdst->picture);
1272     if (psrc->picture.f->data[0] &&
1273         (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1274         return ret;
1275     if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1276         pdst->width             = psrc->width;
1277         pdst->height            = psrc->height;
1278         pdst->bit_depth         = psrc->bit_depth;
1279         pdst->color_type        = psrc->color_type;
1280         pdst->compression_type  = psrc->compression_type;
1281         pdst->interlace_type    = psrc->interlace_type;
1282         pdst->filter_type       = psrc->filter_type;
1283         pdst->cur_w = psrc->cur_w;
1284         pdst->cur_h = psrc->cur_h;
1285         pdst->x_offset = psrc->x_offset;
1286         pdst->y_offset = psrc->y_offset;
1287         pdst->has_trns = psrc->has_trns;
1288
1289         pdst->dispose_op = psrc->dispose_op;
1290
1291         memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1292
1293         pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
1294
1295         ff_thread_release_buffer(dst, &pdst->last_picture);
1296         if (psrc->last_picture.f->data[0] &&
1297             (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
1298             return ret;
1299
1300         ff_thread_release_buffer(dst, &pdst->previous_picture);
1301         if (psrc->previous_picture.f->data[0] &&
1302             (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
1303             return ret;
1304     }
1305
1306     return 0;
1307 }
1308
1309 static av_cold int png_dec_init(AVCodecContext *avctx)
1310 {
1311     PNGDecContext *s = avctx->priv_data;
1312
1313     avctx->color_range = AVCOL_RANGE_JPEG;
1314
1315     s->avctx = avctx;
1316     s->previous_picture.f = av_frame_alloc();
1317     s->last_picture.f = av_frame_alloc();
1318     s->picture.f = av_frame_alloc();
1319     if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1320         av_frame_free(&s->previous_picture.f);
1321         av_frame_free(&s->last_picture.f);
1322         av_frame_free(&s->picture.f);
1323         return AVERROR(ENOMEM);
1324     }
1325
1326     if (!avctx->internal->is_copy) {
1327         avctx->internal->allocate_progress = 1;
1328         ff_pngdsp_init(&s->dsp);
1329     }
1330
1331     return 0;
1332 }
1333
1334 static av_cold int png_dec_end(AVCodecContext *avctx)
1335 {
1336     PNGDecContext *s = avctx->priv_data;
1337
1338     ff_thread_release_buffer(avctx, &s->previous_picture);
1339     av_frame_free(&s->previous_picture.f);
1340     ff_thread_release_buffer(avctx, &s->last_picture);
1341     av_frame_free(&s->last_picture.f);
1342     ff_thread_release_buffer(avctx, &s->picture);
1343     av_frame_free(&s->picture.f);
1344     av_freep(&s->buffer);
1345     s->buffer_size = 0;
1346     av_freep(&s->last_row);
1347     s->last_row_size = 0;
1348     av_freep(&s->tmp_row);
1349     s->tmp_row_size = 0;
1350
1351     return 0;
1352 }
1353
1354 #if CONFIG_APNG_DECODER
1355 AVCodec ff_apng_decoder = {
1356     .name           = "apng",
1357     .long_name      = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1358     .type           = AVMEDIA_TYPE_VIDEO,
1359     .id             = AV_CODEC_ID_APNG,
1360     .priv_data_size = sizeof(PNGDecContext),
1361     .init           = png_dec_init,
1362     .close          = png_dec_end,
1363     .decode         = decode_frame_apng,
1364     .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1365     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1366     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1367 };
1368 #endif
1369
1370 #if CONFIG_PNG_DECODER
1371 AVCodec ff_png_decoder = {
1372     .name           = "png",
1373     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1374     .type           = AVMEDIA_TYPE_VIDEO,
1375     .id             = AV_CODEC_ID_PNG,
1376     .priv_data_size = sizeof(PNGDecContext),
1377     .init           = png_dec_init,
1378     .close          = png_dec_end,
1379     .decode         = decode_frame_png,
1380     .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1381     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1382     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1383 };
1384 #endif