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"
24 #include "libavutil/stereo3d.h"
27 #include "bytestream.h"
33 * - add 2, 4 and 16 bit depth support
38 typedef struct PNGDecContext {
57 uint32_t palette[256];
62 int crow_size; /* compressed row size (include filter type) */
63 int row_size; /* decompressed row size */
64 int pass_row_size; /* decompress row size of the current pass */
69 /* Mask to determine which y pixels can be written in a pass */
70 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
71 0xff, 0xff, 0x0f, 0xcc, 0x33, 0xff, 0x55,
74 /* Mask to determine which pixels to overwrite while displaying */
75 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
76 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
79 /* NOTE: we try to construct a good looking image at each pass. width
80 * is the original image width. We also do pixel format conversion at
82 static void png_put_interlaced_row(uint8_t *dst, int width,
83 int bits_per_pixel, int pass,
84 int color_type, const uint8_t *src)
86 int x, mask, dsp_mask, j, src_x, b, bpp;
90 mask = ff_png_pass_mask[pass];
91 dsp_mask = png_pass_dsp_mask[pass];
93 switch (bits_per_pixel) {
95 /* we must initialize the line to zero before writing to it */
97 memset(dst, 0, (width + 7) >> 3);
99 for (x = 0; x < width; x++) {
101 if ((dsp_mask << j) & 0x80) {
102 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
103 dst[x >> 3] |= b << (7 - j);
105 if ((mask << j) & 0x80)
110 bpp = bits_per_pixel >> 3;
113 if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
114 for (x = 0; x < width; x++) {
116 if ((dsp_mask << j) & 0x80) {
117 *(uint32_t *)d = (s[3] << 24) | (s[0] << 16) | (s[1] << 8) | s[2];
120 if ((mask << j) & 0x80)
124 for (x = 0; x < width; x++) {
126 if ((dsp_mask << j) & 0x80) {
130 if ((mask << j) & 0x80)
138 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
142 for (i = 0; i < w; i++) {
143 int a, b, c, p, pa, pb, pc;
156 if (pa <= pb && pa <= pc)
166 #define UNROLL1(bpp, op) \
175 for (; i < size; i += bpp) { \
176 dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
179 dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
182 dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
185 dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
189 #define UNROLL_FILTER(op) \
192 } else if (bpp == 2) { \
194 } else if (bpp == 3) { \
196 } else if (bpp == 4) { \
199 for (; i < size; i += bpp) { \
201 for (j = 0; j < bpp; j++) \
202 dst[i + j] = op(dst[i + j - bpp], src[i + j], last[i + j]); \
206 /* NOTE: 'dst' can be equal to 'last' */
207 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
208 uint8_t *src, uint8_t *last, int size, int bpp)
210 int i, p, r, g, b, a;
212 switch (filter_type) {
213 case PNG_FILTER_VALUE_NONE:
214 memcpy(dst, src, size);
216 case PNG_FILTER_VALUE_SUB:
217 for (i = 0; i < bpp; i++)
221 for (; i < size; i += bpp) {
222 int s = *(int *)(src + i);
223 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
224 *(int *)(dst + i) = p;
227 #define OP_SUB(x, s, l) x + s
228 UNROLL_FILTER(OP_SUB);
231 case PNG_FILTER_VALUE_UP:
232 dsp->add_bytes_l2(dst, src, last, size);
234 case PNG_FILTER_VALUE_AVG:
235 for (i = 0; i < bpp; i++) {
239 #define OP_AVG(x, s, l) (((x + l) >> 1) + s) & 0xff
240 UNROLL_FILTER(OP_AVG);
242 case PNG_FILTER_VALUE_PAETH:
243 for (i = 0; i < bpp; i++) {
247 if (bpp > 2 && size > 4) {
248 /* would write off the end of the array if we let it process
249 * the last pixel with bpp=3 */
250 int w = bpp == 4 ? size : size - 3;
251 dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
254 ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
259 static av_always_inline void convert_to_rgb32_loco(uint8_t *dst,
264 unsigned int r, g, b, a;
266 for (j = 0; j < width; j++) {
275 *(uint32_t *) dst = (a << 24) | (r << 16) | (g << 8) | b;
281 static void convert_to_rgb32(uint8_t *dst, const uint8_t *src,
285 convert_to_rgb32_loco(dst, src, width, 1);
287 convert_to_rgb32_loco(dst, src, width, 0);
290 static void deloco_rgb24(uint8_t *dst, int size)
293 for (i = 0; i < size; i += 3) {
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;
308 /* need to swap bytes correctly for RGB_ALPHA */
309 if (s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
310 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
311 s->last_row, s->row_size, s->bpp);
312 convert_to_rgb32(ptr, s->tmp_row, s->width,
313 s->filter_type == PNG_FILTER_TYPE_LOCO);
314 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
316 /* in normal case, we avoid one copy */
318 last_row = s->last_row;
320 last_row = ptr - s->image_linesize;
322 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
323 last_row, s->row_size, s->bpp);
325 /* loco lags by 1 row so that it doesn't interfere with top prediction */
326 if (s->filter_type == PNG_FILTER_TYPE_LOCO &&
327 s->color_type == PNG_COLOR_TYPE_RGB && s->y > 0)
328 deloco_rgb24(ptr - s->image_linesize, s->row_size);
330 if (s->y == s->height) {
331 s->state |= PNG_ALLIMAGE;
332 if (s->filter_type == PNG_FILTER_TYPE_LOCO &&
333 s->color_type == PNG_COLOR_TYPE_RGB)
334 deloco_rgb24(ptr, s->row_size);
339 ptr = s->image_buf + s->image_linesize * s->y;
340 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
341 /* if we already read one row, it is time to stop to
342 * wait for the next one */
345 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
346 s->last_row, s->pass_row_size, s->bpp);
347 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
350 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
351 /* NOTE: RGB32 is handled directly in png_put_interlaced_row */
352 png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
353 s->color_type, s->last_row);
356 if (s->y == s->height) {
358 if (s->pass == NB_PASSES - 1) {
359 s->state |= PNG_ALLIMAGE;
364 s->pass_row_size = ff_png_pass_row_size(s->pass,
367 s->crow_size = s->pass_row_size + 1;
368 if (s->pass_row_size != 0)
370 /* skip pass if empty row */
379 static int png_decode_idat(PNGDecContext *s, int length)
382 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
383 s->zstream.next_in = s->gb.buffer;
384 bytestream2_skip(&s->gb, length);
386 /* decode one line if possible */
387 while (s->zstream.avail_in > 0) {
388 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
389 if (ret != Z_OK && ret != Z_STREAM_END) {
392 if (s->zstream.avail_out == 0) {
393 if (!(s->state & PNG_ALLIMAGE)) {
396 s->zstream.avail_out = s->crow_size;
397 s->zstream.next_out = s->crow_buf;
399 if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
400 av_log(NULL, AV_LOG_WARNING,
401 "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
408 static int decode_frame(AVCodecContext *avctx,
409 void *data, int *got_frame,
412 PNGDecContext *const s = avctx->priv_data;
413 const uint8_t *buf = avpkt->data;
414 int buf_size = avpkt->size;
416 uint8_t *crow_buf_base = NULL;
417 uint32_t tag, length;
420 /* check signature */
422 av_log(avctx, AV_LOG_ERROR, "Not enough data %d\n",
424 return AVERROR_INVALIDDATA;
426 if (memcmp(buf, ff_pngsig, 8) != 0 &&
427 memcmp(buf, ff_mngsig, 8) != 0) {
428 char signature[5 * 8 + 1] = { 0 };
430 for (i = 0; i < 8; i++) {
431 av_strlcatf(signature + i * 5, sizeof(signature) - i * 5,
434 av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature %s\n",
436 return AVERROR_INVALIDDATA;
439 bytestream2_init(&s->gb, buf + 8, buf_size - 8);
443 s->zstream.zalloc = ff_png_zalloc;
444 s->zstream.zfree = ff_png_zfree;
445 s->zstream.opaque = NULL;
446 ret = inflateInit(&s->zstream);
450 if (bytestream2_get_bytes_left(&s->gb) <= 0)
452 length = bytestream2_get_be32(&s->gb);
453 if (length > 0x7fffffff)
455 tag = bytestream2_get_le32(&s->gb);
456 ff_dlog(avctx, "png: tag=%c%c%c%c length=%u\n",
459 ((tag >> 16) & 0xff),
460 ((tag >> 24) & 0xff), length);
462 case MKTAG('I', 'H', 'D', 'R'):
465 s->width = bytestream2_get_be32(&s->gb);
466 s->height = bytestream2_get_be32(&s->gb);
467 if (av_image_check_size(s->width, s->height, 0, avctx)) {
468 s->width = s->height = 0;
471 s->bit_depth = bytestream2_get_byte(&s->gb);
472 s->color_type = bytestream2_get_byte(&s->gb);
473 s->compression_type = bytestream2_get_byte(&s->gb);
474 s->filter_type = bytestream2_get_byte(&s->gb);
475 s->interlace_type = bytestream2_get_byte(&s->gb);
476 bytestream2_skip(&s->gb, 4); /* crc */
477 s->state |= PNG_IHDR;
478 ff_dlog(avctx, "width=%d height=%d depth=%d color_type=%d "
479 "compression_type=%d filter_type=%d interlace_type=%d\n",
480 s->width, s->height, s->bit_depth, s->color_type,
481 s->compression_type, s->filter_type, s->interlace_type);
483 case MKTAG('I', 'D', 'A', 'T'):
484 if (!(s->state & PNG_IHDR))
486 if (!(s->state & PNG_IDAT)) {
487 /* init image info */
488 avctx->width = s->width;
489 avctx->height = s->height;
491 s->channels = ff_png_get_nb_channels(s->color_type);
492 s->bits_per_pixel = s->bit_depth * s->channels;
493 s->bpp = (s->bits_per_pixel + 7) >> 3;
494 s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
496 if (s->bit_depth == 8 &&
497 s->color_type == PNG_COLOR_TYPE_RGB) {
498 avctx->pix_fmt = AV_PIX_FMT_RGB24;
499 } else if (s->bit_depth == 8 &&
500 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
501 avctx->pix_fmt = AV_PIX_FMT_RGB32;
502 } else if (s->bit_depth == 8 &&
503 s->color_type == PNG_COLOR_TYPE_GRAY) {
504 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
505 } else if (s->bit_depth == 16 &&
506 s->color_type == PNG_COLOR_TYPE_GRAY) {
507 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
508 } else if (s->bit_depth == 16 &&
509 s->color_type == PNG_COLOR_TYPE_RGB) {
510 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
511 } else if (s->bit_depth == 1 &&
512 s->color_type == PNG_COLOR_TYPE_GRAY) {
513 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
514 } else if (s->bit_depth == 8 &&
515 s->color_type == PNG_COLOR_TYPE_PALETTE) {
516 avctx->pix_fmt = AV_PIX_FMT_PAL8;
517 } else if (s->bit_depth == 8 &&
518 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
519 avctx->pix_fmt = AV_PIX_FMT_YA8;
520 } else if (s->bit_depth == 16 &&
521 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
522 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
527 if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0) {
528 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
531 p->pict_type = AV_PICTURE_TYPE_I;
533 p->interlaced_frame = !!s->interlace_type;
535 /* compute the compressed row size */
536 if (!s->interlace_type) {
537 s->crow_size = s->row_size + 1;
540 s->pass_row_size = ff_png_pass_row_size(s->pass,
543 s->crow_size = s->pass_row_size + 1;
545 ff_dlog(avctx, "row_size=%d crow_size =%d\n",
546 s->row_size, s->crow_size);
547 s->image_buf = p->data[0];
548 s->image_linesize = p->linesize[0];
549 /* copy the palette if needed */
550 if (s->color_type == PNG_COLOR_TYPE_PALETTE)
551 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
552 /* empty row is used if differencing to the first row */
553 s->last_row = av_mallocz(s->row_size);
556 if (s->interlace_type ||
557 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
558 s->tmp_row = av_malloc(s->row_size);
563 crow_buf_base = av_malloc(s->row_size + 16);
567 /* we want crow_buf+1 to be 16-byte aligned */
568 s->crow_buf = crow_buf_base + 15;
569 s->zstream.avail_out = s->crow_size;
570 s->zstream.next_out = s->crow_buf;
572 s->state |= PNG_IDAT;
573 if (png_decode_idat(s, length) < 0)
575 bytestream2_skip(&s->gb, 4); /* crc */
577 case MKTAG('P', 'L', 'T', 'E'):
581 if ((length % 3) != 0 || length > 256 * 3)
583 /* read the palette */
585 for (i = 0; i < n; i++) {
586 r = bytestream2_get_byte(&s->gb);
587 g = bytestream2_get_byte(&s->gb);
588 b = bytestream2_get_byte(&s->gb);
589 s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
592 s->palette[i] = (0xff << 24);
593 s->state |= PNG_PLTE;
594 bytestream2_skip(&s->gb, 4); /* crc */
597 case MKTAG('t', 'R', 'N', 'S'):
601 /* read the transparency. XXX: Only palette mode supported */
602 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
604 !(s->state & PNG_PLTE))
606 for (i = 0; i < length; i++) {
607 v = bytestream2_get_byte(&s->gb);
608 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
610 bytestream2_skip(&s->gb, 4); /* crc */
613 case MKTAG('s', 'T', 'E', 'R'): {
614 int mode = bytestream2_get_byte(&s->gb);
615 AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
619 if (mode == 0 || mode == 1) {
620 stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
621 stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
623 av_log(avctx, AV_LOG_WARNING,
624 "Unknown value in sTER chunk (%d)\n", mode);
626 bytestream2_skip(&s->gb, 4); /* crc */
629 case MKTAG('I', 'E', 'N', 'D'):
630 if (!(s->state & PNG_ALLIMAGE))
632 bytestream2_skip(&s->gb, 4); /* crc */
637 bytestream2_skip(&s->gb, length + 4);
642 /* handle p-frames only if a predecessor frame is available */
643 if (s->prev->data[0]) {
644 if (!(avpkt->flags & AV_PKT_FLAG_KEY)) {
646 uint8_t *pd = p->data[0];
647 uint8_t *pd_last = s->prev->data[0];
649 for (j = 0; j < s->height; j++) {
650 for (i = 0; i < s->width * s->bpp; i++)
652 pd += s->image_linesize;
653 pd_last += s->image_linesize;
658 av_frame_unref(s->prev);
659 if ((ret = av_frame_ref(s->prev, p)) < 0)
664 ret = bytestream2_tell(&s->gb);
666 inflateEnd(&s->zstream);
667 av_free(crow_buf_base);
669 av_freep(&s->last_row);
670 av_freep(&s->tmp_row);
677 static av_cold int png_dec_init(AVCodecContext *avctx)
679 PNGDecContext *s = avctx->priv_data;
681 avctx->color_range = AVCOL_RANGE_JPEG;
683 s->prev = av_frame_alloc();
685 return AVERROR(ENOMEM);
687 ff_pngdsp_init(&s->dsp);
692 static av_cold int png_dec_end(AVCodecContext *avctx)
694 PNGDecContext *s = avctx->priv_data;
696 av_frame_free(&s->prev);
701 AVCodec ff_png_decoder = {
703 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
704 .type = AVMEDIA_TYPE_VIDEO,
705 .id = AV_CODEC_ID_PNG,
706 .priv_data_size = sizeof(PNGDecContext),
707 .init = png_dec_init,
708 .close = png_dec_end,
709 .decode = decode_frame,
710 .capabilities = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,