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