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/imgutils.h"
26 #include "bytestream.h"
31 * - add 16 bit depth support
38 typedef struct PNGDecContext {
40 AVCodecContext *avctx;
43 AVFrame picture1, picture2;
44 AVFrame *current_picture, *last_picture;
59 uint32_t palette[256];
64 int crow_size; /* compressed row size (include filter type) */
65 int row_size; /* decompressed row size */
66 int pass_row_size; /* decompress row size of the current pass */
71 /* Mask to determine which pixels are valid in a pass */
72 static const uint8_t png_pass_mask[NB_PASSES] = {
73 0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
76 /* Mask to determine which y pixels can be written in a pass */
77 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
78 0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
81 /* Mask to determine which pixels to overwrite while displaying */
82 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
83 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
86 /* NOTE: we try to construct a good looking image at each pass. width
87 is the original image width. We also do pixel format conversion at
89 static void png_put_interlaced_row(uint8_t *dst, int width,
90 int bits_per_pixel, int pass,
91 int color_type, const uint8_t *src)
93 int x, mask, dsp_mask, j, src_x, b, bpp;
97 mask = png_pass_mask[pass];
98 dsp_mask = png_pass_dsp_mask[pass];
99 switch(bits_per_pixel) {
102 for(x = 0; x < width; x++) {
104 if ((dsp_mask << j) & 0x80) {
105 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
106 dst[x >> 3] &= 0xFF7F>>j;
107 dst[x >> 3] |= b << (7 - j);
109 if ((mask << j) & 0x80)
115 for(x = 0; x < width; x++) {
118 if ((dsp_mask << j) & 0x80) {
119 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
120 dst[x >> 2] &= 0xFF3F>>j2;
121 dst[x >> 2] |= b << (6 - j2);
123 if ((mask << j) & 0x80)
129 for(x = 0; x < width; x++) {
132 if ((dsp_mask << j) & 0x80) {
133 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
134 dst[x >> 1] &= 0xFF0F>>j2;
135 dst[x >> 1] |= b << (4 - j2);
137 if ((mask << j) & 0x80)
142 bpp = bits_per_pixel >> 3;
145 for(x = 0; x < width; x++) {
147 if ((dsp_mask << j) & 0x80) {
151 if ((mask << j) & 0x80)
158 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
161 for(i = 0; i < w; i++) {
162 int a, b, c, p, pa, pb, pc;
175 if (pa <= pb && pa <= pc)
185 #define UNROLL1(bpp, op) {\
187 if(bpp >= 2) g = dst[1];\
188 if(bpp >= 3) b = dst[2];\
189 if(bpp >= 4) a = dst[3];\
190 for(; i < size; i+=bpp) {\
191 dst[i+0] = r = op(r, src[i+0], last[i+0]);\
192 if(bpp == 1) continue;\
193 dst[i+1] = g = op(g, src[i+1], last[i+1]);\
194 if(bpp == 2) continue;\
195 dst[i+2] = b = op(b, src[i+2], last[i+2]);\
196 if(bpp == 3) continue;\
197 dst[i+3] = a = op(a, src[i+3], last[i+3]);\
201 #define UNROLL_FILTER(op)\
202 if(bpp == 1) UNROLL1(1, op)\
203 else if(bpp == 2) UNROLL1(2, op)\
204 else if(bpp == 3) UNROLL1(3, op)\
205 else if(bpp == 4) UNROLL1(4, op)\
207 for (; i < size; i += bpp) {\
209 for (j = 0; j < bpp; j++)\
210 dst[i+j] = op(dst[i+j-bpp], src[i+j], last[i+j]);\
214 /* NOTE: 'dst' can be equal to 'last' */
215 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
216 uint8_t *src, uint8_t *last, int size, int bpp)
218 int i, p, r, g, b, a;
220 switch(filter_type) {
221 case PNG_FILTER_VALUE_NONE:
222 memcpy(dst, src, size);
224 case PNG_FILTER_VALUE_SUB:
225 for(i = 0; i < bpp; i++) {
230 for(; i < size; i+=bpp) {
231 int s = *(int*)(src+i);
232 p = ((s&0x7f7f7f7f) + (p&0x7f7f7f7f)) ^ ((s^p)&0x80808080);
236 #define OP_SUB(x,s,l) x+s
237 UNROLL_FILTER(OP_SUB);
240 case PNG_FILTER_VALUE_UP:
241 dsp->add_bytes_l2(dst, src, last, size);
243 case PNG_FILTER_VALUE_AVG:
244 for(i = 0; i < bpp; i++) {
248 #define OP_AVG(x,s,l) (((x + l) >> 1) + s) & 0xff
249 UNROLL_FILTER(OP_AVG);
251 case PNG_FILTER_VALUE_PAETH:
252 for(i = 0; i < bpp; i++) {
256 if(bpp > 2 && size > 4) {
257 // would write off the end of the array if we let it process the last pixel with bpp=3
258 int w = bpp==4 ? size : size-3;
259 dsp->add_paeth_prediction(dst+i, src+i, last+i, w-i, bpp);
262 ff_add_png_paeth_prediction(dst+i, src+i, last+i, size-i, bpp);
267 /* This used to be called "deloco" in FFmpeg
268 * and is actually an inverse reversible colorspace transformation */
269 #define YUV2RGB(NAME, TYPE) \
270 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
273 for (i = 0; i < size; i += 3 + alpha) { \
280 YUV2RGB(rgb8, uint8_t)
281 YUV2RGB(rgb16, uint16_t)
283 /* process exactly one decompressed row */
284 static void png_handle_row(PNGDecContext *s)
286 uint8_t *ptr, *last_row;
289 if (!s->interlace_type) {
290 ptr = s->image_buf + s->image_linesize * s->y;
292 last_row = s->last_row;
294 last_row = ptr - s->image_linesize;
296 png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
297 last_row, s->row_size, s->bpp);
298 /* loco lags by 1 row so that it doesn't interfere with top prediction */
299 if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
300 if (s->bit_depth == 16) {
301 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
302 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
304 deloco_rgb8(ptr - s->image_linesize, s->row_size,
305 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
309 if (s->y == s->height) {
310 s->state |= PNG_ALLIMAGE;
311 if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
312 if (s->bit_depth == 16) {
313 deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
314 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
316 deloco_rgb8(ptr, s->row_size,
317 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
324 ptr = s->image_buf + s->image_linesize * s->y;
325 if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
326 /* if we already read one row, it is time to stop to
327 wait for the next one */
330 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
331 s->last_row, s->pass_row_size, s->bpp);
332 FFSWAP(uint8_t*, s->last_row, s->tmp_row);
335 if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
336 png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
337 s->color_type, s->last_row);
340 if (s->y == s->height) {
341 memset(s->last_row, 0, s->row_size);
343 if (s->pass == NB_PASSES - 1) {
344 s->state |= PNG_ALLIMAGE;
349 s->pass_row_size = ff_png_pass_row_size(s->pass,
352 s->crow_size = s->pass_row_size + 1;
353 if (s->pass_row_size != 0)
355 /* skip pass if empty row */
364 static int png_decode_idat(PNGDecContext *s, int length)
367 s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
368 s->zstream.next_in = (unsigned char *)s->gb.buffer;
369 bytestream2_skip(&s->gb, length);
371 /* decode one line if possible */
372 while (s->zstream.avail_in > 0) {
373 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
374 if (ret != Z_OK && ret != Z_STREAM_END) {
375 av_log(s->avctx, AV_LOG_ERROR, "inflate returned %d\n", ret);
378 if (s->zstream.avail_out == 0) {
379 if (!(s->state & PNG_ALLIMAGE)) {
382 s->zstream.avail_out = s->crow_size;
383 s->zstream.next_out = s->crow_buf;
389 static int decode_frame(AVCodecContext *avctx,
390 void *data, int *data_size,
393 const uint8_t *buf = avpkt->data;
394 int buf_size = avpkt->size;
395 PNGDecContext * const s = avctx->priv_data;
396 AVFrame *picture = data;
398 uint8_t *crow_buf_base = NULL;
399 uint32_t tag, length;
403 FFSWAP(AVFrame *, s->current_picture, s->last_picture);
404 avctx->coded_frame= s->current_picture;
405 p = s->current_picture;
407 bytestream2_init(&s->gb, buf, buf_size);
409 /* check signature */
410 sig = bytestream2_get_be64(&s->gb);
413 av_log(avctx, AV_LOG_ERROR, "Missing png signature\n");
419 // memset(s, 0, sizeof(PNGDecContext));
421 s->zstream.zalloc = ff_png_zalloc;
422 s->zstream.zfree = ff_png_zfree;
423 s->zstream.opaque = NULL;
424 ret = inflateInit(&s->zstream);
426 av_log(avctx, AV_LOG_ERROR, "inflateInit returned %d\n", ret);
430 if (bytestream2_get_bytes_left(&s->gb) <= 0) {
431 av_log(avctx, AV_LOG_ERROR, "No bytes left\n");
435 length = bytestream2_get_be32(&s->gb);
436 if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
437 av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
440 tag = bytestream2_get_le32(&s->gb);
441 if (avctx->debug & FF_DEBUG_STARTCODE)
442 av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
445 ((tag >> 16) & 0xff),
446 ((tag >> 24) & 0xff), length);
448 case MKTAG('I', 'H', 'D', 'R'):
451 s->width = bytestream2_get_be32(&s->gb);
452 s->height = bytestream2_get_be32(&s->gb);
453 if(av_image_check_size(s->width, s->height, 0, avctx)){
454 s->width= s->height= 0;
455 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
458 s->bit_depth = bytestream2_get_byte(&s->gb);
459 s->color_type = bytestream2_get_byte(&s->gb);
460 s->compression_type = bytestream2_get_byte(&s->gb);
461 s->filter_type = bytestream2_get_byte(&s->gb);
462 s->interlace_type = bytestream2_get_byte(&s->gb);
463 bytestream2_skip(&s->gb, 4); /* crc */
464 s->state |= PNG_IHDR;
465 if (avctx->debug & FF_DEBUG_PICT_INFO)
466 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
467 s->width, s->height, s->bit_depth, s->color_type,
468 s->compression_type, s->filter_type, s->interlace_type);
470 case MKTAG('I', 'D', 'A', 'T'):
471 if (!(s->state & PNG_IHDR)) {
472 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
475 if (!(s->state & PNG_IDAT)) {
476 /* init image info */
477 avctx->width = s->width;
478 avctx->height = s->height;
480 s->channels = ff_png_get_nb_channels(s->color_type);
481 s->bits_per_pixel = s->bit_depth * s->channels;
482 s->bpp = (s->bits_per_pixel + 7) >> 3;
483 s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
485 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
486 s->color_type == PNG_COLOR_TYPE_RGB) {
487 avctx->pix_fmt = PIX_FMT_RGB24;
488 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
489 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
490 avctx->pix_fmt = PIX_FMT_RGBA;
491 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
492 s->color_type == PNG_COLOR_TYPE_GRAY) {
493 avctx->pix_fmt = PIX_FMT_GRAY8;
494 } else if (s->bit_depth == 16 &&
495 s->color_type == PNG_COLOR_TYPE_GRAY) {
496 avctx->pix_fmt = PIX_FMT_GRAY16BE;
497 } else if (s->bit_depth == 16 &&
498 s->color_type == PNG_COLOR_TYPE_RGB) {
499 avctx->pix_fmt = PIX_FMT_RGB48BE;
500 } else if (s->bit_depth == 16 &&
501 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
502 avctx->pix_fmt = PIX_FMT_RGBA64BE;
503 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
504 s->color_type == PNG_COLOR_TYPE_PALETTE) {
505 avctx->pix_fmt = PIX_FMT_PAL8;
506 } else if (s->bit_depth == 1) {
507 avctx->pix_fmt = PIX_FMT_MONOBLACK;
508 } else if (s->bit_depth == 8 &&
509 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
510 avctx->pix_fmt = PIX_FMT_Y400A;
512 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
513 "and color type %d\n",
514 s->bit_depth, s->color_type);
518 avctx->release_buffer(avctx, p);
521 if(avctx->get_buffer(avctx, p) < 0){
522 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
525 p->pict_type= AV_PICTURE_TYPE_I;
527 p->interlaced_frame = !!s->interlace_type;
529 /* compute the compressed row size */
530 if (!s->interlace_type) {
531 s->crow_size = s->row_size + 1;
534 s->pass_row_size = ff_png_pass_row_size(s->pass,
537 s->crow_size = s->pass_row_size + 1;
539 av_dlog(avctx, "row_size=%d crow_size =%d\n",
540 s->row_size, s->crow_size);
541 s->image_buf = p->data[0];
542 s->image_linesize = p->linesize[0];
543 /* copy the palette if needed */
544 if (avctx->pix_fmt == PIX_FMT_PAL8)
545 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
546 /* empty row is used if differencing to the first row */
547 s->last_row = av_mallocz(s->row_size);
550 if (s->interlace_type ||
551 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
552 s->tmp_row = av_malloc(s->row_size);
557 crow_buf_base = av_malloc(s->row_size + 16);
561 /* we want crow_buf+1 to be 16-byte aligned */
562 s->crow_buf = crow_buf_base + 15;
563 s->zstream.avail_out = s->crow_size;
564 s->zstream.next_out = s->crow_buf;
566 s->state |= PNG_IDAT;
567 if (png_decode_idat(s, length) < 0)
569 bytestream2_skip(&s->gb, 4); /* crc */
571 case MKTAG('P', 'L', 'T', 'E'):
575 if ((length % 3) != 0 || length > 256 * 3)
577 /* read the palette */
580 r = bytestream2_get_byte(&s->gb);
581 g = bytestream2_get_byte(&s->gb);
582 b = bytestream2_get_byte(&s->gb);
583 s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
586 s->palette[i] = (0xff << 24);
588 s->state |= PNG_PLTE;
589 bytestream2_skip(&s->gb, 4); /* crc */
592 case MKTAG('t', 'R', 'N', 'S'):
596 /* read the transparency. XXX: Only palette mode supported */
597 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
599 !(s->state & PNG_PLTE))
601 for(i=0;i<length;i++) {
602 v = bytestream2_get_byte(&s->gb);
603 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
605 bytestream2_skip(&s->gb, 4); /* crc */
608 case MKTAG('I', 'E', 'N', 'D'):
609 if (!(s->state & PNG_ALLIMAGE))
610 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
611 if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
614 bytestream2_skip(&s->gb, 4); /* crc */
619 bytestream2_skip(&s->gb, length + 4);
625 if(s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE){
627 uint8_t *pd = s->current_picture->data[0];
628 for(j=0; j < s->height; j++) {
629 for(i=s->width/8-1; i>=0; i--) {
631 pd[8*i+6]= (pd[i]>>1)&1;
632 pd[8*i+5]= (pd[i]>>2)&1;
633 pd[8*i+4]= (pd[i]>>3)&1;
634 pd[8*i+3]= (pd[i]>>4)&1;
635 pd[8*i+2]= (pd[i]>>5)&1;
636 pd[8*i+1]= (pd[i]>>6)&1;
639 pd += s->image_linesize;
642 if(s->bits_per_pixel == 2){
644 uint8_t *pd = s->current_picture->data[0];
645 for(j=0; j < s->height; j++) {
646 if (s->color_type == PNG_COLOR_TYPE_PALETTE){
647 for(i=s->width/4-1; i>=0; i--) {
649 pd[4*i+2]= (pd[i]>>2)&3;
650 pd[4*i+1]= (pd[i]>>4)&3;
654 for(i=s->width/4-1; i>=0; i--) {
655 pd[4*i+3]= ( pd[i] &3)*0x55;
656 pd[4*i+2]= ((pd[i]>>2)&3)*0x55;
657 pd[4*i+1]= ((pd[i]>>4)&3)*0x55;
658 pd[4*i+0]= ( pd[i]>>6 )*0x55;
661 pd += s->image_linesize;
664 if(s->bits_per_pixel == 4){
666 uint8_t *pd = s->current_picture->data[0];
667 for(j=0; j < s->height; j++) {
668 if (s->color_type == PNG_COLOR_TYPE_PALETTE){
669 for(i=s->width/2-1; i>=0; i--) {
674 for(i=s->width/2-1; i>=0; i--) {
675 pd[2*i+1]= (pd[i]&15)*0x11;
676 pd[2*i+0]= (pd[i]>>4)*0x11;
679 pd += s->image_linesize;
683 /* handle p-frames only if a predecessor frame is available */
684 if(s->last_picture->data[0] != NULL) {
685 if( !(avpkt->flags & AV_PKT_FLAG_KEY)
686 && s->last_picture->width == s->current_picture->width
687 && s->last_picture->height== s->current_picture->height
690 uint8_t *pd = s->current_picture->data[0];
691 uint8_t *pd_last = s->last_picture->data[0];
693 for(j=0; j < s->height; j++) {
694 for(i=0; i < s->width * s->bpp; i++) {
697 pd += s->image_linesize;
698 pd_last += s->image_linesize;
703 *picture= *s->current_picture;
704 *data_size = sizeof(AVFrame);
706 ret = bytestream2_tell(&s->gb);
708 inflateEnd(&s->zstream);
709 av_free(crow_buf_base);
711 av_freep(&s->last_row);
712 av_freep(&s->tmp_row);
719 static av_cold int png_dec_init(AVCodecContext *avctx)
721 PNGDecContext *s = avctx->priv_data;
723 s->current_picture = &s->picture1;
724 s->last_picture = &s->picture2;
725 avcodec_get_frame_defaults(&s->picture1);
726 avcodec_get_frame_defaults(&s->picture2);
728 ff_pngdsp_init(&s->dsp);
735 static av_cold int png_dec_end(AVCodecContext *avctx)
737 PNGDecContext *s = avctx->priv_data;
739 if (s->picture1.data[0])
740 avctx->release_buffer(avctx, &s->picture1);
741 if (s->picture2.data[0])
742 avctx->release_buffer(avctx, &s->picture2);
747 AVCodec ff_png_decoder = {
749 .type = AVMEDIA_TYPE_VIDEO,
750 .id = AV_CODEC_ID_PNG,
751 .priv_data_size = sizeof(PNGDecContext),
752 .init = png_dec_init,
753 .close = png_dec_end,
754 .decode = decode_frame,
755 .capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
756 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),