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 previous_picture;
58 ThreadFrame last_picture;
61 enum PNGHeaderState hdr_state;
62 enum PNGImageState pic_state;
66 int x_offset, y_offset;
67 int last_x_offset, last_y_offset;
68 uint8_t dispose_op, blend_op;
69 uint8_t last_dispose_op;
79 uint8_t transparent_color_be[6];
83 uint32_t palette[256];
86 unsigned int last_row_size;
88 unsigned int tmp_row_size;
92 int crow_size; /* compressed row size (include filter type) */
93 int row_size; /* decompressed row size */
94 int pass_row_size; /* decompress row size of the current pass */
99 /* Mask to determine which pixels are valid in a pass */
100 static const uint8_t png_pass_mask[NB_PASSES] = {
101 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
104 /* Mask to determine which y pixels can be written in a pass */
105 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
106 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
109 /* Mask to determine which pixels to overwrite while displaying */
110 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
111 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
114 /* NOTE: we try to construct a good looking image at each pass. width
115 * is the original image width. We also do pixel format conversion at
117 static void png_put_interlaced_row(uint8_t *dst, int width,
118 int bits_per_pixel, int pass,
119 int color_type, const uint8_t *src)
121 int x, mask, dsp_mask, j, src_x, b, bpp;
125 mask = png_pass_mask[pass];
126 dsp_mask = png_pass_dsp_mask[pass];
128 switch (bits_per_pixel) {
131 for (x = 0; x < width; x++) {
133 if ((dsp_mask << j) & 0x80) {
134 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
135 dst[x >> 3] &= 0xFF7F>>j;
136 dst[x >> 3] |= b << (7 - j);
138 if ((mask << j) & 0x80)
144 for (x = 0; x < width; x++) {
145 int j2 = 2 * (x & 3);
147 if ((dsp_mask << j) & 0x80) {
148 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
149 dst[x >> 2] &= 0xFF3F>>j2;
150 dst[x >> 2] |= b << (6 - j2);
152 if ((mask << j) & 0x80)
158 for (x = 0; x < width; x++) {
161 if ((dsp_mask << j) & 0x80) {
162 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
163 dst[x >> 1] &= 0xFF0F>>j2;
164 dst[x >> 1] |= b << (4 - j2);
166 if ((mask << j) & 0x80)
171 bpp = bits_per_pixel >> 3;
174 for (x = 0; x < width; x++) {
176 if ((dsp_mask << j) & 0x80) {
180 if ((mask << j) & 0x80)
187 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
191 for (i = 0; i < w; i++) {
192 int a, b, c, p, pa, pb, pc;
205 if (pa <= pb && pa <= pc)
215 #define UNROLL1(bpp, op) \
224 for (; i <= size - bpp; i += bpp) { \
225 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
228 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
231 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
234 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
238 #define UNROLL_FILTER(op) \
241 } else if (bpp == 2) { \
243 } else if (bpp == 3) { \
245 } else if (bpp == 4) { \
248 for (; i < size; i++) { \
249 dst[i] = op(dst[i - bpp], src[i], last[i]); \
252 /* NOTE: 'dst' can be equal to 'last' */
253 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
254 uint8_t *src, uint8_t *last, int size, int bpp)
256 int i, p, r, g, b, a;
258 switch (filter_type) {
259 case PNG_FILTER_VALUE_NONE:
260 memcpy(dst, src, size);
262 case PNG_FILTER_VALUE_SUB:
263 for (i = 0; i < bpp; i++)
267 for (; i < size; i += bpp) {
268 unsigned s = *(int *)(src + i);
269 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
270 *(int *)(dst + i) = p;
273 #define OP_SUB(x, s, l) ((x) + (s))
274 UNROLL_FILTER(OP_SUB);
277 case PNG_FILTER_VALUE_UP:
278 dsp->add_bytes_l2(dst, src, last, size);
280 case PNG_FILTER_VALUE_AVG:
281 for (i = 0; i < bpp; i++) {
285 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
286 UNROLL_FILTER(OP_AVG);
288 case PNG_FILTER_VALUE_PAETH:
289 for (i = 0; i < bpp; i++) {
293 if (bpp > 2 && size > 4) {
294 /* would write off the end of the array if we let it process
295 * the last pixel with bpp=3 */
296 int w = (bpp & 3) ? size - 3 : size;
299 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
303 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
308 /* This used to be called "deloco" in FFmpeg
309 * and is actually an inverse reversible colorspace transformation */
310 #define YUV2RGB(NAME, TYPE) \
311 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
314 for (i = 0; i < size; i += 3 + alpha) { \
315 int g = dst [i + 1]; \
321 YUV2RGB(rgb8, uint8_t)
322 YUV2RGB(rgb16, uint16_t)
324 static int percent_missing(PNGDecContext *s)
326 if (s->interlace_type) {
327 return 100 - 100 * s->pass / (NB_PASSES - 1);
329 return 100 - 100 * s->y / s->cur_h;
333 /* process exactly one decompressed row */
334 static void png_handle_row(PNGDecContext *s)
336 uint8_t *ptr, *last_row;
339 if (!s->interlace_type) {
340 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
342 last_row = s->last_row;
344 last_row = ptr - s->image_linesize;
346 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
347 last_row, s->row_size, s->bpp);
348 /* loco lags by 1 row so that it doesn't interfere with top prediction */
349 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
350 if (s->bit_depth == 16) {
351 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
352 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
354 deloco_rgb8(ptr - s->image_linesize, s->row_size,
355 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
359 if (s->y == s->cur_h) {
360 s->pic_state |= PNG_ALLIMAGE;
361 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
362 if (s->bit_depth == 16) {
363 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
364 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
366 deloco_rgb8(ptr, s->row_size,
367 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
374 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
375 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
376 /* if we already read one row, it is time to stop to
377 * wait for the next one */
380 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
381 s->last_row, s->pass_row_size, s->bpp);
382 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
383 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
386 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
387 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
388 s->color_type, s->last_row);
391 if (s->y == s->cur_h) {
392 memset(s->last_row, 0, s->row_size);
394 if (s->pass == NB_PASSES - 1) {
395 s->pic_state |= PNG_ALLIMAGE;
400 s->pass_row_size = ff_png_pass_row_size(s->pass,
403 s->crow_size = s->pass_row_size + 1;
404 if (s->pass_row_size != 0)
406 /* skip pass if empty row */
415 static int png_decode_idat(PNGDecContext *s, int length)
418 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
419 s->zstream.next_in = s->gb.buffer;
420 bytestream2_skip(&s->gb, length);
422 /* decode one line if possible */
423 while (s->zstream.avail_in > 0) {
424 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
425 if (ret != Z_OK && ret != Z_STREAM_END) {
426 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
427 return AVERROR_EXTERNAL;
429 if (s->zstream.avail_out == 0) {
430 if (!(s->pic_state & PNG_ALLIMAGE)) {
433 s->zstream.avail_out = s->crow_size;
434 s->zstream.next_out = s->crow_buf;
436 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
437 av_log(s->avctx, AV_LOG_WARNING,
438 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
445 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
446 const uint8_t *data_end)
453 zstream.zalloc = ff_png_zalloc;
454 zstream.zfree = ff_png_zfree;
455 zstream.opaque = NULL;
456 if (inflateInit(&zstream) != Z_OK)
457 return AVERROR_EXTERNAL;
458 zstream.next_in = data;
459 zstream.avail_in = data_end - data;
460 av_bprint_init(bp, 0, AV_BPRINT_SIZE_UNLIMITED);
462 while (zstream.avail_in > 0) {
463 av_bprint_get_buffer(bp, 2, &buf, &buf_size);
465 ret = AVERROR(ENOMEM);
468 zstream.next_out = buf;
469 zstream.avail_out = buf_size - 1;
470 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
471 if (ret != Z_OK && ret != Z_STREAM_END) {
472 ret = AVERROR_EXTERNAL;
475 bp->len += zstream.next_out - buf;
476 if (ret == Z_STREAM_END)
479 inflateEnd(&zstream);
480 bp->str[bp->len] = 0;
484 inflateEnd(&zstream);
485 av_bprint_finalize(bp, NULL);
489 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
494 for (i = 0; i < size_in; i++)
495 extra += in[i] >= 0x80;
496 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
498 q = out = av_malloc(size_in + extra + 1);
501 for (i = 0; i < size_in; i++) {
503 *(q++) = 0xC0 | (in[i] >> 6);
504 *(q++) = 0x80 | (in[i] & 0x3F);
513 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
517 const uint8_t *data = s->gb.buffer;
518 const uint8_t *data_end = data + length;
519 const uint8_t *keyword = data;
520 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
521 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
526 return AVERROR_INVALIDDATA;
527 data = keyword_end + 1;
530 if (data == data_end)
531 return AVERROR_INVALIDDATA;
534 return AVERROR_INVALIDDATA;
535 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
538 ret = av_bprint_finalize(&bp, (char **)&text);
542 text = (uint8_t *)data;
543 text_len = data_end - text;
546 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
547 txt_utf8 = iso88591_to_utf8(text, text_len);
550 if (!(kw_utf8 && txt_utf8)) {
553 return AVERROR(ENOMEM);
556 av_dict_set(dict, kw_utf8, txt_utf8,
557 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
561 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
565 return AVERROR_INVALIDDATA;
567 if (s->pic_state & PNG_IDAT) {
568 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
569 return AVERROR_INVALIDDATA;
572 if (s->hdr_state & PNG_IHDR) {
573 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
574 return AVERROR_INVALIDDATA;
577 s->width = s->cur_w = bytestream2_get_be32(&s->gb);
578 s->height = s->cur_h = bytestream2_get_be32(&s->gb);
579 if (av_image_check_size(s->width, s->height, 0, avctx)) {
580 s->cur_w = s->cur_h = s->width = s->height = 0;
581 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
582 return AVERROR_INVALIDDATA;
584 s->bit_depth = bytestream2_get_byte(&s->gb);
585 if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
586 s->bit_depth != 8 && s->bit_depth != 16) {
587 av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
590 s->color_type = bytestream2_get_byte(&s->gb);
591 s->compression_type = bytestream2_get_byte(&s->gb);
592 if (s->compression_type) {
593 av_log(avctx, AV_LOG_ERROR, "Invalid compression method %d\n", s->compression_type);
596 s->filter_type = bytestream2_get_byte(&s->gb);
597 s->interlace_type = bytestream2_get_byte(&s->gb);
598 bytestream2_skip(&s->gb, 4); /* crc */
599 s->hdr_state |= PNG_IHDR;
600 if (avctx->debug & FF_DEBUG_PICT_INFO)
601 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
602 "compression_type=%d filter_type=%d interlace_type=%d\n",
603 s->width, s->height, s->bit_depth, s->color_type,
604 s->compression_type, s->filter_type, s->interlace_type);
608 s->cur_w = s->cur_h = s->width = s->height = 0;
610 return AVERROR_INVALIDDATA;
613 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
615 if (s->pic_state & PNG_IDAT) {
616 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
617 return AVERROR_INVALIDDATA;
619 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
620 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
621 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
622 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
623 bytestream2_skip(&s->gb, 1); /* unit specifier */
624 bytestream2_skip(&s->gb, 4); /* crc */
629 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
630 uint32_t length, AVFrame *p)
633 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
635 if (!(s->hdr_state & PNG_IHDR)) {
636 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
637 return AVERROR_INVALIDDATA;
639 if (!(s->pic_state & PNG_IDAT)) {
640 /* init image info */
641 ret = ff_set_dimensions(avctx, s->width, s->height);
645 s->channels = ff_png_get_nb_channels(s->color_type);
646 s->bits_per_pixel = s->bit_depth * s->channels;
647 s->bpp = (s->bits_per_pixel + 7) >> 3;
648 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
650 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
651 s->color_type == PNG_COLOR_TYPE_RGB) {
652 avctx->pix_fmt = AV_PIX_FMT_RGB24;
653 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
654 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
655 avctx->pix_fmt = AV_PIX_FMT_RGBA;
656 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
657 s->color_type == PNG_COLOR_TYPE_GRAY) {
658 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
659 } else if (s->bit_depth == 16 &&
660 s->color_type == PNG_COLOR_TYPE_GRAY) {
661 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
662 } else if (s->bit_depth == 16 &&
663 s->color_type == PNG_COLOR_TYPE_RGB) {
664 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
665 } else if (s->bit_depth == 16 &&
666 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
667 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
668 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
669 s->color_type == PNG_COLOR_TYPE_PALETTE) {
670 avctx->pix_fmt = AV_PIX_FMT_PAL8;
671 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
672 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
673 } else if (s->bit_depth == 8 &&
674 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
675 avctx->pix_fmt = AV_PIX_FMT_YA8;
676 } else if (s->bit_depth == 16 &&
677 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
678 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
680 avpriv_report_missing_feature(avctx,
681 "Bit depth %d color type %d",
682 s->bit_depth, s->color_type);
683 return AVERROR_PATCHWELCOME;
686 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
687 switch (avctx->pix_fmt) {
688 case AV_PIX_FMT_RGB24:
689 avctx->pix_fmt = AV_PIX_FMT_RGBA;
692 case AV_PIX_FMT_RGB48BE:
693 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
696 case AV_PIX_FMT_GRAY8:
697 avctx->pix_fmt = AV_PIX_FMT_YA8;
700 case AV_PIX_FMT_GRAY16BE:
701 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
705 avpriv_request_sample(avctx, "bit depth %d "
706 "and color type %d with TRNS",
707 s->bit_depth, s->color_type);
708 return AVERROR_INVALIDDATA;
711 s->bpp += byte_depth;
714 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
716 if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
717 ff_thread_release_buffer(avctx, &s->previous_picture);
718 if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
721 p->pict_type = AV_PICTURE_TYPE_I;
723 p->interlaced_frame = !!s->interlace_type;
725 ff_thread_finish_setup(avctx);
727 /* compute the compressed row size */
728 if (!s->interlace_type) {
729 s->crow_size = s->row_size + 1;
732 s->pass_row_size = ff_png_pass_row_size(s->pass,
735 s->crow_size = s->pass_row_size + 1;
737 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
738 s->row_size, s->crow_size);
739 s->image_buf = p->data[0];
740 s->image_linesize = p->linesize[0];
741 /* copy the palette if needed */
742 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
743 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
744 /* empty row is used if differencing to the first row */
745 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
747 return AVERROR_INVALIDDATA;
748 if (s->interlace_type ||
749 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
750 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
752 return AVERROR_INVALIDDATA;
755 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
757 return AVERROR(ENOMEM);
759 /* we want crow_buf+1 to be 16-byte aligned */
760 s->crow_buf = s->buffer + 15;
761 s->zstream.avail_out = s->crow_size;
762 s->zstream.next_out = s->crow_buf;
765 s->pic_state |= PNG_IDAT;
767 /* set image to non-transparent bpp while decompressing */
768 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
769 s->bpp -= byte_depth;
771 ret = png_decode_idat(s, length);
773 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
774 s->bpp += byte_depth;
779 bytestream2_skip(&s->gb, 4); /* crc */
784 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
789 if ((length % 3) != 0 || length > 256 * 3)
790 return AVERROR_INVALIDDATA;
791 /* read the palette */
793 for (i = 0; i < n; i++) {
794 r = bytestream2_get_byte(&s->gb);
795 g = bytestream2_get_byte(&s->gb);
796 b = bytestream2_get_byte(&s->gb);
797 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
800 s->palette[i] = (0xFFU << 24);
801 s->hdr_state |= PNG_PLTE;
802 bytestream2_skip(&s->gb, 4); /* crc */
807 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
812 if (!(s->hdr_state & PNG_IHDR)) {
813 av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
814 return AVERROR_INVALIDDATA;
817 if (s->pic_state & PNG_IDAT) {
818 av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
819 return AVERROR_INVALIDDATA;
822 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
823 if (length > 256 || !(s->hdr_state & PNG_PLTE))
824 return AVERROR_INVALIDDATA;
826 for (i = 0; i < length; i++) {
827 unsigned v = bytestream2_get_byte(&s->gb);
828 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
830 } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
831 if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
832 (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
834 return AVERROR_INVALIDDATA;
836 for (i = 0; i < length / 2; i++) {
837 /* only use the least significant bits */
838 v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
840 if (s->bit_depth > 8)
841 AV_WB16(&s->transparent_color_be[2 * i], v);
843 s->transparent_color_be[i] = v;
846 return AVERROR_INVALIDDATA;
849 bytestream2_skip(&s->gb, 4); /* crc */
855 static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
858 uint8_t *data, profile_name[82];
862 while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
864 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
865 return AVERROR_INVALIDDATA;
868 length = FFMAX(length - cnt, 0);
870 if (bytestream2_get_byte(&s->gb) != 0) {
871 av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
872 return AVERROR_INVALIDDATA;
875 length = FFMAX(length - 1, 0);
877 if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
880 ret = av_bprint_finalize(&bp, (char **)&data);
884 sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
887 return AVERROR(ENOMEM);
890 av_dict_set(&sd->metadata, "name", profile_name, 0);
891 memcpy(sd->data, data, bp.len);
894 /* ICC compressed data and CRC */
895 bytestream2_skip(&s->gb, length + 4);
900 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
902 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
904 uint8_t *pd = p->data[0];
905 for (j = 0; j < s->height; j++) {
907 for (k = 7; k >= 1; k--)
908 if ((s->width&7) >= k)
909 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
910 for (i--; i >= 0; i--) {
911 pd[8*i + 7]= pd[i] & 1;
912 pd[8*i + 6]= (pd[i]>>1) & 1;
913 pd[8*i + 5]= (pd[i]>>2) & 1;
914 pd[8*i + 4]= (pd[i]>>3) & 1;
915 pd[8*i + 3]= (pd[i]>>4) & 1;
916 pd[8*i + 2]= (pd[i]>>5) & 1;
917 pd[8*i + 1]= (pd[i]>>6) & 1;
918 pd[8*i + 0]= pd[i]>>7;
920 pd += s->image_linesize;
922 } else if (s->bits_per_pixel == 2) {
924 uint8_t *pd = p->data[0];
925 for (j = 0; j < s->height; j++) {
927 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
928 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
929 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
930 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
931 for (i--; i >= 0; i--) {
932 pd[4*i + 3]= pd[i] & 3;
933 pd[4*i + 2]= (pd[i]>>2) & 3;
934 pd[4*i + 1]= (pd[i]>>4) & 3;
935 pd[4*i + 0]= pd[i]>>6;
938 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
939 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
940 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
941 for (i--; i >= 0; i--) {
942 pd[4*i + 3]= ( pd[i] & 3)*0x55;
943 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
944 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
945 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
948 pd += s->image_linesize;
950 } else if (s->bits_per_pixel == 4) {
952 uint8_t *pd = p->data[0];
953 for (j = 0; j < s->height; j++) {
955 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
956 if (s->width&1) pd[2*i+0]= pd[i]>>4;
957 for (i--; i >= 0; i--) {
958 pd[2*i + 1] = pd[i] & 15;
959 pd[2*i + 0] = pd[i] >> 4;
962 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
963 for (i--; i >= 0; i--) {
964 pd[2*i + 1] = (pd[i] & 15) * 0x11;
965 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
968 pd += s->image_linesize;
973 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
976 uint32_t sequence_number;
977 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
980 return AVERROR_INVALIDDATA;
982 if (!(s->hdr_state & PNG_IHDR)) {
983 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
984 return AVERROR_INVALIDDATA;
987 if (s->pic_state & PNG_IDAT) {
988 av_log(avctx, AV_LOG_ERROR, "fctl after IDAT\n");
989 return AVERROR_INVALIDDATA;
992 s->last_w = s->cur_w;
993 s->last_h = s->cur_h;
994 s->last_x_offset = s->x_offset;
995 s->last_y_offset = s->y_offset;
996 s->last_dispose_op = s->dispose_op;
998 sequence_number = bytestream2_get_be32(&s->gb);
999 cur_w = bytestream2_get_be32(&s->gb);
1000 cur_h = bytestream2_get_be32(&s->gb);
1001 x_offset = bytestream2_get_be32(&s->gb);
1002 y_offset = bytestream2_get_be32(&s->gb);
1003 bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
1004 dispose_op = bytestream2_get_byte(&s->gb);
1005 blend_op = bytestream2_get_byte(&s->gb);
1006 bytestream2_skip(&s->gb, 4); /* crc */
1008 if (sequence_number == 0 &&
1009 (cur_w != s->width ||
1010 cur_h != s->height ||
1013 cur_w <= 0 || cur_h <= 0 ||
1014 x_offset < 0 || y_offset < 0 ||
1015 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
1016 return AVERROR_INVALIDDATA;
1018 if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
1019 av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
1020 return AVERROR_INVALIDDATA;
1023 if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
1024 dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
1025 // No previous frame to revert to for the first frame
1026 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
1027 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
1030 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
1031 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
1032 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
1033 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
1034 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
1035 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
1036 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
1038 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
1039 blend_op = APNG_BLEND_OP_SOURCE;
1044 s->x_offset = x_offset;
1045 s->y_offset = y_offset;
1046 s->dispose_op = dispose_op;
1047 s->blend_op = blend_op;
1052 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
1055 uint8_t *pd = p->data[0];
1056 uint8_t *pd_last = s->last_picture.f->data[0];
1057 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
1059 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1060 for (j = 0; j < s->height; j++) {
1061 for (i = 0; i < ls; i++)
1062 pd[i] += pd_last[i];
1063 pd += s->image_linesize;
1064 pd_last += s->image_linesize;
1068 // divide by 255 and round to nearest
1069 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
1070 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
1072 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
1078 if (s->blend_op == APNG_BLEND_OP_OVER &&
1079 avctx->pix_fmt != AV_PIX_FMT_RGBA &&
1080 avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
1081 avctx->pix_fmt != AV_PIX_FMT_PAL8) {
1082 avpriv_request_sample(avctx, "Blending with pixel format %s",
1083 av_get_pix_fmt_name(avctx->pix_fmt));
1084 return AVERROR_PATCHWELCOME;
1087 buffer = av_malloc_array(s->image_linesize, s->height);
1089 return AVERROR(ENOMEM);
1092 // Do the disposal operation specified by the last frame on the frame
1093 if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
1094 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
1095 memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
1097 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
1098 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
1099 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
1101 memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
1102 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1104 ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
1105 memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
1109 if (s->blend_op == APNG_BLEND_OP_SOURCE) {
1110 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1111 size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
1112 memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
1114 } else { // APNG_BLEND_OP_OVER
1115 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
1116 uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
1117 uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
1118 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
1120 uint8_t foreground_alpha, background_alpha, output_alpha;
1123 // Since we might be blending alpha onto alpha, we use the following equations:
1124 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
1125 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
1127 switch (avctx->pix_fmt) {
1128 case AV_PIX_FMT_RGBA:
1129 foreground_alpha = foreground[3];
1130 background_alpha = background[3];
1133 case AV_PIX_FMT_GRAY8A:
1134 foreground_alpha = foreground[1];
1135 background_alpha = background[1];
1138 case AV_PIX_FMT_PAL8:
1139 foreground_alpha = s->palette[foreground[0]] >> 24;
1140 background_alpha = s->palette[background[0]] >> 24;
1144 if (foreground_alpha == 0)
1147 if (foreground_alpha == 255) {
1148 memcpy(background, foreground, s->bpp);
1152 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1153 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
1154 avpriv_request_sample(avctx, "Alpha blending palette samples");
1155 background[0] = foreground[0];
1159 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
1161 av_assert0(s->bpp <= 10);
1163 for (b = 0; b < s->bpp - 1; ++b) {
1164 if (output_alpha == 0) {
1166 } else if (background_alpha == 255) {
1167 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
1169 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
1172 output[b] = output_alpha;
1173 memcpy(background, output, s->bpp);
1178 // Copy blended buffer into the frame and free
1179 memcpy(p->data[0], buffer, s->image_linesize * s->height);
1185 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1186 AVFrame *p, AVPacket *avpkt)
1188 const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1189 AVDictionary **metadatap = NULL;
1190 uint32_t tag, length;
1191 int decode_next_dat = 0;
1195 length = bytestream2_get_bytes_left(&s->gb);
1198 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1199 avctx->skip_frame == AVDISCARD_ALL) {
1203 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1204 if (!(s->pic_state & PNG_IDAT))
1209 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1210 if ( s->pic_state & PNG_ALLIMAGE
1211 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1213 ret = AVERROR_INVALIDDATA;
1217 length = bytestream2_get_be32(&s->gb);
1218 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1219 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1220 ret = AVERROR_INVALIDDATA;
1223 if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_IGNORE_ERR)) {
1224 uint32_t crc_sig = AV_RB32(s->gb.buffer + length + 4);
1225 uint32_t crc_cal = ~av_crc(crc_tab, UINT32_MAX, s->gb.buffer, length + 4);
1226 if (crc_sig ^ crc_cal) {
1227 av_log(avctx, AV_LOG_ERROR, "CRC mismatch in chunk");
1228 if (avctx->err_recognition & AV_EF_EXPLODE) {
1229 av_log(avctx, AV_LOG_ERROR, ", quitting\n");
1230 ret = AVERROR_INVALIDDATA;
1233 av_log(avctx, AV_LOG_ERROR, ", skipping\n");
1234 bytestream2_skip(&s->gb, 4); /* tag */
1238 tag = bytestream2_get_le32(&s->gb);
1239 if (avctx->debug & FF_DEBUG_STARTCODE)
1240 av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
1241 av_fourcc2str(tag), length);
1243 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1244 avctx->skip_frame == AVDISCARD_ALL) {
1246 case MKTAG('I', 'H', 'D', 'R'):
1247 case MKTAG('p', 'H', 'Y', 's'):
1248 case MKTAG('t', 'E', 'X', 't'):
1249 case MKTAG('I', 'D', 'A', 'T'):
1250 case MKTAG('t', 'R', 'N', 'S'):
1257 metadatap = &p->metadata;
1259 case MKTAG('I', 'H', 'D', 'R'):
1260 if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1263 case MKTAG('p', 'H', 'Y', 's'):
1264 if ((ret = decode_phys_chunk(avctx, s)) < 0)
1267 case MKTAG('f', 'c', 'T', 'L'):
1268 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1270 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1272 decode_next_dat = 1;
1274 case MKTAG('f', 'd', 'A', 'T'):
1275 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1277 if (!decode_next_dat || length < 4) {
1278 ret = AVERROR_INVALIDDATA;
1281 bytestream2_get_be32(&s->gb);
1284 case MKTAG('I', 'D', 'A', 'T'):
1285 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1287 if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1290 case MKTAG('P', 'L', 'T', 'E'):
1291 if (decode_plte_chunk(avctx, s, length) < 0)
1294 case MKTAG('t', 'R', 'N', 'S'):
1295 if (decode_trns_chunk(avctx, s, length) < 0)
1298 case MKTAG('t', 'E', 'X', 't'):
1299 if (decode_text_chunk(s, length, 0, metadatap) < 0)
1300 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1301 bytestream2_skip(&s->gb, length + 4);
1303 case MKTAG('z', 'T', 'X', 't'):
1304 if (decode_text_chunk(s, length, 1, metadatap) < 0)
1305 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1306 bytestream2_skip(&s->gb, length + 4);
1308 case MKTAG('s', 'T', 'E', 'R'): {
1309 int mode = bytestream2_get_byte(&s->gb);
1310 AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
1312 ret = AVERROR(ENOMEM);
1316 if (mode == 0 || mode == 1) {
1317 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
1318 stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
1320 av_log(avctx, AV_LOG_WARNING,
1321 "Unknown value in sTER chunk (%d)\n", mode);
1323 bytestream2_skip(&s->gb, 4); /* crc */
1326 case MKTAG('i', 'C', 'C', 'P'): {
1327 if ((ret = decode_iccp_chunk(s, length, p)) < 0)
1331 case MKTAG('c', 'H', 'R', 'M'): {
1332 AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(p);
1334 ret = AVERROR(ENOMEM);
1338 mdm->white_point[0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1339 mdm->white_point[1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1342 for (i = 0; i < 3; i++) {
1343 mdm->display_primaries[i][0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1344 mdm->display_primaries[i][1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
1347 mdm->has_primaries = 1;
1348 bytestream2_skip(&s->gb, 4); /* crc */
1351 case MKTAG('g', 'A', 'M', 'A'): {
1354 int num = bytestream2_get_be32(&s->gb);
1356 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
1357 av_bprintf(&bp, "%i/%i", num, 100000);
1358 ret = av_bprint_finalize(&bp, &gamma_str);
1362 av_dict_set(&p->metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
1364 bytestream2_skip(&s->gb, 4); /* crc */
1367 case MKTAG('I', 'E', 'N', 'D'):
1368 if (!(s->pic_state & PNG_ALLIMAGE))
1369 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1370 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1371 ret = AVERROR_INVALIDDATA;
1374 bytestream2_skip(&s->gb, 4); /* crc */
1379 bytestream2_skip(&s->gb, length + 4);
1385 if (avctx->codec_id == AV_CODEC_ID_PNG &&
1386 avctx->skip_frame == AVDISCARD_ALL) {
1390 if (percent_missing(s) > avctx->discard_damaged_percentage)
1391 return AVERROR_INVALIDDATA;
1393 if (s->bits_per_pixel <= 4)
1394 handle_small_bpp(s, p);
1396 /* apply transparency if needed */
1397 if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
1398 size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
1399 size_t raw_bpp = s->bpp - byte_depth;
1402 av_assert0(s->bit_depth > 1);
1404 for (y = 0; y < s->height; ++y) {
1405 uint8_t *row = &s->image_buf[s->image_linesize * y];
1407 if (s->bpp == 2 && byte_depth == 1) {
1408 uint8_t *pixel = &row[2 * s->width - 1];
1409 uint8_t *rowp = &row[1 * s->width - 1];
1410 int tcolor = s->transparent_color_be[0];
1411 for (x = s->width; x > 0; --x) {
1412 *pixel-- = *rowp == tcolor ? 0 : 0xff;
1415 } else if (s->bpp == 4 && byte_depth == 1) {
1416 uint8_t *pixel = &row[4 * s->width - 1];
1417 uint8_t *rowp = &row[3 * s->width - 1];
1418 int tcolor = AV_RL24(s->transparent_color_be);
1419 for (x = s->width; x > 0; --x) {
1420 *pixel-- = AV_RL24(rowp-2) == tcolor ? 0 : 0xff;
1426 /* since we're updating in-place, we have to go from right to left */
1427 for (x = s->width; x > 0; --x) {
1428 uint8_t *pixel = &row[s->bpp * (x - 1)];
1429 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
1431 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
1432 memset(&pixel[raw_bpp], 0, byte_depth);
1434 memset(&pixel[raw_bpp], 0xff, byte_depth);
1441 /* handle P-frames only if a predecessor frame is available */
1442 if (s->last_picture.f->data[0]) {
1443 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1444 && s->last_picture.f->width == p->width
1445 && s->last_picture.f->height== p->height
1446 && s->last_picture.f->format== p->format
1448 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1449 handle_p_frame_png(s, p);
1450 else if (CONFIG_APNG_DECODER &&
1451 s->previous_picture.f->width == p->width &&
1452 s->previous_picture.f->height== p->height &&
1453 s->previous_picture.f->format== p->format &&
1454 avctx->codec_id == AV_CODEC_ID_APNG &&
1455 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1459 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1460 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1465 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1466 ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
1470 #if CONFIG_PNG_DECODER
1471 static int decode_frame_png(AVCodecContext *avctx,
1472 void *data, int *got_frame,
1475 PNGDecContext *const s = avctx->priv_data;
1476 const uint8_t *buf = avpkt->data;
1477 int buf_size = avpkt->size;
1482 ff_thread_release_buffer(avctx, &s->last_picture);
1483 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1486 bytestream2_init(&s->gb, buf, buf_size);
1488 /* check signature */
1489 sig = bytestream2_get_be64(&s->gb);
1490 if (sig != PNGSIG &&
1492 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
1493 return AVERROR_INVALIDDATA;
1496 s->y = s->has_trns = 0;
1501 s->zstream.zalloc = ff_png_zalloc;
1502 s->zstream.zfree = ff_png_zfree;
1503 s->zstream.opaque = NULL;
1504 ret = inflateInit(&s->zstream);
1506 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1507 return AVERROR_EXTERNAL;
1510 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1513 if (avctx->skip_frame == AVDISCARD_ALL) {
1515 ret = bytestream2_tell(&s->gb);
1519 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1524 ret = bytestream2_tell(&s->gb);
1526 inflateEnd(&s->zstream);
1532 #if CONFIG_APNG_DECODER
1533 static int decode_frame_apng(AVCodecContext *avctx,
1534 void *data, int *got_frame,
1537 PNGDecContext *const s = avctx->priv_data;
1541 ff_thread_release_buffer(avctx, &s->last_picture);
1542 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1545 if (!(s->hdr_state & PNG_IHDR)) {
1546 if (!avctx->extradata_size)
1547 return AVERROR_INVALIDDATA;
1549 /* only init fields, there is no zlib use in extradata */
1550 s->zstream.zalloc = ff_png_zalloc;
1551 s->zstream.zfree = ff_png_zfree;
1553 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1554 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1558 /* reset state for a new frame */
1559 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1560 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1561 ret = AVERROR_EXTERNAL;
1566 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1567 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1570 if (!(s->pic_state & PNG_ALLIMAGE))
1571 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1572 if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
1573 ret = AVERROR_INVALIDDATA;
1576 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1580 ret = bytestream2_tell(&s->gb);
1583 inflateEnd(&s->zstream);
1588 #if CONFIG_LSCR_DECODER
1589 static int decode_frame_lscr(AVCodecContext *avctx,
1590 void *data, int *got_frame,
1593 PNGDecContext *const s = avctx->priv_data;
1594 GetByteContext *gb = &s->gb;
1595 AVFrame *frame = data;
1596 int ret, nb_blocks, offset = 0;
1598 if (avpkt->size < 2)
1599 return AVERROR_INVALIDDATA;
1600 if (avpkt->size == 2)
1603 bytestream2_init(gb, avpkt->data, avpkt->size);
1605 if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1608 nb_blocks = bytestream2_get_le16(gb);
1609 if (bytestream2_get_bytes_left(gb) < 2 + nb_blocks * (12 + 8))
1610 return AVERROR_INVALIDDATA;
1612 if (s->last_picture.f->data[0]) {
1613 ret = av_frame_copy(frame, s->last_picture.f);
1618 for (int b = 0; b < nb_blocks; b++) {
1619 int x, y, x2, y2, w, h, left;
1620 uint32_t csize, size;
1622 s->zstream.zalloc = ff_png_zalloc;
1623 s->zstream.zfree = ff_png_zfree;
1624 s->zstream.opaque = NULL;
1626 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1627 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1628 ret = AVERROR_EXTERNAL;
1632 bytestream2_seek(gb, 2 + b * 12, SEEK_SET);
1634 x = bytestream2_get_le16(gb);
1635 y = bytestream2_get_le16(gb);
1636 x2 = bytestream2_get_le16(gb);
1637 y2 = bytestream2_get_le16(gb);
1638 s->width = s->cur_w = w = x2-x;
1639 s->height = s->cur_h = h = y2-y;
1641 if (w <= 0 || x < 0 || x >= avctx->width || w + x > avctx->width ||
1642 h <= 0 || y < 0 || y >= avctx->height || h + y > avctx->height) {
1643 ret = AVERROR_INVALIDDATA;
1647 size = bytestream2_get_le32(gb);
1649 frame->key_frame = (nb_blocks == 1) &&
1650 (w == avctx->width) &&
1651 (h == avctx->height) &&
1652 (x == 0) && (y == 0);
1654 bytestream2_seek(gb, 2 + nb_blocks * 12 + offset, SEEK_SET);
1655 csize = bytestream2_get_be32(gb);
1656 if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1657 ret = AVERROR_INVALIDDATA;
1665 s->row_size = w * 3;
1667 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
1669 ret = AVERROR(ENOMEM);
1673 av_fast_padded_malloc(&s->last_row, &s->last_row_size, s->row_size);
1675 ret = AVERROR(ENOMEM);
1679 s->crow_size = w * 3 + 1;
1680 s->crow_buf = s->buffer + 15;
1681 s->zstream.avail_out = s->crow_size;
1682 s->zstream.next_out = s->crow_buf;
1683 s->image_buf = frame->data[0] + (avctx->height - y - 1) * frame->linesize[0] + x * 3;
1684 s->image_linesize =-frame->linesize[0];
1689 ret = png_decode_idat(s, csize);
1694 bytestream2_skip(gb, 4);
1695 csize = bytestream2_get_be32(gb);
1696 if (bytestream2_get_le32(gb) != MKTAG('I', 'D', 'A', 'T')) {
1697 ret = AVERROR_INVALIDDATA;
1703 inflateEnd(&s->zstream);
1706 frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1708 av_frame_unref(s->last_picture.f);
1709 if ((ret = av_frame_ref(s->last_picture.f, frame)) < 0)
1714 inflateEnd(&s->zstream);
1721 static void decode_flush(AVCodecContext *avctx)
1723 PNGDecContext *s = avctx->priv_data;
1725 av_frame_unref(s->last_picture.f);
1731 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1733 PNGDecContext *psrc = src->priv_data;
1734 PNGDecContext *pdst = dst->priv_data;
1740 ff_thread_release_buffer(dst, &pdst->picture);
1741 if (psrc->picture.f->data[0] &&
1742 (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1744 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1745 pdst->width = psrc->width;
1746 pdst->height = psrc->height;
1747 pdst->bit_depth = psrc->bit_depth;
1748 pdst->color_type = psrc->color_type;
1749 pdst->compression_type = psrc->compression_type;
1750 pdst->interlace_type = psrc->interlace_type;
1751 pdst->filter_type = psrc->filter_type;
1752 pdst->cur_w = psrc->cur_w;
1753 pdst->cur_h = psrc->cur_h;
1754 pdst->x_offset = psrc->x_offset;
1755 pdst->y_offset = psrc->y_offset;
1756 pdst->has_trns = psrc->has_trns;
1757 memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
1759 pdst->dispose_op = psrc->dispose_op;
1761 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1763 pdst->hdr_state |= psrc->hdr_state;
1765 ff_thread_release_buffer(dst, &pdst->last_picture);
1766 if (psrc->last_picture.f->data[0] &&
1767 (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
1770 ff_thread_release_buffer(dst, &pdst->previous_picture);
1771 if (psrc->previous_picture.f->data[0] &&
1772 (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
1780 static av_cold int png_dec_init(AVCodecContext *avctx)
1782 PNGDecContext *s = avctx->priv_data;
1784 avctx->color_range = AVCOL_RANGE_JPEG;
1786 if (avctx->codec_id == AV_CODEC_ID_LSCR)
1787 avctx->pix_fmt = AV_PIX_FMT_BGR24;
1790 s->previous_picture.f = av_frame_alloc();
1791 s->last_picture.f = av_frame_alloc();
1792 s->picture.f = av_frame_alloc();
1793 if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1794 av_frame_free(&s->previous_picture.f);
1795 av_frame_free(&s->last_picture.f);
1796 av_frame_free(&s->picture.f);
1797 return AVERROR(ENOMEM);
1800 ff_pngdsp_init(&s->dsp);
1805 static av_cold int png_dec_end(AVCodecContext *avctx)
1807 PNGDecContext *s = avctx->priv_data;
1809 ff_thread_release_buffer(avctx, &s->previous_picture);
1810 av_frame_free(&s->previous_picture.f);
1811 ff_thread_release_buffer(avctx, &s->last_picture);
1812 av_frame_free(&s->last_picture.f);
1813 ff_thread_release_buffer(avctx, &s->picture);
1814 av_frame_free(&s->picture.f);
1815 av_freep(&s->buffer);
1817 av_freep(&s->last_row);
1818 s->last_row_size = 0;
1819 av_freep(&s->tmp_row);
1820 s->tmp_row_size = 0;
1825 #if CONFIG_APNG_DECODER
1826 AVCodec ff_apng_decoder = {
1828 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1829 .type = AVMEDIA_TYPE_VIDEO,
1830 .id = AV_CODEC_ID_APNG,
1831 .priv_data_size = sizeof(PNGDecContext),
1832 .init = png_dec_init,
1833 .close = png_dec_end,
1834 .decode = decode_frame_apng,
1835 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1836 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1837 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
1838 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1842 #if CONFIG_PNG_DECODER
1843 AVCodec ff_png_decoder = {
1845 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1846 .type = AVMEDIA_TYPE_VIDEO,
1847 .id = AV_CODEC_ID_PNG,
1848 .priv_data_size = sizeof(PNGDecContext),
1849 .init = png_dec_init,
1850 .close = png_dec_end,
1851 .decode = decode_frame_png,
1852 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1853 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1854 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1855 FF_CODEC_CAP_ALLOCATE_PROGRESS,
1859 #if CONFIG_LSCR_DECODER
1860 AVCodec ff_lscr_decoder = {
1862 .long_name = NULL_IF_CONFIG_SMALL("LEAD Screen Capture"),
1863 .type = AVMEDIA_TYPE_VIDEO,
1864 .id = AV_CODEC_ID_LSCR,
1865 .priv_data_size = sizeof(PNGDecContext),
1866 .init = png_dec_init,
1867 .close = png_dec_end,
1868 .decode = decode_frame_lscr,
1869 .flush = decode_flush,
1870 .capabilities = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
1871 .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE |
1872 FF_CODEC_CAP_ALLOCATE_PROGRESS,