]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngdec.c
Merge commit '504e3f75bf73a488d39a80a42962bae2a353dd6b'
[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 (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
916         av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
917         return AVERROR_INVALIDDATA;
918     }
919
920     if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
921         // No previous frame to revert to for the first frame
922         // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
923         dispose_op = APNG_DISPOSE_OP_BACKGROUND;
924     }
925
926     if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
927             avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
928             avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
929             avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
930             avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
931             avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
932             avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
933         )) {
934         // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
935         blend_op = APNG_BLEND_OP_SOURCE;
936     }
937
938     s->cur_w      = cur_w;
939     s->cur_h      = cur_h;
940     s->x_offset   = x_offset;
941     s->y_offset   = y_offset;
942     s->dispose_op = dispose_op;
943     s->blend_op   = blend_op;
944
945     return 0;
946 }
947
948 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
949 {
950     int i, j;
951     uint8_t *pd      = p->data[0];
952     uint8_t *pd_last = s->last_picture.f->data[0];
953     int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
954
955     ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
956     for (j = 0; j < s->height; j++) {
957         for (i = 0; i < ls; i++)
958             pd[i] += pd_last[i];
959         pd      += s->image_linesize;
960         pd_last += s->image_linesize;
961     }
962 }
963
964 // divide by 255 and round to nearest
965 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
966 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
967
968 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
969                                AVFrame *p)
970 {
971     size_t x, y;
972     uint8_t *buffer;
973
974     if (s->blend_op == APNG_BLEND_OP_OVER &&
975         avctx->pix_fmt != AV_PIX_FMT_RGBA &&
976         avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
977         avctx->pix_fmt != AV_PIX_FMT_PAL8) {
978         avpriv_request_sample(avctx, "Blending with pixel format %s",
979                               av_get_pix_fmt_name(avctx->pix_fmt));
980         return AVERROR_PATCHWELCOME;
981     }
982
983     buffer = av_malloc_array(s->image_linesize, s->height);
984     if (!buffer)
985         return AVERROR(ENOMEM);
986
987
988     // Do the disposal operation specified by the last frame on the frame
989     if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
990         ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
991         memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
992
993         if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
994             for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
995                 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
996
997         memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
998         ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
999     } else {
1000         ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
1001         memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
1002     }
1003
1004     // Perform blending
1005     if (s->blend_op == APNG_BLEND_OP_SOURCE) {
1006         for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1007             size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
1008             memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
1009         }
1010     } else { // APNG_BLEND_OP_OVER
1011         for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1012             uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
1013             uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
1014             for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1015                 size_t b;
1016                 uint8_t foreground_alpha, background_alpha, output_alpha;
1017                 uint8_t output[4];
1018
1019                 // Since we might be blending alpha onto alpha, we use the following equations:
1020                 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1021                 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1022
1023                 switch (avctx->pix_fmt) {
1024                 case AV_PIX_FMT_RGBA:
1025                     foreground_alpha = foreground[3];
1026                     background_alpha = background[3];
1027                     break;
1028
1029                 case AV_PIX_FMT_GRAY8A:
1030                     foreground_alpha = foreground[1];
1031                     background_alpha = background[1];
1032                     break;
1033
1034                 case AV_PIX_FMT_PAL8:
1035                     foreground_alpha = s->palette[foreground[0]] >> 24;
1036                     background_alpha = s->palette[background[0]] >> 24;
1037                     break;
1038                 }
1039
1040                 if (foreground_alpha == 0)
1041                     continue;
1042
1043                 if (foreground_alpha == 255) {
1044                     memcpy(background, foreground, s->bpp);
1045                     continue;
1046                 }
1047
1048                 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1049                     // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1050                     avpriv_request_sample(avctx, "Alpha blending palette samples");
1051                     background[0] = foreground[0];
1052                     continue;
1053                 }
1054
1055                 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1056
1057                 for (b = 0; b < s->bpp - 1; ++b) {
1058                     if (output_alpha == 0) {
1059                         output[b] = 0;
1060                     } else if (background_alpha == 255) {
1061                         output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1062                     } else {
1063                         output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1064                     }
1065                 }
1066                 output[b] = output_alpha;
1067                 memcpy(background, output, s->bpp);
1068             }
1069         }
1070     }
1071
1072     // Copy blended buffer into the frame and free
1073     memcpy(p->data[0], buffer, s->image_linesize * s->height);
1074     av_free(buffer);
1075
1076     return 0;
1077 }
1078
1079 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1080                                AVFrame *p, AVPacket *avpkt)
1081 {
1082     AVDictionary *metadata  = NULL;
1083     uint32_t tag, length;
1084     int decode_next_dat = 0;
1085     int ret;
1086
1087     for (;;) {
1088         length = bytestream2_get_bytes_left(&s->gb);
1089         if (length <= 0) {
1090             if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1091                 if (!(s->state & PNG_IDAT))
1092                     return 0;
1093                 else
1094                     goto exit_loop;
1095             }
1096             av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1097             if (   s->state & PNG_ALLIMAGE
1098                 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1099                 goto exit_loop;
1100             ret = AVERROR_INVALIDDATA;
1101             goto fail;
1102         }
1103
1104         length = bytestream2_get_be32(&s->gb);
1105         if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1106             av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1107             ret = AVERROR_INVALIDDATA;
1108             goto fail;
1109         }
1110         tag = bytestream2_get_le32(&s->gb);
1111         if (avctx->debug & FF_DEBUG_STARTCODE)
1112             av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
1113                 (tag & 0xff),
1114                 ((tag >> 8) & 0xff),
1115                 ((tag >> 16) & 0xff),
1116                 ((tag >> 24) & 0xff), length);
1117         switch (tag) {
1118         case MKTAG('I', 'H', 'D', 'R'):
1119             if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1120                 goto fail;
1121             break;
1122         case MKTAG('p', 'H', 'Y', 's'):
1123             if ((ret = decode_phys_chunk(avctx, s)) < 0)
1124                 goto fail;
1125             break;
1126         case MKTAG('f', 'c', 'T', 'L'):
1127             if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1128                 goto skip_tag;
1129             if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1130                 goto fail;
1131             decode_next_dat = 1;
1132             break;
1133         case MKTAG('f', 'd', 'A', 'T'):
1134             if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1135                 goto skip_tag;
1136             if (!decode_next_dat) {
1137                 ret = AVERROR_INVALIDDATA;
1138                 goto fail;
1139             }
1140             bytestream2_get_be32(&s->gb);
1141             length -= 4;
1142             /* fallthrough */
1143         case MKTAG('I', 'D', 'A', 'T'):
1144             if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1145                 goto skip_tag;
1146             if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1147                 goto fail;
1148             break;
1149         case MKTAG('P', 'L', 'T', 'E'):
1150             if (decode_plte_chunk(avctx, s, length) < 0)
1151                 goto skip_tag;
1152             break;
1153         case MKTAG('t', 'R', 'N', 'S'):
1154             if (decode_trns_chunk(avctx, s, length) < 0)
1155                 goto skip_tag;
1156             break;
1157         case MKTAG('t', 'E', 'X', 't'):
1158             if (decode_text_chunk(s, length, 0, &metadata) < 0)
1159                 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1160             bytestream2_skip(&s->gb, length + 4);
1161             break;
1162         case MKTAG('z', 'T', 'X', 't'):
1163             if (decode_text_chunk(s, length, 1, &metadata) < 0)
1164                 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1165             bytestream2_skip(&s->gb, length + 4);
1166             break;
1167         case MKTAG('I', 'E', 'N', 'D'):
1168             if (!(s->state & PNG_ALLIMAGE))
1169                 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1170             if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1171                 ret = AVERROR_INVALIDDATA;
1172                 goto fail;
1173             }
1174             bytestream2_skip(&s->gb, 4); /* crc */
1175             goto exit_loop;
1176         default:
1177             /* skip tag */
1178 skip_tag:
1179             bytestream2_skip(&s->gb, length + 4);
1180             break;
1181         }
1182     }
1183 exit_loop:
1184
1185     if (s->bits_per_pixel <= 4)
1186         handle_small_bpp(s, p);
1187
1188     /* apply transparency if needed */
1189     if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1190         size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1191         size_t raw_bpp = s->bpp - byte_depth;
1192         unsigned x, y;
1193
1194         for (y = 0; y < s->height; ++y) {
1195             uint8_t *row = &s->image_buf[s->image_linesize * y];
1196
1197             /* since we're updating in-place, we have to go from right to left */
1198             for (x = s->width; x > 0; --x) {
1199                 uint8_t *pixel = &row[s->bpp * (x - 1)];
1200                 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1201
1202                 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1203                     memset(&pixel[raw_bpp], 0, byte_depth);
1204                 } else {
1205                     memset(&pixel[raw_bpp], 0xff, byte_depth);
1206                 }
1207             }
1208         }
1209     }
1210
1211     /* handle p-frames only if a predecessor frame is available */
1212     if (s->last_picture.f->data[0]) {
1213         if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1214             && s->last_picture.f->width == p->width
1215             && s->last_picture.f->height== p->height
1216             && s->last_picture.f->format== p->format
1217          ) {
1218             if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1219                 handle_p_frame_png(s, p);
1220             else if (CONFIG_APNG_DECODER &&
1221                      avctx->codec_id == AV_CODEC_ID_APNG &&
1222                      (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1223                 goto fail;
1224         }
1225     }
1226     ff_thread_report_progress(&s->picture, INT_MAX, 0);
1227     ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1228
1229     av_frame_set_metadata(p, metadata);
1230     metadata   = NULL;
1231     return 0;
1232
1233 fail:
1234     av_dict_free(&metadata);
1235     ff_thread_report_progress(&s->picture, INT_MAX, 0);
1236     ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1237     return ret;
1238 }
1239
1240 #if CONFIG_PNG_DECODER
1241 static int decode_frame_png(AVCodecContext *avctx,
1242                         void *data, int *got_frame,
1243                         AVPacket *avpkt)
1244 {
1245     PNGDecContext *const s = avctx->priv_data;
1246     const uint8_t *buf     = avpkt->data;
1247     int buf_size           = avpkt->size;
1248     AVFrame *p;
1249     int64_t sig;
1250     int ret;
1251
1252     ff_thread_release_buffer(avctx, &s->last_picture);
1253     FFSWAP(ThreadFrame, s->picture, s->last_picture);
1254     p = s->picture.f;
1255
1256     bytestream2_init(&s->gb, buf, buf_size);
1257
1258     /* check signature */
1259     sig = bytestream2_get_be64(&s->gb);
1260     if (sig != PNGSIG &&
1261         sig != MNGSIG) {
1262         av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1263         return AVERROR_INVALIDDATA;
1264     }
1265
1266     s->y = s->state = s->has_trns = 0;
1267
1268     /* init the zlib */
1269     s->zstream.zalloc = ff_png_zalloc;
1270     s->zstream.zfree  = ff_png_zfree;
1271     s->zstream.opaque = NULL;
1272     ret = inflateInit(&s->zstream);
1273     if (ret != Z_OK) {
1274         av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1275         return AVERROR_EXTERNAL;
1276     }
1277
1278     if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1279         goto the_end;
1280
1281     if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1282         return ret;
1283
1284     *got_frame = 1;
1285
1286     ret = bytestream2_tell(&s->gb);
1287 the_end:
1288     inflateEnd(&s->zstream);
1289     s->crow_buf = NULL;
1290     return ret;
1291 }
1292 #endif
1293
1294 #if CONFIG_APNG_DECODER
1295 static int decode_frame_apng(AVCodecContext *avctx,
1296                         void *data, int *got_frame,
1297                         AVPacket *avpkt)
1298 {
1299     PNGDecContext *const s = avctx->priv_data;
1300     int ret;
1301     AVFrame *p;
1302
1303     ff_thread_release_buffer(avctx, &s->last_picture);
1304     FFSWAP(ThreadFrame, s->picture, s->last_picture);
1305     p = s->picture.f;
1306
1307     if (!(s->state & PNG_IHDR)) {
1308         if (!avctx->extradata_size)
1309             return AVERROR_INVALIDDATA;
1310
1311         /* only init fields, there is no zlib use in extradata */
1312         s->zstream.zalloc = ff_png_zalloc;
1313         s->zstream.zfree  = ff_png_zfree;
1314
1315         bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1316         if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1317             goto end;
1318     }
1319
1320     /* reset state for a new frame */
1321     if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1322         av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1323         ret = AVERROR_EXTERNAL;
1324         goto end;
1325     }
1326     s->y = 0;
1327     s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
1328     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1329     if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1330         goto end;
1331
1332     if (!(s->state & PNG_ALLIMAGE))
1333         av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1334     if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1335         ret = AVERROR_INVALIDDATA;
1336         goto end;
1337     }
1338     if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1339         goto end;
1340
1341     *got_frame = 1;
1342     ret = bytestream2_tell(&s->gb);
1343
1344 end:
1345     inflateEnd(&s->zstream);
1346     return ret;
1347 }
1348 #endif
1349
1350 #if HAVE_THREADS
1351 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1352 {
1353     PNGDecContext *psrc = src->priv_data;
1354     PNGDecContext *pdst = dst->priv_data;
1355     int ret;
1356
1357     if (dst == src)
1358         return 0;
1359
1360     ff_thread_release_buffer(dst, &pdst->picture);
1361     if (psrc->picture.f->data[0] &&
1362         (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1363         return ret;
1364     if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1365         pdst->width             = psrc->width;
1366         pdst->height            = psrc->height;
1367         pdst->bit_depth         = psrc->bit_depth;
1368         pdst->color_type        = psrc->color_type;
1369         pdst->compression_type  = psrc->compression_type;
1370         pdst->interlace_type    = psrc->interlace_type;
1371         pdst->filter_type       = psrc->filter_type;
1372         pdst->cur_w = psrc->cur_w;
1373         pdst->cur_h = psrc->cur_h;
1374         pdst->x_offset = psrc->x_offset;
1375         pdst->y_offset = psrc->y_offset;
1376         pdst->has_trns = psrc->has_trns;
1377         memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1378
1379         pdst->dispose_op = psrc->dispose_op;
1380
1381         memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1382
1383         pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
1384
1385         ff_thread_release_buffer(dst, &pdst->last_picture);
1386         if (psrc->last_picture.f->data[0] &&
1387             (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
1388             return ret;
1389
1390         ff_thread_release_buffer(dst, &pdst->previous_picture);
1391         if (psrc->previous_picture.f->data[0] &&
1392             (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
1393             return ret;
1394     }
1395
1396     return 0;
1397 }
1398 #endif
1399
1400 static av_cold int png_dec_init(AVCodecContext *avctx)
1401 {
1402     PNGDecContext *s = avctx->priv_data;
1403
1404     avctx->color_range = AVCOL_RANGE_JPEG;
1405
1406     s->avctx = avctx;
1407     s->previous_picture.f = av_frame_alloc();
1408     s->last_picture.f = av_frame_alloc();
1409     s->picture.f = av_frame_alloc();
1410     if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1411         av_frame_free(&s->previous_picture.f);
1412         av_frame_free(&s->last_picture.f);
1413         av_frame_free(&s->picture.f);
1414         return AVERROR(ENOMEM);
1415     }
1416
1417     if (!avctx->internal->is_copy) {
1418         avctx->internal->allocate_progress = 1;
1419         ff_pngdsp_init(&s->dsp);
1420     }
1421
1422     return 0;
1423 }
1424
1425 static av_cold int png_dec_end(AVCodecContext *avctx)
1426 {
1427     PNGDecContext *s = avctx->priv_data;
1428
1429     ff_thread_release_buffer(avctx, &s->previous_picture);
1430     av_frame_free(&s->previous_picture.f);
1431     ff_thread_release_buffer(avctx, &s->last_picture);
1432     av_frame_free(&s->last_picture.f);
1433     ff_thread_release_buffer(avctx, &s->picture);
1434     av_frame_free(&s->picture.f);
1435     av_freep(&s->buffer);
1436     s->buffer_size = 0;
1437     av_freep(&s->last_row);
1438     s->last_row_size = 0;
1439     av_freep(&s->tmp_row);
1440     s->tmp_row_size = 0;
1441
1442     return 0;
1443 }
1444
1445 #if CONFIG_APNG_DECODER
1446 AVCodec ff_apng_decoder = {
1447     .name           = "apng",
1448     .long_name      = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1449     .type           = AVMEDIA_TYPE_VIDEO,
1450     .id             = AV_CODEC_ID_APNG,
1451     .priv_data_size = sizeof(PNGDecContext),
1452     .init           = png_dec_init,
1453     .close          = png_dec_end,
1454     .decode         = decode_frame_apng,
1455     .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1456     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1457     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1458 };
1459 #endif
1460
1461 #if CONFIG_PNG_DECODER
1462 AVCodec ff_png_decoder = {
1463     .name           = "png",
1464     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1465     .type           = AVMEDIA_TYPE_VIDEO,
1466     .id             = AV_CODEC_ID_PNG,
1467     .priv_data_size = sizeof(PNGDecContext),
1468     .init           = png_dec_init,
1469     .close          = png_dec_end,
1470     .decode         = decode_frame_png,
1471     .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1472     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1473     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1474 };
1475 #endif