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