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('p', 'H', 'Y', 's'):
471 if (s->state & PNG_IDAT) {
472 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
475 avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
476 avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
477 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
478 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
479 bytestream2_skip(&s->gb, 1); /* unit specifier */
480 bytestream2_skip(&s->gb, 4); /* crc */
482 case MKTAG('I', 'D', 'A', 'T'):
483 if (!(s->state & PNG_IHDR)) {
484 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
487 if (!(s->state & PNG_IDAT)) {
488 /* init image info */
489 avctx->width = s->width;
490 avctx->height = s->height;
492 s->channels = ff_png_get_nb_channels(s->color_type);
493 s->bits_per_pixel = s->bit_depth * s->channels;
494 s->bpp = (s->bits_per_pixel + 7) >> 3;
495 s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
497 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
498 s->color_type == PNG_COLOR_TYPE_RGB) {
499 avctx->pix_fmt = AV_PIX_FMT_RGB24;
500 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
501 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
502 avctx->pix_fmt = AV_PIX_FMT_RGBA;
503 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
504 s->color_type == PNG_COLOR_TYPE_GRAY) {
505 avctx->pix_fmt = AV_PIX_FMT_GRAY8;
506 } else if (s->bit_depth == 16 &&
507 s->color_type == PNG_COLOR_TYPE_GRAY) {
508 avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
509 } else if (s->bit_depth == 16 &&
510 s->color_type == PNG_COLOR_TYPE_RGB) {
511 avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
512 } else if (s->bit_depth == 16 &&
513 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
514 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
515 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
516 s->color_type == PNG_COLOR_TYPE_PALETTE) {
517 avctx->pix_fmt = AV_PIX_FMT_PAL8;
518 } else if (s->bit_depth == 1) {
519 avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
520 } else if (s->bit_depth == 8 &&
521 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
522 avctx->pix_fmt = AV_PIX_FMT_Y400A;
524 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
525 "and color type %d\n",
526 s->bit_depth, s->color_type);
530 avctx->release_buffer(avctx, p);
533 if(avctx->get_buffer(avctx, p) < 0){
534 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
537 p->pict_type= AV_PICTURE_TYPE_I;
539 p->interlaced_frame = !!s->interlace_type;
541 /* compute the compressed row size */
542 if (!s->interlace_type) {
543 s->crow_size = s->row_size + 1;
546 s->pass_row_size = ff_png_pass_row_size(s->pass,
549 s->crow_size = s->pass_row_size + 1;
551 av_dlog(avctx, "row_size=%d crow_size =%d\n",
552 s->row_size, s->crow_size);
553 s->image_buf = p->data[0];
554 s->image_linesize = p->linesize[0];
555 /* copy the palette if needed */
556 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
557 memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
558 /* empty row is used if differencing to the first row */
559 s->last_row = av_mallocz(s->row_size);
562 if (s->interlace_type ||
563 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
564 s->tmp_row = av_malloc(s->row_size);
569 crow_buf_base = av_malloc(s->row_size + 16);
573 /* we want crow_buf+1 to be 16-byte aligned */
574 s->crow_buf = crow_buf_base + 15;
575 s->zstream.avail_out = s->crow_size;
576 s->zstream.next_out = s->crow_buf;
578 s->state |= PNG_IDAT;
579 if (png_decode_idat(s, length) < 0)
581 bytestream2_skip(&s->gb, 4); /* crc */
583 case MKTAG('P', 'L', 'T', 'E'):
587 if ((length % 3) != 0 || length > 256 * 3)
589 /* read the palette */
592 r = bytestream2_get_byte(&s->gb);
593 g = bytestream2_get_byte(&s->gb);
594 b = bytestream2_get_byte(&s->gb);
595 s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
598 s->palette[i] = (0xFFU << 24);
600 s->state |= PNG_PLTE;
601 bytestream2_skip(&s->gb, 4); /* crc */
604 case MKTAG('t', 'R', 'N', 'S'):
608 /* read the transparency. XXX: Only palette mode supported */
609 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
611 !(s->state & PNG_PLTE))
613 for(i=0;i<length;i++) {
614 v = bytestream2_get_byte(&s->gb);
615 s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
617 bytestream2_skip(&s->gb, 4); /* crc */
620 case MKTAG('I', 'E', 'N', 'D'):
621 if (!(s->state & PNG_ALLIMAGE))
622 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
623 if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
626 bytestream2_skip(&s->gb, 4); /* crc */
631 bytestream2_skip(&s->gb, length + 4);
637 if(s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE){
639 uint8_t *pd = s->current_picture->data[0];
640 for(j=0; j < s->height; j++) {
641 for(i=s->width/8-1; i>=0; i--) {
643 pd[8*i+6]= (pd[i]>>1)&1;
644 pd[8*i+5]= (pd[i]>>2)&1;
645 pd[8*i+4]= (pd[i]>>3)&1;
646 pd[8*i+3]= (pd[i]>>4)&1;
647 pd[8*i+2]= (pd[i]>>5)&1;
648 pd[8*i+1]= (pd[i]>>6)&1;
651 pd += s->image_linesize;
654 if(s->bits_per_pixel == 2){
656 uint8_t *pd = s->current_picture->data[0];
657 for(j=0; j < s->height; j++) {
658 if (s->color_type == PNG_COLOR_TYPE_PALETTE){
659 for(i=s->width/4-1; i>=0; i--) {
661 pd[4*i+2]= (pd[i]>>2)&3;
662 pd[4*i+1]= (pd[i]>>4)&3;
666 for(i=s->width/4-1; i>=0; i--) {
667 pd[4*i+3]= ( pd[i] &3)*0x55;
668 pd[4*i+2]= ((pd[i]>>2)&3)*0x55;
669 pd[4*i+1]= ((pd[i]>>4)&3)*0x55;
670 pd[4*i+0]= ( pd[i]>>6 )*0x55;
673 pd += s->image_linesize;
676 if(s->bits_per_pixel == 4){
678 uint8_t *pd = s->current_picture->data[0];
679 for(j=0; j < s->height; j++) {
680 if (s->color_type == PNG_COLOR_TYPE_PALETTE){
681 for(i=s->width/2-1; i>=0; i--) {
686 for(i=s->width/2-1; i>=0; i--) {
687 pd[2*i+1]= (pd[i]&15)*0x11;
688 pd[2*i+0]= (pd[i]>>4)*0x11;
691 pd += s->image_linesize;
695 /* handle p-frames only if a predecessor frame is available */
696 if(s->last_picture->data[0] != NULL) {
697 if( !(avpkt->flags & AV_PKT_FLAG_KEY)
698 && s->last_picture->width == s->current_picture->width
699 && s->last_picture->height== s->current_picture->height
702 uint8_t *pd = s->current_picture->data[0];
703 uint8_t *pd_last = s->last_picture->data[0];
705 for(j=0; j < s->height; j++) {
706 for(i=0; i < s->width * s->bpp; i++) {
709 pd += s->image_linesize;
710 pd_last += s->image_linesize;
715 *picture= *s->current_picture;
716 *data_size = sizeof(AVFrame);
718 ret = bytestream2_tell(&s->gb);
720 inflateEnd(&s->zstream);
721 av_free(crow_buf_base);
723 av_freep(&s->last_row);
724 av_freep(&s->tmp_row);
731 static av_cold int png_dec_init(AVCodecContext *avctx)
733 PNGDecContext *s = avctx->priv_data;
735 s->current_picture = &s->picture1;
736 s->last_picture = &s->picture2;
737 avcodec_get_frame_defaults(&s->picture1);
738 avcodec_get_frame_defaults(&s->picture2);
740 ff_pngdsp_init(&s->dsp);
747 static av_cold int png_dec_end(AVCodecContext *avctx)
749 PNGDecContext *s = avctx->priv_data;
751 if (s->picture1.data[0])
752 avctx->release_buffer(avctx, &s->picture1);
753 if (s->picture2.data[0])
754 avctx->release_buffer(avctx, &s->picture2);
759 AVCodec ff_png_decoder = {
761 .type = AVMEDIA_TYPE_VIDEO,
762 .id = AV_CODEC_ID_PNG,
763 .priv_data_size = sizeof(PNGDecContext),
764 .init = png_dec_init,
765 .close = png_dec_end,
766 .decode = decode_frame,
767 .capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
768 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),