3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
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"
33 #include "bytestream.h"
49 PNG_ALLIMAGE = 1 << 1,
52 typedef struct PNGDecContext {
54 AVCodecContext *avctx;
57 ThreadFrame last_picture;
60 enum PNGHeaderState hdr_state;
61 enum PNGImageState pic_state;
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;
78 uint8_t transparent_color_be[6];
80 uint32_t palette[256];
83 unsigned int last_row_size;
85 unsigned int tmp_row_size;
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 */
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,
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,
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
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
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)
118 int x, mask, dsp_mask, j, src_x, b, bpp;
122 mask = png_pass_mask[pass];
123 dsp_mask = png_pass_dsp_mask[pass];
125 switch (bits_per_pixel) {
128 for (x = 0; x < width; x++) {
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);
135 if ((mask << j) & 0x80)
141 for (x = 0; x < width; x++) {
142 int j2 = 2 * (x & 3);
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);
149 if ((mask << j) & 0x80)
155 for (x = 0; x < width; x++) {
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);
163 if ((mask << j) & 0x80)
168 bpp = bits_per_pixel >> 3;
171 for (x = 0; x < width; x++) {
173 if ((dsp_mask << j) & 0x80) {
177 if ((mask << j) & 0x80)
184 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
188 for (i = 0; i < w; i++) {
189 int a, b, c, p, pa, pb, pc;
202 if (pa <= pb && pa <= pc)
212 #define UNROLL1(bpp, op) \
221 for (; i <= size - bpp; i += bpp) { \
222 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
225 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
228 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
231 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
235 #define UNROLL_FILTER(op) \
238 } else if (bpp == 2) { \
240 } else if (bpp == 3) { \
242 } else if (bpp == 4) { \
245 for (; i < size; i++) { \
246 dst[i] = op(dst[i - bpp], src[i], last[i]); \
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)
253 int i, p, r, g, b, a;
255 switch (filter_type) {
256 case PNG_FILTER_VALUE_NONE:
257 memcpy(dst, src, size);
259 case PNG_FILTER_VALUE_SUB:
260 for (i = 0; i < bpp; i++)
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;
270 #define OP_SUB(x, s, l) ((x) + (s))
271 UNROLL_FILTER(OP_SUB);
274 case PNG_FILTER_VALUE_UP:
275 dsp->add_bytes_l2(dst, src, last, size);
277 case PNG_FILTER_VALUE_AVG:
278 for (i = 0; i < bpp; i++) {
282 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
283 UNROLL_FILTER(OP_AVG);
285 case PNG_FILTER_VALUE_PAETH:
286 for (i = 0; i < bpp; i++) {
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;
296 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
300 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
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) \
311 for (i = 0; i < size; i += 3 + alpha) { \
312 int g = dst [i + 1]; \
318 YUV2RGB(rgb8, uint8_t)
319 YUV2RGB(rgb16, uint16_t)
321 static int percent_missing(PNGDecContext *s)
323 if (s->interlace_type) {
324 return 100 - 100 * s->pass / (NB_PASSES - 1);
326 return 100 - 100 * s->y / s->cur_h;
330 /* process exactly one decompressed row */
331 static void png_handle_row(PNGDecContext *s, uint8_t *dst, ptrdiff_t dst_stride)
333 uint8_t *ptr, *last_row;
336 if (!s->interlace_type) {
337 ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
339 last_row = s->last_row;
341 last_row = ptr - dst_stride;
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);
351 deloco_rgb8(ptr - dst_stride, s->row_size,
352 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
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);
363 deloco_rgb8(ptr, s->row_size,
364 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
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 */
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);
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);
388 if (s->y == s->cur_h) {
389 memset(s->last_row, 0, s->row_size);
391 if (s->pass == NB_PASSES - 1) {
392 s->pic_state |= PNG_ALLIMAGE;
397 s->pass_row_size = ff_png_pass_row_size(s->pass,
400 s->crow_size = s->pass_row_size + 1;
401 if (s->pass_row_size != 0)
403 /* skip pass if empty row */
412 static int png_decode_idat(PNGDecContext *s, int length,
413 uint8_t *dst, ptrdiff_t dst_stride)
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);
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;
427 if (s->zstream.avail_out == 0) {
428 if (!(s->pic_state & PNG_ALLIMAGE)) {
429 png_handle_row(s, dst, dst_stride);
431 s->zstream.avail_out = s->crow_size;
432 s->zstream.next_out = s->crow_buf;
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);
443 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
444 const uint8_t *data_end)
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);
460 while (zstream.avail_in > 0) {
461 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
463 ret = AVERROR(ENOMEM);
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;
473 bp->len += zstream.next_out - buf;
474 if (ret == Z_STREAM_END)
477 inflateEnd(&zstream);
478 bp->str[bp->len] = 0;
482 inflateEnd(&zstream);
483 av_bprint_finalize(bp, NULL);
487 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
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)
496 q = out = av_malloc(size_in + extra + 1);
499 for (i = 0; i < size_in; i++) {
501 *(q++) = 0xC0 | (in[i] >> 6);
502 *(q++) = 0x80 | (in[i] & 0x3F);
511 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
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;
524 return AVERROR_INVALIDDATA;
525 data = keyword_end + 1;
528 if (data == data_end)
529 return AVERROR_INVALIDDATA;
532 return AVERROR_INVALIDDATA;
533 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
536 ret = av_bprint_finalize(&bp, (char **)&text);
540 text = (uint8_t *)data;
541 text_len = data_end - text;
544 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
545 txt_utf8 = iso88591_to_utf8(text, text_len);
548 if (!(kw_utf8 && txt_utf8)) {
551 return AVERROR(ENOMEM);
554 av_dict_set(dict, kw_utf8, txt_utf8,
555 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
559 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
563 return AVERROR_INVALIDDATA;
565 if (s->pic_state & PNG_IDAT) {
566 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
567 return AVERROR_INVALIDDATA;
570 if (s->hdr_state & PNG_IHDR) {
571 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
572 return AVERROR_INVALIDDATA;
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;
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");
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);
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);
606 s->cur_w = s->cur_h = s->width = s->height = 0;
608 return AVERROR_INVALIDDATA;
611 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
613 if (s->pic_state & PNG_IDAT) {
614 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
615 return AVERROR_INVALIDDATA;
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 */
627 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
628 uint32_t length, AVFrame *p)
631 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
633 if (!(s->hdr_state & PNG_IHDR)) {
634 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
635 return AVERROR_INVALIDDATA;
637 if (!(s->pic_state & PNG_IDAT)) {
638 /* init image info */
639 ret = ff_set_dimensions(avctx, s->width, s->height);
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;
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;
678 avpriv_report_missing_feature(avctx,
679 "Bit depth %d color type %d",
680 s->bit_depth, s->color_type);
681 return AVERROR_PATCHWELCOME;
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;
690 case AV_PIX_FMT_RGB48BE:
691 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
694 case AV_PIX_FMT_GRAY8:
695 avctx->pix_fmt = AV_PIX_FMT_YA8;
698 case AV_PIX_FMT_GRAY16BE:
699 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
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;
709 s->bpp += byte_depth;
712 ff_thread_release_buffer(avctx, &s->picture);
713 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
716 p->pict_type = AV_PICTURE_TYPE_I;
718 p->interlaced_frame = !!s->interlace_type;
720 ff_thread_finish_setup(avctx);
722 /* compute the compressed row size */
723 if (!s->interlace_type) {
724 s->crow_size = s->row_size + 1;
727 s->pass_row_size = ff_png_pass_row_size(s->pass,
730 s->crow_size = s->pass_row_size + 1;
732 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
733 s->row_size, s->crow_size);
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);
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);
746 return AVERROR_INVALIDDATA;
749 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
751 return AVERROR(ENOMEM);
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;
759 s->pic_state |= PNG_IDAT;
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;
765 ret = png_decode_idat(s, length, p->data[0], p->linesize[0]);
767 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
768 s->bpp += byte_depth;
773 bytestream2_skip(&s->gb, 4); /* crc */
778 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
783 if ((length % 3) != 0 || length > 256 * 3)
784 return AVERROR_INVALIDDATA;
785 /* read the palette */
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;
794 s->palette[i] = (0xFFU << 24);
795 s->hdr_state |= PNG_PLTE;
796 bytestream2_skip(&s->gb, 4); /* crc */
801 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
806 if (!(s->hdr_state & PNG_IHDR)) {
807 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
808 return AVERROR_INVALIDDATA;
811 if (s->pic_state & PNG_IDAT) {
812 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
813 return AVERROR_INVALIDDATA;
816 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
817 if (length > 256 || !(s->hdr_state & PNG_PLTE))
818 return AVERROR_INVALIDDATA;
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);
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) ||
828 return AVERROR_INVALIDDATA;
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);
834 if (s->bit_depth > 8)
835 AV_WB16(&s->transparent_color_be[2 * i], v);
837 s->transparent_color_be[i] = v;
840 return AVERROR_INVALIDDATA;
843 bytestream2_skip(&s->gb, 4); /* crc */
849 static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
852 uint8_t *data, profile_name[82];
856 while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
858 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
859 return AVERROR_INVALIDDATA;
862 length = FFMAX(length - cnt, 0);
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;
869 length = FFMAX(length - 1, 0);
871 if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
874 ret = av_bprint_finalize(&bp, (char **)&data);
878 sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
881 return AVERROR(ENOMEM);
884 av_dict_set(&sd->metadata, "name", profile_name, 0);
885 memcpy(sd->data, data, bp.len);
888 /* ICC compressed data and CRC */
889 bytestream2_skip(&s->gb, length + 4);
894 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
896 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
898 uint8_t *pd = p->data[0];
899 for (j = 0; j < s->height; j++) {
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;
914 pd += p->linesize[0];
916 } else if (s->bits_per_pixel == 2) {
918 uint8_t *pd = p->data[0];
919 for (j = 0; j < s->height; j++) {
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;
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;
942 pd += p->linesize[0];
944 } else if (s->bits_per_pixel == 4) {
946 uint8_t *pd = p->data[0];
947 for (j = 0; j < s->height; j++) {
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;
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;
962 pd += p->linesize[0];
967 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
970 uint32_t sequence_number;
971 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
974 return AVERROR_INVALIDDATA;
976 if (!(s->hdr_state & PNG_IHDR)) {
977 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
978 return AVERROR_INVALIDDATA;
981 if (s->pic_state & PNG_IDAT) {
982 av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
983 return AVERROR_INVALIDDATA;
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;
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 */
1002 if (sequence_number == 0 &&
1003 (cur_w != s->width ||
1004 cur_h != s->height ||
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;
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;
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;
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
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;
1038 s->x_offset = x_offset;
1039 s->y_offset = y_offset;
1040 s->dispose_op = dispose_op;
1041 s->blend_op = blend_op;
1046 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
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);
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];
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)
1066 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
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];
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;
1085 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
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);
1094 src = s->last_picture.f->data[0];
1095 src_stride = s->last_picture.f->linesize[0];
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);
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);
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);
1115 if (s->blend_op == APNG_BLEND_OP_OVER) {
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) {
1122 uint8_t foreground_alpha, background_alpha, output_alpha;
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
1129 switch (avctx->pix_fmt) {
1130 case AV_PIX_FMT_RGBA:
1131 foreground_alpha = foreground[3];
1132 background_alpha = background[3];
1135 case AV_PIX_FMT_GRAY8A:
1136 foreground_alpha = foreground[1];
1137 background_alpha = background[1];
1140 case AV_PIX_FMT_PAL8:
1141 foreground_alpha = s->palette[foreground[0]] >> 24;
1142 background_alpha = s->palette[background[0]] >> 24;
1146 if (foreground_alpha == 255)
1149 if (foreground_alpha == 0) {
1150 memcpy(foreground, background, s->bpp);
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");
1160 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1162 av_assert0(s->bpp <= 10);
1164 for (b = 0; b < s->bpp - 1; ++b) {
1165 if (output_alpha == 0) {
1167 } else if (background_alpha == 255) {
1168 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1170 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1173 output[b] = output_alpha;
1174 memcpy(foreground, output, s->bpp);
1182 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1183 AVFrame *p, const AVPacket *avpkt)
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;
1192 length = bytestream2_get_bytes_left(&s->gb);
1195 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1196 avctx->skip_frame == AVDISCARD_ALL) {
1200 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1201 if (!(s->pic_state & PNG_IDAT))
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)
1210 ret = AVERROR_INVALIDDATA;
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;
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;
1230 av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1231 bytestream2_skip(&s->gb, 4); /* tag */
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);
1240 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1241 avctx->skip_frame == AVDISCARD_ALL) {
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'):
1254 metadatap = &p->metadata;
1256 case MKTAG('I', 'H', 'D', 'R'):
1257 if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1260 case MKTAG('p', 'H', 'Y', 's'):
1261 if ((ret = decode_phys_chunk(avctx, s)) < 0)
1264 case MKTAG('f', 'c', 'T', 'L'):
1265 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1267 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1269 decode_next_dat = 1;
1271 case MKTAG('f', 'd', 'A', 'T'):
1272 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1274 if (!decode_next_dat || length < 4) {
1275 ret = AVERROR_INVALIDDATA;
1278 bytestream2_get_be32(&s->gb);
1281 case MKTAG('I', 'D', 'A', 'T'):
1282 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1284 if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1287 case MKTAG('P', 'L', 'T', 'E'):
1288 if (decode_plte_chunk(avctx, s, length) < 0)
1291 case MKTAG('t', 'R', 'N', 'S'):
1292 if (decode_trns_chunk(avctx, s, length) < 0)
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);
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);
1305 case MKTAG('s', 'T', 'E', 'R'): {
1306 int mode = bytestream2_get_byte(&s->gb);
1307 AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
1309 ret = AVERROR(ENOMEM);
1313 if (mode == 0 || mode == 1) {
1314 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1315 stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1317 av_log(avctx, AV_LOG_WARNING,
1318 "Unknown value in sTER chunk (%d)\n", mode);
1320 bytestream2_skip(&s->gb, 4); /* crc */
1323 case MKTAG('i', 'C', 'C', 'P'): {
1324 if ((ret = decode_iccp_chunk(s, length, p)) < 0)
1328 case MKTAG('c', 'H', 'R', 'M'): {
1329 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(p);
1331 ret = AVERROR(ENOMEM);
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);
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);
1344 mdm->has_primaries = 1;
1345 bytestream2_skip(&s->gb, 4); /* crc */
1348 case MKTAG('g', 'A', 'M', 'A'): {
1351 int num = bytestream2_get_be32(&s->gb);
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);
1359 av_dict_set(&p->metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1361 bytestream2_skip(&s->gb, 4); /* crc */
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;
1371 bytestream2_skip(&s->gb, 4); /* crc */
1376 bytestream2_skip(&s->gb, length + 4);
1382 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1383 avctx->skip_frame == AVDISCARD_ALL) {
1387 if (percent_missing(s) > avctx->discard_damaged_percentage)
1388 return AVERROR_INVALIDDATA;
1390 if (s->bits_per_pixel <= 4)
1391 handle_small_bpp(s, p);
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;
1399 av_assert0(s->bit_depth > 1);
1401 for (y = 0; y < s->height; ++y) {
1402 uint8_t *row = &p->data[0][p->linesize[0] * y];
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;
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;
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);
1428 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1429 memset(&pixel[raw_bpp], 0, byte_depth);
1431 memset(&pixel[raw_bpp], 0xff, byte_depth);
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
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)
1453 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1458 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1462 #if CONFIG_PNG_DECODER
1463 static int decode_frame_png(AVCodecContext *avctx,
1464 void *data, int *got_frame,
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;
1474 bytestream2_init(&s->gb, buf, buf_size);
1476 /* check signature */
1477 sig = bytestream2_get_be64(&s->gb);
1478 if (sig != PNGSIG &&
1480 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1481 return AVERROR_INVALIDDATA;
1484 s->y = s->has_trns = 0;
1489 s->zstream.zalloc = ff_png_zalloc;
1490 s->zstream.zfree = ff_png_zfree;
1491 s->zstream.opaque = NULL;
1492 ret = inflateInit(&s->zstream);
1494 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1495 return AVERROR_EXTERNAL;
1498 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1501 if (avctx->skip_frame == AVDISCARD_ALL) {
1503 ret = bytestream2_tell(&s->gb);
1507 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
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);
1517 ret = bytestream2_tell(&s->gb);
1519 inflateEnd(&s->zstream);
1525 #if CONFIG_APNG_DECODER
1526 static int decode_frame_apng(AVCodecContext *avctx,
1527 void *data, int *got_frame,
1530 PNGDecContext *const s = avctx->priv_data;
1532 AVFrame *p = s->picture.f;
1534 if (!(s->hdr_state & PNG_IHDR)) {
1535 if (!avctx->extradata_size)
1536 return AVERROR_INVALIDDATA;
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;
1542 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1543 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
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;
1555 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1556 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
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;
1565 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
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);
1578 ret = bytestream2_tell(&s->gb);
1581 inflateEnd(&s->zstream);
1587 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1589 PNGDecContext *psrc = src->priv_data;
1590 PNGDecContext *pdst = dst->priv_data;
1591 ThreadFrame *src_frame = NULL;
1597 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
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));
1613 pdst->dispose_op = psrc->dispose_op;
1615 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1617 pdst->hdr_state |= psrc->hdr_state;
1620 src_frame = psrc->dispose_op == APNG_DISPOSE_OP_NONE ?
1621 &psrc->picture : &psrc->last_picture;
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);
1634 static av_cold int png_dec_init(AVCodecContext *avctx)
1636 PNGDecContext *s = avctx->priv_data;
1638 avctx->color_range = AVCOL_RANGE_JPEG;
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);
1649 ff_pngdsp_init(&s->dsp);
1654 static av_cold int png_dec_end(AVCodecContext *avctx)
1656 PNGDecContext *s = avctx->priv_data;
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);
1664 av_freep(&s->last_row);
1665 s->last_row_size = 0;
1666 av_freep(&s->tmp_row);
1667 s->tmp_row_size = 0;
1672 #if CONFIG_APNG_DECODER
1673 AVCodec ff_apng_decoder = {
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,
1689 #if CONFIG_PNG_DECODER
1690 AVCodec ff_png_decoder = {
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,