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  }
381  return 0;
382 }
383 
384 static int decode_frame(AVCodecContext *avctx,
385  void *data, int *data_size,
386  AVPacket *avpkt)
387 {
388  const uint8_t *buf = avpkt->data;
389  int buf_size = avpkt->size;
390  PNGDecContext * const s = avctx->priv_data;
391  AVFrame *picture = data;
392  AVFrame *p;
393  uint8_t *crow_buf_base = NULL;
394  uint32_t tag, length;
395  int ret;
396 
398  avctx->coded_frame= s->current_picture;
399  p = s->current_picture;
400 
401  /* check signature */
402  if (buf_size < 8 ||
403  memcmp(buf, ff_pngsig, 8) != 0 &&
404  memcmp(buf, ff_mngsig, 8) != 0)
405  return -1;
406 
407  bytestream2_init(&s->gb, buf + 8, buf_size - 8);
408  s->y=
409  s->state=0;
410 // memset(s, 0, sizeof(PNGDecContext));
411  /* init the zlib */
412  s->zstream.zalloc = ff_png_zalloc;
413  s->zstream.zfree = ff_png_zfree;
414  s->zstream.opaque = NULL;
415  ret = inflateInit(&s->zstream);
416  if (ret != Z_OK)
417  return -1;
418  for(;;) {
419  if (bytestream2_get_bytes_left(&s->gb) <= 0)
420  goto fail;
421  length = bytestream2_get_be32(&s->gb);
422  if (length > 0x7fffffff)
423  goto fail;
424  tag = bytestream2_get_le32(&s->gb);
425  av_dlog(avctx, "png: tag=%c%c%c%c length=%u\n",
426  (tag & 0xff),
427  ((tag >> 8) & 0xff),
428  ((tag >> 16) & 0xff),
429  ((tag >> 24) & 0xff), length);
430  switch(tag) {
431  case MKTAG('I', 'H', 'D', 'R'):
432  if (length != 13)
433  goto fail;
434  s->width = bytestream2_get_be32(&s->gb);
435  s->height = bytestream2_get_be32(&s->gb);
436  if(av_image_check_size(s->width, s->height, 0, avctx)){
437  s->width= s->height= 0;
438  goto fail;
439  }
440  s->bit_depth = bytestream2_get_byte(&s->gb);
441  s->color_type = bytestream2_get_byte(&s->gb);
442  s->compression_type = bytestream2_get_byte(&s->gb);
443  s->filter_type = bytestream2_get_byte(&s->gb);
444  s->interlace_type = bytestream2_get_byte(&s->gb);
445  bytestream2_skip(&s->gb, 4); /* crc */
446  s->state |= PNG_IHDR;
447  av_dlog(avctx, "width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
448  s->width, s->height, s->bit_depth, s->color_type,
450  break;
451  case MKTAG('I', 'D', 'A', 'T'):
452  if (!(s->state & PNG_IHDR))
453  goto fail;
454  if (!(s->state & PNG_IDAT)) {
455  /* init image info */
456  avctx->width = s->width;
457  avctx->height = s->height;
458 
460  s->bits_per_pixel = s->bit_depth * s->channels;
461  s->bpp = (s->bits_per_pixel + 7) >> 3;
462  s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
463 
464  if (s->bit_depth == 8 &&
466  avctx->pix_fmt = PIX_FMT_RGB24;
467  } else if (s->bit_depth == 8 &&
469  avctx->pix_fmt = PIX_FMT_RGB32;
470  } else if (s->bit_depth == 8 &&
472  avctx->pix_fmt = PIX_FMT_GRAY8;
473  } else if (s->bit_depth == 16 &&
475  avctx->pix_fmt = PIX_FMT_GRAY16BE;
476  } else if (s->bit_depth == 16 &&
478  avctx->pix_fmt = PIX_FMT_RGB48BE;
479  } else if (s->bit_depth == 1 &&
481  avctx->pix_fmt = PIX_FMT_MONOBLACK;
482  } else if (s->bit_depth == 8 &&
484  avctx->pix_fmt = PIX_FMT_PAL8;
485  } else if (s->bit_depth == 8 &&
487  avctx->pix_fmt = PIX_FMT_Y400A;
488  } else {
489  goto fail;
490  }
491  if(p->data[0])
492  avctx->release_buffer(avctx, p);
493 
494  p->reference= 0;
495  if(avctx->get_buffer(avctx, p) < 0){
496  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
497  goto fail;
498  }
500  p->key_frame= 1;
502 
503  /* compute the compressed row size */
504  if (!s->interlace_type) {
505  s->crow_size = s->row_size + 1;
506  } else {
507  s->pass = 0;
509  s->bits_per_pixel,
510  s->width);
511  s->crow_size = s->pass_row_size + 1;
512  }
513  av_dlog(avctx, "row_size=%d crow_size =%d\n",
514  s->row_size, s->crow_size);
515  s->image_buf = p->data[0];
516  s->image_linesize = p->linesize[0];
517  /* copy the palette if needed */
519  memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
520  /* empty row is used if differencing to the first row */
521  s->last_row = av_mallocz(s->row_size);
522  if (!s->last_row)
523  goto fail;
524  if (s->interlace_type ||
526  s->tmp_row = av_malloc(s->row_size);
527  if (!s->tmp_row)
528  goto fail;
529  }
530  /* compressed row */
531  crow_buf_base = av_malloc(s->row_size + 16);
532  if (!crow_buf_base)
533  goto fail;
534 
535  /* we want crow_buf+1 to be 16-byte aligned */
536  s->crow_buf = crow_buf_base + 15;
537  s->zstream.avail_out = s->crow_size;
538  s->zstream.next_out = s->crow_buf;
539  }
540  s->state |= PNG_IDAT;
541  if (png_decode_idat(s, length) < 0)
542  goto fail;
543  bytestream2_skip(&s->gb, 4); /* crc */
544  break;
545  case MKTAG('P', 'L', 'T', 'E'):
546  {
547  int n, i, r, g, b;
548 
549  if ((length % 3) != 0 || length > 256 * 3)
550  goto skip_tag;
551  /* read the palette */
552  n = length / 3;
553  for(i=0;i<n;i++) {
554  r = bytestream2_get_byte(&s->gb);
555  g = bytestream2_get_byte(&s->gb);
556  b = bytestream2_get_byte(&s->gb);
557  s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
558  }
559  for(;i<256;i++) {
560  s->palette[i] = (0xff << 24);
561  }
562  s->state |= PNG_PLTE;
563  bytestream2_skip(&s->gb, 4); /* crc */
564  }
565  break;
566  case MKTAG('t', 'R', 'N', 'S'):
567  {
568  int v, i;
569 
570  /* read the transparency. XXX: Only palette mode supported */
572  length > 256 ||
573  !(s->state & PNG_PLTE))
574  goto skip_tag;
575  for(i=0;i<length;i++) {
576  v = bytestream2_get_byte(&s->gb);
577  s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
578  }
579  bytestream2_skip(&s->gb, 4); /* crc */
580  }
581  break;
582  case MKTAG('I', 'E', 'N', 'D'):
583  if (!(s->state & PNG_ALLIMAGE))
584  goto fail;
585  bytestream2_skip(&s->gb, 4); /* crc */
586  goto exit_loop;
587  default:
588  /* skip tag */
589  skip_tag:
590  bytestream2_skip(&s->gb, length + 4);
591  break;
592  }
593  }
594  exit_loop:
595  /* handle p-frames only if a predecessor frame is available */
596  if(s->last_picture->data[0] != NULL) {
597  if(!(avpkt->flags & AV_PKT_FLAG_KEY)) {
598  int i, j;
599  uint8_t *pd = s->current_picture->data[0];
600  uint8_t *pd_last = s->last_picture->data[0];
601 
602  for(j=0; j < s->height; j++) {
603  for(i=0; i < s->width * s->bpp; i++) {
604  pd[i] += pd_last[i];
605  }
606  pd += s->image_linesize;
607  pd_last += s->image_linesize;
608  }
609  }
610  }
611 
612  *picture= *s->current_picture;
613  *data_size = sizeof(AVFrame);
614 
615  ret = bytestream2_tell(&s->gb);
616  the_end:
617  inflateEnd(&s->zstream);
618  av_free(crow_buf_base);
619  s->crow_buf = NULL;
620  av_freep(&s->last_row);
621  av_freep(&s->tmp_row);
622  return ret;
623  fail:
624  ret = -1;
625  goto the_end;
626 }
627 
629  PNGDecContext *s = avctx->priv_data;
630 
631  s->current_picture = &s->picture1;
632  s->last_picture = &s->picture2;
635  dsputil_init(&s->dsp, avctx);
636 
637  return 0;
638 }
639 
641 {
642  PNGDecContext *s = avctx->priv_data;
643 
644  if (s->picture1.data[0])
645  avctx->release_buffer(avctx, &s->picture1);
646  if (s->picture2.data[0])
647  avctx->release_buffer(avctx, &s->picture2);
648 
649  return 0;
650 }
651 
653  .name = "png",
654  .type = AVMEDIA_TYPE_VIDEO,
655  .id = CODEC_ID_PNG,
656  .priv_data_size = sizeof(PNGDecContext),
657  .init = png_dec_init,
658  .close = png_dec_end,
659  .decode = decode_frame,
660  .capabilities = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
661  .long_name = NULL_IF_CONFIG_SMALL("PNG image"),
662 };