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, GetByteContext *gb,
425 uint8_t *dst, ptrdiff_t dst_stride)
428 s->zstream.avail_in = bytestream2_get_bytes_left(gb);
429 s->zstream.next_in = gb->buffer;
431 /* decode one line if possible */
432 while (s->zstream.avail_in > 0) {
433 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
434 if (ret != Z_OK && ret != Z_STREAM_END) {
435 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
436 return AVERROR_EXTERNAL;
438 if (s->zstream.avail_out == 0) {
439 if (!(s->pic_state & PNG_ALLIMAGE)) {
440 png_handle_row(s, dst, dst_stride);
442 s->zstream.avail_out = s->crow_size;
443 s->zstream.next_out = s->crow_buf;
445 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
446 av_log(s->avctx, AV_LOG_WARNING,
447 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
454 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
455 const uint8_t *data_end)
462 zstream.zalloc = ff_png_zalloc;
463 zstream.zfree = ff_png_zfree;
464 zstream.opaque = NULL;
465 if (inflateInit(&zstream) != Z_OK)
466 return AVERROR_EXTERNAL;
467 zstream.next_in = data;
468 zstream.avail_in = data_end - data;
469 av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
471 while (zstream.avail_in > 0) {
472 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
474 ret = AVERROR(ENOMEM);
477 zstream.next_out = buf;
478 zstream.avail_out = buf_size - 1;
479 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
480 if (ret != Z_OK && ret != Z_STREAM_END) {
481 ret = AVERROR_EXTERNAL;
484 bp->len += zstream.next_out - buf;
485 if (ret == Z_STREAM_END)
488 inflateEnd(&zstream);
489 bp->str[bp->len] = 0;
493 inflateEnd(&zstream);
494 av_bprint_finalize(bp, NULL);
498 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
503 for (i = 0; i < size_in; i++)
504 extra += in[i] >= 0x80;
505 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
507 q = out = av_malloc(size_in + extra + 1);
510 for (i = 0; i < size_in; i++) {
512 *(q++) = 0xC0 | (in[i] >> 6);
513 *(q++) = 0x80 | (in[i] & 0x3F);
522 static int decode_text_chunk(PNGDecContext *s, GetByteContext *gb, int compressed)
525 const uint8_t *data = gb->buffer;
526 const uint8_t *data_end = gb->buffer_end;
527 const uint8_t *keyword = data;
528 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
529 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
534 return AVERROR_INVALIDDATA;
535 data = keyword_end + 1;
538 if (data == data_end)
539 return AVERROR_INVALIDDATA;
542 return AVERROR_INVALIDDATA;
543 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
546 ret = av_bprint_finalize(&bp, (char **)&text);
550 text = (uint8_t *)data;
551 text_len = data_end - text;
554 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
555 txt_utf8 = iso88591_to_utf8(text, text_len);
558 if (!(kw_utf8 && txt_utf8)) {
561 return AVERROR(ENOMEM);
564 av_dict_set(&s->frame_metadata, kw_utf8, txt_utf8,
565 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
569 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
572 if (bytestream2_get_bytes_left(gb) != 13)
573 return AVERROR_INVALIDDATA;
575 if (s->pic_state & PNG_IDAT) {
576 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
577 return AVERROR_INVALIDDATA;
580 if (s->hdr_state & PNG_IHDR) {
581 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
582 return AVERROR_INVALIDDATA;
585 s->width = s->cur_w = bytestream2_get_be32(gb);
586 s->height = s->cur_h = bytestream2_get_be32(gb);
587 if (av_image_check_size(s->width, s->height, 0, avctx)) {
588 s->cur_w = s->cur_h = s->width = s->height = 0;
589 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
590 return AVERROR_INVALIDDATA;
592 s->bit_depth = bytestream2_get_byte(gb);
593 if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
594 s->bit_depth != 8 && s->bit_depth != 16) {
595 av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
598 s->color_type = bytestream2_get_byte(gb);
599 s->compression_type = bytestream2_get_byte(gb);
600 if (s->compression_type) {
601 av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
604 s->filter_type = bytestream2_get_byte(gb);
605 s->interlace_type = bytestream2_get_byte(gb);
606 s->hdr_state |= PNG_IHDR;
607 if (avctx->debug & FF_DEBUG_PICT_INFO)
608 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
609 "compression_type=%d filter_type=%d interlace_type=%d\n",
610 s->width, s->height, s->bit_depth, s->color_type,
611 s->compression_type, s->filter_type, s->interlace_type);
615 s->cur_w = s->cur_h = s->width = s->height = 0;
617 return AVERROR_INVALIDDATA;
620 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s,
623 if (s->pic_state & PNG_IDAT) {
624 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
625 return AVERROR_INVALIDDATA;
627 avctx->sample_aspect_ratio.num = bytestream2_get_be32(gb);
628 avctx->sample_aspect_ratio.den = bytestream2_get_be32(gb);
629 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
630 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
631 bytestream2_skip(gb, 1); /* unit specifier */
636 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
637 GetByteContext *gb, AVFrame *p)
640 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
642 if (!(s->hdr_state & PNG_IHDR)) {
643 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
644 return AVERROR_INVALIDDATA;
646 if (!(s->pic_state & PNG_IDAT)) {
647 /* init image info */
648 ret = ff_set_dimensions(avctx, s->width, s->height);
652 s->channels = ff_png_get_nb_channels(s->color_type);
653 s->bits_per_pixel = s->bit_depth * s->channels;
654 s->bpp = (s->bits_per_pixel + 7) >> 3;
655 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
657 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
658 s->color_type == PNG_COLOR_TYPE_RGB) {
659 avctx->pix_fmt = AV_PIX_FMT_RGB24;
660 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
661 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
662 avctx->pix_fmt = AV_PIX_FMT_RGBA;
663 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
664 s->color_type == PNG_COLOR_TYPE_GRAY) {
665 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
666 } else if (s->bit_depth == 16 &&
667 s->color_type == PNG_COLOR_TYPE_GRAY) {
668 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
669 } else if (s->bit_depth == 16 &&
670 s->color_type == PNG_COLOR_TYPE_RGB) {
671 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
672 } else if (s->bit_depth == 16 &&
673 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
674 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
675 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
676 s->color_type == PNG_COLOR_TYPE_PALETTE) {
677 avctx->pix_fmt = AV_PIX_FMT_PAL8;
678 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
679 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
680 } else if (s->bit_depth == 8 &&
681 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
682 avctx->pix_fmt = AV_PIX_FMT_YA8;
683 } else if (s->bit_depth == 16 &&
684 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
685 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
687 avpriv_report_missing_feature(avctx,
688 "Bit depth %d color type %d",
689 s->bit_depth, s->color_type);
690 return AVERROR_PATCHWELCOME;
693 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
694 switch (avctx->pix_fmt) {
695 case AV_PIX_FMT_RGB24:
696 avctx->pix_fmt = AV_PIX_FMT_RGBA;
699 case AV_PIX_FMT_RGB48BE:
700 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
703 case AV_PIX_FMT_GRAY8:
704 avctx->pix_fmt = AV_PIX_FMT_YA8;
707 case AV_PIX_FMT_GRAY16BE:
708 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
712 avpriv_request_sample(avctx, "bit depth %d "
713 "and color type %d with TRNS",
714 s->bit_depth, s->color_type);
715 return AVERROR_INVALIDDATA;
718 s->bpp += byte_depth;
721 ff_thread_release_buffer(avctx, &s->picture);
722 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
725 p->pict_type = AV_PICTURE_TYPE_I;
727 p->interlaced_frame = !!s->interlace_type;
729 ff_thread_finish_setup(avctx);
731 /* compute the compressed row size */
732 if (!s->interlace_type) {
733 s->crow_size = s->row_size + 1;
736 s->pass_row_size = ff_png_pass_row_size(s->pass,
739 s->crow_size = s->pass_row_size + 1;
741 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
742 s->row_size, s->crow_size);
744 /* copy the palette if needed */
745 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
746 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
747 /* empty row is used if differencing to the first row */
748 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
750 return AVERROR_INVALIDDATA;
751 if (s->interlace_type ||
752 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
753 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
755 return AVERROR_INVALIDDATA;
758 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
760 return AVERROR(ENOMEM);
762 /* we want crow_buf+1 to be 16-byte aligned */
763 s->crow_buf = s->buffer + 15;
764 s->zstream.avail_out = s->crow_size;
765 s->zstream.next_out = s->crow_buf;
768 s->pic_state |= PNG_IDAT;
770 /* set image to non-transparent bpp while decompressing */
771 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
772 s->bpp -= byte_depth;
774 ret = png_decode_idat(s, gb, p->data[0], p->linesize[0]);
776 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
777 s->bpp += byte_depth;
785 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
788 int length = bytestream2_get_bytes_left(gb);
791 if ((length % 3) != 0 || length > 256 * 3)
792 return AVERROR_INVALIDDATA;
793 /* read the palette */
795 for (i = 0; i < n; i++) {
796 r = bytestream2_get_byte(gb);
797 g = bytestream2_get_byte(gb);
798 b = bytestream2_get_byte(gb);
799 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
802 s->palette[i] = (0xFFU << 24);
803 s->hdr_state |= PNG_PLTE;
808 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
811 int length = bytestream2_get_bytes_left(gb);
814 if (!(s->hdr_state & PNG_IHDR)) {
815 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
816 return AVERROR_INVALIDDATA;
819 if (s->pic_state & PNG_IDAT) {
820 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
821 return AVERROR_INVALIDDATA;
824 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
825 if (length > 256 || !(s->hdr_state & PNG_PLTE))
826 return AVERROR_INVALIDDATA;
828 for (i = 0; i < length; i++) {
829 unsigned v = bytestream2_get_byte(gb);
830 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
832 } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
833 if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
834 (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
836 return AVERROR_INVALIDDATA;
838 for (i = 0; i < length / 2; i++) {
839 /* only use the least significant bits */
840 v = av_mod_uintp2(bytestream2_get_be16(gb), s->bit_depth);
842 if (s->bit_depth > 8)
843 AV_WB16(&s->transparent_color_be[2 * i], v);
845 s->transparent_color_be[i] = v;
848 return AVERROR_INVALIDDATA;
856 static int decode_iccp_chunk(PNGDecContext *s, GetByteContext *gb, AVFrame *f)
861 while ((s->iccp_name[cnt++] = bytestream2_get_byte(gb)) && cnt < 81);
863 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
864 ret = AVERROR_INVALIDDATA;
868 if (bytestream2_get_byte(gb) != 0) {
869 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
870 ret = AVERROR_INVALIDDATA;
874 if ((ret = decode_zbuf(&bp, gb->buffer, gb->buffer_end)) < 0)
877 av_freep(&s->iccp_data);
878 ret = av_bprint_finalize(&bp, (char **)&s->iccp_data);
881 s->iccp_data_len = bp.len;
889 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
891 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
893 uint8_t *pd = p->data[0];
894 for (j = 0; j < s->height; j++) {
896 for (k = 7; k >= 1; k--)
897 if ((s->width&7) >= k)
898 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
899 for (i--; i >= 0; i--) {
900 pd[8*i + 7]= pd[i] & 1;
901 pd[8*i + 6]= (pd[i]>>1) & 1;
902 pd[8*i + 5]= (pd[i]>>2) & 1;
903 pd[8*i + 4]= (pd[i]>>3) & 1;
904 pd[8*i + 3]= (pd[i]>>4) & 1;
905 pd[8*i + 2]= (pd[i]>>5) & 1;
906 pd[8*i + 1]= (pd[i]>>6) & 1;
907 pd[8*i + 0]= pd[i]>>7;
909 pd += p->linesize[0];
911 } else if (s->bits_per_pixel == 2) {
913 uint8_t *pd = p->data[0];
914 for (j = 0; j < s->height; j++) {
916 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
917 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
918 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
919 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
920 for (i--; i >= 0; i--) {
921 pd[4*i + 3]= pd[i] & 3;
922 pd[4*i + 2]= (pd[i]>>2) & 3;
923 pd[4*i + 1]= (pd[i]>>4) & 3;
924 pd[4*i + 0]= pd[i]>>6;
927 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
928 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
929 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
930 for (i--; i >= 0; i--) {
931 pd[4*i + 3]= ( pd[i] & 3)*0x55;
932 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
933 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
934 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
937 pd += p->linesize[0];
939 } else if (s->bits_per_pixel == 4) {
941 uint8_t *pd = p->data[0];
942 for (j = 0; j < s->height; j++) {
944 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
945 if (s->width&1) pd[2*i+0]= pd[i]>>4;
946 for (i--; i >= 0; i--) {
947 pd[2*i + 1] = pd[i] & 15;
948 pd[2*i + 0] = pd[i] >> 4;
951 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
952 for (i--; i >= 0; i--) {
953 pd[2*i + 1] = (pd[i] & 15) * 0x11;
954 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
957 pd += p->linesize[0];
962 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
965 uint32_t sequence_number;
966 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
968 if (bytestream2_get_bytes_left(gb) != 26)
969 return AVERROR_INVALIDDATA;
971 if (!(s->hdr_state & PNG_IHDR)) {
972 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
973 return AVERROR_INVALIDDATA;
976 if (s->pic_state & PNG_IDAT) {
977 av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
978 return AVERROR_INVALIDDATA;
981 s->last_w = s->cur_w;
982 s->last_h = s->cur_h;
983 s->last_x_offset = s->x_offset;
984 s->last_y_offset = s->y_offset;
985 s->last_dispose_op = s->dispose_op;
987 sequence_number = bytestream2_get_be32(gb);
988 cur_w = bytestream2_get_be32(gb);
989 cur_h = bytestream2_get_be32(gb);
990 x_offset = bytestream2_get_be32(gb);
991 y_offset = bytestream2_get_be32(gb);
992 bytestream2_skip(gb, 4); /* delay_num (2), delay_den (2) */
993 dispose_op = bytestream2_get_byte(gb);
994 blend_op = bytestream2_get_byte(gb);
996 if (sequence_number == 0 &&
997 (cur_w != s->width ||
998 cur_h != s->height ||
1001 cur_w <= 0 || cur_h <= 0 ||
1002 x_offset < 0 || y_offset < 0 ||
1003 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1004 return AVERROR_INVALIDDATA;
1006 if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1007 av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1008 return AVERROR_INVALIDDATA;
1011 if ((sequence_number == 0 || !s->last_picture.f->data[0]) &&
1012 dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1013 // No previous frame to revert to for the first frame
1014 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1015 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1018 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1019 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1020 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1021 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1022 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1023 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1024 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1026 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1027 blend_op = APNG_BLEND_OP_SOURCE;
1032 s->x_offset = x_offset;
1033 s->y_offset = y_offset;
1034 s->dispose_op = dispose_op;
1035 s->blend_op = blend_op;
1040 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1043 uint8_t *pd = p->data[0];
1044 uint8_t *pd_last = s->last_picture.f->data[0];
1045 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1047 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1048 for (j = 0; j < s->height; j++) {
1049 for (i = 0; i < ls; i++)
1050 pd[i] += pd_last[i];
1051 pd += p->linesize[0];
1052 pd_last += s->last_picture.f->linesize[0];
1056 // divide by 255 and round to nearest
1057 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1058 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1060 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1063 uint8_t *dst = p->data[0];
1064 ptrdiff_t dst_stride = p->linesize[0];
1065 const uint8_t *src = s->last_picture.f->data[0];
1066 ptrdiff_t src_stride = s->last_picture.f->linesize[0];
1070 if (s->blend_op == APNG_BLEND_OP_OVER &&
1071 avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1072 avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
1073 avctx->pix_fmt != AV_PIX_FMT_PAL8) {
1074 avpriv_request_sample(avctx, "Blending with pixel format %s",
1075 av_get_pix_fmt_name(avctx->pix_fmt));
1076 return AVERROR_PATCHWELCOME;
1079 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1081 // need to reset a rectangle to background:
1082 // create a new writable copy
1083 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
1084 int ret = av_frame_make_writable(s->last_picture.f);
1088 src = s->last_picture.f->data[0];
1089 src_stride = s->last_picture.f->linesize[0];
1091 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; y++) {
1092 memset(s->last_picture.f->data[0] + src_stride * y +
1093 s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1097 // copy unchanged rectangles from the last frame
1098 for (y = 0; y < s->y_offset; y++)
1099 memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
1100 for (y = s->y_offset; y < s->y_offset + s->cur_h; y++) {
1101 memcpy(dst + y * dst_stride, src + y * src_stride, s->x_offset * s->bpp);
1102 memcpy(dst + y * dst_stride + (s->x_offset + s->cur_w) * s->bpp,
1103 src + y * src_stride + (s->x_offset + s->cur_w) * s->bpp,
1104 (p->width - s->cur_w - s->x_offset) * s->bpp);
1106 for (y = s->y_offset + s->cur_h; y < p->height; y++)
1107 memcpy(dst + y * dst_stride, src + y * src_stride, p->width * s->bpp);
1109 if (s->blend_op == APNG_BLEND_OP_OVER) {
1111 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1112 uint8_t *foreground = dst + dst_stride * y + s->bpp * s->x_offset;
1113 const uint8_t *background = src + src_stride * y + s->bpp * s->x_offset;
1114 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1116 uint8_t foreground_alpha, background_alpha, output_alpha;
1119 // Since we might be blending alpha onto alpha, we use the following equations:
1120 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1121 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1123 switch (avctx->pix_fmt) {
1124 case AV_PIX_FMT_RGBA:
1125 foreground_alpha = foreground[3];
1126 background_alpha = background[3];
1129 case AV_PIX_FMT_GRAY8A:
1130 foreground_alpha = foreground[1];
1131 background_alpha = background[1];
1134 case AV_PIX_FMT_PAL8:
1135 foreground_alpha = s->palette[foreground[0]] >> 24;
1136 background_alpha = s->palette[background[0]] >> 24;
1140 if (foreground_alpha == 255)
1143 if (foreground_alpha == 0) {
1144 memcpy(foreground, background, s->bpp);
1148 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1149 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1150 avpriv_request_sample(avctx, "Alpha blending palette samples");
1154 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1156 av_assert0(s->bpp <= 10);
1158 for (b = 0; b < s->bpp - 1; ++b) {
1159 if (output_alpha == 0) {
1161 } else if (background_alpha == 255) {
1162 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1164 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1167 output[b] = output_alpha;
1168 memcpy(foreground, output, s->bpp);
1176 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1177 AVFrame *p, const AVPacket *avpkt)
1179 const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1180 uint32_t tag, length;
1181 int decode_next_dat = 0;
1185 GetByteContext gb_chunk;
1187 length = bytestream2_get_bytes_left(&s->gb);
1190 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1191 avctx->skip_frame == AVDISCARD_ALL) {
1195 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1196 if (!(s->pic_state & PNG_IDAT))
1201 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1202 if ( s->pic_state & PNG_ALLIMAGE
1203 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1205 ret = AVERROR_INVALIDDATA;
1209 length = bytestream2_get_be32(&s->gb);
1210 if (length > 0x7fffffff || length + 8 > bytestream2_get_bytes_left(&s->gb)) {
1211 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1212 ret = AVERROR_INVALIDDATA;
1215 if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_IGNORE_ERR)) {
1216 uint32_t crc_sig = AV_RB32(s->gb.buffer + length + 4);
1217 uint32_t crc_cal = ~av_crc(crc_tab, UINT32_MAX, s->gb.buffer, length + 4);
1218 if (crc_sig ^ crc_cal) {
1219 av_log(avctx, AV_LOG_ERROR, "CRC mismatch in chunk");
1220 if (avctx->err_recognition & AV_EF_EXPLODE) {
1221 av_log(avctx, AV_LOG_ERROR, ", quitting\n");
1222 ret = AVERROR_INVALIDDATA;
1225 av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1226 bytestream2_skip(&s->gb, length + 8); /* tag */
1229 tag = bytestream2_get_le32(&s->gb);
1230 if (avctx->debug & FF_DEBUG_STARTCODE)
1231 av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1232 av_fourcc2str(tag), length);
1234 bytestream2_init(&gb_chunk, s->gb.buffer, length);
1235 bytestream2_skip(&s->gb, length + 4);
1237 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1238 avctx->skip_frame == AVDISCARD_ALL) {
1240 case MKTAG('I', 'H', 'D', 'R'):
1241 case MKTAG('p', 'H', 'Y', 's'):
1242 case MKTAG('t', 'E', 'X', 't'):
1243 case MKTAG('I', 'D', 'A', 'T'):
1244 case MKTAG('t', 'R', 'N', 'S'):
1252 case MKTAG('I', 'H', 'D', 'R'):
1253 if ((ret = decode_ihdr_chunk(avctx, s, &gb_chunk)) < 0)
1256 case MKTAG('p', 'H', 'Y', 's'):
1257 if ((ret = decode_phys_chunk(avctx, s, &gb_chunk)) < 0)
1260 case MKTAG('f', 'c', 'T', 'L'):
1261 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1263 if ((ret = decode_fctl_chunk(avctx, s, &gb_chunk)) < 0)
1265 decode_next_dat = 1;
1267 case MKTAG('f', 'd', 'A', 'T'):
1268 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1270 if (!decode_next_dat || bytestream2_get_bytes_left(&gb_chunk) < 4) {
1271 ret = AVERROR_INVALIDDATA;
1274 bytestream2_get_be32(&gb_chunk);
1276 case MKTAG('I', 'D', 'A', 'T'):
1277 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1279 if ((ret = decode_idat_chunk(avctx, s, &gb_chunk, p)) < 0)
1282 case MKTAG('P', 'L', 'T', 'E'):
1283 decode_plte_chunk(avctx, s, &gb_chunk);
1285 case MKTAG('t', 'R', 'N', 'S'):
1286 decode_trns_chunk(avctx, s, &gb_chunk);
1288 case MKTAG('t', 'E', 'X', 't'):
1289 if (decode_text_chunk(s, &gb_chunk, 0) < 0)
1290 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1292 case MKTAG('z', 'T', 'X', 't'):
1293 if (decode_text_chunk(s, &gb_chunk, 1) < 0)
1294 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1296 case MKTAG('s', 'T', 'E', 'R'): {
1297 int mode = bytestream2_get_byte(&gb_chunk);
1299 if (mode == 0 || mode == 1) {
1300 s->stereo_mode = mode;
1302 av_log(avctx, AV_LOG_WARNING,
1303 "Unknown value in sTER chunk (%d)\n", mode);
1307 case MKTAG('i', 'C', 'C', 'P'): {
1308 if ((ret = decode_iccp_chunk(s, &gb_chunk, p)) < 0)
1312 case MKTAG('c', 'H', 'R', 'M'): {
1315 s->white_point[0] = bytestream2_get_be32(&gb_chunk);
1316 s->white_point[1] = bytestream2_get_be32(&gb_chunk);
1319 for (i = 0; i < 3; i++) {
1320 s->display_primaries[i][0] = bytestream2_get_be32(&gb_chunk);
1321 s->display_primaries[i][1] = bytestream2_get_be32(&gb_chunk);
1326 case MKTAG('g', 'A', 'M', 'A'): {
1329 int num = bytestream2_get_be32(&gb_chunk);
1331 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1332 av_bprintf(&bp, "%i/%i", num, 100000);
1333 ret = av_bprint_finalize(&bp, &gamma_str);
1337 av_dict_set(&s->frame_metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1341 case MKTAG('I', 'E', 'N', 'D'):
1342 if (!(s->pic_state & PNG_ALLIMAGE))
1343 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1344 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1345 ret = AVERROR_INVALIDDATA;
1353 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1354 avctx->skip_frame == AVDISCARD_ALL) {
1358 if (percent_missing(s) > avctx->discard_damaged_percentage)
1359 return AVERROR_INVALIDDATA;
1361 if (s->bits_per_pixel <= 4)
1362 handle_small_bpp(s, p);
1364 /* apply transparency if needed */
1365 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1366 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1367 size_t raw_bpp = s->bpp - byte_depth;
1370 av_assert0(s->bit_depth > 1);
1372 for (y = 0; y < s->height; ++y) {
1373 uint8_t *row = &p->data[0][p->linesize[0] * y];
1375 if (s->bpp == 2 && byte_depth == 1) {
1376 uint8_t *pixel = &row[2 * s->width - 1];
1377 uint8_t *rowp = &row[1 * s->width - 1];
1378 int tcolor = s->transparent_color_be[0];
1379 for (x = s->width; x > 0; --x) {
1380 *pixel-- = *rowp == tcolor ? 0 : 0xff;
1383 } else if (s->bpp == 4 && byte_depth == 1) {
1384 uint8_t *pixel = &row[4 * s->width - 1];
1385 uint8_t *rowp = &row[3 * s->width - 1];
1386 int tcolor = AV_RL24(s->transparent_color_be);
1387 for (x = s->width; x > 0; --x) {
1388 *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1394 /* since we're updating in-place, we have to go from right to left */
1395 for (x = s->width; x > 0; --x) {
1396 uint8_t *pixel = &row[s->bpp * (x - 1)];
1397 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1399 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1400 memset(&pixel[raw_bpp], 0, byte_depth);
1402 memset(&pixel[raw_bpp], 0xff, byte_depth);
1409 /* handle P-frames only if a predecessor frame is available */
1410 if (s->last_picture.f->data[0]) {
1411 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1412 && s->last_picture.f->width == p->width
1413 && s->last_picture.f->height== p->height
1414 && s->last_picture.f->format== p->format
1416 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1417 handle_p_frame_png(s, p);
1418 else if (CONFIG_APNG_DECODER &&
1419 avctx->codec_id == AV_CODEC_ID_APNG &&
1420 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1424 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1429 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1433 static void clear_frame_metadata(PNGDecContext *s)
1435 av_freep(&s->iccp_data);
1436 s->iccp_data_len = 0;
1437 s->iccp_name[0] = 0;
1439 s->stereo_mode = -1;
1443 av_dict_free(&s->frame_metadata);
1446 static int output_frame(PNGDecContext *s, AVFrame *f,
1451 ret = av_frame_ref(f, src);
1456 AVFrameSideData *sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, s->iccp_data_len);
1458 ret = AVERROR(ENOMEM);
1461 memcpy(sd->data, s->iccp_data, s->iccp_data_len);
1463 av_dict_set(&sd->metadata, "name", s->iccp_name, 0);
1466 if (s->stereo_mode >= 0) {
1467 AVStereo3D *stereo3d = av_stereo3d_create_side_data(f);
1469 ret = AVERROR(ENOMEM);
1473 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1474 stereo3d->flags = s->stereo_mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1478 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(f);
1480 ret = AVERROR(ENOMEM);
1484 mdm->white_point[0] = av_make_q(s->white_point[0], 100000);
1485 mdm->white_point[1] = av_make_q(s->white_point[1], 100000);
1488 for (int i = 0; i < 3; i++) {
1489 mdm->display_primaries[i][0] = av_make_q(s->display_primaries[i][0], 100000);
1490 mdm->display_primaries[i][1] = av_make_q(s->display_primaries[i][1], 100000);
1493 mdm->has_primaries = 1;
1496 FFSWAP(AVDictionary*, f->metadata, s->frame_metadata);
1504 #if CONFIG_PNG_DECODER
1505 static int decode_frame_png(AVCodecContext *avctx,
1506 void *data, int *got_frame,
1509 PNGDecContext *const s = avctx->priv_data;
1510 const uint8_t *buf = avpkt->data;
1511 int buf_size = avpkt->size;
1512 AVFrame *dst_frame = data;
1513 AVFrame *p = s->picture.f;
1517 clear_frame_metadata(s);
1519 bytestream2_init(&s->gb, buf, buf_size);
1521 /* check signature */
1522 sig = bytestream2_get_be64(&s->gb);
1523 if (sig != PNGSIG &&
1525 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1526 return AVERROR_INVALIDDATA;
1529 s->y = s->has_trns = 0;
1534 s->zstream.zalloc = ff_png_zalloc;
1535 s->zstream.zfree = ff_png_zfree;
1536 s->zstream.opaque = NULL;
1537 ret = inflateInit(&s->zstream);
1539 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1540 return AVERROR_EXTERNAL;
1543 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1546 if (avctx->skip_frame == AVDISCARD_ALL) {
1548 ret = bytestream2_tell(&s->gb);
1552 ret = output_frame(s, dst_frame, s->picture.f);
1556 if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1557 ff_thread_release_buffer(avctx, &s->last_picture);
1558 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1563 ret = bytestream2_tell(&s->gb);
1565 inflateEnd(&s->zstream);
1571 #if CONFIG_APNG_DECODER
1572 static int decode_frame_apng(AVCodecContext *avctx,
1573 void *data, int *got_frame,
1576 PNGDecContext *const s = avctx->priv_data;
1577 AVFrame *dst_frame = data;
1579 AVFrame *p = s->picture.f;
1581 clear_frame_metadata(s);
1583 if (!(s->hdr_state & PNG_IHDR)) {
1584 if (!avctx->extradata_size)
1585 return AVERROR_INVALIDDATA;
1587 /* only init fields, there is no zlib use in extradata */
1588 s->zstream.zalloc = ff_png_zalloc;
1589 s->zstream.zfree = ff_png_zfree;
1591 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1592 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1596 /* reset state for a new frame */
1597 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1598 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1599 ret = AVERROR_EXTERNAL;
1604 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1605 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1608 if (!(s->pic_state & PNG_ALLIMAGE))
1609 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1610 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1611 ret = AVERROR_INVALIDDATA;
1615 ret = output_frame(s, dst_frame, s->picture.f);
1619 if (!(avctx->active_thread_type & FF_THREAD_FRAME)) {
1620 if (s->dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1621 ff_thread_release_buffer(avctx, &s->picture);
1622 } else if (s->dispose_op == APNG_DISPOSE_OP_NONE) {
1623 ff_thread_release_buffer(avctx, &s->last_picture);
1624 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1629 ret = bytestream2_tell(&s->gb);
1632 inflateEnd(&s->zstream);
1638 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1640 PNGDecContext *psrc = src->priv_data;
1641 PNGDecContext *pdst = dst->priv_data;
1642 ThreadFrame *src_frame = NULL;
1648 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1650 pdst->width = psrc->width;
1651 pdst->height = psrc->height;
1652 pdst->bit_depth = psrc->bit_depth;
1653 pdst->color_type = psrc->color_type;
1654 pdst->compression_type = psrc->compression_type;
1655 pdst->interlace_type = psrc->interlace_type;
1656 pdst->filter_type = psrc->filter_type;
1657 pdst->cur_w = psrc->cur_w;
1658 pdst->cur_h = psrc->cur_h;
1659 pdst->x_offset = psrc->x_offset;
1660 pdst->y_offset = psrc->y_offset;
1661 pdst->has_trns = psrc->has_trns;
1662 memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1664 pdst->dispose_op = psrc->dispose_op;
1666 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1668 pdst->hdr_state |= psrc->hdr_state;
1671 src_frame = psrc->dispose_op == APNG_DISPOSE_OP_NONE ?
1672 &psrc->picture : &psrc->last_picture;
1674 ff_thread_release_buffer(dst, &pdst->last_picture);
1675 if (src_frame && src_frame->f->data[0]) {
1676 ret = ff_thread_ref_frame(&pdst->last_picture, src_frame);
1685 static av_cold int png_dec_init(AVCodecContext *avctx)
1687 PNGDecContext *s = avctx->priv_data;
1689 avctx->color_range = AVCOL_RANGE_JPEG;
1692 s->last_picture.f = av_frame_alloc();
1693 s->picture.f = av_frame_alloc();
1694 if (!s->last_picture.f || !s->picture.f) {
1695 av_frame_free(&s->last_picture.f);
1696 av_frame_free(&s->picture.f);
1697 return AVERROR(ENOMEM);
1700 ff_pngdsp_init(&s->dsp);
1705 static av_cold int png_dec_end(AVCodecContext *avctx)
1707 PNGDecContext *s = avctx->priv_data;
1709 ff_thread_release_buffer(avctx, &s->last_picture);
1710 av_frame_free(&s->last_picture.f);
1711 ff_thread_release_buffer(avctx, &s->picture);
1712 av_frame_free(&s->picture.f);
1713 av_freep(&s->buffer);
1715 av_freep(&s->last_row);
1716 s->last_row_size = 0;
1717 av_freep(&s->tmp_row);
1718 s->tmp_row_size = 0;
1720 av_freep(&s->iccp_data);
1721 av_dict_free(&s->frame_metadata);
1726 #if CONFIG_APNG_DECODER
1727 AVCodec ff_apng_decoder = {
1729 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1730 .type = AVMEDIA_TYPE_VIDEO,
1731 .id = AV_CODEC_ID_APNG,
1732 .priv_data_size = sizeof(PNGDecContext),
1733 .init = png_dec_init,
1734 .close = png_dec_end,
1735 .decode = decode_frame_apng,
1736 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1737 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1738 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
1739 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1743 #if CONFIG_PNG_DECODER
1744 AVCodec ff_png_decoder = {
1746 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1747 .type = AVMEDIA_TYPE_VIDEO,
1748 .id = AV_CODEC_ID_PNG,
1749 .priv_data_size = sizeof(PNGDecContext),
1750 .init = png_dec_init,
1751 .close = png_dec_end,
1752 .decode = decode_frame_png,
1753 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1754 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1755 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1756 FF_CODEC_CAP_ALLOCATE_PROGRESS,