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 uint32_t palette[256];
95 unsigned int last_row_size;
97 unsigned int tmp_row_size;
101 int crow_size; /* compressed row size (include filter type) */
102 int row_size; /* decompressed row size */
103 int pass_row_size; /* decompress row size of the current pass */
108 /* Mask to determine which pixels are valid in a pass */
109 static const uint8_t png_pass_mask[NB_PASSES] = {
110 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
113 /* Mask to determine which y pixels can be written in a pass */
114 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
115 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
118 /* Mask to determine which pixels to overwrite while displaying */
119 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
120 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
123 /* NOTE: we try to construct a good looking image at each pass. width
124 * is the original image width. We also do pixel format conversion at
126 static void png_put_interlaced_row(uint8_t *dst, int width,
127 int bits_per_pixel, int pass,
128 int color_type, const uint8_t *src)
130 int x, mask, dsp_mask, j, src_x, b, bpp;
134 mask = png_pass_mask[pass];
135 dsp_mask = png_pass_dsp_mask[pass];
137 switch (bits_per_pixel) {
140 for (x = 0; x < width; x++) {
142 if ((dsp_mask << j) & 0x80) {
143 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
144 dst[x >> 3] &= 0xFF7F>>j;
145 dst[x >> 3] |= b << (7 - j);
147 if ((mask << j) & 0x80)
153 for (x = 0; x < width; x++) {
154 int j2 = 2 * (x & 3);
156 if ((dsp_mask << j) & 0x80) {
157 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
158 dst[x >> 2] &= 0xFF3F>>j2;
159 dst[x >> 2] |= b << (6 - j2);
161 if ((mask << j) & 0x80)
167 for (x = 0; x < width; x++) {
170 if ((dsp_mask << j) & 0x80) {
171 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
172 dst[x >> 1] &= 0xFF0F>>j2;
173 dst[x >> 1] |= b << (4 - j2);
175 if ((mask << j) & 0x80)
180 bpp = bits_per_pixel >> 3;
183 for (x = 0; x < width; x++) {
185 if ((dsp_mask << j) & 0x80) {
189 if ((mask << j) & 0x80)
196 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
200 for (i = 0; i < w; i++) {
201 int a, b, c, p, pa, pb, pc;
214 if (pa <= pb && pa <= pc)
224 #define UNROLL1(bpp, op) \
233 for (; i <= size - bpp; i += bpp) { \
234 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
237 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
240 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
243 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
247 #define UNROLL_FILTER(op) \
250 } else if (bpp == 2) { \
252 } else if (bpp == 3) { \
254 } else if (bpp == 4) { \
257 for (; i < size; i++) { \
258 dst[i] = op(dst[i - bpp], src[i], last[i]); \
261 /* NOTE: 'dst' can be equal to 'last' */
262 void ff_png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
263 uint8_t *src, uint8_t *last, int size, int bpp)
265 int i, p, r, g, b, a;
267 switch (filter_type) {
268 case PNG_FILTER_VALUE_NONE:
269 memcpy(dst, src, size);
271 case PNG_FILTER_VALUE_SUB:
272 for (i = 0; i < bpp; i++)
276 for (; i < size; i += bpp) {
277 unsigned s = *(int *)(src + i);
278 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
279 *(int *)(dst + i) = p;
282 #define OP_SUB(x, s, l) ((x) + (s))
283 UNROLL_FILTER(OP_SUB);
286 case PNG_FILTER_VALUE_UP:
287 dsp->add_bytes_l2(dst, src, last, size);
289 case PNG_FILTER_VALUE_AVG:
290 for (i = 0; i < bpp; i++) {
294 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
295 UNROLL_FILTER(OP_AVG);
297 case PNG_FILTER_VALUE_PAETH:
298 for (i = 0; i < bpp; i++) {
302 if (bpp > 2 && size > 4) {
303 /* would write off the end of the array if we let it process
304 * the last pixel with bpp=3 */
305 int w = (bpp & 3) ? size - 3 : size;
308 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
312 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
317 /* This used to be called "deloco" in FFmpeg
318 * and is actually an inverse reversible colorspace transformation */
319 #define YUV2RGB(NAME, TYPE) \
320 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
323 for (i = 0; i < size; i += 3 + alpha) { \
324 int g = dst [i + 1]; \
330 YUV2RGB(rgb8, uint8_t)
331 YUV2RGB(rgb16, uint16_t)
333 static int percent_missing(PNGDecContext *s)
335 if (s->interlace_type) {
336 return 100 - 100 * s->pass / (NB_PASSES - 1);
338 return 100 - 100 * s->y / s->cur_h;
342 /* process exactly one decompressed row */
343 static void png_handle_row(PNGDecContext *s, uint8_t *dst, ptrdiff_t dst_stride)
345 uint8_t *ptr, *last_row;
348 if (!s->interlace_type) {
349 ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
351 last_row = s->last_row;
353 last_row = ptr - dst_stride;
355 ff_png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
356 last_row, s->row_size, s->bpp);
357 /* loco lags by 1 row so that it doesn't interfere with top prediction */
358 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
359 if (s->bit_depth == 16) {
360 deloco_rgb16((uint16_t *)(ptr - dst_stride), s->row_size / 2,
361 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
363 deloco_rgb8(ptr - dst_stride, s->row_size,
364 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
368 if (s->y == s->cur_h) {
369 s->pic_state |= PNG_ALLIMAGE;
370 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
371 if (s->bit_depth == 16) {
372 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
373 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
375 deloco_rgb8(ptr, s->row_size,
376 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
383 ptr = dst + dst_stride * (s->y + s->y_offset) + s->x_offset * s->bpp;
384 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
385 /* if we already read one row, it is time to stop to
386 * wait for the next one */
389 ff_png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
390 s->last_row, s->pass_row_size, s->bpp);
391 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
392 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
395 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
396 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
397 s->color_type, s->last_row);
400 if (s->y == s->cur_h) {
401 memset(s->last_row, 0, s->row_size);
403 if (s->pass == NB_PASSES - 1) {
404 s->pic_state |= PNG_ALLIMAGE;
409 s->pass_row_size = ff_png_pass_row_size(s->pass,
412 s->crow_size = s->pass_row_size + 1;
413 if (s->pass_row_size != 0)
415 /* skip pass if empty row */
424 static int png_decode_idat(PNGDecContext *s, int length,
425 uint8_t *dst, ptrdiff_t dst_stride)
428 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
429 s->zstream.next_in = s->gb.buffer;
430 bytestream2_skip(&s->gb, length);
432 /* decode one line if possible */
433 while (s->zstream.avail_in > 0) {
434 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
435 if (ret != Z_OK && ret != Z_STREAM_END) {
436 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
437 return AVERROR_EXTERNAL;
439 if (s->zstream.avail_out == 0) {
440 if (!(s->pic_state & PNG_ALLIMAGE)) {
441 png_handle_row(s, dst, dst_stride);
443 s->zstream.avail_out = s->crow_size;
444 s->zstream.next_out = s->crow_buf;
446 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
447 av_log(s->avctx, AV_LOG_WARNING,
448 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
455 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
456 const uint8_t *data_end)
463 zstream.zalloc = ff_png_zalloc;
464 zstream.zfree = ff_png_zfree;
465 zstream.opaque = NULL;
466 if (inflateInit(&zstream) != Z_OK)
467 return AVERROR_EXTERNAL;
468 zstream.next_in = data;
469 zstream.avail_in = data_end - data;
470 av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
472 while (zstream.avail_in > 0) {
473 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
475 ret = AVERROR(ENOMEM);
478 zstream.next_out = buf;
479 zstream.avail_out = buf_size - 1;
480 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
481 if (ret != Z_OK && ret != Z_STREAM_END) {
482 ret = AVERROR_EXTERNAL;
485 bp->len += zstream.next_out - buf;
486 if (ret == Z_STREAM_END)
489 inflateEnd(&zstream);
490 bp->str[bp->len] = 0;
494 inflateEnd(&zstream);
495 av_bprint_finalize(bp, NULL);
499 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
504 for (i = 0; i < size_in; i++)
505 extra += in[i] >= 0x80;
506 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
508 q = out = av_malloc(size_in + extra + 1);
511 for (i = 0; i < size_in; i++) {
513 *(q++) = 0xC0 | (in[i] >> 6);
514 *(q++) = 0x80 | (in[i] & 0x3F);
523 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed)
526 const uint8_t *data = s->gb.buffer;
527 const uint8_t *data_end = data + length;
528 const uint8_t *keyword = data;
529 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
530 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
535 return AVERROR_INVALIDDATA;
536 data = keyword_end + 1;
539 if (data == data_end)
540 return AVERROR_INVALIDDATA;
543 return AVERROR_INVALIDDATA;
544 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
547 ret = av_bprint_finalize(&bp, (char **)&text);
551 text = (uint8_t *)data;
552 text_len = data_end - text;
555 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
556 txt_utf8 = iso88591_to_utf8(text, text_len);
559 if (!(kw_utf8 && txt_utf8)) {
562 return AVERROR(ENOMEM);
565 av_dict_set(&s->frame_metadata, kw_utf8, txt_utf8,
566 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
570 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
574 return AVERROR_INVALIDDATA;
576 if (s->pic_state & PNG_IDAT) {
577 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
578 return AVERROR_INVALIDDATA;
581 if (s->hdr_state & PNG_IHDR) {
582 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
583 return AVERROR_INVALIDDATA;
586 s->width = s->cur_w = bytestream2_get_be32(&s->gb);
587 s->height = s->cur_h = bytestream2_get_be32(&s->gb);
588 if (av_image_check_size(s->width, s->height, 0, avctx)) {
589 s->cur_w = s->cur_h = s->width = s->height = 0;
590 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
591 return AVERROR_INVALIDDATA;
593 s->bit_depth = bytestream2_get_byte(&s->gb);
594 if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
595 s->bit_depth != 8 && s->bit_depth != 16) {
596 av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
599 s->color_type = bytestream2_get_byte(&s->gb);
600 s->compression_type = bytestream2_get_byte(&s->gb);
601 if (s->compression_type) {
602 av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
605 s->filter_type = bytestream2_get_byte(&s->gb);
606 s->interlace_type = bytestream2_get_byte(&s->gb);
607 bytestream2_skip(&s->gb, 4); /* crc */
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)
624 if (s->pic_state & PNG_IDAT) {
625 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
626 return AVERROR_INVALIDDATA;
628 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
629 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
630 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
631 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
632 bytestream2_skip(&s->gb, 1); /* unit specifier */
633 bytestream2_skip(&s->gb, 4); /* crc */
638 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
639 uint32_t length, 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, length, p->data[0], p->linesize[0]);
778 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
779 s->bpp += byte_depth;
784 bytestream2_skip(&s->gb, 4); /* crc */
789 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
794 if ((length % 3) != 0 || length > 256 * 3)
795 return AVERROR_INVALIDDATA;
796 /* read the palette */
798 for (i = 0; i < n; i++) {
799 r = bytestream2_get_byte(&s->gb);
800 g = bytestream2_get_byte(&s->gb);
801 b = bytestream2_get_byte(&s->gb);
802 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
805 s->palette[i] = (0xFFU << 24);
806 s->hdr_state |= PNG_PLTE;
807 bytestream2_skip(&s->gb, 4); /* crc */
812 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
817 if (!(s->hdr_state & PNG_IHDR)) {
818 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
819 return AVERROR_INVALIDDATA;
822 if (s->pic_state & PNG_IDAT) {
823 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
824 return AVERROR_INVALIDDATA;
827 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
828 if (length > 256 || !(s->hdr_state & PNG_PLTE))
829 return AVERROR_INVALIDDATA;
831 for (i = 0; i < length; i++) {
832 unsigned v = bytestream2_get_byte(&s->gb);
833 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
835 } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
836 if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
837 (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
839 return AVERROR_INVALIDDATA;
841 for (i = 0; i < length / 2; i++) {
842 /* only use the least significant bits */
843 v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
845 if (s->bit_depth > 8)
846 AV_WB16(&s->transparent_color_be[2 * i], v);
848 s->transparent_color_be[i] = v;
851 return AVERROR_INVALIDDATA;
854 bytestream2_skip(&s->gb, 4); /* crc */
860 static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
865 while ((s->iccp_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
867 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
868 ret = AVERROR_INVALIDDATA;
872 length = FFMAX(length - cnt, 0);
874 if (bytestream2_get_byte(&s->gb) != 0) {
875 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
876 ret = AVERROR_INVALIDDATA;
880 length = FFMAX(length - 1, 0);
882 if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
885 av_freep(&s->iccp_data);
886 ret = av_bprint_finalize(&bp, (char **)&s->iccp_data);
889 s->iccp_data_len = bp.len;
891 /* ICC compressed data and CRC */
892 bytestream2_skip(&s->gb, length + 4);
900 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
902 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
904 uint8_t *pd = p->data[0];
905 for (j = 0; j < s->height; j++) {
907 for (k = 7; k >= 1; k--)
908 if ((s->width&7) >= k)
909 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
910 for (i--; i >= 0; i--) {
911 pd[8*i + 7]= pd[i] & 1;
912 pd[8*i + 6]= (pd[i]>>1) & 1;
913 pd[8*i + 5]= (pd[i]>>2) & 1;
914 pd[8*i + 4]= (pd[i]>>3) & 1;
915 pd[8*i + 3]= (pd[i]>>4) & 1;
916 pd[8*i + 2]= (pd[i]>>5) & 1;
917 pd[8*i + 1]= (pd[i]>>6) & 1;
918 pd[8*i + 0]= pd[i]>>7;
920 pd += p->linesize[0];
922 } else if (s->bits_per_pixel == 2) {
924 uint8_t *pd = p->data[0];
925 for (j = 0; j < s->height; j++) {
927 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
928 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
929 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
930 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
931 for (i--; i >= 0; i--) {
932 pd[4*i + 3]= pd[i] & 3;
933 pd[4*i + 2]= (pd[i]>>2) & 3;
934 pd[4*i + 1]= (pd[i]>>4) & 3;
935 pd[4*i + 0]= pd[i]>>6;
938 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
939 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
940 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
941 for (i--; i >= 0; i--) {
942 pd[4*i + 3]= ( pd[i] & 3)*0x55;
943 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
944 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
945 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
948 pd += p->linesize[0];
950 } else if (s->bits_per_pixel == 4) {
952 uint8_t *pd = p->data[0];
953 for (j = 0; j < s->height; j++) {
955 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
956 if (s->width&1) pd[2*i+0]= pd[i]>>4;
957 for (i--; i >= 0; i--) {
958 pd[2*i + 1] = pd[i] & 15;
959 pd[2*i + 0] = pd[i] >> 4;
962 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
963 for (i--; i >= 0; i--) {
964 pd[2*i + 1] = (pd[i] & 15) * 0x11;
965 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
968 pd += p->linesize[0];
973 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
976 uint32_t sequence_number;
977 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
980 return AVERROR_INVALIDDATA;
982 if (!(s->hdr_state & PNG_IHDR)) {
983 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
984 return AVERROR_INVALIDDATA;
987 if (s->pic_state & PNG_IDAT) {
988 av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
989 return AVERROR_INVALIDDATA;
992 s->last_w = s->cur_w;
993 s->last_h = s->cur_h;
994 s->last_x_offset = s->x_offset;
995 s->last_y_offset = s->y_offset;
996 s->last_dispose_op = s->dispose_op;
998 sequence_number = bytestream2_get_be32(&s->gb);
999 cur_w = bytestream2_get_be32(&s->gb);
1000 cur_h = bytestream2_get_be32(&s->gb);
1001 x_offset = bytestream2_get_be32(&s->gb);
1002 y_offset = bytestream2_get_be32(&s->gb);
1003 bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
1004 dispose_op = bytestream2_get_byte(&s->gb);
1005 blend_op = bytestream2_get_byte(&s->gb);
1006 bytestream2_skip(&s->gb, 4); /* crc */
1008 if (sequence_number == 0 &&
1009 (cur_w != s->width ||
1010 cur_h != s->height ||
1013 cur_w <= 0 || cur_h <= 0 ||
1014 x_offset < 0 || y_offset < 0 ||
1015 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1016 return AVERROR_INVALIDDATA;
1018 if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1019 av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1020 return AVERROR_INVALIDDATA;
1023 if ((sequence_number == 0 || !s->last_picture.f->data[0]) &&
1024 dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1025 // No previous frame to revert to for the first frame
1026 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1027 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1030 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1031 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1032 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1033 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1034 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1035 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1036 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1038 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1039 blend_op = APNG_BLEND_OP_SOURCE;
1044 s->x_offset = x_offset;
1045 s->y_offset = y_offset;
1046 s->dispose_op = dispose_op;
1047 s->blend_op = blend_op;
1052 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1055 uint8_t *pd = p->data[0];
1056 uint8_t *pd_last = s->last_picture.f->data[0];
1057 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1059 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1060 for (j = 0; j < s->height; j++) {
1061 for (i = 0; i < ls; i++)
1062 pd[i] += pd_last[i];
1063 pd += p->linesize[0];
1064 pd_last += s->last_picture.f->linesize[0];
1068 // divide by 255 and round to nearest
1069 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1070 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1072 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1075 uint8_t *dst = p->data[0];
1076 ptrdiff_t dst_stride = p->linesize[0];
1077 const uint8_t *src = s->last_picture.f->data[0];
1078 ptrdiff_t src_stride = s->last_picture.f->linesize[0];
1082 if (s->blend_op == APNG_BLEND_OP_OVER &&
1083 avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1084 avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
1085 avctx->pix_fmt != AV_PIX_FMT_PAL8) {
1086 avpriv_request_sample(avctx, "Blending with pixel format %s",
1087 av_get_pix_fmt_name(avctx->pix_fmt));
1088 return AVERROR_PATCHWELCOME;
1091 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1093 // need to reset a rectangle to background:
1094 // create a new writable copy
1095 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
1096 int ret = av_frame_make_writable(s->last_picture.f);
1100 src = s->last_picture.f->data[0];
1101 src_stride = s->last_picture.f->linesize[0];
1103 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; y++) {
1104 memset(s->last_picture.f->data[0] + src_stride * y +
1105 s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1109 // copy unchanged rectangles from the last frame
1110 for (y = 0; y < s->y_offset; y++)
1111 memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
1112 for (y = s->y_offset; y < s->y_offset + s->cur_h; y++) {
1113 memcpy(dst + y * dst_stride, src + y * src_stride, s->x_offset * s->bpp);
1114 memcpy(dst + y * dst_stride + (s->x_offset + s->cur_w) * s->bpp,
1115 src + y * src_stride + (s->x_offset + s->cur_w) * s->bpp,
1116 (p->width - s->cur_w - s->x_offset) * s->bpp);
1118 for (y = s->y_offset + s->cur_h; y < p->height; y++)
1119 memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
1121 if (s->blend_op == APNG_BLEND_OP_OVER) {
1123 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1124 uint8_t *foreground = dst + dst_stride * y + s->bpp * s->x_offset;
1125 const uint8_t *background = src + src_stride * y + s->bpp * s->x_offset;
1126 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1128 uint8_t foreground_alpha, background_alpha, output_alpha;
1131 // Since we might be blending alpha onto alpha, we use the following equations:
1132 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1133 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1135 switch (avctx->pix_fmt) {
1136 case AV_PIX_FMT_RGBA:
1137 foreground_alpha = foreground[3];
1138 background_alpha = background[3];
1141 case AV_PIX_FMT_GRAY8A:
1142 foreground_alpha = foreground[1];
1143 background_alpha = background[1];
1146 case AV_PIX_FMT_PAL8:
1147 foreground_alpha = s->palette[foreground[0]] >> 24;
1148 background_alpha = s->palette[background[0]] >> 24;
1152 if (foreground_alpha == 255)
1155 if (foreground_alpha == 0) {
1156 memcpy(foreground, background, s->bpp);
1160 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1161 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1162 avpriv_request_sample(avctx, "Alpha blending palette samples");
1166 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1168 av_assert0(s->bpp <= 10);
1170 for (b = 0; b < s->bpp - 1; ++b) {
1171 if (output_alpha == 0) {
1173 } else if (background_alpha == 255) {
1174 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1176 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1179 output[b] = output_alpha;
1180 memcpy(foreground, output, s->bpp);
1188 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1189 AVFrame *p, const AVPacket *avpkt)
1191 const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1192 uint32_t tag, length;
1193 int decode_next_dat = 0;
1197 length = bytestream2_get_bytes_left(&s->gb);
1200 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1201 avctx->skip_frame == AVDISCARD_ALL) {
1205 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1206 if (!(s->pic_state & PNG_IDAT))
1211 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1212 if ( s->pic_state & PNG_ALLIMAGE
1213 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1215 ret = AVERROR_INVALIDDATA;
1219 length = bytestream2_get_be32(&s->gb);
1220 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1221 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1222 ret = AVERROR_INVALIDDATA;
1225 if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_IGNORE_ERR)) {
1226 uint32_t crc_sig = AV_RB32(s->gb.buffer + length + 4);
1227 uint32_t crc_cal = ~av_crc(crc_tab, UINT32_MAX, s->gb.buffer, length + 4);
1228 if (crc_sig ^ crc_cal) {
1229 av_log(avctx, AV_LOG_ERROR, "CRC mismatch in chunk");
1230 if (avctx->err_recognition & AV_EF_EXPLODE) {
1231 av_log(avctx, AV_LOG_ERROR, ", quitting\n");
1232 ret = AVERROR_INVALIDDATA;
1235 av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1236 bytestream2_skip(&s->gb, 4); /* tag */
1240 tag = bytestream2_get_le32(&s->gb);
1241 if (avctx->debug & FF_DEBUG_STARTCODE)
1242 av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1243 av_fourcc2str(tag), length);
1245 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1246 avctx->skip_frame == AVDISCARD_ALL) {
1248 case MKTAG('I', 'H', 'D', 'R'):
1249 case MKTAG('p', 'H', 'Y', 's'):
1250 case MKTAG('t', 'E', 'X', 't'):
1251 case MKTAG('I', 'D', 'A', 'T'):
1252 case MKTAG('t', 'R', 'N', 'S'):
1260 case MKTAG('I', 'H', 'D', 'R'):
1261 if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1264 case MKTAG('p', 'H', 'Y', 's'):
1265 if ((ret = decode_phys_chunk(avctx, s)) < 0)
1268 case MKTAG('f', 'c', 'T', 'L'):
1269 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1271 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1273 decode_next_dat = 1;
1275 case MKTAG('f', 'd', 'A', 'T'):
1276 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1278 if (!decode_next_dat || length < 4) {
1279 ret = AVERROR_INVALIDDATA;
1282 bytestream2_get_be32(&s->gb);
1285 case MKTAG('I', 'D', 'A', 'T'):
1286 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1288 if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1291 case MKTAG('P', 'L', 'T', 'E'):
1292 if (decode_plte_chunk(avctx, s, length) < 0)
1295 case MKTAG('t', 'R', 'N', 'S'):
1296 if (decode_trns_chunk(avctx, s, length) < 0)
1299 case MKTAG('t', 'E', 'X', 't'):
1300 if (decode_text_chunk(s, length, 0) < 0)
1301 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1302 bytestream2_skip(&s->gb, length + 4);
1304 case MKTAG('z', 'T', 'X', 't'):
1305 if (decode_text_chunk(s, length, 1) < 0)
1306 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1307 bytestream2_skip(&s->gb, length + 4);
1309 case MKTAG('s', 'T', 'E', 'R'): {
1310 int mode = bytestream2_get_byte(&s->gb);
1312 if (mode == 0 || mode == 1) {
1313 s->stereo_mode = mode;
1315 av_log(avctx, AV_LOG_WARNING,
1316 "Unknown value in sTER chunk (%d)\n", mode);
1318 bytestream2_skip(&s->gb, 4); /* crc */
1321 case MKTAG('i', 'C', 'C', 'P'): {
1322 if ((ret = decode_iccp_chunk(s, length, p)) < 0)
1326 case MKTAG('c', 'H', 'R', 'M'): {
1329 s->white_point[0] = bytestream2_get_be32(&s->gb);
1330 s->white_point[1] = bytestream2_get_be32(&s->gb);
1333 for (i = 0; i < 3; i++) {
1334 s->display_primaries[i][0] = bytestream2_get_be32(&s->gb);
1335 s->display_primaries[i][1] = bytestream2_get_be32(&s->gb);
1338 bytestream2_skip(&s->gb, 4); /* crc */
1341 case MKTAG('g', 'A', 'M', 'A'): {
1344 int num = bytestream2_get_be32(&s->gb);
1346 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1347 av_bprintf(&bp, "%i/%i", num, 100000);
1348 ret = av_bprint_finalize(&bp, &gamma_str);
1352 av_dict_set(&s->frame_metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1354 bytestream2_skip(&s->gb, 4); /* crc */
1357 case MKTAG('I', 'E', 'N', 'D'):
1358 if (!(s->pic_state & PNG_ALLIMAGE))
1359 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1360 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1361 ret = AVERROR_INVALIDDATA;
1364 bytestream2_skip(&s->gb, 4); /* crc */
1369 bytestream2_skip(&s->gb, length + 4);
1375 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1376 avctx->skip_frame == AVDISCARD_ALL) {
1380 if (percent_missing(s) > avctx->discard_damaged_percentage)
1381 return AVERROR_INVALIDDATA;
1383 if (s->bits_per_pixel <= 4)
1384 handle_small_bpp(s, p);
1386 /* apply transparency if needed */
1387 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1388 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1389 size_t raw_bpp = s->bpp - byte_depth;
1392 av_assert0(s->bit_depth > 1);
1394 for (y = 0; y < s->height; ++y) {
1395 uint8_t *row = &p->data[0][p->linesize[0] * y];
1397 if (s->bpp == 2 && byte_depth == 1) {
1398 uint8_t *pixel = &row[2 * s->width - 1];
1399 uint8_t *rowp = &row[1 * s->width - 1];
1400 int tcolor = s->transparent_color_be[0];
1401 for (x = s->width; x > 0; --x) {
1402 *pixel-- = *rowp == tcolor ? 0 : 0xff;
1405 } else if (s->bpp == 4 && byte_depth == 1) {
1406 uint8_t *pixel = &row[4 * s->width - 1];
1407 uint8_t *rowp = &row[3 * s->width - 1];
1408 int tcolor = AV_RL24(s->transparent_color_be);
1409 for (x = s->width; x > 0; --x) {
1410 *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1416 /* since we're updating in-place, we have to go from right to left */
1417 for (x = s->width; x > 0; --x) {
1418 uint8_t *pixel = &row[s->bpp * (x - 1)];
1419 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1421 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1422 memset(&pixel[raw_bpp], 0, byte_depth);
1424 memset(&pixel[raw_bpp], 0xff, byte_depth);
1431 /* handle P-frames only if a predecessor frame is available */
1432 if (s->last_picture.f->data[0]) {
1433 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1434 && s->last_picture.f->width == p->width
1435 && s->last_picture.f->height== p->height
1436 && s->last_picture.f->format== p->format
1438 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1439 handle_p_frame_png(s, p);
1440 else if (CONFIG_APNG_DECODER &&
1441 avctx->codec_id == AV_CODEC_ID_APNG &&
1442 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1446 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1451 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1455 static void clear_frame_metadata(PNGDecContext *s)
1457 av_freep(&s->iccp_data);
1458 s->iccp_data_len = 0;
1459 s->iccp_name[0] = 0;
1461 s->stereo_mode = -1;
1465 av_dict_free(&s->frame_metadata);
1468 static int output_frame(PNGDecContext *s, AVFrame *f,
1473 ret = av_frame_ref(f, src);
1478 AVFrameSideData *sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, s->iccp_data_len);
1480 ret = AVERROR(ENOMEM);
1483 memcpy(sd->data, s->iccp_data, s->iccp_data_len);
1485 av_dict_set(&sd->metadata, "name", s->iccp_name, 0);
1488 if (s->stereo_mode >= 0) {
1489 AVStereo3D *stereo3d = av_stereo3d_create_side_data(f);
1491 ret = AVERROR(ENOMEM);
1495 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1496 stereo3d->flags = s->stereo_mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1500 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(f);
1502 ret = AVERROR(ENOMEM);
1506 mdm->white_point[0] = av_make_q(s->white_point[0], 100000);
1507 mdm->white_point[1] = av_make_q(s->white_point[1], 100000);
1510 for (int i = 0; i < 3; i++) {
1511 mdm->display_primaries[i][0] = av_make_q(s->display_primaries[i][0], 100000);
1512 mdm->display_primaries[i][1] = av_make_q(s->display_primaries[i][1], 100000);
1515 mdm->has_primaries = 1;
1518 FFSWAP(AVDictionary*, f->metadata, s->frame_metadata);
1526 #if CONFIG_PNG_DECODER
1527 static int decode_frame_png(AVCodecContext *avctx,
1528 void *data, int *got_frame,
1531 PNGDecContext *const s = avctx->priv_data;
1532 const uint8_t *buf = avpkt->data;
1533 int buf_size = avpkt->size;
1534 AVFrame *dst_frame = data;
1535 AVFrame *p = s->picture.f;
1539 clear_frame_metadata(s);
1541 bytestream2_init(&s->gb, buf, buf_size);
1543 /* check signature */
1544 sig = bytestream2_get_be64(&s->gb);
1545 if (sig != PNGSIG &&
1547 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1548 return AVERROR_INVALIDDATA;
1551 s->y = s->has_trns = 0;
1556 s->zstream.zalloc = ff_png_zalloc;
1557 s->zstream.zfree = ff_png_zfree;
1558 s->zstream.opaque = NULL;
1559 ret = inflateInit(&s->zstream);
1561 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1562 return AVERROR_EXTERNAL;
1565 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1568 if (avctx->skip_frame == AVDISCARD_ALL) {
1570 ret = bytestream2_tell(&s->gb);
1574 ret = output_frame(s, dst_frame, s->picture.f);
1578 if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1579 ff_thread_release_buffer(avctx, &s->last_picture);
1580 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1585 ret = bytestream2_tell(&s->gb);
1587 inflateEnd(&s->zstream);
1593 #if CONFIG_APNG_DECODER
1594 static int decode_frame_apng(AVCodecContext *avctx,
1595 void *data, int *got_frame,
1598 PNGDecContext *const s = avctx->priv_data;
1599 AVFrame *dst_frame = data;
1601 AVFrame *p = s->picture.f;
1603 clear_frame_metadata(s);
1605 if (!(s->hdr_state & PNG_IHDR)) {
1606 if (!avctx->extradata_size)
1607 return AVERROR_INVALIDDATA;
1609 /* only init fields, there is no zlib use in extradata */
1610 s->zstream.zalloc = ff_png_zalloc;
1611 s->zstream.zfree = ff_png_zfree;
1613 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1614 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1618 /* reset state for a new frame */
1619 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1620 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1621 ret = AVERROR_EXTERNAL;
1626 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1627 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1630 if (!(s->pic_state & PNG_ALLIMAGE))
1631 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1632 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1633 ret = AVERROR_INVALIDDATA;
1637 ret = output_frame(s, dst_frame, s->picture.f);
1641 if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1642 if (s->dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1643 ff_thread_release_buffer(avctx, &s->picture);
1644 } else if (s->dispose_op == APNG_DISPOSE_OP_NONE) {
1645 ff_thread_release_buffer(avctx, &s->last_picture);
1646 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1651 ret = bytestream2_tell(&s->gb);
1654 inflateEnd(&s->zstream);
1660 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1662 PNGDecContext *psrc = src->priv_data;
1663 PNGDecContext *pdst = dst->priv_data;
1664 ThreadFrame *src_frame = NULL;
1670 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1672 pdst->width = psrc->width;
1673 pdst->height = psrc->height;
1674 pdst->bit_depth = psrc->bit_depth;
1675 pdst->color_type = psrc->color_type;
1676 pdst->compression_type = psrc->compression_type;
1677 pdst->interlace_type = psrc->interlace_type;
1678 pdst->filter_type = psrc->filter_type;
1679 pdst->cur_w = psrc->cur_w;
1680 pdst->cur_h = psrc->cur_h;
1681 pdst->x_offset = psrc->x_offset;
1682 pdst->y_offset = psrc->y_offset;
1683 pdst->has_trns = psrc->has_trns;
1684 memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1686 pdst->dispose_op = psrc->dispose_op;
1688 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1690 pdst->hdr_state |= psrc->hdr_state;
1693 src_frame = psrc->dispose_op == APNG_DISPOSE_OP_NONE ?
1694 &psrc->picture : &psrc->last_picture;
1696 ff_thread_release_buffer(dst, &pdst->last_picture);
1697 if (src_frame && src_frame->f->data[0]) {
1698 ret = ff_thread_ref_frame(&pdst->last_picture, src_frame);
1707 static av_cold int png_dec_init(AVCodecContext *avctx)
1709 PNGDecContext *s = avctx->priv_data;
1711 avctx->color_range = AVCOL_RANGE_JPEG;
1714 s->last_picture.f = av_frame_alloc();
1715 s->picture.f = av_frame_alloc();
1716 if (!s->last_picture.f || !s->picture.f) {
1717 av_frame_free(&s->last_picture.f);
1718 av_frame_free(&s->picture.f);
1719 return AVERROR(ENOMEM);
1722 ff_pngdsp_init(&s->dsp);
1727 static av_cold int png_dec_end(AVCodecContext *avctx)
1729 PNGDecContext *s = avctx->priv_data;
1731 ff_thread_release_buffer(avctx, &s->last_picture);
1732 av_frame_free(&s->last_picture.f);
1733 ff_thread_release_buffer(avctx, &s->picture);
1734 av_frame_free(&s->picture.f);
1735 av_freep(&s->buffer);
1737 av_freep(&s->last_row);
1738 s->last_row_size = 0;
1739 av_freep(&s->tmp_row);
1740 s->tmp_row_size = 0;
1742 av_freep(&s->iccp_data);
1743 av_dict_free(&s->frame_metadata);
1748 #if CONFIG_APNG_DECODER
1749 AVCodec ff_apng_decoder = {
1751 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1752 .type = AVMEDIA_TYPE_VIDEO,
1753 .id = AV_CODEC_ID_APNG,
1754 .priv_data_size = sizeof(PNGDecContext),
1755 .init = png_dec_init,
1756 .close = png_dec_end,
1757 .decode = decode_frame_apng,
1758 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1759 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1760 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
1761 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1765 #if CONFIG_PNG_DECODER
1766 AVCodec ff_png_decoder = {
1768 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1769 .type = AVMEDIA_TYPE_VIDEO,
1770 .id = AV_CODEC_ID_PNG,
1771 .priv_data_size = sizeof(PNGDecContext),
1772 .init = png_dec_init,
1773 .close = png_dec_end,
1774 .decode = decode_frame_png,
1775 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1776 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1777 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1778 FF_CODEC_CAP_ALLOCATE_PROGRESS,