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