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