3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/avstring.h"
23 #include "libavutil/imgutils.h"
25 #include "bytestream.h"
31 * - add 2, 4 and 16 bit depth support
36 typedef struct PNGDecContext {
55 uint32_t palette[256];
60 int crow_size; /* compressed row size (include filter type) */
61 int row_size; /* decompressed row size */
62 int pass_row_size; /* decompress row size of the current pass */
67 /* Mask to determine which y pixels can be written in a pass */
68 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
69 0xff, 0xff, 0x0f, 0xcc, 0x33, 0xff, 0x55,
72 /* Mask to determine which pixels to overwrite while displaying */
73 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
74 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
77 /* NOTE: we try to construct a good looking image at each pass. width
78 * is the original image width. We also do pixel format conversion at
80 static void png_put_interlaced_row(uint8_t *dst, int width,
81 int bits_per_pixel, int pass,
82 int color_type, const uint8_t *src)
84 int x, mask, dsp_mask, j, src_x, b, bpp;
88 mask = ff_png_pass_mask[pass];
89 dsp_mask = png_pass_dsp_mask[pass];
91 switch (bits_per_pixel) {
93 /* we must initialize the line to zero before writing to it */
95 memset(dst, 0, (width + 7) >> 3);
97 for (x = 0; x < width; x++) {
99 if ((dsp_mask << j) & 0x80) {
100 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
101 dst[x >> 3] |= b << (7 - j);
103 if ((mask << j) & 0x80)
108 bpp = bits_per_pixel >> 3;
111 if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
112 for (x = 0; x < width; x++) {
114 if ((dsp_mask << j) & 0x80) {
115 *(uint32_t *)d = (s[3] << 24) | (s[0] << 16) | (s[1] << 8) | s[2];
118 if ((mask << j) & 0x80)
122 for (x = 0; x < width; x++) {
124 if ((dsp_mask << j) & 0x80) {
128 if ((mask << j) & 0x80)
136 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
140 for (i = 0; i < w; i++) {
141 int a, b, c, p, pa, pb, pc;
154 if (pa <= pb && pa <= pc)
164 #define UNROLL1(bpp, op) \
173 for (; i < size; i += bpp) { \
174 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
177 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
180 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
183 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
187 #define UNROLL_FILTER(op) \
190 } else if (bpp == 2) { \
192 } else if (bpp == 3) { \
194 } else if (bpp == 4) { \
197 for (; i < size; i += bpp) { \
199 for (j = 0; j < bpp; j++) \
200 dst[i + j] = op(dst[i + j - bpp], src[i + j], last[i + j]); \
204 /* NOTE: 'dst' can be equal to 'last' */
205 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
206 uint8_t *src, uint8_t *last, int size, int bpp)
208 int i, p, r, g, b, a;
210 switch (filter_type) {
211 case PNG_FILTER_VALUE_NONE:
212 memcpy(dst, src, size);
214 case PNG_FILTER_VALUE_SUB:
215 for (i = 0; i < bpp; i++)
219 for (; i < size; i += bpp) {
220 int s = *(int *)(src + i);
221 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
222 *(int *)(dst + i) = p;
225 #define OP_SUB(x, s, l) x + s
226 UNROLL_FILTER(OP_SUB);
229 case PNG_FILTER_VALUE_UP:
230 dsp->add_bytes_l2(dst, src, last, size);
232 case PNG_FILTER_VALUE_AVG:
233 for (i = 0; i < bpp; i++) {
237 #define OP_AVG(x, s, l) (((x + l) >> 1) + s) & 0xff
238 UNROLL_FILTER(OP_AVG);
240 case PNG_FILTER_VALUE_PAETH:
241 for (i = 0; i < bpp; i++) {
245 if (bpp > 2 && size > 4) {
246 /* would write off the end of the array if we let it process
247 * the last pixel with bpp=3 */
248 int w = bpp == 4 ? size : size - 3;
249 dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
252 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
257 static av_always_inline void convert_to_rgb32_loco(uint8_t *dst,
262 unsigned int r, g, b, a;
264 for (j = 0; j < width; j++) {
273 *(uint32_t *) dst = (a << 24) | (r << 16) | (g << 8) | b;
279 static void convert_to_rgb32(uint8_t *dst, const uint8_t *src,
283 convert_to_rgb32_loco(dst, src, width, 1);
285 convert_to_rgb32_loco(dst, src, width, 0);
288 static void deloco_rgb24(uint8_t *dst, int size)
291 for (i = 0; i < size; i += 3) {
298 /* process exactly one decompressed row */
299 static void png_handle_row(PNGDecContext *s)
301 uint8_t *ptr, *last_row;
304 if (!s->interlace_type) {
305 ptr = s->image_buf + s->image_linesize * s->y;
306 /* need to swap bytes correctly for RGB_ALPHA */
307 if (s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
308 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
309 s->last_row, s->row_size, s->bpp);
310 convert_to_rgb32(ptr, s->tmp_row, s->width,
311 s->filter_type == PNG_FILTER_TYPE_LOCO);
312 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
314 /* in normal case, we avoid one copy */
316 last_row = s->last_row;
318 last_row = ptr - s->image_linesize;
320 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
321 last_row, s->row_size, s->bpp);
323 /* loco lags by 1 row so that it doesn't interfere with top prediction */
324 if (s->filter_type == PNG_FILTER_TYPE_LOCO &&
325 s->color_type == PNG_COLOR_TYPE_RGB && s->y > 0)
326 deloco_rgb24(ptr - s->image_linesize, s->row_size);
328 if (s->y == s->height) {
329 s->state |= PNG_ALLIMAGE;
330 if (s->filter_type == PNG_FILTER_TYPE_LOCO &&
331 s->color_type == PNG_COLOR_TYPE_RGB)
332 deloco_rgb24(ptr, s->row_size);
337 ptr = s->image_buf + s->image_linesize * s->y;
338 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
339 /* if we already read one row, it is time to stop to
340 * wait for the next one */
343 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
344 s->last_row, s->pass_row_size, s->bpp);
345 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
348 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
349 /* NOTE: RGB32 is handled directly in png_put_interlaced_row */
350 png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
351 s->color_type, s->last_row);
354 if (s->y == s->height) {
356 if (s->pass == NB_PASSES - 1) {
357 s->state |= PNG_ALLIMAGE;
362 s->pass_row_size = ff_png_pass_row_size(s->pass,
365 s->crow_size = s->pass_row_size + 1;
366 if (s->pass_row_size != 0)
368 /* skip pass if empty row */
377 static int png_decode_idat(PNGDecContext *s, int length)
380 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
381 s->zstream.next_in = s->gb.buffer;
382 bytestream2_skip(&s->gb, length);
384 /* decode one line if possible */
385 while (s->zstream.avail_in > 0) {
386 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
387 if (ret != Z_OK && ret != Z_STREAM_END) {
390 if (s->zstream.avail_out == 0) {
391 if (!(s->state & PNG_ALLIMAGE)) {
394 s->zstream.avail_out = s->crow_size;
395 s->zstream.next_out = s->crow_buf;
397 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
398 av_log(NULL, AV_LOG_WARNING,
399 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
406 static int decode_frame(AVCodecContext *avctx,
407 void *data, int *got_frame,
410 PNGDecContext *const s = avctx->priv_data;
411 const uint8_t *buf = avpkt->data;
412 int buf_size = avpkt->size;
414 uint8_t *crow_buf_base = NULL;
415 uint32_t tag, length;
418 /* check signature */
420 av_log(avctx, AV_LOG_ERROR, "Not enough data %d\n",
422 return AVERROR_INVALIDDATA;
424 if (memcmp(buf, ff_pngsig, 8) != 0 &&
425 memcmp(buf, ff_mngsig, 8) != 0) {
426 char signature[5 * 8 + 1] = { 0 };
428 for (i = 0; i < 8; i++) {
429 av_strlcatf(signature + i * 5, sizeof(signature) - i * 5,
432 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature %s\n",
434 return AVERROR_INVALIDDATA;
437 bytestream2_init(&s->gb, buf + 8, buf_size - 8);
441 s->zstream.zalloc = ff_png_zalloc;
442 s->zstream.zfree = ff_png_zfree;
443 s->zstream.opaque = NULL;
444 ret = inflateInit(&s->zstream);
448 if (bytestream2_get_bytes_left(&s->gb) <= 0)
450 length = bytestream2_get_be32(&s->gb);
451 if (length > 0x7fffffff)
453 tag = bytestream2_get_le32(&s->gb);
454 ff_dlog(avctx, "png: tag=%c%c%c%c length=%u\n",
457 ((tag >> 16) & 0xff),
458 ((tag >> 24) & 0xff), length);
460 case MKTAG('I', 'H', 'D', 'R'):
463 s->width = bytestream2_get_be32(&s->gb);
464 s->height = bytestream2_get_be32(&s->gb);
465 if (av_image_check_size(s->width, s->height, 0, avctx)) {
466 s->width = s->height = 0;
469 s->bit_depth = bytestream2_get_byte(&s->gb);
470 s->color_type = bytestream2_get_byte(&s->gb);
471 s->compression_type = bytestream2_get_byte(&s->gb);
472 s->filter_type = bytestream2_get_byte(&s->gb);
473 s->interlace_type = bytestream2_get_byte(&s->gb);
474 bytestream2_skip(&s->gb, 4); /* crc */
475 s->state |= PNG_IHDR;
476 ff_dlog(avctx, "width=%d height=%d depth=%d color_type=%d "
477 "compression_type=%d filter_type=%d interlace_type=%d\n",
478 s->width, s->height, s->bit_depth, s->color_type,
479 s->compression_type, s->filter_type, s->interlace_type);
481 case MKTAG('I', 'D', 'A', 'T'):
482 if (!(s->state & PNG_IHDR))
484 if (!(s->state & PNG_IDAT)) {
485 /* init image info */
486 avctx->width = s->width;
487 avctx->height = s->height;
489 s->channels = ff_png_get_nb_channels(s->color_type);
490 s->bits_per_pixel = s->bit_depth * s->channels;
491 s->bpp = (s->bits_per_pixel + 7) >> 3;
492 s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
494 if (s->bit_depth == 8 &&
495 s->color_type == PNG_COLOR_TYPE_RGB) {
496 avctx->pix_fmt = AV_PIX_FMT_RGB24;
497 } else if (s->bit_depth == 8 &&
498 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
499 avctx->pix_fmt = AV_PIX_FMT_RGB32;
500 } else if (s->bit_depth == 8 &&
501 s->color_type == PNG_COLOR_TYPE_GRAY) {
502 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
503 } else if (s->bit_depth == 16 &&
504 s->color_type == PNG_COLOR_TYPE_GRAY) {
505 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
506 } else if (s->bit_depth == 16 &&
507 s->color_type == PNG_COLOR_TYPE_RGB) {
508 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
509 } else if (s->bit_depth == 1 &&
510 s->color_type == PNG_COLOR_TYPE_GRAY) {
511 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
512 } else if (s->bit_depth == 8 &&
513 s->color_type == PNG_COLOR_TYPE_PALETTE) {
514 avctx->pix_fmt = AV_PIX_FMT_PAL8;
515 } else if (s->bit_depth == 8 &&
516 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
517 avctx->pix_fmt = AV_PIX_FMT_YA8;
518 } else if (s->bit_depth == 16 &&
519 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
520 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
525 if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0) {
526 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
529 p->pict_type = AV_PICTURE_TYPE_I;
531 p->interlaced_frame = !!s->interlace_type;
533 /* compute the compressed row size */
534 if (!s->interlace_type) {
535 s->crow_size = s->row_size + 1;
538 s->pass_row_size = ff_png_pass_row_size(s->pass,
541 s->crow_size = s->pass_row_size + 1;
543 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
544 s->row_size, s->crow_size);
545 s->image_buf = p->data[0];
546 s->image_linesize = p->linesize[0];
547 /* copy the palette if needed */
548 if (s->color_type == PNG_COLOR_TYPE_PALETTE)
549 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
550 /* empty row is used if differencing to the first row */
551 s->last_row = av_mallocz(s->row_size);
554 if (s->interlace_type ||
555 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
556 s->tmp_row = av_malloc(s->row_size);
561 crow_buf_base = av_malloc(s->row_size + 16);
565 /* we want crow_buf+1 to be 16-byte aligned */
566 s->crow_buf = crow_buf_base + 15;
567 s->zstream.avail_out = s->crow_size;
568 s->zstream.next_out = s->crow_buf;
570 s->state |= PNG_IDAT;
571 if (png_decode_idat(s, length) < 0)
573 bytestream2_skip(&s->gb, 4); /* crc */
575 case MKTAG('P', 'L', 'T', 'E'):
579 if ((length % 3) != 0 || length > 256 * 3)
581 /* read the palette */
583 for (i = 0; i < n; i++) {
584 r = bytestream2_get_byte(&s->gb);
585 g = bytestream2_get_byte(&s->gb);
586 b = bytestream2_get_byte(&s->gb);
587 s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
590 s->palette[i] = (0xff << 24);
591 s->state |= PNG_PLTE;
592 bytestream2_skip(&s->gb, 4); /* crc */
595 case MKTAG('t', 'R', 'N', 'S'):
599 /* read the transparency. XXX: Only palette mode supported */
600 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
602 !(s->state & PNG_PLTE))
604 for (i = 0; i < length; i++) {
605 v = bytestream2_get_byte(&s->gb);
606 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
608 bytestream2_skip(&s->gb, 4); /* crc */
611 case MKTAG('I', 'E', 'N', 'D'):
612 if (!(s->state & PNG_ALLIMAGE))
614 bytestream2_skip(&s->gb, 4); /* crc */
619 bytestream2_skip(&s->gb, length + 4);
624 /* handle p-frames only if a predecessor frame is available */
625 if (s->prev->data[0]) {
626 if (!(avpkt->flags & AV_PKT_FLAG_KEY)) {
628 uint8_t *pd = p->data[0];
629 uint8_t *pd_last = s->prev->data[0];
631 for (j = 0; j < s->height; j++) {
632 for (i = 0; i < s->width * s->bpp; i++)
634 pd += s->image_linesize;
635 pd_last += s->image_linesize;
640 av_frame_unref(s->prev);
641 if ((ret = av_frame_ref(s->prev, p)) < 0)
646 ret = bytestream2_tell(&s->gb);
648 inflateEnd(&s->zstream);
649 av_free(crow_buf_base);
651 av_freep(&s->last_row);
652 av_freep(&s->tmp_row);
659 static av_cold int png_dec_init(AVCodecContext *avctx)
661 PNGDecContext *s = avctx->priv_data;
663 avctx->color_range = AVCOL_RANGE_JPEG;
665 s->prev = av_frame_alloc();
667 return AVERROR(ENOMEM);
669 ff_pngdsp_init(&s->dsp);
674 static av_cold int png_dec_end(AVCodecContext *avctx)
676 PNGDecContext *s = avctx->priv_data;
678 av_frame_free(&s->prev);
683 AVCodec ff_png_decoder = {
685 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
686 .type = AVMEDIA_TYPE_VIDEO,
687 .id = AV_CODEC_ID_PNG,
688 .priv_data_size = sizeof(PNGDecContext),
689 .init = png_dec_init,
690 .close = png_dec_end,
691 .decode = decode_frame,
692 .capabilities = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,