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