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