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