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