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