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 AVDictionary *frame_metadata;
62 uint8_t iccp_name[82];
69 uint32_t white_point[2];
70 uint32_t display_primaries[3][2];
72 enum PNGHeaderState hdr_state;
73 enum PNGImageState pic_state;
77 int x_offset, y_offset;
78 int last_x_offset, last_y_offset;
79 uint8_t dispose_op, blend_op;
80 uint8_t last_dispose_op;
90 uint8_t transparent_color_be[6];
92 uint8_t *background_buf;
93 unsigned background_buf_allocated;
94 uint32_t palette[256];
97 unsigned int last_row_size;
99 unsigned int tmp_row_size;
103 int crow_size; /* compressed row size (include filter type) */
104 int row_size; /* decompressed row size */
105 int pass_row_size; /* decompress row size of the current pass */
110 /* Mask to determine which pixels are valid in a pass */
111 static const uint8_t png_pass_mask[NB_PASSES] = {
112 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
115 /* Mask to determine which y pixels can be written in a pass */
116 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
117 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
120 /* Mask to determine which pixels to overwrite while displaying */
121 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
122 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
125 /* NOTE: we try to construct a good looking image at each pass. width
126 * is the original image width. We also do pixel format conversion at
128 static void png_put_interlaced_row(uint8_t *dst, int width,
129 int bits_per_pixel, int pass,
130 int color_type, const uint8_t *src)
132 int x, mask, dsp_mask, j, src_x, b, bpp;
136 mask = png_pass_mask[pass];
137 dsp_mask = png_pass_dsp_mask[pass];
139 switch (bits_per_pixel) {
142 for (x = 0; x < width; x++) {
144 if ((dsp_mask << j) & 0x80) {
145 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
146 dst[x >> 3] &= 0xFF7F>>j;
147 dst[x >> 3] |= b << (7 - j);
149 if ((mask << j) & 0x80)
155 for (x = 0; x < width; x++) {
156 int j2 = 2 * (x & 3);
158 if ((dsp_mask << j) & 0x80) {
159 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
160 dst[x >> 2] &= 0xFF3F>>j2;
161 dst[x >> 2] |= b << (6 - j2);
163 if ((mask << j) & 0x80)
169 for (x = 0; x < width; x++) {
172 if ((dsp_mask << j) & 0x80) {
173 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
174 dst[x >> 1] &= 0xFF0F>>j2;
175 dst[x >> 1] |= b << (4 - j2);
177 if ((mask << j) & 0x80)
182 bpp = bits_per_pixel >> 3;
185 for (x = 0; x < width; x++) {
187 if ((dsp_mask << j) & 0x80) {
191 if ((mask << j) & 0x80)
198 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
202 for (i = 0; i < w; i++) {
203 int a, b, c, p, pa, pb, pc;
216 if (pa <= pb && pa <= pc)
226 #define UNROLL1(bpp, op) \
235 for (; i <= size - bpp; i += bpp) { \
236 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
239 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
242 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
245 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
249 #define UNROLL_FILTER(op) \
252 } else if (bpp == 2) { \
254 } else if (bpp == 3) { \
256 } else if (bpp == 4) { \
259 for (; i < size; i++) { \
260 dst[i] = op(dst[i - bpp], src[i], last[i]); \
263 /* NOTE: 'dst' can be equal to 'last' */
264 void ff_png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
265 uint8_t *src, uint8_t *last, int size, int bpp)
267 int i, p, r, g, b, a;
269 switch (filter_type) {
270 case PNG_FILTER_VALUE_NONE:
271 memcpy(dst, src, size);
273 case PNG_FILTER_VALUE_SUB:
274 for (i = 0; i < bpp; i++)
278 for (; i < size; i += bpp) {
279 unsigned s = *(int *)(src + i);
280 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
281 *(int *)(dst + i) = p;
284 #define OP_SUB(x, s, l) ((x) + (s))
285 UNROLL_FILTER(OP_SUB);
288 case PNG_FILTER_VALUE_UP:
289 dsp->add_bytes_l2(dst, src, last, size);
291 case PNG_FILTER_VALUE_AVG:
292 for (i = 0; i < bpp; i++) {
296 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
297 UNROLL_FILTER(OP_AVG);
299 case PNG_FILTER_VALUE_PAETH:
300 for (i = 0; i < bpp; i++) {
304 if (bpp > 2 && size > 4) {
305 /* would write off the end of the array if we let it process
306 * the last pixel with bpp=3 */
307 int w = (bpp & 3) ? size - 3 : size;
310 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
314 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
319 /* This used to be called "deloco" in FFmpeg
320 * and is actually an inverse reversible colorspace transformation */
321 #define YUV2RGB(NAME, TYPE) \
322 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
325 for (i = 0; i < size; i += 3 + alpha) { \
326 int g = dst [i + 1]; \
332 YUV2RGB(rgb8, uint8_t)
333 YUV2RGB(rgb16, uint16_t)
335 static int percent_missing(PNGDecContext *s)
337 if (s->interlace_type) {
338 return 100 - 100 * s->pass / (NB_PASSES - 1);
340 return 100 - 100 * s->y / s->cur_h;
344 /* process exactly one decompressed row */
345 static void png_handle_row(PNGDecContext *s, uint8_t *dst, ptrdiff_t dst_stride)
347 uint8_t *ptr, *last_row;
350 if (!s->interlace_type) {
351 ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
353 last_row = s->last_row;
355 last_row = ptr - dst_stride;
357 ff_png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
358 last_row, s->row_size, s->bpp);
359 /* loco lags by 1 row so that it doesn't interfere with top prediction */
360 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
361 if (s->bit_depth == 16) {
362 deloco_rgb16((uint16_t *)(ptr - dst_stride), s->row_size / 2,
363 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
365 deloco_rgb8(ptr - dst_stride, s->row_size,
366 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
370 if (s->y == s->cur_h) {
371 s->pic_state |= PNG_ALLIMAGE;
372 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
373 if (s->bit_depth == 16) {
374 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
375 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
377 deloco_rgb8(ptr, s->row_size,
378 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
385 ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
386 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
387 /* if we already read one row, it is time to stop to
388 * wait for the next one */
391 ff_png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
392 s->last_row, s->pass_row_size, s->bpp);
393 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
394 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
397 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
398 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
399 s->color_type, s->last_row);
402 if (s->y == s->cur_h) {
403 memset(s->last_row, 0, s->row_size);
405 if (s->pass == NB_PASSES - 1) {
406 s->pic_state |= PNG_ALLIMAGE;
411 s->pass_row_size = ff_png_pass_row_size(s->pass,
414 s->crow_size = s->pass_row_size + 1;
415 if (s->pass_row_size != 0)
417 /* skip pass if empty row */
426 static int png_decode_idat(PNGDecContext *s, GetByteContext *gb,
427 uint8_t *dst, ptrdiff_t dst_stride)
430 s->zstream.avail_in = bytestream2_get_bytes_left(gb);
431 s->zstream.next_in = gb->buffer;
433 /* decode one line if possible */
434 while (s->zstream.avail_in > 0) {
435 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
436 if (ret != Z_OK && ret != Z_STREAM_END) {
437 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
438 return AVERROR_EXTERNAL;
440 if (s->zstream.avail_out == 0) {
441 if (!(s->pic_state & PNG_ALLIMAGE)) {
442 png_handle_row(s, dst, dst_stride);
444 s->zstream.avail_out = s->crow_size;
445 s->zstream.next_out = s->crow_buf;
447 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
448 av_log(s->avctx, AV_LOG_WARNING,
449 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
456 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
457 const uint8_t *data_end)
464 zstream.zalloc = ff_png_zalloc;
465 zstream.zfree = ff_png_zfree;
466 zstream.opaque = NULL;
467 if (inflateInit(&zstream) != Z_OK)
468 return AVERROR_EXTERNAL;
469 zstream.next_in = data;
470 zstream.avail_in = data_end - data;
471 av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
473 while (zstream.avail_in > 0) {
474 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
476 ret = AVERROR(ENOMEM);
479 zstream.next_out = buf;
480 zstream.avail_out = buf_size - 1;
481 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
482 if (ret != Z_OK && ret != Z_STREAM_END) {
483 ret = AVERROR_EXTERNAL;
486 bp->len += zstream.next_out - buf;
487 if (ret == Z_STREAM_END)
490 inflateEnd(&zstream);
491 bp->str[bp->len] = 0;
495 inflateEnd(&zstream);
496 av_bprint_finalize(bp, NULL);
500 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
505 for (i = 0; i < size_in; i++)
506 extra += in[i] >= 0x80;
507 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
509 q = out = av_malloc(size_in + extra + 1);
512 for (i = 0; i < size_in; i++) {
514 *(q++) = 0xC0 | (in[i] >> 6);
515 *(q++) = 0x80 | (in[i] & 0x3F);
524 static int decode_text_chunk(PNGDecContext *s, GetByteContext *gb, int compressed)
527 const uint8_t *data = gb->buffer;
528 const uint8_t *data_end = gb->buffer_end;
529 const uint8_t *keyword = data;
530 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
531 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
536 return AVERROR_INVALIDDATA;
537 data = keyword_end + 1;
540 if (data == data_end)
541 return AVERROR_INVALIDDATA;
544 return AVERROR_INVALIDDATA;
545 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
548 ret = av_bprint_finalize(&bp, (char **)&text);
552 text = (uint8_t *)data;
553 text_len = data_end - text;
556 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
557 txt_utf8 = iso88591_to_utf8(text, text_len);
560 if (!(kw_utf8 && txt_utf8)) {
563 return AVERROR(ENOMEM);
566 av_dict_set(&s->frame_metadata, kw_utf8, txt_utf8,
567 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
571 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
574 if (bytestream2_get_bytes_left(gb) != 13)
575 return AVERROR_INVALIDDATA;
577 if (s->pic_state & PNG_IDAT) {
578 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
579 return AVERROR_INVALIDDATA;
582 if (s->hdr_state & PNG_IHDR) {
583 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
584 return AVERROR_INVALIDDATA;
587 s->width = s->cur_w = bytestream2_get_be32(gb);
588 s->height = s->cur_h = bytestream2_get_be32(gb);
589 if (av_image_check_size(s->width, s->height, 0, avctx)) {
590 s->cur_w = s->cur_h = s->width = s->height = 0;
591 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
592 return AVERROR_INVALIDDATA;
594 s->bit_depth = bytestream2_get_byte(gb);
595 if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
596 s->bit_depth != 8 && s->bit_depth != 16) {
597 av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
600 s->color_type = bytestream2_get_byte(gb);
601 s->compression_type = bytestream2_get_byte(gb);
602 if (s->compression_type) {
603 av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
606 s->filter_type = bytestream2_get_byte(gb);
607 s->interlace_type = bytestream2_get_byte(gb);
608 s->hdr_state |= PNG_IHDR;
609 if (avctx->debug & FF_DEBUG_PICT_INFO)
610 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
611 "compression_type=%d filter_type=%d interlace_type=%d\n",
612 s->width, s->height, s->bit_depth, s->color_type,
613 s->compression_type, s->filter_type, s->interlace_type);
617 s->cur_w = s->cur_h = s->width = s->height = 0;
619 return AVERROR_INVALIDDATA;
622 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s,
625 if (s->pic_state & PNG_IDAT) {
626 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
627 return AVERROR_INVALIDDATA;
629 avctx->sample_aspect_ratio.num = bytestream2_get_be32(gb);
630 avctx->sample_aspect_ratio.den = bytestream2_get_be32(gb);
631 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
632 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
633 bytestream2_skip(gb, 1); /* unit specifier */
638 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
639 GetByteContext *gb, AVFrame *p)
642 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
644 if (!(s->hdr_state & PNG_IHDR)) {
645 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
646 return AVERROR_INVALIDDATA;
648 if (!(s->pic_state & PNG_IDAT)) {
649 /* init image info */
650 ret = ff_set_dimensions(avctx, s->width, s->height);
654 s->channels = ff_png_get_nb_channels(s->color_type);
655 s->bits_per_pixel = s->bit_depth * s->channels;
656 s->bpp = (s->bits_per_pixel + 7) >> 3;
657 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
659 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
660 s->color_type == PNG_COLOR_TYPE_RGB) {
661 avctx->pix_fmt = AV_PIX_FMT_RGB24;
662 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
663 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
664 avctx->pix_fmt = AV_PIX_FMT_RGBA;
665 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
666 s->color_type == PNG_COLOR_TYPE_GRAY) {
667 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
668 } else if (s->bit_depth == 16 &&
669 s->color_type == PNG_COLOR_TYPE_GRAY) {
670 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
671 } else if (s->bit_depth == 16 &&
672 s->color_type == PNG_COLOR_TYPE_RGB) {
673 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
674 } else if (s->bit_depth == 16 &&
675 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
676 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
677 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
678 s->color_type == PNG_COLOR_TYPE_PALETTE) {
679 avctx->pix_fmt = AV_PIX_FMT_PAL8;
680 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
681 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
682 } else if (s->bit_depth == 8 &&
683 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
684 avctx->pix_fmt = AV_PIX_FMT_YA8;
685 } else if (s->bit_depth == 16 &&
686 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
687 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
689 avpriv_report_missing_feature(avctx,
690 "Bit depth %d color type %d",
691 s->bit_depth, s->color_type);
692 return AVERROR_PATCHWELCOME;
695 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
696 switch (avctx->pix_fmt) {
697 case AV_PIX_FMT_RGB24:
698 avctx->pix_fmt = AV_PIX_FMT_RGBA;
701 case AV_PIX_FMT_RGB48BE:
702 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
705 case AV_PIX_FMT_GRAY8:
706 avctx->pix_fmt = AV_PIX_FMT_YA8;
709 case AV_PIX_FMT_GRAY16BE:
710 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
714 avpriv_request_sample(avctx, "bit depth %d "
715 "and color type %d with TRNS",
716 s->bit_depth, s->color_type);
717 return AVERROR_INVALIDDATA;
720 s->bpp += byte_depth;
723 ff_thread_release_buffer(avctx, &s->picture);
724 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
727 p->pict_type = AV_PICTURE_TYPE_I;
729 p->interlaced_frame = !!s->interlace_type;
731 ff_thread_finish_setup(avctx);
733 /* compute the compressed row size */
734 if (!s->interlace_type) {
735 s->crow_size = s->row_size + 1;
738 s->pass_row_size = ff_png_pass_row_size(s->pass,
741 s->crow_size = s->pass_row_size + 1;
743 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
744 s->row_size, s->crow_size);
746 /* copy the palette if needed */
747 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
748 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
749 /* empty row is used if differencing to the first row */
750 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
752 return AVERROR_INVALIDDATA;
753 if (s->interlace_type ||
754 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
755 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
757 return AVERROR_INVALIDDATA;
760 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
762 return AVERROR(ENOMEM);
764 /* we want crow_buf+1 to be 16-byte aligned */
765 s->crow_buf = s->buffer + 15;
766 s->zstream.avail_out = s->crow_size;
767 s->zstream.next_out = s->crow_buf;
770 s->pic_state |= PNG_IDAT;
772 /* set image to non-transparent bpp while decompressing */
773 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
774 s->bpp -= byte_depth;
776 ret = png_decode_idat(s, gb, p->data[0], p->linesize[0]);
778 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
779 s->bpp += byte_depth;
787 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
790 int length = bytestream2_get_bytes_left(gb);
793 if ((length % 3) != 0 || length > 256 * 3)
794 return AVERROR_INVALIDDATA;
795 /* read the palette */
797 for (i = 0; i < n; i++) {
798 r = bytestream2_get_byte(gb);
799 g = bytestream2_get_byte(gb);
800 b = bytestream2_get_byte(gb);
801 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
804 s->palette[i] = (0xFFU << 24);
805 s->hdr_state |= PNG_PLTE;
810 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
813 int length = bytestream2_get_bytes_left(gb);
816 if (!(s->hdr_state & PNG_IHDR)) {
817 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
818 return AVERROR_INVALIDDATA;
821 if (s->pic_state & PNG_IDAT) {
822 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
823 return AVERROR_INVALIDDATA;
826 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
827 if (length > 256 || !(s->hdr_state & PNG_PLTE))
828 return AVERROR_INVALIDDATA;
830 for (i = 0; i < length; i++) {
831 unsigned v = bytestream2_get_byte(gb);
832 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
834 } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
835 if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
836 (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
838 return AVERROR_INVALIDDATA;
840 for (i = 0; i < length / 2; i++) {
841 /* only use the least significant bits */
842 v = av_mod_uintp2(bytestream2_get_be16(gb), s->bit_depth);
844 if (s->bit_depth > 8)
845 AV_WB16(&s->transparent_color_be[2 * i], v);
847 s->transparent_color_be[i] = v;
850 return AVERROR_INVALIDDATA;
858 static int decode_iccp_chunk(PNGDecContext *s, GetByteContext *gb, AVFrame *f)
863 while ((s->iccp_name[cnt++] = bytestream2_get_byte(gb)) && cnt < 81);
865 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
866 ret = AVERROR_INVALIDDATA;
870 if (bytestream2_get_byte(gb) != 0) {
871 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
872 ret = AVERROR_INVALIDDATA;
876 if ((ret = decode_zbuf(&bp, gb->buffer, gb->buffer_end)) < 0)
879 av_freep(&s->iccp_data);
880 ret = av_bprint_finalize(&bp, (char **)&s->iccp_data);
883 s->iccp_data_len = bp.len;
891 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
893 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
895 uint8_t *pd = p->data[0];
896 for (j = 0; j < s->height; j++) {
898 for (k = 7; k >= 1; k--)
899 if ((s->width&7) >= k)
900 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
901 for (i--; i >= 0; i--) {
902 pd[8*i + 7]= pd[i] & 1;
903 pd[8*i + 6]= (pd[i]>>1) & 1;
904 pd[8*i + 5]= (pd[i]>>2) & 1;
905 pd[8*i + 4]= (pd[i]>>3) & 1;
906 pd[8*i + 3]= (pd[i]>>4) & 1;
907 pd[8*i + 2]= (pd[i]>>5) & 1;
908 pd[8*i + 1]= (pd[i]>>6) & 1;
909 pd[8*i + 0]= pd[i]>>7;
911 pd += p->linesize[0];
913 } else if (s->bits_per_pixel == 2) {
915 uint8_t *pd = p->data[0];
916 for (j = 0; j < s->height; j++) {
918 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
919 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
920 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
921 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
922 for (i--; i >= 0; i--) {
923 pd[4*i + 3]= pd[i] & 3;
924 pd[4*i + 2]= (pd[i]>>2) & 3;
925 pd[4*i + 1]= (pd[i]>>4) & 3;
926 pd[4*i + 0]= pd[i]>>6;
929 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
930 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
931 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
932 for (i--; i >= 0; i--) {
933 pd[4*i + 3]= ( pd[i] & 3)*0x55;
934 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
935 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
936 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
939 pd += p->linesize[0];
941 } else if (s->bits_per_pixel == 4) {
943 uint8_t *pd = p->data[0];
944 for (j = 0; j < s->height; j++) {
946 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
947 if (s->width&1) pd[2*i+0]= pd[i]>>4;
948 for (i--; i >= 0; i--) {
949 pd[2*i + 1] = pd[i] & 15;
950 pd[2*i + 0] = pd[i] >> 4;
953 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
954 for (i--; i >= 0; i--) {
955 pd[2*i + 1] = (pd[i] & 15) * 0x11;
956 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
959 pd += p->linesize[0];
964 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
967 uint32_t sequence_number;
968 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
970 if (bytestream2_get_bytes_left(gb) != 26)
971 return AVERROR_INVALIDDATA;
973 if (!(s->hdr_state & PNG_IHDR)) {
974 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
975 return AVERROR_INVALIDDATA;
978 if (s->pic_state & PNG_IDAT) {
979 av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
980 return AVERROR_INVALIDDATA;
983 s->last_w = s->cur_w;
984 s->last_h = s->cur_h;
985 s->last_x_offset = s->x_offset;
986 s->last_y_offset = s->y_offset;
987 s->last_dispose_op = s->dispose_op;
989 sequence_number = bytestream2_get_be32(gb);
990 cur_w = bytestream2_get_be32(gb);
991 cur_h = bytestream2_get_be32(gb);
992 x_offset = bytestream2_get_be32(gb);
993 y_offset = bytestream2_get_be32(gb);
994 bytestream2_skip(gb, 4); /* delay_num (2), delay_den (2) */
995 dispose_op = bytestream2_get_byte(gb);
996 blend_op = bytestream2_get_byte(gb);
998 if (sequence_number == 0 &&
999 (cur_w != s->width ||
1000 cur_h != s->height ||
1003 cur_w <= 0 || cur_h <= 0 ||
1004 x_offset < 0 || y_offset < 0 ||
1005 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1006 return AVERROR_INVALIDDATA;
1008 if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1009 av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1010 return AVERROR_INVALIDDATA;
1013 if ((sequence_number == 0 || !s->last_picture.f->data[0]) &&
1014 dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1015 // No previous frame to revert to for the first frame
1016 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1017 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1020 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1021 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1022 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1023 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1024 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1025 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1026 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1028 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1029 blend_op = APNG_BLEND_OP_SOURCE;
1034 s->x_offset = x_offset;
1035 s->y_offset = y_offset;
1036 s->dispose_op = dispose_op;
1037 s->blend_op = blend_op;
1042 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1045 uint8_t *pd = p->data[0];
1046 uint8_t *pd_last = s->last_picture.f->data[0];
1047 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1049 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1050 for (j = 0; j < s->height; j++) {
1051 for (i = 0; i < ls; i++)
1052 pd[i] += pd_last[i];
1053 pd += p->linesize[0];
1054 pd_last += s->last_picture.f->linesize[0];
1058 // divide by 255 and round to nearest
1059 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1060 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1062 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1065 uint8_t *dst = p->data[0];
1066 ptrdiff_t dst_stride = p->linesize[0];
1067 const uint8_t *src = s->last_picture.f->data[0];
1068 ptrdiff_t src_stride = s->last_picture.f->linesize[0];
1072 if (s->blend_op == APNG_BLEND_OP_OVER &&
1073 avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1074 avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
1075 avctx->pix_fmt != AV_PIX_FMT_PAL8) {
1076 avpriv_request_sample(avctx, "Blending with pixel format %s",
1077 av_get_pix_fmt_name(avctx->pix_fmt));
1078 return AVERROR_PATCHWELCOME;
1081 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1083 // need to reset a rectangle to background:
1084 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
1085 av_fast_malloc(&s->background_buf, &s->background_buf_allocated,
1086 src_stride * p->height);
1087 if (!s->background_buf)
1088 return AVERROR(ENOMEM);
1090 memcpy(s->background_buf, src, src_stride * p->height);
1092 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; y++) {
1093 memset(s->background_buf + src_stride * y +
1094 s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1097 src = s->background_buf;
1100 // copy unchanged rectangles from the last frame
1101 for (y = 0; y < s->y_offset; y++)
1102 memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
1103 for (y = s->y_offset; y < s->y_offset + s->cur_h; y++) {
1104 memcpy(dst + y * dst_stride, src + y * src_stride, s->x_offset * s->bpp);
1105 memcpy(dst + y * dst_stride + (s->x_offset + s->cur_w) * s->bpp,
1106 src + y * src_stride + (s->x_offset + s->cur_w) * s->bpp,
1107 (p->width - s->cur_w - s->x_offset) * s->bpp);
1109 for (y = s->y_offset + s->cur_h; y < p->height; y++)
1110 memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
1112 if (s->blend_op == APNG_BLEND_OP_OVER) {
1114 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1115 uint8_t *foreground = dst + dst_stride * y + s->bpp * s->x_offset;
1116 const uint8_t *background = src + src_stride * y + s->bpp * s->x_offset;
1117 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1119 uint8_t foreground_alpha, background_alpha, output_alpha;
1122 // Since we might be blending alpha onto alpha, we use the following equations:
1123 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1124 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1126 switch (avctx->pix_fmt) {
1127 case AV_PIX_FMT_RGBA:
1128 foreground_alpha = foreground[3];
1129 background_alpha = background[3];
1132 case AV_PIX_FMT_GRAY8A:
1133 foreground_alpha = foreground[1];
1134 background_alpha = background[1];
1137 case AV_PIX_FMT_PAL8:
1138 foreground_alpha = s->palette[foreground[0]] >> 24;
1139 background_alpha = s->palette[background[0]] >> 24;
1143 if (foreground_alpha == 255)
1146 if (foreground_alpha == 0) {
1147 memcpy(foreground, background, s->bpp);
1151 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1152 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1153 avpriv_request_sample(avctx, "Alpha blending palette samples");
1157 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1159 av_assert0(s->bpp <= 10);
1161 for (b = 0; b < s->bpp - 1; ++b) {
1162 if (output_alpha == 0) {
1164 } else if (background_alpha == 255) {
1165 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1167 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1170 output[b] = output_alpha;
1171 memcpy(foreground, output, s->bpp);
1179 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1180 AVFrame *p, const AVPacket *avpkt)
1182 const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1183 uint32_t tag, length;
1184 int decode_next_dat = 0;
1188 GetByteContext gb_chunk;
1190 length = bytestream2_get_bytes_left(&s->gb);
1193 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1194 avctx->skip_frame == AVDISCARD_ALL) {
1198 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1199 if (!(s->pic_state & PNG_IDAT))
1204 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1205 if ( s->pic_state & PNG_ALLIMAGE
1206 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1208 ret = AVERROR_INVALIDDATA;
1212 length = bytestream2_get_be32(&s->gb);
1213 if (length > 0x7fffffff || length + 8 > bytestream2_get_bytes_left(&s->gb)) {
1214 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1215 ret = AVERROR_INVALIDDATA;
1218 if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_IGNORE_ERR)) {
1219 uint32_t crc_sig = AV_RB32(s->gb.buffer + length + 4);
1220 uint32_t crc_cal = ~av_crc(crc_tab, UINT32_MAX, s->gb.buffer, length + 4);
1221 if (crc_sig ^ crc_cal) {
1222 av_log(avctx, AV_LOG_ERROR, "CRC mismatch in chunk");
1223 if (avctx->err_recognition & AV_EF_EXPLODE) {
1224 av_log(avctx, AV_LOG_ERROR, ", quitting\n");
1225 ret = AVERROR_INVALIDDATA;
1228 av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1229 bytestream2_skip(&s->gb, length + 8); /* tag */
1232 tag = bytestream2_get_le32(&s->gb);
1233 if (avctx->debug & FF_DEBUG_STARTCODE)
1234 av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1235 av_fourcc2str(tag), length);
1237 bytestream2_init(&gb_chunk, s->gb.buffer, length);
1238 bytestream2_skip(&s->gb, length + 4);
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'):
1255 case MKTAG('I', 'H', 'D', 'R'):
1256 if ((ret = decode_ihdr_chunk(avctx, s, &gb_chunk)) < 0)
1259 case MKTAG('p', 'H', 'Y', 's'):
1260 if ((ret = decode_phys_chunk(avctx, s, &gb_chunk)) < 0)
1263 case MKTAG('f', 'c', 'T', 'L'):
1264 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1266 if ((ret = decode_fctl_chunk(avctx, s, &gb_chunk)) < 0)
1268 decode_next_dat = 1;
1270 case MKTAG('f', 'd', 'A', 'T'):
1271 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1273 if (!decode_next_dat || bytestream2_get_bytes_left(&gb_chunk) < 4) {
1274 ret = AVERROR_INVALIDDATA;
1277 bytestream2_get_be32(&gb_chunk);
1279 case MKTAG('I', 'D', 'A', 'T'):
1280 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1282 if ((ret = decode_idat_chunk(avctx, s, &gb_chunk, p)) < 0)
1285 case MKTAG('P', 'L', 'T', 'E'):
1286 decode_plte_chunk(avctx, s, &gb_chunk);
1288 case MKTAG('t', 'R', 'N', 'S'):
1289 decode_trns_chunk(avctx, s, &gb_chunk);
1291 case MKTAG('t', 'E', 'X', 't'):
1292 if (decode_text_chunk(s, &gb_chunk, 0) < 0)
1293 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1295 case MKTAG('z', 'T', 'X', 't'):
1296 if (decode_text_chunk(s, &gb_chunk, 1) < 0)
1297 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1299 case MKTAG('s', 'T', 'E', 'R'): {
1300 int mode = bytestream2_get_byte(&gb_chunk);
1302 if (mode == 0 || mode == 1) {
1303 s->stereo_mode = mode;
1305 av_log(avctx, AV_LOG_WARNING,
1306 "Unknown value in sTER chunk (%d)\n", mode);
1310 case MKTAG('i', 'C', 'C', 'P'): {
1311 if ((ret = decode_iccp_chunk(s, &gb_chunk, p)) < 0)
1315 case MKTAG('c', 'H', 'R', 'M'): {
1318 s->white_point[0] = bytestream2_get_be32(&gb_chunk);
1319 s->white_point[1] = bytestream2_get_be32(&gb_chunk);
1322 for (i = 0; i < 3; i++) {
1323 s->display_primaries[i][0] = bytestream2_get_be32(&gb_chunk);
1324 s->display_primaries[i][1] = bytestream2_get_be32(&gb_chunk);
1329 case MKTAG('g', 'A', 'M', 'A'): {
1332 int num = bytestream2_get_be32(&gb_chunk);
1334 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1335 av_bprintf(&bp, "%i/%i", num, 100000);
1336 ret = av_bprint_finalize(&bp, &gamma_str);
1340 av_dict_set(&s->frame_metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1344 case MKTAG('I', 'E', 'N', 'D'):
1345 if (!(s->pic_state & PNG_ALLIMAGE))
1346 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1347 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1348 ret = AVERROR_INVALIDDATA;
1356 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1357 avctx->skip_frame == AVDISCARD_ALL) {
1361 if (percent_missing(s) > avctx->discard_damaged_percentage)
1362 return AVERROR_INVALIDDATA;
1364 if (s->bits_per_pixel <= 4)
1365 handle_small_bpp(s, p);
1367 /* apply transparency if needed */
1368 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1369 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1370 size_t raw_bpp = s->bpp - byte_depth;
1373 av_assert0(s->bit_depth > 1);
1375 for (y = 0; y < s->height; ++y) {
1376 uint8_t *row = &p->data[0][p->linesize[0] * y];
1378 if (s->bpp == 2 && byte_depth == 1) {
1379 uint8_t *pixel = &row[2 * s->width - 1];
1380 uint8_t *rowp = &row[1 * s->width - 1];
1381 int tcolor = s->transparent_color_be[0];
1382 for (x = s->width; x > 0; --x) {
1383 *pixel-- = *rowp == tcolor ? 0 : 0xff;
1386 } else if (s->bpp == 4 && byte_depth == 1) {
1387 uint8_t *pixel = &row[4 * s->width - 1];
1388 uint8_t *rowp = &row[3 * s->width - 1];
1389 int tcolor = AV_RL24(s->transparent_color_be);
1390 for (x = s->width; x > 0; --x) {
1391 *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1397 /* since we're updating in-place, we have to go from right to left */
1398 for (x = s->width; x > 0; --x) {
1399 uint8_t *pixel = &row[s->bpp * (x - 1)];
1400 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1402 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1403 memset(&pixel[raw_bpp], 0, byte_depth);
1405 memset(&pixel[raw_bpp], 0xff, byte_depth);
1412 /* handle P-frames only if a predecessor frame is available */
1413 if (s->last_picture.f->data[0]) {
1414 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1415 && s->last_picture.f->width == p->width
1416 && s->last_picture.f->height== p->height
1417 && s->last_picture.f->format== p->format
1419 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1420 handle_p_frame_png(s, p);
1421 else if (CONFIG_APNG_DECODER &&
1422 avctx->codec_id == AV_CODEC_ID_APNG &&
1423 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1427 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1432 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1436 static void clear_frame_metadata(PNGDecContext *s)
1438 av_freep(&s->iccp_data);
1439 s->iccp_data_len = 0;
1440 s->iccp_name[0] = 0;
1442 s->stereo_mode = -1;
1446 av_dict_free(&s->frame_metadata);
1449 static int output_frame(PNGDecContext *s, AVFrame *f,
1454 ret = av_frame_ref(f, src);
1459 AVFrameSideData *sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, s->iccp_data_len);
1461 ret = AVERROR(ENOMEM);
1464 memcpy(sd->data, s->iccp_data, s->iccp_data_len);
1466 av_dict_set(&sd->metadata, "name", s->iccp_name, 0);
1469 if (s->stereo_mode >= 0) {
1470 AVStereo3D *stereo3d = av_stereo3d_create_side_data(f);
1472 ret = AVERROR(ENOMEM);
1476 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1477 stereo3d->flags = s->stereo_mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1481 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(f);
1483 ret = AVERROR(ENOMEM);
1487 mdm->white_point[0] = av_make_q(s->white_point[0], 100000);
1488 mdm->white_point[1] = av_make_q(s->white_point[1], 100000);
1491 for (int i = 0; i < 3; i++) {
1492 mdm->display_primaries[i][0] = av_make_q(s->display_primaries[i][0], 100000);
1493 mdm->display_primaries[i][1] = av_make_q(s->display_primaries[i][1], 100000);
1496 mdm->has_primaries = 1;
1499 FFSWAP(AVDictionary*, f->metadata, s->frame_metadata);
1507 #if CONFIG_PNG_DECODER
1508 static int decode_frame_png(AVCodecContext *avctx,
1509 void *data, int *got_frame,
1512 PNGDecContext *const s = avctx->priv_data;
1513 const uint8_t *buf = avpkt->data;
1514 int buf_size = avpkt->size;
1515 AVFrame *dst_frame = data;
1516 AVFrame *p = s->picture.f;
1520 clear_frame_metadata(s);
1522 bytestream2_init(&s->gb, buf, buf_size);
1524 /* check signature */
1525 sig = bytestream2_get_be64(&s->gb);
1526 if (sig != PNGSIG &&
1528 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1529 return AVERROR_INVALIDDATA;
1532 s->y = s->has_trns = 0;
1537 s->zstream.zalloc = ff_png_zalloc;
1538 s->zstream.zfree = ff_png_zfree;
1539 s->zstream.opaque = NULL;
1540 ret = inflateInit(&s->zstream);
1542 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1543 return AVERROR_EXTERNAL;
1546 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1549 if (avctx->skip_frame == AVDISCARD_ALL) {
1551 ret = bytestream2_tell(&s->gb);
1555 ret = output_frame(s, dst_frame, s->picture.f);
1559 if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1560 ff_thread_release_buffer(avctx, &s->last_picture);
1561 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1566 ret = bytestream2_tell(&s->gb);
1568 inflateEnd(&s->zstream);
1574 #if CONFIG_APNG_DECODER
1575 static int decode_frame_apng(AVCodecContext *avctx,
1576 void *data, int *got_frame,
1579 PNGDecContext *const s = avctx->priv_data;
1580 AVFrame *dst_frame = data;
1582 AVFrame *p = s->picture.f;
1584 clear_frame_metadata(s);
1586 if (!(s->hdr_state & PNG_IHDR)) {
1587 if (!avctx->extradata_size)
1588 return AVERROR_INVALIDDATA;
1590 /* only init fields, there is no zlib use in extradata */
1591 s->zstream.zalloc = ff_png_zalloc;
1592 s->zstream.zfree = ff_png_zfree;
1594 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1595 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1599 /* reset state for a new frame */
1600 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1601 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1602 ret = AVERROR_EXTERNAL;
1607 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1608 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1611 if (!(s->pic_state & PNG_ALLIMAGE))
1612 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1613 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1614 ret = AVERROR_INVALIDDATA;
1618 ret = output_frame(s, dst_frame, s->picture.f);
1622 if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1623 if (s->dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1624 ff_thread_release_buffer(avctx, &s->picture);
1625 } else if (s->dispose_op == APNG_DISPOSE_OP_NONE) {
1626 ff_thread_release_buffer(avctx, &s->last_picture);
1627 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1632 ret = bytestream2_tell(&s->gb);
1635 inflateEnd(&s->zstream);
1641 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1643 PNGDecContext *psrc = src->priv_data;
1644 PNGDecContext *pdst = dst->priv_data;
1645 ThreadFrame *src_frame = NULL;
1651 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1653 pdst->width = psrc->width;
1654 pdst->height = psrc->height;
1655 pdst->bit_depth = psrc->bit_depth;
1656 pdst->color_type = psrc->color_type;
1657 pdst->compression_type = psrc->compression_type;
1658 pdst->interlace_type = psrc->interlace_type;
1659 pdst->filter_type = psrc->filter_type;
1660 pdst->cur_w = psrc->cur_w;
1661 pdst->cur_h = psrc->cur_h;
1662 pdst->x_offset = psrc->x_offset;
1663 pdst->y_offset = psrc->y_offset;
1664 pdst->has_trns = psrc->has_trns;
1665 memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1667 pdst->dispose_op = psrc->dispose_op;
1669 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1671 pdst->hdr_state |= psrc->hdr_state;
1674 src_frame = psrc->dispose_op == APNG_DISPOSE_OP_NONE ?
1675 &psrc->picture : &psrc->last_picture;
1677 ff_thread_release_buffer(dst, &pdst->last_picture);
1678 if (src_frame && src_frame->f->data[0]) {
1679 ret = ff_thread_ref_frame(&pdst->last_picture, src_frame);
1688 static av_cold int png_dec_init(AVCodecContext *avctx)
1690 PNGDecContext *s = avctx->priv_data;
1692 avctx->color_range = AVCOL_RANGE_JPEG;
1695 s->last_picture.f = av_frame_alloc();
1696 s->picture.f = av_frame_alloc();
1697 if (!s->last_picture.f || !s->picture.f) {
1698 av_frame_free(&s->last_picture.f);
1699 av_frame_free(&s->picture.f);
1700 return AVERROR(ENOMEM);
1703 ff_pngdsp_init(&s->dsp);
1708 static av_cold int png_dec_end(AVCodecContext *avctx)
1710 PNGDecContext *s = avctx->priv_data;
1712 ff_thread_release_buffer(avctx, &s->last_picture);
1713 av_frame_free(&s->last_picture.f);
1714 ff_thread_release_buffer(avctx, &s->picture);
1715 av_frame_free(&s->picture.f);
1716 av_freep(&s->buffer);
1718 av_freep(&s->last_row);
1719 s->last_row_size = 0;
1720 av_freep(&s->tmp_row);
1721 s->tmp_row_size = 0;
1722 av_freep(&s->background_buf);
1724 av_freep(&s->iccp_data);
1725 av_dict_free(&s->frame_metadata);
1730 #if CONFIG_APNG_DECODER
1731 AVCodec ff_apng_decoder = {
1733 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1734 .type = AVMEDIA_TYPE_VIDEO,
1735 .id = AV_CODEC_ID_APNG,
1736 .priv_data_size = sizeof(PNGDecContext),
1737 .init = png_dec_init,
1738 .close = png_dec_end,
1739 .decode = decode_frame_apng,
1740 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1741 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1742 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
1743 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1747 #if CONFIG_PNG_DECODER
1748 AVCodec ff_png_decoder = {
1750 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1751 .type = AVMEDIA_TYPE_VIDEO,
1752 .id = AV_CODEC_ID_PNG,
1753 .priv_data_size = sizeof(PNGDecContext),
1754 .init = png_dec_init,
1755 .close = png_dec_end,
1756 .decode = decode_frame_png,
1757 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1758 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1759 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1760 FF_CODEC_CAP_ALLOCATE_PROGRESS,