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