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