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/imgutils.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavutil/stereo3d.h"
29 #include "libavutil/mastering_display_metadata.h"
32 #include "bytestream.h"
48 PNG_ALLIMAGE = 1 << 1,
51 typedef struct PNGDecContext {
53 AVCodecContext *avctx;
56 ThreadFrame previous_picture;
57 ThreadFrame last_picture;
60 enum PNGHeaderState hdr_state;
61 enum PNGImageState pic_state;
65 int x_offset, y_offset;
66 int last_x_offset, last_y_offset;
67 uint8_t dispose_op, blend_op;
68 uint8_t last_dispose_op;
78 uint8_t transparent_color_be[6];
82 uint32_t palette[256];
85 unsigned int last_row_size;
87 unsigned int tmp_row_size;
91 int crow_size; /* compressed row size (include filter type) */
92 int row_size; /* decompressed row size */
93 int pass_row_size; /* decompress row size of the current pass */
98 /* Mask to determine which pixels are valid in a pass */
99 static const uint8_t png_pass_mask[NB_PASSES] = {
100 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
103 /* Mask to determine which y pixels can be written in a pass */
104 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
105 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
108 /* Mask to determine which pixels to overwrite while displaying */
109 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
110 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
113 /* NOTE: we try to construct a good looking image at each pass. width
114 * is the original image width. We also do pixel format conversion at
116 static void png_put_interlaced_row(uint8_t *dst, int width,
117 int bits_per_pixel, int pass,
118 int color_type, const uint8_t *src)
120 int x, mask, dsp_mask, j, src_x, b, bpp;
124 mask = png_pass_mask[pass];
125 dsp_mask = png_pass_dsp_mask[pass];
127 switch (bits_per_pixel) {
130 for (x = 0; x < width; x++) {
132 if ((dsp_mask << j) & 0x80) {
133 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
134 dst[x >> 3] &= 0xFF7F>>j;
135 dst[x >> 3] |= b << (7 - j);
137 if ((mask << j) & 0x80)
143 for (x = 0; x < width; x++) {
144 int j2 = 2 * (x & 3);
146 if ((dsp_mask << j) & 0x80) {
147 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
148 dst[x >> 2] &= 0xFF3F>>j2;
149 dst[x >> 2] |= b << (6 - j2);
151 if ((mask << j) & 0x80)
157 for (x = 0; x < width; x++) {
160 if ((dsp_mask << j) & 0x80) {
161 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
162 dst[x >> 1] &= 0xFF0F>>j2;
163 dst[x >> 1] |= b << (4 - j2);
165 if ((mask << j) & 0x80)
170 bpp = bits_per_pixel >> 3;
173 for (x = 0; x < width; x++) {
175 if ((dsp_mask << j) & 0x80) {
179 if ((mask << j) & 0x80)
186 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
190 for (i = 0; i < w; i++) {
191 int a, b, c, p, pa, pb, pc;
204 if (pa <= pb && pa <= pc)
214 #define UNROLL1(bpp, op) \
223 for (; i <= size - bpp; i += bpp) { \
224 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
227 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
230 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
233 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
237 #define UNROLL_FILTER(op) \
240 } else if (bpp == 2) { \
242 } else if (bpp == 3) { \
244 } else if (bpp == 4) { \
247 for (; i < size; i++) { \
248 dst[i] = op(dst[i - bpp], src[i], last[i]); \
251 /* NOTE: 'dst' can be equal to 'last' */
252 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
253 uint8_t *src, uint8_t *last, int size, int bpp)
255 int i, p, r, g, b, a;
257 switch (filter_type) {
258 case PNG_FILTER_VALUE_NONE:
259 memcpy(dst, src, size);
261 case PNG_FILTER_VALUE_SUB:
262 for (i = 0; i < bpp; i++)
266 for (; i < size; i += bpp) {
267 unsigned s = *(int *)(src + i);
268 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
269 *(int *)(dst + i) = p;
272 #define OP_SUB(x, s, l) ((x) + (s))
273 UNROLL_FILTER(OP_SUB);
276 case PNG_FILTER_VALUE_UP:
277 dsp->add_bytes_l2(dst, src, last, size);
279 case PNG_FILTER_VALUE_AVG:
280 for (i = 0; i < bpp; i++) {
284 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
285 UNROLL_FILTER(OP_AVG);
287 case PNG_FILTER_VALUE_PAETH:
288 for (i = 0; i < bpp; i++) {
292 if (bpp > 2 && size > 4) {
293 /* would write off the end of the array if we let it process
294 * the last pixel with bpp=3 */
295 int w = (bpp & 3) ? size - 3 : size;
298 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
302 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
307 /* This used to be called "deloco" in FFmpeg
308 * and is actually an inverse reversible colorspace transformation */
309 #define YUV2RGB(NAME, TYPE) \
310 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
313 for (i = 0; i < size; i += 3 + alpha) { \
314 int g = dst [i + 1]; \
320 YUV2RGB(rgb8, uint8_t)
321 YUV2RGB(rgb16, uint16_t)
323 static int percent_missing(PNGDecContext *s)
325 if (s->interlace_type) {
326 return 100 - 100 * s->pass / (NB_PASSES - 1);
328 return 100 - 100 * s->y / s->cur_h;
332 /* process exactly one decompressed row */
333 static void png_handle_row(PNGDecContext *s)
335 uint8_t *ptr, *last_row;
338 if (!s->interlace_type) {
339 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
341 last_row = s->last_row;
343 last_row = ptr - s->image_linesize;
345 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
346 last_row, s->row_size, s->bpp);
347 /* loco lags by 1 row so that it doesn't interfere with top prediction */
348 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
349 if (s->bit_depth == 16) {
350 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
351 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
353 deloco_rgb8(ptr - s->image_linesize, s->row_size,
354 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
358 if (s->y == s->cur_h) {
359 s->pic_state |= PNG_ALLIMAGE;
360 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
361 if (s->bit_depth == 16) {
362 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
363 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
365 deloco_rgb8(ptr, s->row_size,
366 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
373 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
374 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
375 /* if we already read one row, it is time to stop to
376 * wait for the next one */
379 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
380 s->last_row, s->pass_row_size, s->bpp);
381 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
382 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
385 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
386 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
387 s->color_type, s->last_row);
390 if (s->y == s->cur_h) {
391 memset(s->last_row, 0, s->row_size);
393 if (s->pass == NB_PASSES - 1) {
394 s->pic_state |= PNG_ALLIMAGE;
399 s->pass_row_size = ff_png_pass_row_size(s->pass,
402 s->crow_size = s->pass_row_size + 1;
403 if (s->pass_row_size != 0)
405 /* skip pass if empty row */
414 static int png_decode_idat(PNGDecContext *s, int length)
417 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
418 s->zstream.next_in = s->gb.buffer;
419 bytestream2_skip(&s->gb, length);
421 /* decode one line if possible */
422 while (s->zstream.avail_in > 0) {
423 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
424 if (ret != Z_OK && ret != Z_STREAM_END) {
425 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
426 return AVERROR_EXTERNAL;
428 if (s->zstream.avail_out == 0) {
429 if (!(s->pic_state & PNG_ALLIMAGE)) {
432 s->zstream.avail_out = s->crow_size;
433 s->zstream.next_out = s->crow_buf;
435 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
436 av_log(s->avctx, AV_LOG_WARNING,
437 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
444 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
445 const uint8_t *data_end)
452 zstream.zalloc = ff_png_zalloc;
453 zstream.zfree = ff_png_zfree;
454 zstream.opaque = NULL;
455 if (inflateInit(&zstream) != Z_OK)
456 return AVERROR_EXTERNAL;
457 zstream.next_in = data;
458 zstream.avail_in = data_end - data;
459 av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
461 while (zstream.avail_in > 0) {
462 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
464 ret = AVERROR(ENOMEM);
467 zstream.next_out = buf;
468 zstream.avail_out = buf_size - 1;
469 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
470 if (ret != Z_OK && ret != Z_STREAM_END) {
471 ret = AVERROR_EXTERNAL;
474 bp->len += zstream.next_out - buf;
475 if (ret == Z_STREAM_END)
478 inflateEnd(&zstream);
479 bp->str[bp->len] = 0;
483 inflateEnd(&zstream);
484 av_bprint_finalize(bp, NULL);
488 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
493 for (i = 0; i < size_in; i++)
494 extra += in[i] >= 0x80;
495 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
497 q = out = av_malloc(size_in + extra + 1);
500 for (i = 0; i < size_in; i++) {
502 *(q++) = 0xC0 | (in[i] >> 6);
503 *(q++) = 0x80 | (in[i] & 0x3F);
512 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
516 const uint8_t *data = s->gb.buffer;
517 const uint8_t *data_end = data + length;
518 const uint8_t *keyword = data;
519 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
520 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
525 return AVERROR_INVALIDDATA;
526 data = keyword_end + 1;
529 if (data == data_end)
530 return AVERROR_INVALIDDATA;
533 return AVERROR_INVALIDDATA;
534 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
537 ret = av_bprint_finalize(&bp, (char **)&text);
541 text = (uint8_t *)data;
542 text_len = data_end - text;
545 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
546 txt_utf8 = iso88591_to_utf8(text, text_len);
549 if (!(kw_utf8 && txt_utf8)) {
552 return AVERROR(ENOMEM);
555 av_dict_set(dict, kw_utf8, txt_utf8,
556 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
560 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
564 return AVERROR_INVALIDDATA;
566 if (s->pic_state & PNG_IDAT) {
567 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
568 return AVERROR_INVALIDDATA;
571 if (s->hdr_state & PNG_IHDR) {
572 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
573 return AVERROR_INVALIDDATA;
576 s->width = s->cur_w = bytestream2_get_be32(&s->gb);
577 s->height = s->cur_h = bytestream2_get_be32(&s->gb);
578 if (av_image_check_size(s->width, s->height, 0, avctx)) {
579 s->cur_w = s->cur_h = s->width = s->height = 0;
580 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
581 return AVERROR_INVALIDDATA;
583 s->bit_depth = bytestream2_get_byte(&s->gb);
584 if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
585 s->bit_depth != 8 && s->bit_depth != 16) {
586 av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
589 s->color_type = bytestream2_get_byte(&s->gb);
590 s->compression_type = bytestream2_get_byte(&s->gb);
591 if (s->compression_type) {
592 av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
595 s->filter_type = bytestream2_get_byte(&s->gb);
596 s->interlace_type = bytestream2_get_byte(&s->gb);
597 bytestream2_skip(&s->gb, 4); /* crc */
598 s->hdr_state |= PNG_IHDR;
599 if (avctx->debug & FF_DEBUG_PICT_INFO)
600 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
601 "compression_type=%d filter_type=%d interlace_type=%d\n",
602 s->width, s->height, s->bit_depth, s->color_type,
603 s->compression_type, s->filter_type, s->interlace_type);
607 s->cur_w = s->cur_h = s->width = s->height = 0;
609 return AVERROR_INVALIDDATA;
612 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
614 if (s->pic_state & PNG_IDAT) {
615 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
616 return AVERROR_INVALIDDATA;
618 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
619 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
620 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
621 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
622 bytestream2_skip(&s->gb, 1); /* unit specifier */
623 bytestream2_skip(&s->gb, 4); /* crc */
628 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
629 uint32_t length, AVFrame *p)
632 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
634 if (!(s->hdr_state & PNG_IHDR)) {
635 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
636 return AVERROR_INVALIDDATA;
638 if (!(s->pic_state & PNG_IDAT)) {
639 /* init image info */
640 ret = ff_set_dimensions(avctx, s->width, s->height);
644 s->channels = ff_png_get_nb_channels(s->color_type);
645 s->bits_per_pixel = s->bit_depth * s->channels;
646 s->bpp = (s->bits_per_pixel + 7) >> 3;
647 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
649 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
650 s->color_type == PNG_COLOR_TYPE_RGB) {
651 avctx->pix_fmt = AV_PIX_FMT_RGB24;
652 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
653 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
654 avctx->pix_fmt = AV_PIX_FMT_RGBA;
655 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
656 s->color_type == PNG_COLOR_TYPE_GRAY) {
657 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
658 } else if (s->bit_depth == 16 &&
659 s->color_type == PNG_COLOR_TYPE_GRAY) {
660 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
661 } else if (s->bit_depth == 16 &&
662 s->color_type == PNG_COLOR_TYPE_RGB) {
663 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
664 } else if (s->bit_depth == 16 &&
665 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
666 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
667 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
668 s->color_type == PNG_COLOR_TYPE_PALETTE) {
669 avctx->pix_fmt = AV_PIX_FMT_PAL8;
670 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
671 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
672 } else if (s->bit_depth == 8 &&
673 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
674 avctx->pix_fmt = AV_PIX_FMT_YA8;
675 } else if (s->bit_depth == 16 &&
676 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
677 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
679 avpriv_report_missing_feature(avctx,
680 "Bit depth %d color type %d",
681 s->bit_depth, s->color_type);
682 return AVERROR_PATCHWELCOME;
685 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
686 switch (avctx->pix_fmt) {
687 case AV_PIX_FMT_RGB24:
688 avctx->pix_fmt = AV_PIX_FMT_RGBA;
691 case AV_PIX_FMT_RGB48BE:
692 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
695 case AV_PIX_FMT_GRAY8:
696 avctx->pix_fmt = AV_PIX_FMT_YA8;
699 case AV_PIX_FMT_GRAY16BE:
700 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
704 avpriv_request_sample(avctx, "bit depth %d "
705 "and color type %d with TRNS",
706 s->bit_depth, s->color_type);
707 return AVERROR_INVALIDDATA;
710 s->bpp += byte_depth;
713 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
715 if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
716 ff_thread_release_buffer(avctx, &s->previous_picture);
717 if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
720 p->pict_type = AV_PICTURE_TYPE_I;
722 p->interlaced_frame = !!s->interlace_type;
724 ff_thread_finish_setup(avctx);
726 /* compute the compressed row size */
727 if (!s->interlace_type) {
728 s->crow_size = s->row_size + 1;
731 s->pass_row_size = ff_png_pass_row_size(s->pass,
734 s->crow_size = s->pass_row_size + 1;
736 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
737 s->row_size, s->crow_size);
738 s->image_buf = p->data[0];
739 s->image_linesize = p->linesize[0];
740 /* copy the palette if needed */
741 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
742 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
743 /* empty row is used if differencing to the first row */
744 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
746 return AVERROR_INVALIDDATA;
747 if (s->interlace_type ||
748 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
749 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
751 return AVERROR_INVALIDDATA;
754 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
756 return AVERROR(ENOMEM);
758 /* we want crow_buf+1 to be 16-byte aligned */
759 s->crow_buf = s->buffer + 15;
760 s->zstream.avail_out = s->crow_size;
761 s->zstream.next_out = s->crow_buf;
764 s->pic_state |= PNG_IDAT;
766 /* set image to non-transparent bpp while decompressing */
767 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
768 s->bpp -= byte_depth;
770 ret = png_decode_idat(s, length);
772 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
773 s->bpp += byte_depth;
778 bytestream2_skip(&s->gb, 4); /* crc */
783 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
788 if ((length % 3) != 0 || length > 256 * 3)
789 return AVERROR_INVALIDDATA;
790 /* read the palette */
792 for (i = 0; i < n; i++) {
793 r = bytestream2_get_byte(&s->gb);
794 g = bytestream2_get_byte(&s->gb);
795 b = bytestream2_get_byte(&s->gb);
796 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
799 s->palette[i] = (0xFFU << 24);
800 s->hdr_state |= PNG_PLTE;
801 bytestream2_skip(&s->gb, 4); /* crc */
806 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
811 if (!(s->hdr_state & PNG_IHDR)) {
812 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
813 return AVERROR_INVALIDDATA;
816 if (s->pic_state & PNG_IDAT) {
817 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
818 return AVERROR_INVALIDDATA;
821 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
822 if (length > 256 || !(s->hdr_state & PNG_PLTE))
823 return AVERROR_INVALIDDATA;
825 for (i = 0; i < length; i++) {
826 unsigned v = bytestream2_get_byte(&s->gb);
827 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
829 } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
830 if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
831 (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
833 return AVERROR_INVALIDDATA;
835 for (i = 0; i < length / 2; i++) {
836 /* only use the least significant bits */
837 v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
839 if (s->bit_depth > 8)
840 AV_WB16(&s->transparent_color_be[2 * i], v);
842 s->transparent_color_be[i] = v;
845 return AVERROR_INVALIDDATA;
848 bytestream2_skip(&s->gb, 4); /* crc */
854 static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
857 uint8_t *data, profile_name[82];
861 while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
863 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
864 return AVERROR_INVALIDDATA;
867 length = FFMAX(length - cnt, 0);
869 if (bytestream2_get_byte(&s->gb) != 0) {
870 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
871 return AVERROR_INVALIDDATA;
874 length = FFMAX(length - 1, 0);
876 if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
879 ret = av_bprint_finalize(&bp, (char **)&data);
883 sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
886 return AVERROR(ENOMEM);
889 av_dict_set(&sd->metadata, "name", profile_name, 0);
890 memcpy(sd->data, data, bp.len);
893 /* ICC compressed data and CRC */
894 bytestream2_skip(&s->gb, length + 4);
899 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
901 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
903 uint8_t *pd = p->data[0];
904 for (j = 0; j < s->height; j++) {
906 for (k = 7; k >= 1; k--)
907 if ((s->width&7) >= k)
908 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
909 for (i--; i >= 0; i--) {
910 pd[8*i + 7]= pd[i] & 1;
911 pd[8*i + 6]= (pd[i]>>1) & 1;
912 pd[8*i + 5]= (pd[i]>>2) & 1;
913 pd[8*i + 4]= (pd[i]>>3) & 1;
914 pd[8*i + 3]= (pd[i]>>4) & 1;
915 pd[8*i + 2]= (pd[i]>>5) & 1;
916 pd[8*i + 1]= (pd[i]>>6) & 1;
917 pd[8*i + 0]= pd[i]>>7;
919 pd += s->image_linesize;
921 } else if (s->bits_per_pixel == 2) {
923 uint8_t *pd = p->data[0];
924 for (j = 0; j < s->height; j++) {
926 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
927 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
928 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
929 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
930 for (i--; i >= 0; i--) {
931 pd[4*i + 3]= pd[i] & 3;
932 pd[4*i + 2]= (pd[i]>>2) & 3;
933 pd[4*i + 1]= (pd[i]>>4) & 3;
934 pd[4*i + 0]= pd[i]>>6;
937 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
938 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
939 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
940 for (i--; i >= 0; i--) {
941 pd[4*i + 3]= ( pd[i] & 3)*0x55;
942 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
943 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
944 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
947 pd += s->image_linesize;
949 } else if (s->bits_per_pixel == 4) {
951 uint8_t *pd = p->data[0];
952 for (j = 0; j < s->height; j++) {
954 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
955 if (s->width&1) pd[2*i+0]= pd[i]>>4;
956 for (i--; i >= 0; i--) {
957 pd[2*i + 1] = pd[i] & 15;
958 pd[2*i + 0] = pd[i] >> 4;
961 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
962 for (i--; i >= 0; i--) {
963 pd[2*i + 1] = (pd[i] & 15) * 0x11;
964 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
967 pd += s->image_linesize;
972 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
975 uint32_t sequence_number;
976 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
979 return AVERROR_INVALIDDATA;
981 if (!(s->hdr_state & PNG_IHDR)) {
982 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
983 return AVERROR_INVALIDDATA;
986 s->last_w = s->cur_w;
987 s->last_h = s->cur_h;
988 s->last_x_offset = s->x_offset;
989 s->last_y_offset = s->y_offset;
990 s->last_dispose_op = s->dispose_op;
992 sequence_number = bytestream2_get_be32(&s->gb);
993 cur_w = bytestream2_get_be32(&s->gb);
994 cur_h = bytestream2_get_be32(&s->gb);
995 x_offset = bytestream2_get_be32(&s->gb);
996 y_offset = bytestream2_get_be32(&s->gb);
997 bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
998 dispose_op = bytestream2_get_byte(&s->gb);
999 blend_op = bytestream2_get_byte(&s->gb);
1000 bytestream2_skip(&s->gb, 4); /* crc */
1002 if (sequence_number == 0 &&
1003 (cur_w != s->width ||
1004 cur_h != s->height ||
1007 cur_w <= 0 || cur_h <= 0 ||
1008 x_offset < 0 || y_offset < 0 ||
1009 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1010 return AVERROR_INVALIDDATA;
1012 if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1013 av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1014 return AVERROR_INVALIDDATA;
1017 if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
1018 dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1019 // No previous frame to revert to for the first frame
1020 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1021 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1024 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1025 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1026 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1027 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1028 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1029 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1030 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1032 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1033 blend_op = APNG_BLEND_OP_SOURCE;
1038 s->x_offset = x_offset;
1039 s->y_offset = y_offset;
1040 s->dispose_op = dispose_op;
1041 s->blend_op = blend_op;
1046 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1049 uint8_t *pd = p->data[0];
1050 uint8_t *pd_last = s->last_picture.f->data[0];
1051 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1053 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1054 for (j = 0; j < s->height; j++) {
1055 for (i = 0; i < ls; i++)
1056 pd[i] += pd_last[i];
1057 pd += s->image_linesize;
1058 pd_last += s->image_linesize;
1062 // divide by 255 and round to nearest
1063 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1064 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1066 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
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 buffer = av_malloc_array(s->image_linesize, s->height);
1083 return AVERROR(ENOMEM);
1086 // Do the disposal operation specified by the last frame on the frame
1087 if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
1088 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1089 memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
1091 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
1092 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
1093 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1095 memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
1096 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1098 ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
1099 memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
1103 if (s->blend_op == APNG_BLEND_OP_SOURCE) {
1104 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1105 size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
1106 memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
1108 } else { // APNG_BLEND_OP_OVER
1109 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1110 uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
1111 uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
1112 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1114 uint8_t foreground_alpha, background_alpha, output_alpha;
1117 // Since we might be blending alpha onto alpha, we use the following equations:
1118 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1119 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1121 switch (avctx->pix_fmt) {
1122 case AV_PIX_FMT_RGBA:
1123 foreground_alpha = foreground[3];
1124 background_alpha = background[3];
1127 case AV_PIX_FMT_GRAY8A:
1128 foreground_alpha = foreground[1];
1129 background_alpha = background[1];
1132 case AV_PIX_FMT_PAL8:
1133 foreground_alpha = s->palette[foreground[0]] >> 24;
1134 background_alpha = s->palette[background[0]] >> 24;
1138 if (foreground_alpha == 0)
1141 if (foreground_alpha == 255) {
1142 memcpy(background, foreground, s->bpp);
1146 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1147 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1148 avpriv_request_sample(avctx, "Alpha blending palette samples");
1149 background[0] = foreground[0];
1153 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1155 av_assert0(s->bpp <= 10);
1157 for (b = 0; b < s->bpp - 1; ++b) {
1158 if (output_alpha == 0) {
1160 } else if (background_alpha == 255) {
1161 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1163 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1166 output[b] = output_alpha;
1167 memcpy(background, output, s->bpp);
1172 // Copy blended buffer into the frame and free
1173 memcpy(p->data[0], buffer, s->image_linesize * s->height);
1179 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1180 AVFrame *p, AVPacket *avpkt)
1182 AVDictionary **metadatap = NULL;
1183 uint32_t tag, length;
1184 int decode_next_dat = 0;
1188 length = bytestream2_get_bytes_left(&s->gb);
1191 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1192 avctx->skip_frame == AVDISCARD_ALL) {
1196 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1197 if (!(s->pic_state & PNG_IDAT))
1202 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1203 if ( s->pic_state & PNG_ALLIMAGE
1204 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1206 ret = AVERROR_INVALIDDATA;
1210 length = bytestream2_get_be32(&s->gb);
1211 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1212 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1213 ret = AVERROR_INVALIDDATA;
1216 tag = bytestream2_get_le32(&s->gb);
1217 if (avctx->debug & FF_DEBUG_STARTCODE)
1218 av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1219 av_fourcc2str(tag), length);
1221 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1222 avctx->skip_frame == AVDISCARD_ALL) {
1224 case MKTAG('I', 'H', 'D', 'R'):
1225 case MKTAG('p', 'H', 'Y', 's'):
1226 case MKTAG('t', 'E', 'X', 't'):
1227 case MKTAG('I', 'D', 'A', 'T'):
1228 case MKTAG('t', 'R', 'N', 'S'):
1235 metadatap = &p->metadata;
1237 case MKTAG('I', 'H', 'D', 'R'):
1238 if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1241 case MKTAG('p', 'H', 'Y', 's'):
1242 if ((ret = decode_phys_chunk(avctx, s)) < 0)
1245 case MKTAG('f', 'c', 'T', 'L'):
1246 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1248 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1250 decode_next_dat = 1;
1252 case MKTAG('f', 'd', 'A', 'T'):
1253 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1255 if (!decode_next_dat || length < 4) {
1256 ret = AVERROR_INVALIDDATA;
1259 bytestream2_get_be32(&s->gb);
1262 case MKTAG('I', 'D', 'A', 'T'):
1263 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1265 if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1268 case MKTAG('P', 'L', 'T', 'E'):
1269 if (decode_plte_chunk(avctx, s, length) < 0)
1272 case MKTAG('t', 'R', 'N', 'S'):
1273 if (decode_trns_chunk(avctx, s, length) < 0)
1276 case MKTAG('t', 'E', 'X', 't'):
1277 if (decode_text_chunk(s, length, 0, metadatap) < 0)
1278 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1279 bytestream2_skip(&s->gb, length + 4);
1281 case MKTAG('z', 'T', 'X', 't'):
1282 if (decode_text_chunk(s, length, 1, metadatap) < 0)
1283 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1284 bytestream2_skip(&s->gb, length + 4);
1286 case MKTAG('s', 'T', 'E', 'R'): {
1287 int mode = bytestream2_get_byte(&s->gb);
1288 AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
1290 ret = AVERROR(ENOMEM);
1294 if (mode == 0 || mode == 1) {
1295 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1296 stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1298 av_log(avctx, AV_LOG_WARNING,
1299 "Unknown value in sTER chunk (%d)\n", mode);
1301 bytestream2_skip(&s->gb, 4); /* crc */
1304 case MKTAG('i', 'C', 'C', 'P'): {
1305 if ((ret = decode_iccp_chunk(s, length, p)) < 0)
1309 case MKTAG('c', 'H', 'R', 'M'): {
1310 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(p);
1312 ret = AVERROR(ENOMEM);
1316 mdm->white_point[0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1317 mdm->white_point[1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1320 for (i = 0; i < 3; i++) {
1321 mdm->display_primaries[i][0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1322 mdm->display_primaries[i][1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1325 mdm->has_primaries = 1;
1326 bytestream2_skip(&s->gb, 4); /* crc */
1329 case MKTAG('g', 'A', 'M', 'A'): {
1332 int num = bytestream2_get_be32(&s->gb);
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(&p->metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1342 bytestream2_skip(&s->gb, 4); /* crc */
1345 case MKTAG('I', 'E', 'N', 'D'):
1346 if (!(s->pic_state & PNG_ALLIMAGE))
1347 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1348 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1349 ret = AVERROR_INVALIDDATA;
1352 bytestream2_skip(&s->gb, 4); /* crc */
1357 bytestream2_skip(&s->gb, length + 4);
1363 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1364 avctx->skip_frame == AVDISCARD_ALL) {
1368 if (percent_missing(s) > avctx->discard_damaged_percentage)
1369 return AVERROR_INVALIDDATA;
1371 if (s->bits_per_pixel <= 4)
1372 handle_small_bpp(s, p);
1374 /* apply transparency if needed */
1375 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1376 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1377 size_t raw_bpp = s->bpp - byte_depth;
1380 av_assert0(s->bit_depth > 1);
1382 for (y = 0; y < s->height; ++y) {
1383 uint8_t *row = &s->image_buf[s->image_linesize * y];
1385 if (s->bpp == 2 && byte_depth == 1) {
1386 uint8_t *pixel = &row[2 * s->width - 1];
1387 uint8_t *rowp = &row[1 * s->width - 1];
1388 int tcolor = s->transparent_color_be[0];
1389 for (x = s->width; x > 0; --x) {
1390 *pixel-- = *rowp == tcolor ? 0 : 0xff;
1393 } else if (s->bpp == 4 && byte_depth == 1) {
1394 uint8_t *pixel = &row[4 * s->width - 1];
1395 uint8_t *rowp = &row[3 * s->width - 1];
1396 int tcolor = AV_RL24(s->transparent_color_be);
1397 for (x = s->width; x > 0; --x) {
1398 *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1404 /* since we're updating in-place, we have to go from right to left */
1405 for (x = s->width; x > 0; --x) {
1406 uint8_t *pixel = &row[s->bpp * (x - 1)];
1407 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1409 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1410 memset(&pixel[raw_bpp], 0, byte_depth);
1412 memset(&pixel[raw_bpp], 0xff, byte_depth);
1419 /* handle P-frames only if a predecessor frame is available */
1420 if (s->last_picture.f->data[0]) {
1421 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1422 && s->last_picture.f->width == p->width
1423 && s->last_picture.f->height== p->height
1424 && s->last_picture.f->format== p->format
1426 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1427 handle_p_frame_png(s, p);
1428 else if (CONFIG_APNG_DECODER &&
1429 s->previous_picture.f->width == p->width &&
1430 s->previous_picture.f->height== p->height &&
1431 s->previous_picture.f->format== p->format &&
1432 avctx->codec_id == AV_CODEC_ID_APNG &&
1433 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1437 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1438 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1443 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1444 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1448 #if CONFIG_PNG_DECODER
1449 static int decode_frame_png(AVCodecContext *avctx,
1450 void *data, int *got_frame,
1453 PNGDecContext *const s = avctx->priv_data;
1454 const uint8_t *buf = avpkt->data;
1455 int buf_size = avpkt->size;
1460 ff_thread_release_buffer(avctx, &s->last_picture);
1461 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1464 bytestream2_init(&s->gb, buf, buf_size);
1466 /* check signature */
1467 sig = bytestream2_get_be64(&s->gb);
1468 if (sig != PNGSIG &&
1470 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1471 return AVERROR_INVALIDDATA;
1474 s->y = s->has_trns = 0;
1479 s->zstream.zalloc = ff_png_zalloc;
1480 s->zstream.zfree = ff_png_zfree;
1481 s->zstream.opaque = NULL;
1482 ret = inflateInit(&s->zstream);
1484 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1485 return AVERROR_EXTERNAL;
1488 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1491 if (avctx->skip_frame == AVDISCARD_ALL) {
1493 ret = bytestream2_tell(&s->gb);
1497 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1502 ret = bytestream2_tell(&s->gb);
1504 inflateEnd(&s->zstream);
1510 #if CONFIG_APNG_DECODER
1511 static int decode_frame_apng(AVCodecContext *avctx,
1512 void *data, int *got_frame,
1515 PNGDecContext *const s = avctx->priv_data;
1519 ff_thread_release_buffer(avctx, &s->last_picture);
1520 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1523 if (!(s->hdr_state & PNG_IHDR)) {
1524 if (!avctx->extradata_size)
1525 return AVERROR_INVALIDDATA;
1527 /* only init fields, there is no zlib use in extradata */
1528 s->zstream.zalloc = ff_png_zalloc;
1529 s->zstream.zfree = ff_png_zfree;
1531 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1532 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1536 /* reset state for a new frame */
1537 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1538 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1539 ret = AVERROR_EXTERNAL;
1544 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1545 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1548 if (!(s->pic_state & PNG_ALLIMAGE))
1549 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1550 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1551 ret = AVERROR_INVALIDDATA;
1554 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1558 ret = bytestream2_tell(&s->gb);
1561 inflateEnd(&s->zstream);
1566 #if CONFIG_LSCR_DECODER
1567 static int decode_frame_lscr(AVCodecContext *avctx,
1568 void *data, int *got_frame,
1571 PNGDecContext *const s = avctx->priv_data;
1572 GetByteContext *gb = &s->gb;
1573 AVFrame *frame = data;
1574 int ret, nb_blocks, offset = 0;
1576 if (avpkt->size < 2)
1577 return AVERROR_INVALIDDATA;
1579 bytestream2_init(gb, avpkt->data, avpkt->size);
1581 if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1584 nb_blocks = bytestream2_get_le16(gb);
1585 if (bytestream2_get_bytes_left(gb) < 2 + nb_blocks * (12 + 8))
1586 return AVERROR_INVALIDDATA;
1588 if (s->last_picture.f->data[0]) {
1589 ret = av_frame_copy(frame, s->last_picture.f);
1594 for (int b = 0; b < nb_blocks; b++) {
1595 int x, y, x2, y2, w, h, left;
1596 uint32_t csize, size;
1598 s->zstream.zalloc = ff_png_zalloc;
1599 s->zstream.zfree = ff_png_zfree;
1600 s->zstream.opaque = NULL;
1602 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1603 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1604 ret = AVERROR_EXTERNAL;
1608 bytestream2_seek(gb, 2 + b * 12, SEEK_SET);
1610 x = bytestream2_get_le16(gb);
1611 y = bytestream2_get_le16(gb);
1612 x2 = bytestream2_get_le16(gb);
1613 y2 = bytestream2_get_le16(gb);
1614 s->width = s->cur_w = w = x2-x;
1615 s->height = s->cur_h = h = y2-y;
1617 if (w <= 0 || x < 0 || x >= avctx->width || w + x > avctx->width ||
1618 h <= 0 || y < 0 || y >= avctx->height || h + y > avctx->height) {
1619 ret = AVERROR_INVALIDDATA;
1623 size = bytestream2_get_le32(gb);
1625 frame->key_frame = (nb_blocks == 1) &&
1626 (w == avctx->width) &&
1627 (h == avctx->height) &&
1628 (x == 0) && (y == 0);
1630 bytestream2_seek(gb, 2 + nb_blocks * 12 + offset, SEEK_SET);
1631 csize = bytestream2_get_be32(gb);
1632 if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1633 ret = AVERROR_INVALIDDATA;
1641 s->row_size = w * 3;
1643 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
1645 ret = AVERROR(ENOMEM);
1649 av_fast_padded_malloc(&s->last_row, &s->last_row_size, s->row_size);
1651 ret = AVERROR(ENOMEM);
1655 s->crow_size = w * 3 + 1;
1656 s->crow_buf = s->buffer + 15;
1657 s->zstream.avail_out = s->crow_size;
1658 s->zstream.next_out = s->crow_buf;
1659 s->image_buf = frame->data[0] + (avctx->height - y - 1) * frame->linesize[0] + x * 3;
1660 s->image_linesize =-frame->linesize[0];
1665 ret = png_decode_idat(s, csize);
1670 bytestream2_skip(gb, 4);
1671 csize = bytestream2_get_be32(gb);
1672 if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1673 ret = AVERROR_INVALIDDATA;
1679 inflateEnd(&s->zstream);
1682 frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1684 av_frame_unref(s->last_picture.f);
1685 if ((ret = av_frame_ref(s->last_picture.f, frame)) < 0)
1690 inflateEnd(&s->zstream);
1697 static void decode_flush(AVCodecContext *avctx)
1699 PNGDecContext *s = avctx->priv_data;
1701 av_frame_unref(s->last_picture.f);
1707 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1709 PNGDecContext *psrc = src->priv_data;
1710 PNGDecContext *pdst = dst->priv_data;
1716 ff_thread_release_buffer(dst, &pdst->picture);
1717 if (psrc->picture.f->data[0] &&
1718 (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1720 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1721 pdst->width = psrc->width;
1722 pdst->height = psrc->height;
1723 pdst->bit_depth = psrc->bit_depth;
1724 pdst->color_type = psrc->color_type;
1725 pdst->compression_type = psrc->compression_type;
1726 pdst->interlace_type = psrc->interlace_type;
1727 pdst->filter_type = psrc->filter_type;
1728 pdst->cur_w = psrc->cur_w;
1729 pdst->cur_h = psrc->cur_h;
1730 pdst->x_offset = psrc->x_offset;
1731 pdst->y_offset = psrc->y_offset;
1732 pdst->has_trns = psrc->has_trns;
1733 memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1735 pdst->dispose_op = psrc->dispose_op;
1737 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1739 pdst->hdr_state |= psrc->hdr_state;
1741 ff_thread_release_buffer(dst, &pdst->last_picture);
1742 if (psrc->last_picture.f->data[0] &&
1743 (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
1746 ff_thread_release_buffer(dst, &pdst->previous_picture);
1747 if (psrc->previous_picture.f->data[0] &&
1748 (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
1756 static av_cold int png_dec_init(AVCodecContext *avctx)
1758 PNGDecContext *s = avctx->priv_data;
1760 avctx->color_range = AVCOL_RANGE_JPEG;
1762 if (avctx->codec_id == AV_CODEC_ID_LSCR)
1763 avctx->pix_fmt = AV_PIX_FMT_BGR24;
1766 s->previous_picture.f = av_frame_alloc();
1767 s->last_picture.f = av_frame_alloc();
1768 s->picture.f = av_frame_alloc();
1769 if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1770 av_frame_free(&s->previous_picture.f);
1771 av_frame_free(&s->last_picture.f);
1772 av_frame_free(&s->picture.f);
1773 return AVERROR(ENOMEM);
1776 ff_pngdsp_init(&s->dsp);
1781 static av_cold int png_dec_end(AVCodecContext *avctx)
1783 PNGDecContext *s = avctx->priv_data;
1785 ff_thread_release_buffer(avctx, &s->previous_picture);
1786 av_frame_free(&s->previous_picture.f);
1787 ff_thread_release_buffer(avctx, &s->last_picture);
1788 av_frame_free(&s->last_picture.f);
1789 ff_thread_release_buffer(avctx, &s->picture);
1790 av_frame_free(&s->picture.f);
1791 av_freep(&s->buffer);
1793 av_freep(&s->last_row);
1794 s->last_row_size = 0;
1795 av_freep(&s->tmp_row);
1796 s->tmp_row_size = 0;
1801 #if CONFIG_APNG_DECODER
1802 AVCodec ff_apng_decoder = {
1804 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1805 .type = AVMEDIA_TYPE_VIDEO,
1806 .id = AV_CODEC_ID_APNG,
1807 .priv_data_size = sizeof(PNGDecContext),
1808 .init = png_dec_init,
1809 .close = png_dec_end,
1810 .decode = decode_frame_apng,
1811 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1812 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1813 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
1814 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1818 #if CONFIG_PNG_DECODER
1819 AVCodec ff_png_decoder = {
1821 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1822 .type = AVMEDIA_TYPE_VIDEO,
1823 .id = AV_CODEC_ID_PNG,
1824 .priv_data_size = sizeof(PNGDecContext),
1825 .init = png_dec_init,
1826 .close = png_dec_end,
1827 .decode = decode_frame_png,
1828 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1829 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1830 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1831 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1835 #if CONFIG_LSCR_DECODER
1836 AVCodec ff_lscr_decoder = {
1838 .long_name = NULL_IF_CONFIG_SMALL("LEAD Screen Capture"),
1839 .type = AVMEDIA_TYPE_VIDEO,
1840 .id = AV_CODEC_ID_LSCR,
1841 .priv_data_size = sizeof(PNGDecContext),
1842 .init = png_dec_init,
1843 .close = png_dec_end,
1844 .decode = decode_frame_lscr,
1845 .flush = decode_flush,
1846 .capabilities = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1847 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1848 FF_CODEC_CAP_ALLOCATE_PROGRESS,