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 last_picture;
47 int x_offset, y_offset;
48 uint8_t dispose_op, blend_op;
60 uint32_t palette[256];
63 unsigned int last_row_size;
65 unsigned int tmp_row_size;
69 int crow_size; /* compressed row size (include filter type) */
70 int row_size; /* decompressed row size */
71 int pass_row_size; /* decompress row size of the current pass */
76 /* Mask to determine which pixels are valid in a pass */
77 static const uint8_t png_pass_mask[NB_PASSES] = {
78 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
81 /* Mask to determine which y pixels can be written in a pass */
82 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
83 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
86 /* Mask to determine which pixels to overwrite while displaying */
87 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
88 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
91 /* NOTE: we try to construct a good looking image at each pass. width
92 * is the original image width. We also do pixel format conversion at
94 static void png_put_interlaced_row(uint8_t *dst, int width,
95 int bits_per_pixel, int pass,
96 int color_type, const uint8_t *src)
98 int x, mask, dsp_mask, j, src_x, b, bpp;
102 mask = png_pass_mask[pass];
103 dsp_mask = png_pass_dsp_mask[pass];
105 switch (bits_per_pixel) {
108 for (x = 0; x < width; x++) {
110 if ((dsp_mask << j) & 0x80) {
111 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
112 dst[x >> 3] &= 0xFF7F>>j;
113 dst[x >> 3] |= b << (7 - j);
115 if ((mask << j) & 0x80)
121 for (x = 0; x < width; x++) {
122 int j2 = 2 * (x & 3);
124 if ((dsp_mask << j) & 0x80) {
125 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
126 dst[x >> 2] &= 0xFF3F>>j2;
127 dst[x >> 2] |= b << (6 - j2);
129 if ((mask << j) & 0x80)
135 for (x = 0; x < width; x++) {
138 if ((dsp_mask << j) & 0x80) {
139 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
140 dst[x >> 1] &= 0xFF0F>>j2;
141 dst[x >> 1] |= b << (4 - j2);
143 if ((mask << j) & 0x80)
148 bpp = bits_per_pixel >> 3;
151 for (x = 0; x < width; x++) {
153 if ((dsp_mask << j) & 0x80) {
157 if ((mask << j) & 0x80)
164 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
168 for (i = 0; i < w; i++) {
169 int a, b, c, p, pa, pb, pc;
182 if (pa <= pb && pa <= pc)
192 #define UNROLL1(bpp, op) \
201 for (; i <= size - bpp; i += bpp) { \
202 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
205 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
208 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
211 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
215 #define UNROLL_FILTER(op) \
218 } else if (bpp == 2) { \
220 } else if (bpp == 3) { \
222 } else if (bpp == 4) { \
225 for (; i < size; i++) { \
226 dst[i] = op(dst[i - bpp], src[i], last[i]); \
229 /* NOTE: 'dst' can be equal to 'last' */
230 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
231 uint8_t *src, uint8_t *last, int size, int bpp)
233 int i, p, r, g, b, a;
235 switch (filter_type) {
236 case PNG_FILTER_VALUE_NONE:
237 memcpy(dst, src, size);
239 case PNG_FILTER_VALUE_SUB:
240 for (i = 0; i < bpp; i++)
244 for (; i < size; i += bpp) {
245 unsigned s = *(int *)(src + i);
246 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
247 *(int *)(dst + i) = p;
250 #define OP_SUB(x, s, l) ((x) + (s))
251 UNROLL_FILTER(OP_SUB);
254 case PNG_FILTER_VALUE_UP:
255 dsp->add_bytes_l2(dst, src, last, size);
257 case PNG_FILTER_VALUE_AVG:
258 for (i = 0; i < bpp; i++) {
262 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
263 UNROLL_FILTER(OP_AVG);
265 case PNG_FILTER_VALUE_PAETH:
266 for (i = 0; i < bpp; i++) {
270 if (bpp > 2 && size > 4) {
271 /* would write off the end of the array if we let it process
272 * the last pixel with bpp=3 */
273 int w = bpp == 4 ? size : size - 3;
275 dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
279 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
284 /* This used to be called "deloco" in FFmpeg
285 * and is actually an inverse reversible colorspace transformation */
286 #define YUV2RGB(NAME, TYPE) \
287 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
290 for (i = 0; i < size; i += 3 + alpha) { \
291 int g = dst [i + 1]; \
297 YUV2RGB(rgb8, uint8_t)
298 YUV2RGB(rgb16, uint16_t)
300 /* process exactly one decompressed row */
301 static void png_handle_row(PNGDecContext *s)
303 uint8_t *ptr, *last_row;
306 if (!s->interlace_type) {
307 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
309 last_row = s->last_row;
311 last_row = ptr - s->image_linesize;
313 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
314 last_row, s->row_size, s->bpp);
315 /* loco lags by 1 row so that it doesn't interfere with top prediction */
316 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
317 if (s->bit_depth == 16) {
318 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
319 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
321 deloco_rgb8(ptr - s->image_linesize, s->row_size,
322 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
326 if (s->y == s->cur_h) {
327 s->state |= PNG_ALLIMAGE;
328 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
329 if (s->bit_depth == 16) {
330 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
331 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
333 deloco_rgb8(ptr, s->row_size,
334 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
341 ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
342 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
343 /* if we already read one row, it is time to stop to
344 * wait for the next one */
347 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
348 s->last_row, s->pass_row_size, s->bpp);
349 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
350 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
353 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
354 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
355 s->color_type, s->last_row);
358 if (s->y == s->cur_h) {
359 memset(s->last_row, 0, s->row_size);
361 if (s->pass == NB_PASSES - 1) {
362 s->state |= PNG_ALLIMAGE;
367 s->pass_row_size = ff_png_pass_row_size(s->pass,
370 s->crow_size = s->pass_row_size + 1;
371 if (s->pass_row_size != 0)
373 /* skip pass if empty row */
382 static int png_decode_idat(PNGDecContext *s, int length)
385 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
386 s->zstream.next_in = (unsigned char *)s->gb.buffer;
387 bytestream2_skip(&s->gb, length);
389 /* decode one line if possible */
390 while (s->zstream.avail_in > 0) {
391 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
392 if (ret != Z_OK && ret != Z_STREAM_END) {
393 av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
394 return AVERROR_EXTERNAL;
396 if (s->zstream.avail_out == 0) {
397 if (!(s->state & PNG_ALLIMAGE)) {
400 s->zstream.avail_out = s->crow_size;
401 s->zstream.next_out = s->crow_buf;
403 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
404 av_log(NULL, AV_LOG_WARNING,
405 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
412 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
413 const uint8_t *data_end)
420 zstream.zalloc = ff_png_zalloc;
421 zstream.zfree = ff_png_zfree;
422 zstream.opaque = NULL;
423 if (inflateInit(&zstream) != Z_OK)
424 return AVERROR_EXTERNAL;
425 zstream.next_in = (unsigned char *)data;
426 zstream.avail_in = data_end - data;
427 av_bprint_init(bp, 0, -1);
429 while (zstream.avail_in > 0) {
430 av_bprint_get_buffer(bp, 1, &buf, &buf_size);
432 ret = AVERROR(ENOMEM);
435 zstream.next_out = buf;
436 zstream.avail_out = buf_size;
437 ret = inflate(&zstream, Z_PARTIAL_FLUSH);
438 if (ret != Z_OK && ret != Z_STREAM_END) {
439 ret = AVERROR_EXTERNAL;
442 bp->len += zstream.next_out - buf;
443 if (ret == Z_STREAM_END)
446 inflateEnd(&zstream);
447 bp->str[bp->len] = 0;
451 inflateEnd(&zstream);
452 av_bprint_finalize(bp, NULL);
456 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
461 for (i = 0; i < size_in; i++)
462 extra += in[i] >= 0x80;
463 if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
465 q = out = av_malloc(size_in + extra + 1);
468 for (i = 0; i < size_in; i++) {
470 *(q++) = 0xC0 | (in[i] >> 6);
471 *(q++) = 0x80 | (in[i] & 0x3F);
480 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
484 const uint8_t *data = s->gb.buffer;
485 const uint8_t *data_end = data + length;
486 const uint8_t *keyword = data;
487 const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
488 uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
493 return AVERROR_INVALIDDATA;
494 data = keyword_end + 1;
497 if (data == data_end)
498 return AVERROR_INVALIDDATA;
501 return AVERROR_INVALIDDATA;
502 if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
505 av_bprint_finalize(&bp, (char **)&text);
507 return AVERROR(ENOMEM);
509 text = (uint8_t *)data;
510 text_len = data_end - text;
513 kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
514 txt_utf8 = iso88591_to_utf8(text, text_len);
517 if (!(kw_utf8 && txt_utf8)) {
520 return AVERROR(ENOMEM);
523 av_dict_set(dict, kw_utf8, txt_utf8,
524 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
528 static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
532 return AVERROR_INVALIDDATA;
534 if (s->state & PNG_IDAT) {
535 av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
536 return AVERROR_INVALIDDATA;
539 s->width = s->cur_w = bytestream2_get_be32(&s->gb);
540 s->height = s->cur_h = bytestream2_get_be32(&s->gb);
541 if (av_image_check_size(s->width, s->height, 0, avctx)) {
542 s->width = s->height = 0;
543 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
544 return AVERROR_INVALIDDATA;
546 s->bit_depth = bytestream2_get_byte(&s->gb);
547 s->color_type = bytestream2_get_byte(&s->gb);
548 s->compression_type = bytestream2_get_byte(&s->gb);
549 s->filter_type = bytestream2_get_byte(&s->gb);
550 s->interlace_type = bytestream2_get_byte(&s->gb);
551 bytestream2_skip(&s->gb, 4); /* crc */
552 s->state |= PNG_IHDR;
553 if (avctx->debug & FF_DEBUG_PICT_INFO)
554 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
555 "compression_type=%d filter_type=%d interlace_type=%d\n",
556 s->width, s->height, s->bit_depth, s->color_type,
557 s->compression_type, s->filter_type, s->interlace_type);
562 static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
564 if (s->state & PNG_IDAT) {
565 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
566 return AVERROR_INVALIDDATA;
568 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
569 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
570 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
571 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
572 bytestream2_skip(&s->gb, 1); /* unit specifier */
573 bytestream2_skip(&s->gb, 4); /* crc */
578 static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
579 uint32_t length, AVFrame *p)
583 if (!(s->state & PNG_IHDR)) {
584 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
585 return AVERROR_INVALIDDATA;
587 if (!(s->state & PNG_IDAT)) {
588 /* init image info */
589 avctx->width = s->width;
590 avctx->height = s->height;
592 s->channels = ff_png_get_nb_channels(s->color_type);
593 s->bits_per_pixel = s->bit_depth * s->channels;
594 s->bpp = (s->bits_per_pixel + 7) >> 3;
595 s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
597 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
598 s->color_type == PNG_COLOR_TYPE_RGB) {
599 avctx->pix_fmt = AV_PIX_FMT_RGB24;
600 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
601 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
602 avctx->pix_fmt = AV_PIX_FMT_RGBA;
603 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
604 s->color_type == PNG_COLOR_TYPE_GRAY) {
605 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
606 } else if (s->bit_depth == 16 &&
607 s->color_type == PNG_COLOR_TYPE_GRAY) {
608 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
609 } else if (s->bit_depth == 16 &&
610 s->color_type == PNG_COLOR_TYPE_RGB) {
611 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
612 } else if (s->bit_depth == 16 &&
613 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
614 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
615 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
616 s->color_type == PNG_COLOR_TYPE_PALETTE) {
617 avctx->pix_fmt = AV_PIX_FMT_PAL8;
618 } else if (s->bit_depth == 1 && s->bits_per_pixel == 1) {
619 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
620 } else if (s->bit_depth == 8 &&
621 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
622 avctx->pix_fmt = AV_PIX_FMT_YA8;
623 } else if (s->bit_depth == 16 &&
624 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
625 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
627 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
628 "and color type %d\n",
629 s->bit_depth, s->color_type);
630 return AVERROR_INVALIDDATA;
633 if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
635 ff_thread_finish_setup(avctx);
637 p->pict_type = AV_PICTURE_TYPE_I;
639 p->interlaced_frame = !!s->interlace_type;
641 /* compute the compressed row size */
642 if (!s->interlace_type) {
643 s->crow_size = s->row_size + 1;
646 s->pass_row_size = ff_png_pass_row_size(s->pass,
649 s->crow_size = s->pass_row_size + 1;
651 av_dlog(avctx, "row_size=%d crow_size =%d\n",
652 s->row_size, s->crow_size);
653 s->image_buf = p->data[0];
654 s->image_linesize = p->linesize[0];
655 /* copy the palette if needed */
656 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
657 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
658 /* empty row is used if differencing to the first row */
659 av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
661 return AVERROR_INVALIDDATA;
662 if (s->interlace_type ||
663 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
664 av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
666 return AVERROR_INVALIDDATA;
669 av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
671 return AVERROR(ENOMEM);
673 /* we want crow_buf+1 to be 16-byte aligned */
674 s->crow_buf = s->buffer + 15;
675 s->zstream.avail_out = s->crow_size;
676 s->zstream.next_out = s->crow_buf;
678 s->state |= PNG_IDAT;
679 if ((ret = png_decode_idat(s, length)) < 0)
681 bytestream2_skip(&s->gb, 4); /* crc */
686 static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
691 if ((length % 3) != 0 || length > 256 * 3)
692 return AVERROR_INVALIDDATA;
693 /* read the palette */
695 for (i = 0; i < n; i++) {
696 r = bytestream2_get_byte(&s->gb);
697 g = bytestream2_get_byte(&s->gb);
698 b = bytestream2_get_byte(&s->gb);
699 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
702 s->palette[i] = (0xFFU << 24);
703 s->state |= PNG_PLTE;
704 bytestream2_skip(&s->gb, 4); /* crc */
709 static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
714 /* read the transparency. XXX: Only palette mode supported */
715 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
717 !(s->state & PNG_PLTE))
718 return AVERROR_INVALIDDATA;
719 for (i = 0; i < length; i++) {
720 v = bytestream2_get_byte(&s->gb);
721 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
723 bytestream2_skip(&s->gb, 4); /* crc */
728 static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
730 if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
732 uint8_t *pd = p->data[0];
733 for (j = 0; j < s->height; j++) {
735 for (k = 7; k >= 1; k--)
736 if ((s->width&7) >= k)
737 pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
738 for (i--; i >= 0; i--) {
739 pd[8*i + 7]= pd[i] & 1;
740 pd[8*i + 6]= (pd[i]>>1) & 1;
741 pd[8*i + 5]= (pd[i]>>2) & 1;
742 pd[8*i + 4]= (pd[i]>>3) & 1;
743 pd[8*i + 3]= (pd[i]>>4) & 1;
744 pd[8*i + 2]= (pd[i]>>5) & 1;
745 pd[8*i + 1]= (pd[i]>>6) & 1;
746 pd[8*i + 0]= pd[i]>>7;
748 pd += s->image_linesize;
750 } else if (s->bits_per_pixel == 2) {
752 uint8_t *pd = p->data[0];
753 for (j = 0; j < s->height; j++) {
755 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
756 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
757 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
758 if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
759 for (i--; i >= 0; i--) {
760 pd[4*i + 3]= pd[i] & 3;
761 pd[4*i + 2]= (pd[i]>>2) & 3;
762 pd[4*i + 1]= (pd[i]>>4) & 3;
763 pd[4*i + 0]= pd[i]>>6;
766 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
767 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
768 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
769 for (i--; i >= 0; i--) {
770 pd[4*i + 3]= ( pd[i] & 3)*0x55;
771 pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
772 pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
773 pd[4*i + 0]= ( pd[i]>>6 )*0x55;
776 pd += s->image_linesize;
778 } else if (s->bits_per_pixel == 4) {
780 uint8_t *pd = p->data[0];
781 for (j = 0; j < s->height; j++) {
783 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
784 if (s->width&1) pd[2*i+0]= pd[i]>>4;
785 for (i--; i >= 0; i--) {
786 pd[2*i + 1] = pd[i] & 15;
787 pd[2*i + 0] = pd[i] >> 4;
790 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
791 for (i--; i >= 0; i--) {
792 pd[2*i + 1] = (pd[i] & 15) * 0x11;
793 pd[2*i + 0] = (pd[i] >> 4) * 0x11;
796 pd += s->image_linesize;
801 static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
804 uint32_t sequence_number;
807 return AVERROR_INVALIDDATA;
809 sequence_number = bytestream2_get_be32(&s->gb);
810 s->cur_w = bytestream2_get_be32(&s->gb);
811 s->cur_h = bytestream2_get_be32(&s->gb);
812 s->x_offset = bytestream2_get_be32(&s->gb);
813 s->y_offset = bytestream2_get_be32(&s->gb);
814 bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
815 s->dispose_op = bytestream2_get_byte(&s->gb);
816 s->blend_op = bytestream2_get_byte(&s->gb);
817 bytestream2_skip(&s->gb, 4); /* crc */
819 if (sequence_number == 0 &&
820 (s->cur_w != s->width ||
821 s->cur_h != s->height ||
824 s->cur_w <= 0 || s->cur_h <= 0 ||
825 s->x_offset < 0 || s->y_offset < 0 ||
826 s->cur_w > s->width - s->x_offset|| s->cur_h > s->height - s->y_offset)
827 return AVERROR_INVALIDDATA;
829 /* always (re)start with a clean frame */
830 if (sequence_number == 0)
831 s->dispose_op = APNG_DISPOSE_OP_BACKGROUND;
833 if (s->dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
834 av_log(avctx, AV_LOG_ERROR,
835 "Dispose operation 'previous' is not yet implemented, using 'none'.\n");
836 s->dispose_op = APNG_DISPOSE_OP_NONE;
842 static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
845 uint8_t *pd = p->data[0];
846 uint8_t *pd_last = s->last_picture.f->data[0];
847 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
849 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
850 for (j = 0; j < s->height; j++) {
851 for (i = 0; i < ls; i++)
853 pd += s->image_linesize;
854 pd_last += s->image_linesize;
858 // divide by 255 and round to nearest
859 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
860 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
862 static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
866 uint8_t *pd = p->data[0];
867 /* TODO make pd_last point to the one before for APNG_DISPOSE_OP_PREVIOUS */
868 uint8_t *pd_last = s->last_picture.f->data[0];
869 int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
871 if (s->blend_op == APNG_BLEND_OP_OVER &&
872 avctx->pix_fmt != AV_PIX_FMT_RGBA && avctx->pix_fmt != AV_PIX_FMT_ARGB) {
873 avpriv_request_sample(avctx, "Blending with pixel format %s",
874 av_get_pix_fmt_name(avctx->pix_fmt));
875 return AVERROR_PATCHWELCOME;
878 ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
879 for (j = 0; j < s->y_offset; j++) {
880 for (i = 0; i < ls; i++)
882 pd += s->image_linesize;
883 pd_last += s->image_linesize;
886 if (s->dispose_op != APNG_DISPOSE_OP_BACKGROUND && s->blend_op == APNG_BLEND_OP_OVER) {
887 uint8_t ri, gi, bi, ai;
889 if (avctx->pix_fmt == AV_PIX_FMT_RGBA) {
901 for (j = s->y_offset; j < s->y_offset + s->cur_h; j++) {
902 for (i = 0; i < s->x_offset * s->bpp; i++)
904 for (; i < (s->x_offset + s->cur_w) * s->bpp; i += s->bpp) {
905 uint8_t alpha = pd[i+ai];
907 /* output = alpha * foreground + (1-alpha) * background */
910 pd[i+ri] = pd_last[i+ri];
911 pd[i+gi] = pd_last[i+gi];
912 pd[i+bi] = pd_last[i+bi];
918 pd[i+ri] = FAST_DIV255(alpha * pd[i+ri] + (255 - alpha) * pd_last[i+ri]);
919 pd[i+gi] = FAST_DIV255(alpha * pd[i+gi] + (255 - alpha) * pd_last[i+gi]);
920 pd[i+bi] = FAST_DIV255(alpha * pd[i+bi] + (255 - alpha) * pd_last[i+bi]);
927 pd += s->image_linesize;
928 pd_last += s->image_linesize;
931 for (j = s->y_offset; j < s->y_offset + s->cur_h; j++) {
932 for (i = 0; i < s->x_offset * s->bpp; i++)
934 for (i = (s->x_offset + s->cur_w) * s->bpp; i < ls; i++)
936 pd += s->image_linesize;
937 pd_last += s->image_linesize;
941 for (j = s->y_offset + s->cur_h; j < s->height; j++) {
942 for (i = 0; i < ls; i++)
944 pd += s->image_linesize;
945 pd_last += s->image_linesize;
951 static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
952 AVFrame *p, AVPacket *avpkt)
954 AVDictionary *metadata = NULL;
955 uint32_t tag, length;
956 int decode_next_dat = 0;
957 int ret = AVERROR_INVALIDDATA;
960 length = bytestream2_get_bytes_left(&s->gb);
962 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
963 if (!(s->state & PNG_IDAT))
968 av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
969 if ( s->state & PNG_ALLIMAGE
970 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
975 length = bytestream2_get_be32(&s->gb);
976 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
977 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
980 tag = bytestream2_get_le32(&s->gb);
981 if (avctx->debug & FF_DEBUG_STARTCODE)
982 av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
985 ((tag >> 16) & 0xff),
986 ((tag >> 24) & 0xff), length);
988 case MKTAG('I', 'H', 'D', 'R'):
989 if (decode_ihdr_chunk(avctx, s, length) < 0)
992 case MKTAG('p', 'H', 'Y', 's'):
993 if (decode_phys_chunk(avctx, s) < 0)
996 case MKTAG('f', 'c', 'T', 'L'):
997 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
999 if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1001 decode_next_dat = 1;
1003 case MKTAG('f', 'd', 'A', 'T'):
1004 if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1006 if (!decode_next_dat)
1008 bytestream2_get_be32(&s->gb);
1011 case MKTAG('I', 'D', 'A', 'T'):
1012 if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1014 if (decode_idat_chunk(avctx, s, length, p) < 0)
1017 case MKTAG('P', 'L', 'T', 'E'):
1018 if (decode_plte_chunk(avctx, s, length) < 0)
1021 case MKTAG('t', 'R', 'N', 'S'):
1022 if (decode_trns_chunk(avctx, s, length) < 0)
1025 case MKTAG('t', 'E', 'X', 't'):
1026 if (decode_text_chunk(s, length, 0, &metadata) < 0)
1027 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1028 bytestream2_skip(&s->gb, length + 4);
1030 case MKTAG('z', 'T', 'X', 't'):
1031 if (decode_text_chunk(s, length, 1, &metadata) < 0)
1032 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1033 bytestream2_skip(&s->gb, length + 4);
1035 case MKTAG('I', 'E', 'N', 'D'):
1036 if (!(s->state & PNG_ALLIMAGE))
1037 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1038 if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1041 bytestream2_skip(&s->gb, 4); /* crc */
1046 bytestream2_skip(&s->gb, length + 4);
1052 if (s->bits_per_pixel <= 4)
1053 handle_small_bpp(s, p);
1055 /* handle p-frames only if a predecessor frame is available */
1056 if (s->last_picture.f->data[0]) {
1057 if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1058 && s->last_picture.f->width == p->width
1059 && s->last_picture.f->height== p->height
1060 && s->last_picture.f->format== p->format
1062 if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1063 handle_p_frame_png(s, p);
1064 else if (CONFIG_APNG_DECODER &&
1065 avctx->codec_id == AV_CODEC_ID_APNG &&
1066 (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1070 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1072 av_frame_set_metadata(p, metadata);
1077 av_dict_free(&metadata);
1078 ff_thread_report_progress(&s->picture, INT_MAX, 0);
1082 #if CONFIG_PNG_DECODER
1083 static int decode_frame_png(AVCodecContext *avctx,
1084 void *data, int *got_frame,
1087 PNGDecContext *const s = avctx->priv_data;
1088 const uint8_t *buf = avpkt->data;
1089 int buf_size = avpkt->size;
1094 ff_thread_release_buffer(avctx, &s->last_picture);
1095 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1098 bytestream2_init(&s->gb, buf, buf_size);
1100 /* check signature */
1101 sig = bytestream2_get_be64(&s->gb);
1102 if (sig != PNGSIG &&
1104 av_log(avctx, AV_LOG_ERROR, "Missing png signature\n");
1105 return AVERROR_INVALIDDATA;
1108 s->y = s->state = 0;
1111 s->zstream.zalloc = ff_png_zalloc;
1112 s->zstream.zfree = ff_png_zfree;
1113 s->zstream.opaque = NULL;
1114 ret = inflateInit(&s->zstream);
1116 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1117 return AVERROR_EXTERNAL;
1120 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1123 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1128 ret = bytestream2_tell(&s->gb);
1130 inflateEnd(&s->zstream);
1136 #if CONFIG_APNG_DECODER
1137 static int decode_frame_apng(AVCodecContext *avctx,
1138 void *data, int *got_frame,
1141 PNGDecContext *const s = avctx->priv_data;
1145 ff_thread_release_buffer(avctx, &s->last_picture);
1146 FFSWAP(ThreadFrame, s->picture, s->last_picture);
1149 if (!(s->state & PNG_IHDR)) {
1150 if (!avctx->extradata_size)
1151 return AVERROR_INVALIDDATA;
1153 /* only init fields, there is no zlib use in extradata */
1154 s->zstream.zalloc = ff_png_zalloc;
1155 s->zstream.zfree = ff_png_zfree;
1157 bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1158 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1162 /* reset state for a new frame */
1163 if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1164 av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1165 ret = AVERROR_EXTERNAL;
1169 s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
1170 bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1171 if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1174 if (!(s->state & PNG_ALLIMAGE))
1175 av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1176 if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1177 ret = AVERROR_INVALIDDATA;
1180 if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1184 ret = bytestream2_tell(&s->gb);
1187 inflateEnd(&s->zstream);
1192 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1194 PNGDecContext *psrc = src->priv_data;
1195 PNGDecContext *pdst = dst->priv_data;
1200 ff_thread_release_buffer(dst, &pdst->picture);
1201 if (psrc->picture.f->data[0])
1202 return ff_thread_ref_frame(&pdst->picture, &psrc->picture);
1207 static av_cold int png_dec_init(AVCodecContext *avctx)
1209 PNGDecContext *s = avctx->priv_data;
1212 s->last_picture.f = av_frame_alloc();
1213 s->picture.f = av_frame_alloc();
1214 if (!s->last_picture.f || !s->picture.f)
1215 return AVERROR(ENOMEM);
1217 if (!avctx->internal->is_copy) {
1218 avctx->internal->allocate_progress = 1;
1219 ff_pngdsp_init(&s->dsp);
1225 static av_cold int png_dec_end(AVCodecContext *avctx)
1227 PNGDecContext *s = avctx->priv_data;
1229 ff_thread_release_buffer(avctx, &s->last_picture);
1230 av_frame_free(&s->last_picture.f);
1231 ff_thread_release_buffer(avctx, &s->picture);
1232 av_frame_free(&s->picture.f);
1233 av_freep(&s->buffer);
1235 av_freep(&s->last_row);
1236 s->last_row_size = 0;
1237 av_freep(&s->tmp_row);
1238 s->tmp_row_size = 0;
1243 #if CONFIG_APNG_DECODER
1244 AVCodec ff_apng_decoder = {
1246 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1247 .type = AVMEDIA_TYPE_VIDEO,
1248 .id = AV_CODEC_ID_APNG,
1249 .priv_data_size = sizeof(PNGDecContext),
1250 .init = png_dec_init,
1251 .close = png_dec_end,
1252 .decode = decode_frame_apng,
1253 .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1254 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1255 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
1259 #if CONFIG_PNG_DECODER
1260 AVCodec ff_png_decoder = {
1262 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1263 .type = AVMEDIA_TYPE_VIDEO,
1264 .id = AV_CODEC_ID_PNG,
1265 .priv_data_size = sizeof(PNGDecContext),
1266 .init = png_dec_init,
1267 .close = png_dec_end,
1268 .decode = decode_frame_png,
1269 .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
1270 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1271 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,