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