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/bprint.h"
25 #include "libavutil/imgutils.h"
27 #include "bytestream.h"
36 typedef struct PNGDecContext {
38 AVCodecContext *avctx;
41 ThreadFrame previous_picture;
42 ThreadFrame last_picture;
49 int x_offset, y_offset;
50 int last_x_offset, last_y_offset;
51 uint8_t dispose_op, blend_op;
52 uint8_t last_dispose_op;
65 uint32_t palette[256];
68 unsigned int last_row_size;
70 unsigned int tmp_row_size;
74 int crow_size; /* compressed row size (include filter type) */
75 int row_size; /* decompressed row size */
76 int pass_row_size; /* decompress row size of the current pass */
81 /* Mask to determine which pixels are valid in a pass */
82 static const uint8_t png_pass_mask[NB_PASSES] = {
83 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
86 /* Mask to determine which y pixels can be written in a pass */
87 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
88 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
91 /* Mask to determine which pixels to overwrite while displaying */
92 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
93 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
96 /* NOTE: we try to construct a good looking image at each pass. width
97 * is the original image width. We also do pixel format conversion at
99 static void png_put_interlaced_row(uint8_t *dst, int width,
100 int bits_per_pixel, int pass,
101 int color_type, const uint8_t *src)
103 int x, mask, dsp_mask, j, src_x, b, bpp;
107 mask = png_pass_mask[pass];
108 dsp_mask = png_pass_dsp_mask[pass];
110 switch (bits_per_pixel) {
113 for (x = 0; x < width; x++) {
115 if ((dsp_mask << j) & 0x80) {
116 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
117 dst[x >> 3] &= 0xFF7F>>j;
118 dst[x >> 3] |= b << (7 - j);
120 if ((mask << j) & 0x80)
126 for (x = 0; x < width; x++) {
127 int j2 = 2 * (x & 3);
129 if ((dsp_mask << j) & 0x80) {
130 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
131 dst[x >> 2] &= 0xFF3F>>j2;
132 dst[x >> 2] |= b << (6 - j2);
134 if ((mask << j) & 0x80)
140 for (x = 0; x < width; x++) {
143 if ((dsp_mask << j) & 0x80) {
144 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
145 dst[x >> 1] &= 0xFF0F>>j2;
146 dst[x >> 1] |= b << (4 - j2);
148 if ((mask << j) & 0x80)
153 bpp = bits_per_pixel >> 3;
156 for (x = 0; x < width; x++) {
158 if ((dsp_mask << j) & 0x80) {
162 if ((mask << j) & 0x80)
169 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
173 for (i = 0; i < w; i++) {
174 int a, b, c, p, pa, pb, pc;
187 if (pa <= pb && pa <= pc)
197 #define UNROLL1(bpp, op) \
206 for (; i <= size - bpp; i += bpp) { \
207 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
210 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
213 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
216 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
220 #define UNROLL_FILTER(op) \
223 } else if (bpp == 2) { \
225 } else if (bpp == 3) { \
227 } else if (bpp == 4) { \
230 for (; i < size; i++) { \
231 dst[i] = op(dst[i - bpp], src[i], last[i]); \
234 /* NOTE: 'dst' can be equal to 'last' */
235 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
236 uint8_t *src, uint8_t *last, int size, int bpp)
238 int i, p, r, g, b, a;
240 switch (filter_type) {
241 case PNG_FILTER_VALUE_NONE:
242 memcpy(dst, src, size);
244 case PNG_FILTER_VALUE_SUB:
245 for (i = 0; i < bpp; i++)
249 for (; i < size; i += bpp) {
250 unsigned s = *(int *)(src + i);
251 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
252 *(int *)(dst + i) = p;
255 #define OP_SUB(x, s, l) ((x) + (s))
256 UNROLL_FILTER(OP_SUB);
259 case PNG_FILTER_VALUE_UP:
260 dsp->add_bytes_l2(dst, src, last, size);
262 case PNG_FILTER_VALUE_AVG:
263 for (i = 0; i < bpp; i++) {
267 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
268 UNROLL_FILTER(OP_AVG);
270 case PNG_FILTER_VALUE_PAETH:
271 for (i = 0; i < bpp; i++) {
275 if (bpp > 2 && size > 4) {
276 /* would write off the end of the array if we let it process
277 * the last pixel with bpp=3 */
278 int w = (bpp & 3) ? size - 3 : size;
281 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
285 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
290 /* This used to be called "deloco" in FFmpeg
291 * and is actually an inverse reversible colorspace transformation */
292 #define YUV2RGB(NAME, TYPE) \
293 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
296 for (i = 0; i < size; i += 3 + alpha) { \
297 int g = dst [i + 1]; \
303 YUV2RGB(rgb8, uint8_t)
304 YUV2RGB(rgb16, uint16_t)
306 /* process exactly one decompressed row */
307 static void png_handle_row(PNGDecContext *s)
309 uint8_t *ptr, *last_row;
312 if (!s->interlace_type) {
313 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
315 last_row = s->last_row;
317 last_row = ptr - s->image_linesize;
319 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
320 last_row, s->row_size, s->bpp);
321 /* loco lags by 1 row so that it doesn't interfere with top prediction */
322 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
323 if (s->bit_depth == 16) {
324 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
325 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
327 deloco_rgb8(ptr - s->image_linesize, s->row_size,
328 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
332 if (s->y == s->cur_h) {
333 s->state |= PNG_ALLIMAGE;
334 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
335 if (s->bit_depth == 16) {
336 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
337 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
339 deloco_rgb8(ptr, s->row_size,
340 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
347 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
348 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
349 /* if we already read one row, it is time to stop to
350 * wait for the next one */
353 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
354 s->last_row, s->pass_row_size, s->bpp);
355 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
356 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
359 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
360 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
361 s->color_type, s->last_row);
364 if (s->y == s->cur_h) {
365 memset(s->last_row, 0, s->row_size);
367 if (s->pass == NB_PASSES - 1) {
368 s->state |= PNG_ALLIMAGE;
373 s->pass_row_size = ff_png_pass_row_size(s->pass,
376 s->crow_size = s->pass_row_size + 1;
377 if (s->pass_row_size != 0)
379 /* skip pass if empty row */
388 static int png_decode_idat(PNGDecContext *s, int length)
391 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
392 s->zstream.next_in = (unsigned char *)s->gb.buffer;
393 bytestream2_skip(&s->gb, length);
395 /* decode one line if possible */
396 while (s->zstream.avail_in > 0) {
397 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
398 if (ret != Z_OK && ret != Z_STREAM_END) {
399 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
400 return AVERROR_EXTERNAL;
402 if (s->zstream.avail_out == 0) {
403 if (!(s->state & PNG_ALLIMAGE)) {
406 s->zstream.avail_out = s->crow_size;
407 s->zstream.next_out = s->crow_buf;
409 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
410 av_log(NULL, AV_LOG_WARNING,
411 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
418 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
419 const uint8_t *data_end)
426 zstream.zalloc = ff_png_zalloc;
427 zstream.zfree = ff_png_zfree;
428 zstream.opaque = NULL;
429 if (inflateInit(&zstream) != Z_OK)
430 return AVERROR_EXTERNAL;
431 zstream.next_in = (unsigned char *)data;
432 zstream.avail_in = data_end - data;
433 av_bprint_init(bp, 0, -1);
435 while (zstream.avail_in > 0) {
436 av_bprint_get_buffer(bp, 1, &buf, &buf_size);
438 ret = AVERROR(ENOMEM);
441 zstream.next_out = buf;
442 zstream.avail_out = buf_size;
443 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
444 if (ret != Z_OK && ret != Z_STREAM_END) {
445 ret = AVERROR_EXTERNAL;
448 bp->len += zstream.next_out - buf;
449 if (ret == Z_STREAM_END)
452 inflateEnd(&zstream);
453 bp->str[bp->len] = 0;
457 inflateEnd(&zstream);
458 av_bprint_finalize(bp, NULL);
462 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
467 for (i = 0; i < size_in; i++)
468 extra += in[i] >= 0x80;
469 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
471 q = out = av_malloc(size_in + extra + 1);
474 for (i = 0; i < size_in; i++) {
476 *(q++) = 0xC0 | (in[i] >> 6);
477 *(q++) = 0x80 | (in[i] & 0x3F);
486 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
490 const uint8_t *data = s->gb.buffer;
491 const uint8_t *data_end = data + length;
492 const uint8_t *keyword = data;
493 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
494 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
499 return AVERROR_INVALIDDATA;
500 data = keyword_end + 1;
503 if (data == data_end)
504 return AVERROR_INVALIDDATA;
507 return AVERROR_INVALIDDATA;
508 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
511 av_bprint_finalize(&bp, (char **)&text);
513 return AVERROR(ENOMEM);
515 text = (uint8_t *)data;
516 text_len = data_end - text;
519 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
520 txt_utf8 = iso88591_to_utf8(text, text_len);
523 if (!(kw_utf8 && txt_utf8)) {
526 return AVERROR(ENOMEM);
529 av_dict_set(dict, kw_utf8, txt_utf8,
530 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
534 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
538 return AVERROR_INVALIDDATA;
540 if (s->state & PNG_IDAT) {
541 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
542 return AVERROR_INVALIDDATA;
545 if (s->state & PNG_IHDR) {
546 av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
547 return AVERROR_INVALIDDATA;
550 s->width = s->cur_w = bytestream2_get_be32(&s->gb);
551 s->height = s->cur_h = bytestream2_get_be32(&s->gb);
552 if (av_image_check_size(s->width, s->height, 0, avctx)) {
553 s->cur_w = s->cur_h = s->width = s->height = 0;
554 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
555 return AVERROR_INVALIDDATA;
557 s->bit_depth = bytestream2_get_byte(&s->gb);
558 s->color_type = bytestream2_get_byte(&s->gb);
559 s->compression_type = bytestream2_get_byte(&s->gb);
560 s->filter_type = bytestream2_get_byte(&s->gb);
561 s->interlace_type = bytestream2_get_byte(&s->gb);
562 bytestream2_skip(&s->gb, 4); /* crc */
563 s->state |= PNG_IHDR;
564 if (avctx->debug & FF_DEBUG_PICT_INFO)
565 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
566 "compression_type=%d filter_type=%d interlace_type=%d\n",
567 s->width, s->height, s->bit_depth, s->color_type,
568 s->compression_type, s->filter_type, s->interlace_type);
573 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
575 if (s->state & PNG_IDAT) {
576 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
577 return AVERROR_INVALIDDATA;
579 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
580 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
581 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
582 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
583 bytestream2_skip(&s->gb, 1); /* unit specifier */
584 bytestream2_skip(&s->gb, 4); /* crc */
589 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
590 uint32_t length, AVFrame *p)
594 if (!(s->state & PNG_IHDR)) {
595 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
596 return AVERROR_INVALIDDATA;
598 if (!(s->state & PNG_IDAT)) {
599 /* init image info */
600 avctx->width = s->width;
601 avctx->height = s->height;
603 s->channels = ff_png_get_nb_channels(s->color_type);
604 s->bits_per_pixel = s->bit_depth * s->channels;
605 s->bpp = (s->bits_per_pixel + 7) >> 3;
606 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
608 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
609 s->color_type == PNG_COLOR_TYPE_RGB) {
610 avctx->pix_fmt = AV_PIX_FMT_RGB24;
611 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
612 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
613 avctx->pix_fmt = AV_PIX_FMT_RGBA;
614 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
615 s->color_type == PNG_COLOR_TYPE_GRAY) {
616 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
617 } else if (s->bit_depth == 16 &&
618 s->color_type == PNG_COLOR_TYPE_GRAY) {
619 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
620 } else if (s->bit_depth == 16 &&
621 s->color_type == PNG_COLOR_TYPE_RGB) {
622 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
623 } else if (s->bit_depth == 16 &&
624 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
625 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
626 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
627 s->color_type == PNG_COLOR_TYPE_PALETTE) {
628 avctx->pix_fmt = AV_PIX_FMT_PAL8;
629 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
630 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
631 } else if (s->bit_depth == 8 &&
632 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
633 avctx->pix_fmt = AV_PIX_FMT_YA8;
634 } else if (s->bit_depth == 16 &&
635 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
636 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
638 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
639 "and color type %d\n",
640 s->bit_depth, s->color_type);
641 return AVERROR_INVALIDDATA;
644 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
646 ff_thread_finish_setup(avctx);
648 p->pict_type = AV_PICTURE_TYPE_I;
650 p->interlaced_frame = !!s->interlace_type;
652 /* compute the compressed row size */
653 if (!s->interlace_type) {
654 s->crow_size = s->row_size + 1;
657 s->pass_row_size = ff_png_pass_row_size(s->pass,
660 s->crow_size = s->pass_row_size + 1;
662 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
663 s->row_size, s->crow_size);
664 s->image_buf = p->data[0];
665 s->image_linesize = p->linesize[0];
666 /* copy the palette if needed */
667 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
668 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
669 /* empty row is used if differencing to the first row */
670 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
672 return AVERROR_INVALIDDATA;
673 if (s->interlace_type ||
674 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
675 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
677 return AVERROR_INVALIDDATA;
680 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
682 return AVERROR(ENOMEM);
684 /* we want crow_buf+1 to be 16-byte aligned */
685 s->crow_buf = s->buffer + 15;
686 s->zstream.avail_out = s->crow_size;
687 s->zstream.next_out = s->crow_buf;
689 s->state |= PNG_IDAT;
690 if ((ret = png_decode_idat(s, length)) < 0)
692 bytestream2_skip(&s->gb, 4); /* crc */
697 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
702 if ((length % 3) != 0 || length > 256 * 3)
703 return AVERROR_INVALIDDATA;
704 /* read the palette */
706 for (i = 0; i < n; i++) {
707 r = bytestream2_get_byte(&s->gb);
708 g = bytestream2_get_byte(&s->gb);
709 b = bytestream2_get_byte(&s->gb);
710 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
713 s->palette[i] = (0xFFU << 24);
714 s->state |= PNG_PLTE;
715 bytestream2_skip(&s->gb, 4); /* crc */
720 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
725 /* read the transparency. XXX: Only palette mode supported */
726 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
728 !(s->state & PNG_PLTE))
729 return AVERROR_INVALIDDATA;
730 for (i = 0; i < length; i++) {
731 v = bytestream2_get_byte(&s->gb);
732 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
734 bytestream2_skip(&s->gb, 4); /* crc */
741 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
743 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
745 uint8_t *pd = p->data[0];
746 for (j = 0; j < s->height; j++) {
748 for (k = 7; k >= 1; k--)
749 if ((s->width&7) >= k)
750 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
751 for (i--; i >= 0; i--) {
752 pd[8*i + 7]= pd[i] & 1;
753 pd[8*i + 6]= (pd[i]>>1) & 1;
754 pd[8*i + 5]= (pd[i]>>2) & 1;
755 pd[8*i + 4]= (pd[i]>>3) & 1;
756 pd[8*i + 3]= (pd[i]>>4) & 1;
757 pd[8*i + 2]= (pd[i]>>5) & 1;
758 pd[8*i + 1]= (pd[i]>>6) & 1;
759 pd[8*i + 0]= pd[i]>>7;
761 pd += s->image_linesize;
763 } else if (s->bits_per_pixel == 2) {
765 uint8_t *pd = p->data[0];
766 for (j = 0; j < s->height; j++) {
768 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
769 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
770 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
771 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
772 for (i--; i >= 0; i--) {
773 pd[4*i + 3]= pd[i] & 3;
774 pd[4*i + 2]= (pd[i]>>2) & 3;
775 pd[4*i + 1]= (pd[i]>>4) & 3;
776 pd[4*i + 0]= pd[i]>>6;
779 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
780 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
781 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
782 for (i--; i >= 0; i--) {
783 pd[4*i + 3]= ( pd[i] & 3)*0x55;
784 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
785 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
786 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
789 pd += s->image_linesize;
791 } else if (s->bits_per_pixel == 4) {
793 uint8_t *pd = p->data[0];
794 for (j = 0; j < s->height; j++) {
796 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
797 if (s->width&1) pd[2*i+0]= pd[i]>>4;
798 for (i--; i >= 0; i--) {
799 pd[2*i + 1] = pd[i] & 15;
800 pd[2*i + 0] = pd[i] >> 4;
803 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
804 for (i--; i >= 0; i--) {
805 pd[2*i + 1] = (pd[i] & 15) * 0x11;
806 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
809 pd += s->image_linesize;
814 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
817 uint32_t sequence_number;
818 int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
821 return AVERROR_INVALIDDATA;
823 if (!(s->state & PNG_IHDR)) {
824 av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
825 return AVERROR_INVALIDDATA;
828 s->last_w = s->cur_w;
829 s->last_h = s->cur_h;
830 s->last_x_offset = s->x_offset;
831 s->last_y_offset = s->y_offset;
832 s->last_dispose_op = s->dispose_op;
834 sequence_number = bytestream2_get_be32(&s->gb);
835 cur_w = bytestream2_get_be32(&s->gb);
836 cur_h = bytestream2_get_be32(&s->gb);
837 x_offset = bytestream2_get_be32(&s->gb);
838 y_offset = bytestream2_get_be32(&s->gb);
839 bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
840 dispose_op = bytestream2_get_byte(&s->gb);
841 blend_op = bytestream2_get_byte(&s->gb);
842 bytestream2_skip(&s->gb, 4); /* crc */
844 if (sequence_number == 0 &&
845 (cur_w != s->width ||
846 cur_h != s->height ||
849 cur_w <= 0 || cur_h <= 0 ||
850 x_offset < 0 || y_offset < 0 ||
851 cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
852 return AVERROR_INVALIDDATA;
854 if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
855 // No previous frame to revert to for the first frame
856 // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
857 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
860 if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
861 avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
862 avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
863 avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
864 avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
865 avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
866 avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
868 // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
869 blend_op = APNG_BLEND_OP_SOURCE;
874 s->x_offset = x_offset;
875 s->y_offset = y_offset;
876 s->dispose_op = dispose_op;
877 s->blend_op = blend_op;
882 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
885 uint8_t *pd = p->data[0];
886 uint8_t *pd_last = s->last_picture.f->data[0];
887 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
889 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
890 for (j = 0; j < s->height; j++) {
891 for (i = 0; i < ls; i++)
893 pd += s->image_linesize;
894 pd_last += s->image_linesize;
898 // divide by 255 and round to nearest
899 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
900 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
902 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
906 uint8_t *buffer = av_malloc(s->image_linesize * s->height);
909 return AVERROR(ENOMEM);
911 if (s->blend_op == APNG_BLEND_OP_OVER &&
912 avctx->pix_fmt != AV_PIX_FMT_RGBA &&
913 avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
914 avctx->pix_fmt != AV_PIX_FMT_PAL8) {
915 avpriv_request_sample(avctx, "Blending with pixel format %s",
916 av_get_pix_fmt_name(avctx->pix_fmt));
917 return AVERROR_PATCHWELCOME;
920 // Copy the previous frame to the buffer
921 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
922 memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
924 // Do the disposal operation specified by the last frame on the frame
925 if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
926 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
927 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
928 } else if (s->last_dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
929 ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
930 for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y) {
931 size_t row_start = s->image_linesize * y + s->bpp * s->last_x_offset;
932 memcpy(buffer + row_start, s->previous_picture.f->data[0] + row_start, s->bpp * s->last_w);
937 if (s->blend_op == APNG_BLEND_OP_SOURCE) {
938 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
939 size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
940 memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
942 } else { // APNG_BLEND_OP_OVER
943 for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
944 uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
945 uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
946 for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
948 uint8_t foreground_alpha, background_alpha, output_alpha;
951 // Since we might be blending alpha onto alpha, we use the following equations:
952 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
953 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
955 switch (avctx->pix_fmt) {
956 case AV_PIX_FMT_RGBA:
957 foreground_alpha = foreground[3];
958 background_alpha = background[3];
961 case AV_PIX_FMT_GRAY8A:
962 foreground_alpha = foreground[1];
963 background_alpha = background[1];
966 case AV_PIX_FMT_PAL8:
967 foreground_alpha = s->palette[foreground[0]] >> 24;
968 background_alpha = s->palette[background[0]] >> 24;
972 if (foreground_alpha == 0)
975 if (foreground_alpha == 255) {
976 memcpy(background, foreground, s->bpp);
980 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
981 // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
982 avpriv_request_sample(avctx, "Alpha blending palette samples");
983 background[0] = foreground[0];
987 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
989 for (b = 0; b < s->bpp - 1; ++b) {
990 if (output_alpha == 0) {
992 } else if (background_alpha == 255) {
993 output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
995 output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
998 output[b] = output_alpha;
999 memcpy(background, output, s->bpp);
1004 // Copy blended buffer into the frame and free
1005 memcpy(p->data[0], buffer, s->image_linesize * s->height);
1011 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
1012 AVFrame *p, AVPacket *avpkt)
1014 AVDictionary *metadata = NULL;
1015 uint32_t tag, length;
1016 int decode_next_dat = 0;
1020 length = bytestream2_get_bytes_left(&s->gb);
1022 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
1023 if (!(s->state & PNG_IDAT))
1028 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
1029 if ( s->state & PNG_ALLIMAGE
1030 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
1032 ret = AVERROR_INVALIDDATA;
1036 length = bytestream2_get_be32(&s->gb);
1037 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
1038 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
1039 ret = AVERROR_INVALIDDATA;
1042 tag = bytestream2_get_le32(&s->gb);
1043 if (avctx->debug & FF_DEBUG_STARTCODE)
1044 av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
1046 ((tag >> 8) & 0xff),
1047 ((tag >> 16) & 0xff),
1048 ((tag >> 24) & 0xff), length);
1050 case MKTAG('I', 'H', 'D', 'R'):
1051 if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
1054 case MKTAG('p', 'H', 'Y', 's'):
1055 if ((ret = decode_phys_chunk(avctx, s)) < 0)
1058 case MKTAG('f', 'c', 'T', 'L'):
1059 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1061 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1063 decode_next_dat = 1;
1065 case MKTAG('f', 'd', 'A', 'T'):
1066 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1068 if (!decode_next_dat) {
1069 ret = AVERROR_INVALIDDATA;
1072 bytestream2_get_be32(&s->gb);
1075 case MKTAG('I', 'D', 'A', 'T'):
1076 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1078 if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
1081 case MKTAG('P', 'L', 'T', 'E'):
1082 if (decode_plte_chunk(avctx, s, length) < 0)
1085 case MKTAG('t', 'R', 'N', 'S'):
1086 if (decode_trns_chunk(avctx, s, length) < 0)
1089 case MKTAG('t', 'E', 'X', 't'):
1090 if (decode_text_chunk(s, length, 0, &metadata) < 0)
1091 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1092 bytestream2_skip(&s->gb, length + 4);
1094 case MKTAG('z', 'T', 'X', 't'):
1095 if (decode_text_chunk(s, length, 1, &metadata) < 0)
1096 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1097 bytestream2_skip(&s->gb, length + 4);
1099 case MKTAG('I', 'E', 'N', 'D'):
1100 if (!(s->state & PNG_ALLIMAGE))
1101 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1102 if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1103 ret = AVERROR_INVALIDDATA;
1106 bytestream2_skip(&s->gb, 4); /* crc */
1111 bytestream2_skip(&s->gb, length + 4);
1117 if (s->bits_per_pixel <= 4)
1118 handle_small_bpp(s, p);
1120 /* handle p-frames only if a predecessor frame is available */
1121 if (s->last_picture.f->data[0]) {
1122 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1123 && s->last_picture.f->width == p->width
1124 && s->last_picture.f->height== p->height
1125 && s->last_picture.f->format== p->format
1127 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1128 handle_p_frame_png(s, p);
1129 else if (CONFIG_APNG_DECODER &&
1130 avctx->codec_id == AV_CODEC_ID_APNG &&
1131 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1135 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1137 av_frame_set_metadata(p, metadata);
1142 av_dict_free(&metadata);
1143 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1147 #if CONFIG_PNG_DECODER
1148 static int decode_frame_png(AVCodecContext *avctx,
1149 void *data, int *got_frame,
1152 PNGDecContext *const s = avctx->priv_data;
1153 const uint8_t *buf = avpkt->data;
1154 int buf_size = avpkt->size;
1159 ff_thread_release_buffer(avctx, &s->last_picture);
1160 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1163 bytestream2_init(&s->gb, buf, buf_size);
1165 /* check signature */
1166 sig = bytestream2_get_be64(&s->gb);
1167 if (sig != PNGSIG &&
1169 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature (%d).\n", buf_size);
1170 return AVERROR_INVALIDDATA;
1173 s->y = s->state = 0;
1176 s->zstream.zalloc = ff_png_zalloc;
1177 s->zstream.zfree = ff_png_zfree;
1178 s->zstream.opaque = NULL;
1179 ret = inflateInit(&s->zstream);
1181 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1182 return AVERROR_EXTERNAL;
1185 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1188 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1193 ret = bytestream2_tell(&s->gb);
1195 inflateEnd(&s->zstream);
1201 #if CONFIG_APNG_DECODER
1202 static int decode_frame_apng(AVCodecContext *avctx,
1203 void *data, int *got_frame,
1206 PNGDecContext *const s = avctx->priv_data;
1211 ff_thread_release_buffer(avctx, &s->previous_picture);
1212 tmp = s->previous_picture;
1213 s->previous_picture = s->last_picture;
1214 s->last_picture = s->picture;
1218 if (!(s->state & PNG_IHDR)) {
1219 if (!avctx->extradata_size)
1220 return AVERROR_INVALIDDATA;
1222 /* only init fields, there is no zlib use in extradata */
1223 s->zstream.zalloc = ff_png_zalloc;
1224 s->zstream.zfree = ff_png_zfree;
1226 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1227 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1231 /* reset state for a new frame */
1232 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1233 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1234 ret = AVERROR_EXTERNAL;
1238 s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
1239 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1240 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1243 if (!(s->state & PNG_ALLIMAGE))
1244 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1245 if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1246 ret = AVERROR_INVALIDDATA;
1249 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1253 ret = bytestream2_tell(&s->gb);
1256 inflateEnd(&s->zstream);
1261 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1263 PNGDecContext *psrc = src->priv_data;
1264 PNGDecContext *pdst = dst->priv_data;
1270 ff_thread_release_buffer(dst, &pdst->picture);
1271 if (psrc->picture.f->data[0] &&
1272 (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1274 if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1275 pdst->width = psrc->width;
1276 pdst->height = psrc->height;
1277 pdst->bit_depth = psrc->bit_depth;
1278 pdst->color_type = psrc->color_type;
1279 pdst->compression_type = psrc->compression_type;
1280 pdst->interlace_type = psrc->interlace_type;
1281 pdst->filter_type = psrc->filter_type;
1282 pdst->cur_w = psrc->cur_w;
1283 pdst->cur_h = psrc->cur_h;
1284 pdst->x_offset = psrc->x_offset;
1285 pdst->y_offset = psrc->y_offset;
1286 pdst->has_trns = psrc->has_trns;
1288 pdst->dispose_op = psrc->dispose_op;
1290 memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
1292 pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);
1294 ff_thread_release_buffer(dst, &pdst->last_picture);
1295 if (psrc->last_picture.f->data[0])
1296 return ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture);
1302 static av_cold int png_dec_init(AVCodecContext *avctx)
1304 PNGDecContext *s = avctx->priv_data;
1306 avctx->color_range = AVCOL_RANGE_JPEG;
1309 s->previous_picture.f = av_frame_alloc();
1310 s->last_picture.f = av_frame_alloc();
1311 s->picture.f = av_frame_alloc();
1312 if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1313 av_frame_free(&s->previous_picture.f);
1314 av_frame_free(&s->last_picture.f);
1315 av_frame_free(&s->picture.f);
1316 return AVERROR(ENOMEM);
1319 if (!avctx->internal->is_copy) {
1320 avctx->internal->allocate_progress = 1;
1321 ff_pngdsp_init(&s->dsp);
1327 static av_cold int png_dec_end(AVCodecContext *avctx)
1329 PNGDecContext *s = avctx->priv_data;
1331 ff_thread_release_buffer(avctx, &s->previous_picture);
1332 av_frame_free(&s->previous_picture.f);
1333 ff_thread_release_buffer(avctx, &s->last_picture);
1334 av_frame_free(&s->last_picture.f);
1335 ff_thread_release_buffer(avctx, &s->picture);
1336 av_frame_free(&s->picture.f);
1337 av_freep(&s->buffer);
1339 av_freep(&s->last_row);
1340 s->last_row_size = 0;
1341 av_freep(&s->tmp_row);
1342 s->tmp_row_size = 0;
1347 #if CONFIG_APNG_DECODER
1348 AVCodec ff_apng_decoder = {
1350 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1351 .type = AVMEDIA_TYPE_VIDEO,
1352 .id = AV_CODEC_ID_APNG,
1353 .priv_data_size = sizeof(PNGDecContext),
1354 .init = png_dec_init,
1355 .close = png_dec_end,
1356 .decode = decode_frame_apng,
1357 .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1358 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1359 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
1363 #if CONFIG_PNG_DECODER
1364 AVCodec ff_png_decoder = {
1366 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1367 .type = AVMEDIA_TYPE_VIDEO,
1368 .id = AV_CODEC_ID_PNG,
1369 .priv_data_size = sizeof(PNGDecContext),
1370 .init = png_dec_init,
1371 .close = png_dec_end,
1372 .decode = decode_frame_png,
1373 .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1374 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1375 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,