Libav
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 typedef struct PNGDecContext {
36 
39 
40  int state;
41  int width, height;
42  int bit_depth;
47  int channels;
49  int bpp;
50 
53  uint32_t palette[256];
57  int pass;
58  int crow_size; /* compressed row size (include filter type) */
59  int row_size; /* decompressed row size */
60  int pass_row_size; /* decompress row size of the current pass */
61  int y;
62  z_stream zstream;
64 
65 /* Mask to determine which y pixels can be written in a pass */
67  0xff, 0xff, 0x0f, 0xcc, 0x33, 0xff, 0x55,
68 };
69 
70 /* Mask to determine which pixels to overwrite while displaying */
72  0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
73 };
74 
75 /* NOTE: we try to construct a good looking image at each pass. width
76  is the original image width. We also do pixel format conversion at
77  this stage */
78 static void png_put_interlaced_row(uint8_t *dst, int width,
79  int bits_per_pixel, int pass,
80  int color_type, const uint8_t *src)
81 {
82  int x, mask, dsp_mask, j, src_x, b, bpp;
83  uint8_t *d;
84  const uint8_t *s;
85 
86  mask = ff_png_pass_mask[pass];
87  dsp_mask = png_pass_dsp_mask[pass];
88 
89  switch (bits_per_pixel) {
90  case 1:
91  /* we must initialize the line to zero before writing to it */
92  if (pass == 0)
93  memset(dst, 0, (width + 7) >> 3);
94  src_x = 0;
95  for (x = 0; x < width; x++) {
96  j = (x & 7);
97  if ((dsp_mask << j) & 0x80) {
98  b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
99  dst[x >> 3] |= b << (7 - j);
100  }
101  if ((mask << j) & 0x80)
102  src_x++;
103  }
104  break;
105  default:
106  bpp = bits_per_pixel >> 3;
107  d = dst;
108  s = src;
109  if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
110  for (x = 0; x < width; x++) {
111  j = x & 7;
112  if ((dsp_mask << j) & 0x80) {
113  *(uint32_t *)d = (s[3] << 24) | (s[0] << 16) | (s[1] << 8) | s[2];
114  }
115  d += bpp;
116  if ((mask << j) & 0x80)
117  s += bpp;
118  }
119  } else {
120  for(x = 0; x < width; x++) {
121  j = x & 7;
122  if ((dsp_mask << j) & 0x80) {
123  memcpy(d, s, bpp);
124  }
125  d += bpp;
126  if ((mask << j) & 0x80)
127  s += bpp;
128  }
129  }
130  break;
131  }
132 }
133 
134 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
135 {
136  int i;
137  for (i = 0; i < w; i++) {
138  int a, b, c, p, pa, pb, pc;
139 
140  a = dst[i - bpp];
141  b = top[i];
142  c = top[i - bpp];
143 
144  p = b - c;
145  pc = a - c;
146 
147  pa = abs(p);
148  pb = abs(pc);
149  pc = abs(p + pc);
150 
151  if (pa <= pb && pa <= pc)
152  p = a;
153  else if (pb <= pc)
154  p = b;
155  else
156  p = c;
157  dst[i] = p + src[i];
158  }
159 }
160 
161 #define UNROLL1(bpp, op) {\
162  r = dst[0];\
163  if(bpp >= 2) g = dst[1];\
164  if(bpp >= 3) b = dst[2];\
165  if(bpp >= 4) a = dst[3];\
166  for(; i < size; i+=bpp) {\
167  dst[i+0] = r = op(r, src[i+0], last[i+0]);\
168  if(bpp == 1) continue;\
169  dst[i+1] = g = op(g, src[i+1], last[i+1]);\
170  if(bpp == 2) continue;\
171  dst[i+2] = b = op(b, src[i+2], last[i+2]);\
172  if(bpp == 3) continue;\
173  dst[i+3] = a = op(a, src[i+3], last[i+3]);\
174  }\
175 }
176 
177 #define UNROLL_FILTER(op)\
178  if(bpp == 1) UNROLL1(1, op)\
179  else if(bpp == 2) UNROLL1(2, op)\
180  else if(bpp == 3) UNROLL1(3, op)\
181  else if(bpp == 4) UNROLL1(4, op)\
182  else {\
183  for (; i < size; i += bpp) {\
184  int j;\
185  for (j = 0; j < bpp; j++)\
186  dst[i+j] = op(dst[i+j-bpp], src[i+j], last[i+j]);\
187  }\
188  }
189 
190 /* NOTE: 'dst' can be equal to 'last' */
191 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
192  uint8_t *src, uint8_t *last, int size, int bpp)
193 {
194  int i, p, r, g, b, a;
195 
196  switch (filter_type) {
198  memcpy(dst, src, size);
199  break;
201  for (i = 0; i < bpp; i++) {
202  dst[i] = src[i];
203  }
204  if (bpp == 4) {
205  p = *(int*)dst;
206  for (; i < size; i += bpp) {
207  int s = *(int*)(src + i);
208  p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
209  *(int*)(dst + i) = p;
210  }
211  } else {
212 #define OP_SUB(x,s,l) x+s
214  }
215  break;
216  case PNG_FILTER_VALUE_UP:
217  dsp->add_bytes_l2(dst, src, last, size);
218  break;
220  for (i = 0; i < bpp; i++) {
221  p = (last[i] >> 1);
222  dst[i] = p + src[i];
223  }
224 #define OP_AVG(x,s,l) (((x + l) >> 1) + s) & 0xff
226  break;
228  for (i = 0; i < bpp; i++) {
229  p = last[i];
230  dst[i] = p + src[i];
231  }
232  if (bpp > 1 && size > 4) {
233  // would write off the end of the array if we let it process the last pixel with bpp=3
234  int w = bpp == 4 ? size : size - 3;
235  dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
236  i = w;
237  }
238  ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
239  break;
240  }
241 }
242 
244  const uint8_t *src,
245  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  if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
382  av_log(NULL, AV_LOG_WARNING, "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
383  return 0;
384  }
385  }
386  return 0;
387 }
388 
389 static int decode_frame(AVCodecContext *avctx,
390  void *data, int *got_frame,
391  AVPacket *avpkt)
392 {
393  PNGDecContext * const s = avctx->priv_data;
394  const uint8_t *buf = avpkt->data;
395  int buf_size = avpkt->size;
396  AVFrame *p = data;
397  uint8_t *crow_buf_base = NULL;
398  uint32_t tag, length;
399  int ret;
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 = s->state = 0;
409 
410  /* init the zlib */
411  s->zstream.zalloc = ff_png_zalloc;
412  s->zstream.zfree = ff_png_zfree;
413  s->zstream.opaque = NULL;
414  ret = inflateInit(&s->zstream);
415  if (ret != Z_OK)
416  return -1;
417  for (;;) {
418  if (bytestream2_get_bytes_left(&s->gb) <= 0)
419  goto fail;
420  length = bytestream2_get_be32(&s->gb);
421  if (length > 0x7fffffff)
422  goto fail;
423  tag = bytestream2_get_le32(&s->gb);
424  av_dlog(avctx, "png: tag=%c%c%c%c length=%u\n",
425  (tag & 0xff),
426  ((tag >> 8) & 0xff),
427  ((tag >> 16) & 0xff),
428  ((tag >> 24) & 0xff), length);
429  switch (tag) {
430  case MKTAG('I', 'H', 'D', 'R'):
431  if (length != 13)
432  goto fail;
433  s->width = bytestream2_get_be32(&s->gb);
434  s->height = bytestream2_get_be32(&s->gb);
435  if (av_image_check_size(s->width, s->height, 0, avctx)) {
436  s->width = s->height = 0;
437  goto fail;
438  }
439  s->bit_depth = bytestream2_get_byte(&s->gb);
440  s->color_type = bytestream2_get_byte(&s->gb);
441  s->compression_type = bytestream2_get_byte(&s->gb);
442  s->filter_type = bytestream2_get_byte(&s->gb);
443  s->interlace_type = bytestream2_get_byte(&s->gb);
444  bytestream2_skip(&s->gb, 4); /* crc */
445  s->state |= PNG_IHDR;
446  av_dlog(avctx, "width=%d height=%d depth=%d color_type=%d "
447  "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 = AV_PIX_FMT_RGB24;
467  } else if (s->bit_depth == 8 &&
469  avctx->pix_fmt = AV_PIX_FMT_RGB32;
470  } else if (s->bit_depth == 8 &&
472  avctx->pix_fmt = AV_PIX_FMT_GRAY8;
473  } else if (s->bit_depth == 16 &&
475  avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
476  } else if (s->bit_depth == 16 &&
478  avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
479  } else if (s->bit_depth == 1 &&
481  avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
482  } else if (s->bit_depth == 8 &&
484  avctx->pix_fmt = AV_PIX_FMT_PAL8;
485  } else if (s->bit_depth == 8 &&
487  avctx->pix_fmt = AV_PIX_FMT_Y400A;
488  } else {
489  goto fail;
490  }
491 
492  if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0) {
493  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
494  goto fail;
495  }
497  p->key_frame = 1;
499 
500  /* compute the compressed row size */
501  if (!s->interlace_type) {
502  s->crow_size = s->row_size + 1;
503  } else {
504  s->pass = 0;
506  s->bits_per_pixel,
507  s->width);
508  s->crow_size = s->pass_row_size + 1;
509  }
510  av_dlog(avctx, "row_size=%d crow_size =%d\n",
511  s->row_size, s->crow_size);
512  s->image_buf = p->data[0];
513  s->image_linesize = p->linesize[0];
514  /* copy the palette if needed */
516  memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
517  /* empty row is used if differencing to the first row */
518  s->last_row = av_mallocz(s->row_size);
519  if (!s->last_row)
520  goto fail;
521  if (s->interlace_type ||
523  s->tmp_row = av_malloc(s->row_size);
524  if (!s->tmp_row)
525  goto fail;
526  }
527  /* compressed row */
528  crow_buf_base = av_malloc(s->row_size + 16);
529  if (!crow_buf_base)
530  goto fail;
531 
532  /* we want crow_buf+1 to be 16-byte aligned */
533  s->crow_buf = crow_buf_base + 15;
534  s->zstream.avail_out = s->crow_size;
535  s->zstream.next_out = s->crow_buf;
536  }
537  s->state |= PNG_IDAT;
538  if (png_decode_idat(s, length) < 0)
539  goto fail;
540  bytestream2_skip(&s->gb, 4); /* crc */
541  break;
542  case MKTAG('P', 'L', 'T', 'E'):
543  {
544  int n, i, r, g, b;
545 
546  if ((length % 3) != 0 || length > 256 * 3)
547  goto skip_tag;
548  /* read the palette */
549  n = length / 3;
550  for (i = 0; i < n; i++) {
551  r = bytestream2_get_byte(&s->gb);
552  g = bytestream2_get_byte(&s->gb);
553  b = bytestream2_get_byte(&s->gb);
554  s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
555  }
556  for (; i < 256; i++) {
557  s->palette[i] = (0xff << 24);
558  }
559  s->state |= PNG_PLTE;
560  bytestream2_skip(&s->gb, 4); /* crc */
561  }
562  break;
563  case MKTAG('t', 'R', 'N', 'S'):
564  {
565  int v, i;
566 
567  /* read the transparency. XXX: Only palette mode supported */
569  length > 256 ||
570  !(s->state & PNG_PLTE))
571  goto skip_tag;
572  for (i = 0; i < length; i++) {
573  v = bytestream2_get_byte(&s->gb);
574  s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
575  }
576  bytestream2_skip(&s->gb, 4); /* crc */
577  }
578  break;
579  case MKTAG('I', 'E', 'N', 'D'):
580  if (!(s->state & PNG_ALLIMAGE))
581  goto fail;
582  bytestream2_skip(&s->gb, 4); /* crc */
583  goto exit_loop;
584  default:
585  /* skip tag */
586  skip_tag:
587  bytestream2_skip(&s->gb, length + 4);
588  break;
589  }
590  }
591  exit_loop:
592  /* handle p-frames only if a predecessor frame is available */
593  if (s->prev->data[0]) {
594  if (!(avpkt->flags & AV_PKT_FLAG_KEY)) {
595  int i, j;
596  uint8_t *pd = p->data[0];
597  uint8_t *pd_last = s->prev->data[0];
598 
599  for (j = 0; j < s->height; j++) {
600  for (i = 0; i < s->width * s->bpp; i++) {
601  pd[i] += pd_last[i];
602  }
603  pd += s->image_linesize;
604  pd_last += s->image_linesize;
605  }
606  }
607  }
608 
609  av_frame_unref(s->prev);
610  if ((ret = av_frame_ref(s->prev, p)) < 0)
611  goto fail;
612 
613  *got_frame = 1;
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 {
630  PNGDecContext *s = avctx->priv_data;
631 
632  avctx->color_range = AVCOL_RANGE_JPEG;
633 
634  s->prev = av_frame_alloc();
635  if (!s->prev)
636  return AVERROR(ENOMEM);
637 
638  ff_pngdsp_init(&s->dsp);
639 
640  return 0;
641 }
642 
644 {
645  PNGDecContext *s = avctx->priv_data;
646 
647  av_frame_free(&s->prev);
648 
649  return 0;
650 }
651 
653  .name = "png",
654  .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
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 };