pngdec.c
Go to the documentation of this file.
1 /*
2  * PNG image format
3  * Copyright (c) 2003 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
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.
11  *
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.
16  *
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
20  */
21 #include "libavutil/imgutils.h"
22 #include "avcodec.h"
23 #include "bytestream.h"
24 #include "png.h"
25 #include "dsputil.h"
26 
27 /* TODO:
28  * - add 2, 4 and 16 bit depth support
29  */
30 
31 #include <zlib.h>
32 
33 //#define DEBUG
34 
35 typedef struct PNGDecContext {
37 
41 
42  int state;
43  int width, height;
44  int bit_depth;
49  int channels;
51  int bpp;
52 
53  uint8_t *image_buf;
55  uint32_t palette[256];
56  uint8_t *crow_buf;
57  uint8_t *last_row;
58  uint8_t *tmp_row;
59  int pass;
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 */
63  int y;
64  z_stream zstream;
66 
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,
70 };
71 
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
75 };
76 
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
79  this stage */
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)
83 {
84  int x, mask, dsp_mask, j, src_x, b, bpp;
85  uint8_t *d;
86  const uint8_t *s;
87 
88  mask = ff_png_pass_mask[pass];
89  dsp_mask = png_pass_dsp_mask[pass];
90  switch(bits_per_pixel) {
91  case 1:
92  /* we must initialize the line to zero before writing to it */
93  if (pass == 0)
94  memset(dst, 0, (width + 7) >> 3);
95  src_x = 0;
96  for(x = 0; x < width; x++) {
97  j = (x & 7);
98  if ((dsp_mask << j) & 0x80) {
99  b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
100  dst[x >> 3] |= b << (7 - j);
101  }
102  if ((mask << j) & 0x80)
103  src_x++;
104  }
105  break;
106  default:
107  bpp = bits_per_pixel >> 3;
108  d = dst;
109  s = src;
110  if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
111  for(x = 0; x < width; x++) {
112  j = x & 7;
113  if ((dsp_mask << j) & 0x80) {
114  *(uint32_t *)d = (s[3] << 24) | (s[0] << 16) | (s[1] << 8) | s[2];
115  }
116  d += bpp;
117  if ((mask << j) & 0x80)
118  s += bpp;
119  }
120  } else {
121  for(x = 0; x < width; x++) {
122  j = x & 7;
123  if ((dsp_mask << j) & 0x80) {
124  memcpy(d, s, bpp);
125  }
126  d += bpp;
127  if ((mask << j) & 0x80)
128  s += bpp;
129  }
130  }
131  break;
132  }
133 }
134 
135 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
136 {
137  int i;
138  for(i = 0; i < w; i++) {
139  int a, b, c, p, pa, pb, pc;
140 
141  a = dst[i - bpp];
142  b = top[i];
143  c = top[i - bpp];
144 
145  p = b - c;
146  pc = a - c;
147 
148  pa = abs(p);
149  pb = abs(pc);
150  pc = abs(p + pc);
151 
152  if (pa <= pb && pa <= pc)
153  p = a;
154  else if (pb <= pc)
155  p = b;
156  else
157  p = c;
158  dst[i] = p + src[i];
159  }
160 }
161 
162 #define UNROLL1(bpp, op) {\
163  r = dst[0];\
164  if(bpp >= 2) g = dst[1];\
165  if(bpp >= 3) b = dst[2];\
166  if(bpp >= 4) a = dst[3];\
167  for(; i < size; i+=bpp) {\
168  dst[i+0] = r = op(r, src[i+0], last[i+0]);\
169  if(bpp == 1) continue;\
170  dst[i+1] = g = op(g, src[i+1], last[i+1]);\
171  if(bpp == 2) continue;\
172  dst[i+2] = b = op(b, src[i+2], last[i+2]);\
173  if(bpp == 3) continue;\
174  dst[i+3] = a = op(a, src[i+3], last[i+3]);\
175  }\
176 }
177 
178 #define UNROLL_FILTER(op)\
179  if(bpp == 1) UNROLL1(1, op)\
180  else if(bpp == 2) UNROLL1(2, op)\
181  else if(bpp == 3) UNROLL1(3, op)\
182  else if(bpp == 4) UNROLL1(4, op)\
183  else {\
184  for (; i < size; i += bpp) {\
185  int j;\
186  for (j = 0; j < bpp; j++)\
187  dst[i+j] = op(dst[i+j-bpp], src[i+j], last[i+j]);\
188  }\
189  }
190 
191 /* NOTE: 'dst' can be equal to 'last' */
192 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
193  uint8_t *src, uint8_t *last, int size, int bpp)
194 {
195  int i, p, r, g, b, a;
196 
197  switch(filter_type) {
199  memcpy(dst, src, size);
200  break;
202  for(i = 0; i < bpp; i++) {
203  dst[i] = src[i];
204  }
205  if(bpp == 4) {
206  p = *(int*)dst;
207  for(; i < size; i+=bpp) {
208  int s = *(int*)(src+i);
209  p = ((s&0x7f7f7f7f) + (p&0x7f7f7f7f)) ^ ((s^p)&0x80808080);
210  *(int*)(dst+i) = p;
211  }
212  } else {
213 #define OP_SUB(x,s,l) x+s
215  }
216  break;
217  case PNG_FILTER_VALUE_UP:
218  dsp->add_bytes_l2(dst, src, last, size);
219  break;
221  for(i = 0; i < bpp; i++) {
222  p = (last[i] >> 1);
223  dst[i] = p + src[i];
224  }
225 #define OP_AVG(x,s,l) (((x + l) >> 1) + s) & 0xff
227  break;
229  for(i = 0; i < bpp; i++) {
230  p = last[i];
231  dst[i] = p + src[i];
232  }
233  if(bpp > 1 && size > 4) {
234  // would write off the end of the array if we let it process the last pixel with bpp=3
235  int w = bpp==4 ? size : size-3;
236  dsp->add_png_paeth_prediction(dst+i, src+i, last+i, w-i, bpp);
237  i = w;
238  }
239  ff_add_png_paeth_prediction(dst+i, src+i, last+i, size-i, bpp);
240  break;
241  }
242 }
243 
244 static av_always_inline void convert_to_rgb32_loco(uint8_t *dst, const uint8_t *src, int width, int loco)
245 {
246  int j;
247  unsigned int r, g, b, a;
248 
249  for(j = 0;j < width; j++) {
250  r = src[0];
251  g = src[1];
252  b = src[2];
253  a = src[3];
254  if(loco) {
255  r = (r+g)&0xff;
256  b = (b+g)&0xff;
257  }
258  *(uint32_t *)dst = (a << 24) | (r << 16) | (g << 8) | b;
259  dst += 4;
260  src += 4;
261  }
262 }
263 
264 static void convert_to_rgb32(uint8_t *dst, const uint8_t *src, int width, int loco)
265 {
266  if(loco)
267  convert_to_rgb32_loco(dst, src, width, 1);
268  else
269  convert_to_rgb32_loco(dst, src, width, 0);
270 }
271 
272 static void deloco_rgb24(uint8_t *dst, int size)
273 {
274  int i;
275  for(i=0; i<size; i+=3) {
276  int g = dst[i+1];
277  dst[i+0] += g;
278  dst[i+2] += g;
279  }
280 }
281 
282 /* process exactly one decompressed row */
284 {
285  uint8_t *ptr, *last_row;
286  int got_line;
287 
288  if (!s->interlace_type) {
289  ptr = s->image_buf + s->image_linesize * s->y;
290  /* need to swap bytes correctly for RGB_ALPHA */
292  png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
293  s->last_row, s->row_size, s->bpp);
295  FFSWAP(uint8_t*, s->last_row, s->tmp_row);
296  } else {
297  /* in normal case, we avoid one copy */
298  if (s->y == 0)
299  last_row = s->last_row;
300  else
301  last_row = ptr - s->image_linesize;
302 
303  png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
304  last_row, s->row_size, s->bpp);
305  }
306  /* loco lags by 1 row so that it doesn't interfere with top prediction */
307  if (s->filter_type == PNG_FILTER_TYPE_LOCO &&
308  s->color_type == PNG_COLOR_TYPE_RGB && s->y > 0)
309  deloco_rgb24(ptr - s->image_linesize, s->row_size);
310  s->y++;
311  if (s->y == s->height) {
312  s->state |= PNG_ALLIMAGE;
313  if (s->filter_type == PNG_FILTER_TYPE_LOCO &&
315  deloco_rgb24(ptr, s->row_size);
316  }
317  } else {
318  got_line = 0;
319  for(;;) {
320  ptr = s->image_buf + s->image_linesize * s->y;
321  if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
322  /* if we already read one row, it is time to stop to
323  wait for the next one */
324  if (got_line)
325  break;
326  png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
327  s->last_row, s->pass_row_size, s->bpp);
328  FFSWAP(uint8_t*, s->last_row, s->tmp_row);
329  got_line = 1;
330  }
331  if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
332  /* NOTE: RGB32 is handled directly in png_put_interlaced_row */
334  s->color_type, s->last_row);
335  }
336  s->y++;
337  if (s->y == s->height) {
338  for(;;) {
339  if (s->pass == NB_PASSES - 1) {
340  s->state |= PNG_ALLIMAGE;
341  goto the_end;
342  } else {
343  s->pass++;
344  s->y = 0;
346  s->bits_per_pixel,
347  s->width);
348  s->crow_size = s->pass_row_size + 1;
349  if (s->pass_row_size != 0)
350  break;
351  /* skip pass if empty row */
352  }
353  }
354  }
355  }
356  the_end: ;
357  }
358 }
359 
360 static int png_decode_idat(PNGDecContext *s, int length)
361 {
362  int ret;
363  s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
364  s->zstream.next_in = s->gb.buffer;
365  bytestream2_skip(&s->gb, length);
366 
367  /* decode one line if possible */
368  while (s->zstream.avail_in > 0) {
369  ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
370  if (ret != Z_OK && ret != Z_STREAM_END) {
371  return -1;
372  }
373  if (s->zstream.avail_out == 0) {
374  if (!(s->state & PNG_ALLIMAGE)) {
375  png_handle_row(s);
376  }
377  s->zstream.avail_out = s->crow_size;
378  s->zstream.next_out = s->crow_buf;
379  }
380  if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
381  av_log(NULL, AV_LOG_WARNING, "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
382  return 0;
383  }
384  }
385  return 0;
386 }
387 
388 static int decode_frame(AVCodecContext *avctx,
389  void *data, int *data_size,
390  AVPacket *avpkt)
391 {
392  const uint8_t *buf = avpkt->data;
393  int buf_size = avpkt->size;
394  PNGDecContext * const s = avctx->priv_data;
395  AVFrame *picture = data;
396  AVFrame *p;
397  uint8_t *crow_buf_base = NULL;
398  uint32_t tag, length;
399  int ret;
400 
402  avctx->coded_frame= s->current_picture;
403  p = s->current_picture;
404 
405  /* check signature */
406  if (buf_size < 8 ||
407  memcmp(buf, ff_pngsig, 8) != 0 &&
408  memcmp(buf, ff_mngsig, 8) != 0)
409  return -1;
410 
411  bytestream2_init(&s->gb, buf + 8, buf_size - 8);
412  s->y=
413  s->state=0;
414 // memset(s, 0, sizeof(PNGDecContext));
415  /* init the zlib */
416  s->zstream.zalloc = ff_png_zalloc;
417  s->zstream.zfree = ff_png_zfree;
418  s->zstream.opaque = NULL;
419  ret = inflateInit(&s->zstream);
420  if (ret != Z_OK)
421  return -1;
422  for(;;) {
423  if (bytestream2_get_bytes_left(&s->gb) <= 0)
424  goto fail;
425  length = bytestream2_get_be32(&s->gb);
426  if (length > 0x7fffffff)
427  goto fail;
428  tag = bytestream2_get_le32(&s->gb);
429  av_dlog(avctx, "png: tag=%c%c%c%c length=%u\n",
430  (tag & 0xff),
431  ((tag >> 8) & 0xff),
432  ((tag >> 16) & 0xff),
433  ((tag >> 24) & 0xff), length);
434  switch(tag) {
435  case MKTAG('I', 'H', 'D', 'R'):
436  if (length != 13)
437  goto fail;
438  s->width = bytestream2_get_be32(&s->gb);
439  s->height = bytestream2_get_be32(&s->gb);
440  if(av_image_check_size(s->width, s->height, 0, avctx)){
441  s->width= s->height= 0;
442  goto fail;
443  }
444  s->bit_depth = bytestream2_get_byte(&s->gb);
445  s->color_type = bytestream2_get_byte(&s->gb);
446  s->compression_type = bytestream2_get_byte(&s->gb);
447  s->filter_type = bytestream2_get_byte(&s->gb);
448  s->interlace_type = bytestream2_get_byte(&s->gb);
449  bytestream2_skip(&s->gb, 4); /* crc */
450  s->state |= PNG_IHDR;
451  av_dlog(avctx, "width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
452  s->width, s->height, s->bit_depth, s->color_type,
454  break;
455  case MKTAG('I', 'D', 'A', 'T'):
456  if (!(s->state & PNG_IHDR))
457  goto fail;
458  if (!(s->state & PNG_IDAT)) {
459  /* init image info */
460  avctx->width = s->width;
461  avctx->height = s->height;
462 
464  s->bits_per_pixel = s->bit_depth * s->channels;
465  s->bpp = (s->bits_per_pixel + 7) >> 3;
466  s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
467 
468  if (s->bit_depth == 8 &&
470  avctx->pix_fmt = PIX_FMT_RGB24;
471  } else if (s->bit_depth == 8 &&
473  avctx->pix_fmt = PIX_FMT_RGB32;
474  } else if (s->bit_depth == 8 &&
476  avctx->pix_fmt = PIX_FMT_GRAY8;
477  } else if (s->bit_depth == 16 &&
479  avctx->pix_fmt = PIX_FMT_GRAY16BE;
480  } else if (s->bit_depth == 16 &&
482  avctx->pix_fmt = PIX_FMT_RGB48BE;
483  } else if (s->bit_depth == 1 &&
485  avctx->pix_fmt = PIX_FMT_MONOBLACK;
486  } else if (s->bit_depth == 8 &&
488  avctx->pix_fmt = PIX_FMT_PAL8;
489  } else if (s->bit_depth == 8 &&
491  avctx->pix_fmt = PIX_FMT_Y400A;
492  } else {
493  goto fail;
494  }
495  if(p->data[0])
496  avctx->release_buffer(avctx, p);
497 
498  p->reference= 0;
499  if(avctx->get_buffer(avctx, p) < 0){
500  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
501  goto fail;
502  }
504  p->key_frame= 1;
506 
507  /* compute the compressed row size */
508  if (!s->interlace_type) {
509  s->crow_size = s->row_size + 1;
510  } else {
511  s->pass = 0;
513  s->bits_per_pixel,
514  s->width);
515  s->crow_size = s->pass_row_size + 1;
516  }
517  av_dlog(avctx, "row_size=%d crow_size =%d\n",
518  s->row_size, s->crow_size);
519  s->image_buf = p->data[0];
520  s->image_linesize = p->linesize[0];
521  /* copy the palette if needed */
523  memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
524  /* empty row is used if differencing to the first row */
525  s->last_row = av_mallocz(s->row_size);
526  if (!s->last_row)
527  goto fail;
528  if (s->interlace_type ||
530  s->tmp_row = av_malloc(s->row_size);
531  if (!s->tmp_row)
532  goto fail;
533  }
534  /* compressed row */
535  crow_buf_base = av_malloc(s->row_size + 16);
536  if (!crow_buf_base)
537  goto fail;
538 
539  /* we want crow_buf+1 to be 16-byte aligned */
540  s->crow_buf = crow_buf_base + 15;
541  s->zstream.avail_out = s->crow_size;
542  s->zstream.next_out = s->crow_buf;
543  }
544  s->state |= PNG_IDAT;
545  if (png_decode_idat(s, length) < 0)
546  goto fail;
547  bytestream2_skip(&s->gb, 4); /* crc */
548  break;
549  case MKTAG('P', 'L', 'T', 'E'):
550  {
551  int n, i, r, g, b;
552 
553  if ((length % 3) != 0 || length > 256 * 3)
554  goto skip_tag;
555  /* read the palette */
556  n = length / 3;
557  for(i=0;i<n;i++) {
558  r = bytestream2_get_byte(&s->gb);
559  g = bytestream2_get_byte(&s->gb);
560  b = bytestream2_get_byte(&s->gb);
561  s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
562  }
563  for(;i<256;i++) {
564  s->palette[i] = (0xff << 24);
565  }
566  s->state |= PNG_PLTE;
567  bytestream2_skip(&s->gb, 4); /* crc */
568  }
569  break;
570  case MKTAG('t', 'R', 'N', 'S'):
571  {
572  int v, i;
573 
574  /* read the transparency. XXX: Only palette mode supported */
576  length > 256 ||
577  !(s->state & PNG_PLTE))
578  goto skip_tag;
579  for(i=0;i<length;i++) {
580  v = bytestream2_get_byte(&s->gb);
581  s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
582  }
583  bytestream2_skip(&s->gb, 4); /* crc */
584  }
585  break;
586  case MKTAG('I', 'E', 'N', 'D'):
587  if (!(s->state & PNG_ALLIMAGE))
588  goto fail;
589  bytestream2_skip(&s->gb, 4); /* crc */
590  goto exit_loop;
591  default:
592  /* skip tag */
593  skip_tag:
594  bytestream2_skip(&s->gb, length + 4);
595  break;
596  }
597  }
598  exit_loop:
599  /* handle p-frames only if a predecessor frame is available */
600  if(s->last_picture->data[0] != NULL) {
601  if(!(avpkt->flags & AV_PKT_FLAG_KEY)) {
602  int i, j;
603  uint8_t *pd = s->current_picture->data[0];
604  uint8_t *pd_last = s->last_picture->data[0];
605 
606  for(j=0; j < s->height; j++) {
607  for(i=0; i < s->width * s->bpp; i++) {
608  pd[i] += pd_last[i];
609  }
610  pd += s->image_linesize;
611  pd_last += s->image_linesize;
612  }
613  }
614  }
615 
616  *picture= *s->current_picture;
617  *data_size = sizeof(AVFrame);
618 
619  ret = bytestream2_tell(&s->gb);
620  the_end:
621  inflateEnd(&s->zstream);
622  av_free(crow_buf_base);
623  s->crow_buf = NULL;
624  av_freep(&s->last_row);
625  av_freep(&s->tmp_row);
626  return ret;
627  fail:
628  ret = -1;
629  goto the_end;
630 }
631 
633  PNGDecContext *s = avctx->priv_data;
634 
635  s->current_picture = &s->picture1;
636  s->last_picture = &s->picture2;
639  dsputil_init(&s->dsp, avctx);
640 
641  return 0;
642 }
643 
645 {
646  PNGDecContext *s = avctx->priv_data;
647 
648  if (s->picture1.data[0])
649  avctx->release_buffer(avctx, &s->picture1);
650  if (s->picture2.data[0])
651  avctx->release_buffer(avctx, &s->picture2);
652 
653  return 0;
654 }
655 
657  .name = "png",
658  .type = AVMEDIA_TYPE_VIDEO,
659  .id = CODEC_ID_PNG,
660  .priv_data_size = sizeof(PNGDecContext),
661  .init = png_dec_init,
662  .close = png_dec_end,
663  .decode = decode_frame,
664  .capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
665  .long_name = NULL_IF_CONFIG_SMALL("PNG image"),
666 };