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 /* process exactly one decompressed row */
324 static void png_handle_row(PNGDecContext *s)
326 uint8_t *ptr, *last_row;
329 if (!s->interlace_type) {
330 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
332 last_row = s->last_row;
334 last_row = ptr - s->image_linesize;
336 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
337 last_row, s->row_size, s->bpp);
338 /* loco lags by 1 row so that it doesn't interfere with top prediction */
339 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
340 if (s->bit_depth == 16) {
341 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
342 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
344 deloco_rgb8(ptr - s->image_linesize, s->row_size,
345 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
349 if (s->y == s->cur_h) {
350 s->pic_state |= PNG_ALLIMAGE;
351 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
352 if (s->bit_depth == 16) {
353 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
354 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
356 deloco_rgb8(ptr, s->row_size,
357 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
364 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
365 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
366 /* if we already read one row, it is time to stop to
367 * wait for the next one */
370 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
371 s->last_row, s->pass_row_size, s->bpp);
372 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
373 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
376 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
377 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
378 s->color_type, s->last_row);
381 if (s->y == s->cur_h) {
382 memset(s->last_row, 0, s->row_size);
384 if (s->pass == NB_PASSES - 1) {
385 s->pic_state |= PNG_ALLIMAGE;
390 s->pass_row_size = ff_png_pass_row_size(s->pass,
393 s->crow_size = s->pass_row_size + 1;
394 if (s->pass_row_size != 0)
396 /* skip pass if empty row */
405 static int png_decode_idat(PNGDecContext *s, int length)
408 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
409 s->zstream.next_in = (unsigned char *)s->gb.buffer;
410 bytestream2_skip(&s->gb, length);
412 /* decode one line if possible */
413 while (s->zstream.avail_in > 0) {
414 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
415 if (ret != Z_OK && ret != Z_STREAM_END) {
416 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
417 return AVERROR_EXTERNAL;
419 if (s->zstream.avail_out == 0) {
420 if (!(s->pic_state & PNG_ALLIMAGE)) {
423 s->zstream.avail_out = s->crow_size;
424 s->zstream.next_out = s->crow_buf;
426 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
427 av_log(NULL, AV_LOG_WARNING,
428 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
435 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
436 const uint8_t *data_end)
443 zstream.zalloc = ff_png_zalloc;
444 zstream.zfree = ff_png_zfree;
445 zstream.opaque = NULL;
446 if (inflateInit(&zstream) != Z_OK)
447 return AVERROR_EXTERNAL;
448 zstream.next_in = (unsigned char *)data;
449 zstream.avail_in = data_end - data;
450 av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
452 while (zstream.avail_in > 0) {
453 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
455 ret = AVERROR(ENOMEM);
458 zstream.next_out = buf;
459 zstream.avail_out = buf_size - 1;
460 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
461 if (ret != Z_OK && ret != Z_STREAM_END) {
462 ret = AVERROR_EXTERNAL;
465 bp->len += zstream.next_out - buf;
466 if (ret == Z_STREAM_END)
469 inflateEnd(&zstream);
470 bp->str[bp->len] = 0;
474 inflateEnd(&zstream);
475 av_bprint_finalize(bp, NULL);
479 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
484 for (i = 0; i < size_in; i++)
485 extra += in[i] >= 0x80;
486 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
488 q = out = av_malloc(size_in + extra + 1);
491 for (i = 0; i < size_in; i++) {
493 *(q++) = 0xC0 | (in[i] >> 6);
494 *(q++) = 0x80 | (in[i] & 0x3F);
503 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
507 const uint8_t *data = s->gb.buffer;
508 const uint8_t *data_end = data + length;
509 const uint8_t *keyword = data;
510 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
511 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
516 return AVERROR_INVALIDDATA;
517 data = keyword_end + 1;
520 if (data == data_end)
521 return AVERROR_INVALIDDATA;
524 return AVERROR_INVALIDDATA;
525 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
528 ret = av_bprint_finalize(&bp, (char **)&text);
532 text = (uint8_t *)data;
533 text_len = data_end - text;
536 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
537 txt_utf8 = iso88591_to_utf8(text, text_len);
540 if (!(kw_utf8 && txt_utf8)) {
543 return AVERROR(ENOMEM);
546 av_dict_set(dict, kw_utf8, txt_utf8,
547 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
551 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
555 return AVERROR_INVALIDDATA;
557 if (s->pic_state & PNG_IDAT) {
558 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
559 return AVERROR_INVALIDDATA;
562 if (s->hdr_state & PNG_IHDR) {
563 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
564 return AVERROR_INVALIDDATA;
567 s->width = s->cur_w = bytestream2_get_be32(&s->gb);
568 s->height = s->cur_h = bytestream2_get_be32(&s->gb);
569 if (av_image_check_size(s->width, s->height, 0, avctx)) {
570 s->cur_w = s->cur_h = s->width = s->height = 0;
571 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
572 return AVERROR_INVALIDDATA;
574 s->bit_depth = bytestream2_get_byte(&s->gb);
575 if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
576 s->bit_depth != 8 && s->bit_depth != 16) {
577 av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
580 s->color_type = bytestream2_get_byte(&s->gb);
581 s->compression_type = bytestream2_get_byte(&s->gb);
582 if (s->compression_type) {
583 av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
586 s->filter_type = bytestream2_get_byte(&s->gb);
587 s->interlace_type = bytestream2_get_byte(&s->gb);
588 bytestream2_skip(&s->gb, 4); /* crc */
589 s->hdr_state |= PNG_IHDR;
590 if (avctx->debug & FF_DEBUG_PICT_INFO)
591 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
592 "compression_type=%d filter_type=%d interlace_type=%d\n",
593 s->width, s->height, s->bit_depth, s->color_type,
594 s->compression_type, s->filter_type, s->interlace_type);
598 s->cur_w = s->cur_h = s->width = s->height = 0;
600 return AVERROR_INVALIDDATA;
603 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
605 if (s->pic_state & PNG_IDAT) {
606 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
607 return AVERROR_INVALIDDATA;
609 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
610 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
611 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
612 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
613 bytestream2_skip(&s->gb, 1); /* unit specifier */
614 bytestream2_skip(&s->gb, 4); /* crc */
619 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
620 uint32_t length, AVFrame *p)
623 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
625 if (!(s->hdr_state & PNG_IHDR)) {
626 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
627 return AVERROR_INVALIDDATA;
629 if (!(s->pic_state & PNG_IDAT)) {
630 /* init image info */
631 ret = ff_set_dimensions(avctx, s->width, s->height);
635 s->channels = ff_png_get_nb_channels(s->color_type);
636 s->bits_per_pixel = s->bit_depth * s->channels;
637 s->bpp = (s->bits_per_pixel + 7) >> 3;
638 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
640 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
641 s->color_type == PNG_COLOR_TYPE_RGB) {
642 avctx->pix_fmt = AV_PIX_FMT_RGB24;
643 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
644 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
645 avctx->pix_fmt = AV_PIX_FMT_RGBA;
646 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
647 s->color_type == PNG_COLOR_TYPE_GRAY) {
648 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
649 } else if (s->bit_depth == 16 &&
650 s->color_type == PNG_COLOR_TYPE_GRAY) {
651 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
652 } else if (s->bit_depth == 16 &&
653 s->color_type == PNG_COLOR_TYPE_RGB) {
654 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
655 } else if (s->bit_depth == 16 &&
656 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
657 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
658 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
659 s->color_type == PNG_COLOR_TYPE_PALETTE) {
660 avctx->pix_fmt = AV_PIX_FMT_PAL8;
661 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
662 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
663 } else if (s->bit_depth == 8 &&
664 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
665 avctx->pix_fmt = AV_PIX_FMT_YA8;
666 } else if (s->bit_depth == 16 &&
667 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
668 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
670 avpriv_report_missing_feature(avctx,
671 "Bit depth %d color type %d",
672 s->bit_depth, s->color_type);
673 return AVERROR_PATCHWELCOME;
676 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
677 switch (avctx->pix_fmt) {
678 case AV_PIX_FMT_RGB24:
679 avctx->pix_fmt = AV_PIX_FMT_RGBA;
682 case AV_PIX_FMT_RGB48BE:
683 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
686 case AV_PIX_FMT_GRAY8:
687 avctx->pix_fmt = AV_PIX_FMT_YA8;
690 case AV_PIX_FMT_GRAY16BE:
691 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
695 avpriv_request_sample(avctx, "bit depth %d "
696 "and color type %d with TRNS",
697 s->bit_depth, s->color_type);
698 return AVERROR_INVALIDDATA;
701 s->bpp += byte_depth;
704 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
706 if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
707 ff_thread_release_buffer(avctx, &s->previous_picture);
708 if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
711 p->pict_type = AV_PICTURE_TYPE_I;
713 p->interlaced_frame = !!s->interlace_type;
715 ff_thread_finish_setup(avctx);
717 /* compute the compressed row size */
718 if (!s->interlace_type) {
719 s->crow_size = s->row_size + 1;
722 s->pass_row_size = ff_png_pass_row_size(s->pass,
725 s->crow_size = s->pass_row_size + 1;
727 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
728 s->row_size, s->crow_size);
729 s->image_buf = p->data[0];
730 s->image_linesize = p->linesize[0];
731 /* copy the palette if needed */
732 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
733 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
734 /* empty row is used if differencing to the first row */
735 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
737 return AVERROR_INVALIDDATA;
738 if (s->interlace_type ||
739 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
740 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
742 return AVERROR_INVALIDDATA;
745 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
747 return AVERROR(ENOMEM);
749 /* we want crow_buf+1 to be 16-byte aligned */
750 s->crow_buf = s->buffer + 15;
751 s->zstream.avail_out = s->crow_size;
752 s->zstream.next_out = s->crow_buf;
755 s->pic_state |= PNG_IDAT;
757 /* set image to non-transparent bpp while decompressing */
758 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
759 s->bpp -= byte_depth;
761 ret = png_decode_idat(s, length);
763 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
764 s->bpp += byte_depth;
769 bytestream2_skip(&s->gb, 4); /* crc */
774 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
779 if ((length % 3) != 0 || length > 256 * 3)
780 return AVERROR_INVALIDDATA;
781 /* read the palette */
783 for (i = 0; i < n; i++) {
784 r = bytestream2_get_byte(&s->gb);
785 g = bytestream2_get_byte(&s->gb);
786 b = bytestream2_get_byte(&s->gb);
787 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
790 s->palette[i] = (0xFFU << 24);
791 s->hdr_state |= PNG_PLTE;
792 bytestream2_skip(&s->gb, 4); /* crc */
797 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
802 if (!(s->hdr_state & PNG_IHDR)) {
803 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
804 return AVERROR_INVALIDDATA;
807 if (s->pic_state & PNG_IDAT) {
808 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
809 return AVERROR_INVALIDDATA;
812 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
813 if (length > 256 || !(s->hdr_state & PNG_PLTE))
814 return AVERROR_INVALIDDATA;
816 for (i = 0; i < length; i++) {
817 unsigned v = bytestream2_get_byte(&s->gb);
818 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
820 } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
821 if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
822 (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
824 return AVERROR_INVALIDDATA;
826 for (i = 0; i < length / 2; i++) {
827 /* only use the least significant bits */
828 v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
830 if (s->bit_depth > 8)
831 AV_WB16(&s->transparent_color_be[2 * i], v);
833 s->transparent_color_be[i] = v;
836 return AVERROR_INVALIDDATA;
839 bytestream2_skip(&s->gb, 4); /* crc */
845 static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
848 uint8_t *data, profile_name[82];
852 while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
854 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
855 return AVERROR_INVALIDDATA;
858 length = FFMAX(length - cnt, 0);
860 if (bytestream2_get_byte(&s->gb) != 0) {
861 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
862 return AVERROR_INVALIDDATA;
865 length = FFMAX(length - 1, 0);
867 if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
870 ret = av_bprint_finalize(&bp, (char **)&data);
874 sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
877 return AVERROR(ENOMEM);
880 av_dict_set(&sd->metadata, "name", profile_name, 0);
881 memcpy(sd->data, data, bp.len);
884 /* ICC compressed data and CRC */
885 bytestream2_skip(&s->gb, length + 4);
890 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
892 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
894 uint8_t *pd = p->data[0];
895 for (j = 0; j < s->height; j++) {
897 for (k = 7; k >= 1; k--)
898 if ((s->width&7) >= k)
899 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
900 for (i--; i >= 0; i--) {
901 pd[8*i + 7]= pd[i] & 1;
902 pd[8*i + 6]= (pd[i]>>1) & 1;
903 pd[8*i + 5]= (pd[i]>>2) & 1;
904 pd[8*i + 4]= (pd[i]>>3) & 1;
905 pd[8*i + 3]= (pd[i]>>4) & 1;
906 pd[8*i + 2]= (pd[i]>>5) & 1;
907 pd[8*i + 1]= (pd[i]>>6) & 1;
908 pd[8*i + 0]= pd[i]>>7;
910 pd += s->image_linesize;
912 } else if (s->bits_per_pixel == 2) {
914 uint8_t *pd = p->data[0];
915 for (j = 0; j < s->height; j++) {
917 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
918 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
919 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
920 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
921 for (i--; i >= 0; i--) {
922 pd[4*i + 3]= pd[i] & 3;
923 pd[4*i + 2]= (pd[i]>>2) & 3;
924 pd[4*i + 1]= (pd[i]>>4) & 3;
925 pd[4*i + 0]= pd[i]>>6;
928 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
929 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
930 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
931 for (i--; i >= 0; i--) {
932 pd[4*i + 3]= ( pd[i] & 3)*0x55;
933 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
934 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
935 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
938 pd += s->image_linesize;
940 } else if (s->bits_per_pixel == 4) {
942 uint8_t *pd = p->data[0];
943 for (j = 0; j < s->height; j++) {
945 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
946 if (s->width&1) pd[2*i+0]= pd[i]>>4;
947 for (i--; i >= 0; i--) {
948 pd[2*i + 1] = pd[i] & 15;
949 pd[2*i + 0] = pd[i] >> 4;
952 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
953 for (i--; i >= 0; i--) {
954 pd[2*i + 1] = (pd[i] & 15) * 0x11;
955 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
958 pd += s->image_linesize;
963 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
966 uint32_t sequence_number;
967 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
970 return AVERROR_INVALIDDATA;
972 if (!(s->hdr_state & PNG_IHDR)) {
973 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
974 return AVERROR_INVALIDDATA;
977 s->last_w = s->cur_w;
978 s->last_h = s->cur_h;
979 s->last_x_offset = s->x_offset;
980 s->last_y_offset = s->y_offset;
981 s->last_dispose_op = s->dispose_op;
983 sequence_number = bytestream2_get_be32(&s->gb);
984 cur_w = bytestream2_get_be32(&s->gb);
985 cur_h = bytestream2_get_be32(&s->gb);
986 x_offset = bytestream2_get_be32(&s->gb);
987 y_offset = bytestream2_get_be32(&s->gb);
988 bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
989 dispose_op = bytestream2_get_byte(&s->gb);
990 blend_op = bytestream2_get_byte(&s->gb);
991 bytestream2_skip(&s->gb, 4); /* crc */
993 if (sequence_number == 0 &&
994 (cur_w != s->width ||
995 cur_h != s->height ||
998 cur_w <= 0 || cur_h <= 0 ||
999 x_offset < 0 || y_offset < 0 ||
1000 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1001 return AVERROR_INVALIDDATA;
1003 if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1004 av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1005 return AVERROR_INVALIDDATA;
1008 if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
1009 dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1010 // No previous frame to revert to for the first frame
1011 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1012 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1015 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1016 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1017 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1018 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1019 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1020 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1021 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1023 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1024 blend_op = APNG_BLEND_OP_SOURCE;
1029 s->x_offset = x_offset;
1030 s->y_offset = y_offset;
1031 s->dispose_op = dispose_op;
1032 s->blend_op = blend_op;
1037 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1040 uint8_t *pd = p->data[0];
1041 uint8_t *pd_last = s->last_picture.f->data[0];
1042 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1044 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1045 for (j = 0; j < s->height; j++) {
1046 for (i = 0; i < ls; i++)
1047 pd[i] += pd_last[i];
1048 pd += s->image_linesize;
1049 pd_last += s->image_linesize;
1053 // divide by 255 and round to nearest
1054 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1055 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1057 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1063 if (s->blend_op == APNG_BLEND_OP_OVER &&
1064 avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1065 avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
1066 avctx->pix_fmt != AV_PIX_FMT_PAL8) {
1067 avpriv_request_sample(avctx, "Blending with pixel format %s",
1068 av_get_pix_fmt_name(avctx->pix_fmt));
1069 return AVERROR_PATCHWELCOME;
1072 buffer = av_malloc_array(s->image_linesize, s->height);
1074 return AVERROR(ENOMEM);
1077 // Do the disposal operation specified by the last frame on the frame
1078 if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
1079 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1080 memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
1082 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
1083 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
1084 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1086 memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
1087 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1089 ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
1090 memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
1094 if (s->blend_op == APNG_BLEND_OP_SOURCE) {
1095 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1096 size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
1097 memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
1099 } else { // APNG_BLEND_OP_OVER
1100 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1101 uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
1102 uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
1103 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1105 uint8_t foreground_alpha, background_alpha, output_alpha;
1108 // Since we might be blending alpha onto alpha, we use the following equations:
1109 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1110 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1112 switch (avctx->pix_fmt) {
1113 case AV_PIX_FMT_RGBA:
1114 foreground_alpha = foreground[3];
1115 background_alpha = background[3];
1118 case AV_PIX_FMT_GRAY8A:
1119 foreground_alpha = foreground[1];
1120 background_alpha = background[1];
1123 case AV_PIX_FMT_PAL8:
1124 foreground_alpha = s->palette[foreground[0]] >> 24;
1125 background_alpha = s->palette[background[0]] >> 24;
1129 if (foreground_alpha == 0)
1132 if (foreground_alpha == 255) {
1133 memcpy(background, foreground, s->bpp);
1137 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1138 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1139 avpriv_request_sample(avctx, "Alpha blending palette samples");
1140 background[0] = foreground[0];
1144 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1146 av_assert0(s->bpp <= 10);
1148 for (b = 0; b < s->bpp - 1; ++b) {
1149 if (output_alpha == 0) {
1151 } else if (background_alpha == 255) {
1152 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1154 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1157 output[b] = output_alpha;
1158 memcpy(background, output, s->bpp);
1163 // Copy blended buffer into the frame and free
1164 memcpy(p->data[0], buffer, s->image_linesize * s->height);
1170 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1171 AVFrame *p, AVPacket *avpkt)
1173 AVDictionary **metadatap = NULL;
1174 uint32_t tag, length;
1175 int decode_next_dat = 0;
1179 length = bytestream2_get_bytes_left(&s->gb);
1182 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1183 avctx->skip_frame == AVDISCARD_ALL) {
1187 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1188 if (!(s->pic_state & PNG_IDAT))
1193 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1194 if ( s->pic_state & PNG_ALLIMAGE
1195 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1197 ret = AVERROR_INVALIDDATA;
1201 length = bytestream2_get_be32(&s->gb);
1202 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1203 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1204 ret = AVERROR_INVALIDDATA;
1207 tag = bytestream2_get_le32(&s->gb);
1208 if (avctx->debug & FF_DEBUG_STARTCODE)
1209 av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1210 av_fourcc2str(tag), length);
1212 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1213 avctx->skip_frame == AVDISCARD_ALL) {
1215 case MKTAG('I', 'H', 'D', 'R'):
1216 case MKTAG('p', 'H', 'Y', 's'):
1217 case MKTAG('t', 'E', 'X', 't'):
1218 case MKTAG('I', 'D', 'A', 'T'):
1219 case MKTAG('t', 'R', 'N', 'S'):
1226 metadatap = &p->metadata;
1228 case MKTAG('I', 'H', 'D', 'R'):
1229 if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1232 case MKTAG('p', 'H', 'Y', 's'):
1233 if ((ret = decode_phys_chunk(avctx, s)) < 0)
1236 case MKTAG('f', 'c', 'T', 'L'):
1237 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1239 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1241 decode_next_dat = 1;
1243 case MKTAG('f', 'd', 'A', 'T'):
1244 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1246 if (!decode_next_dat) {
1247 ret = AVERROR_INVALIDDATA;
1250 bytestream2_get_be32(&s->gb);
1253 case MKTAG('I', 'D', 'A', 'T'):
1254 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1256 if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1259 case MKTAG('P', 'L', 'T', 'E'):
1260 if (decode_plte_chunk(avctx, s, length) < 0)
1263 case MKTAG('t', 'R', 'N', 'S'):
1264 if (decode_trns_chunk(avctx, s, length) < 0)
1267 case MKTAG('t', 'E', 'X', 't'):
1268 if (decode_text_chunk(s, length, 0, metadatap) < 0)
1269 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1270 bytestream2_skip(&s->gb, length + 4);
1272 case MKTAG('z', 'T', 'X', 't'):
1273 if (decode_text_chunk(s, length, 1, metadatap) < 0)
1274 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1275 bytestream2_skip(&s->gb, length + 4);
1277 case MKTAG('s', 'T', 'E', 'R'): {
1278 int mode = bytestream2_get_byte(&s->gb);
1279 AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
1283 if (mode == 0 || mode == 1) {
1284 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1285 stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1287 av_log(avctx, AV_LOG_WARNING,
1288 "Unknown value in sTER chunk (%d)\n", mode);
1290 bytestream2_skip(&s->gb, 4); /* crc */
1293 case MKTAG('i', 'C', 'C', 'P'): {
1294 if (decode_iccp_chunk(s, length, p) < 0)
1298 case MKTAG('c', 'H', 'R', 'M'): {
1299 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(p);
1301 ret = AVERROR(ENOMEM);
1305 mdm->white_point[0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1306 mdm->white_point[1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1309 for (i = 0; i < 3; i++) {
1310 mdm->display_primaries[i][0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1311 mdm->display_primaries[i][1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1314 mdm->has_primaries = 1;
1315 bytestream2_skip(&s->gb, 4); /* crc */
1318 case MKTAG('g', 'A', 'M', 'A'): {
1321 int num = bytestream2_get_be32(&s->gb);
1323 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1324 av_bprintf(&bp, "%i/%i", num, 100000);
1325 ret = av_bprint_finalize(&bp, &gamma_str);
1329 av_dict_set(&p->metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1331 bytestream2_skip(&s->gb, 4); /* crc */
1334 case MKTAG('I', 'E', 'N', 'D'):
1335 if (!(s->pic_state & PNG_ALLIMAGE))
1336 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1337 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1338 ret = AVERROR_INVALIDDATA;
1341 bytestream2_skip(&s->gb, 4); /* crc */
1346 bytestream2_skip(&s->gb, length + 4);
1352 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1353 avctx->skip_frame == AVDISCARD_ALL) {
1357 if (s->bits_per_pixel <= 4)
1358 handle_small_bpp(s, p);
1360 /* apply transparency if needed */
1361 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1362 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1363 size_t raw_bpp = s->bpp - byte_depth;
1366 av_assert0(s->bit_depth > 1);
1368 for (y = 0; y < s->height; ++y) {
1369 uint8_t *row = &s->image_buf[s->image_linesize * y];
1371 if (s->bpp == 2 && byte_depth == 1) {
1372 uint8_t *pixel = &row[2 * s->width - 1];
1373 uint8_t *rowp = &row[1 * s->width - 1];
1374 int tcolor = s->transparent_color_be[0];
1375 for (x = s->width; x > 0; --x) {
1376 *pixel-- = *rowp == tcolor ? 0 : 0xff;
1379 } else if (s->bpp == 4 && byte_depth == 1) {
1380 uint8_t *pixel = &row[4 * s->width - 1];
1381 uint8_t *rowp = &row[3 * s->width - 1];
1382 int tcolor = AV_RL24(s->transparent_color_be);
1383 for (x = s->width; x > 0; --x) {
1384 *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1390 /* since we're updating in-place, we have to go from right to left */
1391 for (x = s->width; x > 0; --x) {
1392 uint8_t *pixel = &row[s->bpp * (x - 1)];
1393 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1395 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1396 memset(&pixel[raw_bpp], 0, byte_depth);
1398 memset(&pixel[raw_bpp], 0xff, byte_depth);
1405 /* handle P-frames only if a predecessor frame is available */
1406 if (s->last_picture.f->data[0]) {
1407 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1408 && s->last_picture.f->width == p->width
1409 && s->last_picture.f->height== p->height
1410 && s->last_picture.f->format== p->format
1412 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1413 handle_p_frame_png(s, p);
1414 else if (CONFIG_APNG_DECODER &&
1415 s->previous_picture.f->width == p->width &&
1416 s->previous_picture.f->height== p->height &&
1417 s->previous_picture.f->format== p->format &&
1418 avctx->codec_id == AV_CODEC_ID_APNG &&
1419 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1423 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1424 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1429 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1430 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1434 #if CONFIG_PNG_DECODER
1435 static int decode_frame_png(AVCodecContext *avctx,
1436 void *data, int *got_frame,
1439 PNGDecContext *const s = avctx->priv_data;
1440 const uint8_t *buf = avpkt->data;
1441 int buf_size = avpkt->size;
1446 ff_thread_release_buffer(avctx, &s->last_picture);
1447 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1450 bytestream2_init(&s->gb, buf, buf_size);
1452 /* check signature */
1453 sig = bytestream2_get_be64(&s->gb);
1454 if (sig != PNGSIG &&
1456 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1457 return AVERROR_INVALIDDATA;
1460 s->y = s->has_trns = 0;
1465 s->zstream.zalloc = ff_png_zalloc;
1466 s->zstream.zfree = ff_png_zfree;
1467 s->zstream.opaque = NULL;
1468 ret = inflateInit(&s->zstream);
1470 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1471 return AVERROR_EXTERNAL;
1474 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1477 if (avctx->skip_frame == AVDISCARD_ALL) {
1479 ret = bytestream2_tell(&s->gb);
1483 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1488 ret = bytestream2_tell(&s->gb);
1490 inflateEnd(&s->zstream);
1496 #if CONFIG_APNG_DECODER
1497 static int decode_frame_apng(AVCodecContext *avctx,
1498 void *data, int *got_frame,
1501 PNGDecContext *const s = avctx->priv_data;
1505 ff_thread_release_buffer(avctx, &s->last_picture);
1506 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1509 if (!(s->hdr_state & PNG_IHDR)) {
1510 if (!avctx->extradata_size)
1511 return AVERROR_INVALIDDATA;
1513 /* only init fields, there is no zlib use in extradata */
1514 s->zstream.zalloc = ff_png_zalloc;
1515 s->zstream.zfree = ff_png_zfree;
1517 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1518 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1522 /* reset state for a new frame */
1523 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1524 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1525 ret = AVERROR_EXTERNAL;
1530 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1531 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1534 if (!(s->pic_state & PNG_ALLIMAGE))
1535 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1536 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1537 ret = AVERROR_INVALIDDATA;
1540 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1544 ret = bytestream2_tell(&s->gb);
1547 inflateEnd(&s->zstream);
1552 #if CONFIG_LSCR_DECODER
1553 static int decode_frame_lscr(AVCodecContext *avctx,
1554 void *data, int *got_frame,
1557 PNGDecContext *const s = avctx->priv_data;
1558 GetByteContext *gb = &s->gb;
1559 AVFrame *frame = data;
1560 int ret, nb_blocks, offset = 0;
1562 if (avpkt->size < 2)
1563 return AVERROR_INVALIDDATA;
1565 bytestream2_init(gb, avpkt->data, avpkt->size);
1567 if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1570 nb_blocks = bytestream2_get_le16(gb);
1571 if (bytestream2_get_bytes_left(gb) < 2 + nb_blocks * (12 + 8))
1572 return AVERROR_INVALIDDATA;
1574 if (s->last_picture.f->data[0]) {
1575 ret = av_frame_copy(frame, s->last_picture.f);
1580 for (int b = 0; b < nb_blocks; b++) {
1581 int x, y, x2, y2, w, h, left;
1582 uint32_t csize, size;
1584 s->zstream.zalloc = ff_png_zalloc;
1585 s->zstream.zfree = ff_png_zfree;
1586 s->zstream.opaque = NULL;
1588 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1589 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1590 ret = AVERROR_EXTERNAL;
1594 bytestream2_seek(gb, 2 + b * 12, SEEK_SET);
1596 x = bytestream2_get_le16(gb);
1597 y = bytestream2_get_le16(gb);
1598 x2 = bytestream2_get_le16(gb);
1599 y2 = bytestream2_get_le16(gb);
1600 s->width = s->cur_w = w = x2-x;
1601 s->height = s->cur_h = h = y2-y;
1603 if (w <= 0 || x < 0 || x >= avctx->width || w + x > avctx->width ||
1604 h <= 0 || y < 0 || y >= avctx->height || h + y > avctx->height) {
1605 ret = AVERROR_INVALIDDATA;
1609 size = bytestream2_get_le32(gb);
1611 frame->key_frame = (nb_blocks == 1) &&
1612 (w == avctx->width) &&
1613 (h == avctx->height) &&
1614 (x == 0) && (y == 0);
1616 bytestream2_seek(gb, 2 + nb_blocks * 12 + offset, SEEK_SET);
1617 csize = bytestream2_get_be32(gb);
1618 if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1619 ret = AVERROR_INVALIDDATA;
1627 s->row_size = w * 3;
1629 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
1631 ret = AVERROR(ENOMEM);
1635 av_fast_padded_malloc(&s->last_row, &s->last_row_size, s->row_size);
1637 ret = AVERROR(ENOMEM);
1641 s->crow_size = w * 3 + 1;
1642 s->crow_buf = s->buffer + 15;
1643 s->zstream.avail_out = s->crow_size;
1644 s->zstream.next_out = s->crow_buf;
1645 s->image_buf = frame->data[0] + (avctx->height - y - 1) * frame->linesize[0] + x * 3;
1646 s->image_linesize =-frame->linesize[0];
1651 ret = png_decode_idat(s, csize);
1656 bytestream2_skip(gb, 4);
1657 csize = bytestream2_get_be32(gb);
1658 if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1659 ret = AVERROR_INVALIDDATA;
1665 inflateEnd(&s->zstream);
1668 frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1670 av_frame_unref(s->last_picture.f);
1671 if ((ret = av_frame_ref(s->last_picture.f, frame)) < 0)
1676 inflateEnd(&s->zstream);
1683 static void decode_flush(AVCodecContext *avctx)
1685 PNGDecContext *s = avctx->priv_data;
1687 av_frame_unref(s->last_picture.f);
1693 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1695 PNGDecContext *psrc = src->priv_data;
1696 PNGDecContext *pdst = dst->priv_data;
1702 ff_thread_release_buffer(dst, &pdst->picture);
1703 if (psrc->picture.f->data[0] &&
1704 (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1706 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1707 pdst->width = psrc->width;
1708 pdst->height = psrc->height;
1709 pdst->bit_depth = psrc->bit_depth;
1710 pdst->color_type = psrc->color_type;
1711 pdst->compression_type = psrc->compression_type;
1712 pdst->interlace_type = psrc->interlace_type;
1713 pdst->filter_type = psrc->filter_type;
1714 pdst->cur_w = psrc->cur_w;
1715 pdst->cur_h = psrc->cur_h;
1716 pdst->x_offset = psrc->x_offset;
1717 pdst->y_offset = psrc->y_offset;
1718 pdst->has_trns = psrc->has_trns;
1719 memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1721 pdst->dispose_op = psrc->dispose_op;
1723 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1725 pdst->hdr_state |= psrc->hdr_state;
1727 ff_thread_release_buffer(dst, &pdst->last_picture);
1728 if (psrc->last_picture.f->data[0] &&
1729 (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
1732 ff_thread_release_buffer(dst, &pdst->previous_picture);
1733 if (psrc->previous_picture.f->data[0] &&
1734 (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
1742 static av_cold int png_dec_init(AVCodecContext *avctx)
1744 PNGDecContext *s = avctx->priv_data;
1746 avctx->color_range = AVCOL_RANGE_JPEG;
1748 if (avctx->codec_id == AV_CODEC_ID_LSCR)
1749 avctx->pix_fmt = AV_PIX_FMT_BGR24;
1752 s->previous_picture.f = av_frame_alloc();
1753 s->last_picture.f = av_frame_alloc();
1754 s->picture.f = av_frame_alloc();
1755 if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1756 av_frame_free(&s->previous_picture.f);
1757 av_frame_free(&s->last_picture.f);
1758 av_frame_free(&s->picture.f);
1759 return AVERROR(ENOMEM);
1762 if (!avctx->internal->is_copy) {
1763 avctx->internal->allocate_progress = 1;
1764 ff_pngdsp_init(&s->dsp);
1770 static av_cold int png_dec_end(AVCodecContext *avctx)
1772 PNGDecContext *s = avctx->priv_data;
1774 ff_thread_release_buffer(avctx, &s->previous_picture);
1775 av_frame_free(&s->previous_picture.f);
1776 ff_thread_release_buffer(avctx, &s->last_picture);
1777 av_frame_free(&s->last_picture.f);
1778 ff_thread_release_buffer(avctx, &s->picture);
1779 av_frame_free(&s->picture.f);
1780 av_freep(&s->buffer);
1782 av_freep(&s->last_row);
1783 s->last_row_size = 0;
1784 av_freep(&s->tmp_row);
1785 s->tmp_row_size = 0;
1790 #if CONFIG_APNG_DECODER
1791 AVCodec ff_apng_decoder = {
1793 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1794 .type = AVMEDIA_TYPE_VIDEO,
1795 .id = AV_CODEC_ID_APNG,
1796 .priv_data_size = sizeof(PNGDecContext),
1797 .init = png_dec_init,
1798 .close = png_dec_end,
1799 .decode = decode_frame_apng,
1800 .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1801 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1802 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1803 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1807 #if CONFIG_PNG_DECODER
1808 AVCodec ff_png_decoder = {
1810 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1811 .type = AVMEDIA_TYPE_VIDEO,
1812 .id = AV_CODEC_ID_PNG,
1813 .priv_data_size = sizeof(PNGDecContext),
1814 .init = png_dec_init,
1815 .close = png_dec_end,
1816 .decode = decode_frame_png,
1817 .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1818 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1819 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1820 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE,
1824 #if CONFIG_LSCR_DECODER
1825 AVCodec ff_lscr_decoder = {
1827 .long_name = NULL_IF_CONFIG_SMALL("LEAD Screen Capture"),
1828 .type = AVMEDIA_TYPE_VIDEO,
1829 .id = AV_CODEC_ID_LSCR,
1830 .priv_data_size = sizeof(PNGDecContext),
1831 .init = png_dec_init,
1832 .close = png_dec_end,
1833 .decode = decode_frame_lscr,
1834 .flush = decode_flush,
1835 .capabilities = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1836 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE,