FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
pngenc.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 FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21 #include "avcodec.h"
22 #include "internal.h"
23 #include "bytestream.h"
24 #include "dsputil.h"
25 #include "png.h"
26 
27 #include "libavutil/avassert.h"
28 #include "libavutil/opt.h"
29 
30 /* TODO:
31  * - add 2, 4 and 16 bit depth support
32  */
33 
34 #include <zlib.h>
35 
36 #define IOBUF_SIZE 4096
37 
38 typedef struct PNGEncContext {
39  AVClass *class;
41 
46 
48 
49  z_stream zstream;
51  int dpi; ///< Physical pixel density, in dots per inch, if set
52  int dpm; ///< Physical pixel density, in dots per meter, if set
54 
55 static void png_get_interlaced_row(uint8_t *dst, int row_size,
56  int bits_per_pixel, int pass,
57  const uint8_t *src, int width)
58 {
59  int x, mask, dst_x, j, b, bpp;
60  uint8_t *d;
61  const uint8_t *s;
62  static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
63 
64  mask = masks[pass];
65  switch(bits_per_pixel) {
66  case 1:
67  memset(dst, 0, row_size);
68  dst_x = 0;
69  for(x = 0; x < width; x++) {
70  j = (x & 7);
71  if ((mask << j) & 0x80) {
72  b = (src[x >> 3] >> (7 - j)) & 1;
73  dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
74  dst_x++;
75  }
76  }
77  break;
78  default:
79  bpp = bits_per_pixel >> 3;
80  d = dst;
81  s = src;
82  for(x = 0; x < width; x++) {
83  j = x & 7;
84  if ((mask << j) & 0x80) {
85  memcpy(d, s, bpp);
86  d += bpp;
87  }
88  s += bpp;
89  }
90  break;
91  }
92 }
93 
94 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
95 {
96  int i;
97  for(i = 0; i < w; i++) {
98  int a, b, c, p, pa, pb, pc;
99 
100  a = src[i - bpp];
101  b = top[i];
102  c = top[i - bpp];
103 
104  p = b - c;
105  pc = a - c;
106 
107  pa = abs(p);
108  pb = abs(pc);
109  pc = abs(p + pc);
110 
111  if (pa <= pb && pa <= pc)
112  p = a;
113  else if (pb <= pc)
114  p = b;
115  else
116  p = c;
117  dst[i] = src[i] - p;
118  }
119 }
120 
121 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
122  uint8_t *src, uint8_t *top, int size, int bpp)
123 {
124  int i;
125 
126  switch(filter_type) {
128  memcpy(dst, src, size);
129  break;
131  dsp->diff_bytes(dst, src, src-bpp, size);
132  memcpy(dst, src, bpp);
133  break;
134  case PNG_FILTER_VALUE_UP:
135  dsp->diff_bytes(dst, src, top, size);
136  break;
138  for(i = 0; i < bpp; i++)
139  dst[i] = src[i] - (top[i] >> 1);
140  for(; i < size; i++)
141  dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
142  break;
144  for(i = 0; i < bpp; i++)
145  dst[i] = src[i] - top[i];
146  sub_png_paeth_prediction(dst+i, src+i, top+i, size-i, bpp);
147  break;
148  }
149 }
150 
152  uint8_t *src, uint8_t *top, int size, int bpp)
153 {
154  int pred = s->filter_type;
155  av_assert0(bpp || !pred);
156  if(!top && pred)
157  pred = PNG_FILTER_VALUE_SUB;
158  if(pred == PNG_FILTER_VALUE_MIXED) {
159  int i;
160  int cost, bcost = INT_MAX;
161  uint8_t *buf1 = dst, *buf2 = dst + size + 16;
162  for(pred=0; pred<5; pred++) {
163  png_filter_row(&s->dsp, buf1+1, pred, src, top, size, bpp);
164  buf1[0] = pred;
165  cost = 0;
166  for(i=0; i<=size; i++)
167  cost += abs((int8_t)buf1[i]);
168  if(cost < bcost) {
169  bcost = cost;
170  FFSWAP(uint8_t*, buf1, buf2);
171  }
172  }
173  return buf2;
174  } else {
175  png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
176  dst[0] = pred;
177  return dst;
178  }
179 }
180 
181 static void png_write_chunk(uint8_t **f, uint32_t tag,
182  const uint8_t *buf, int length)
183 {
184  uint32_t crc;
185  uint8_t tagbuf[4];
186 
187  bytestream_put_be32(f, length);
188  crc = crc32(0, Z_NULL, 0);
189  AV_WL32(tagbuf, tag);
190  crc = crc32(crc, tagbuf, 4);
191  bytestream_put_be32(f, av_bswap32(tag));
192  if (length > 0) {
193  crc = crc32(crc, buf, length);
194  memcpy(*f, buf, length);
195  *f += length;
196  }
197  bytestream_put_be32(f, crc);
198 }
199 
200 /* XXX: do filtering */
201 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
202 {
203  int ret;
204 
205  s->zstream.avail_in = size;
206  s->zstream.next_in = (uint8_t *)data;
207  while (s->zstream.avail_in > 0) {
208  ret = deflate(&s->zstream, Z_NO_FLUSH);
209  if (ret != Z_OK)
210  return -1;
211  if (s->zstream.avail_out == 0) {
212  if(s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
213  png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
214  s->zstream.avail_out = IOBUF_SIZE;
215  s->zstream.next_out = s->buf;
216  }
217  }
218  return 0;
219 }
220 
222  const AVFrame *pict, int *got_packet)
223 {
224  PNGEncContext *s = avctx->priv_data;
225  AVFrame * const p= &s->picture;
226  int bit_depth, color_type, y, len, row_size, ret, is_progressive;
227  int bits_per_pixel, pass_row_size, enc_row_size;
228  int64_t max_packet_size;
229  int compression_level;
230  uint8_t *ptr, *top;
231  uint8_t *crow_base = NULL, *crow_buf, *crow;
232  uint8_t *progressive_buf = NULL;
233  uint8_t *top_buf = NULL;
234 
235  *p = *pict;
237  p->key_frame= 1;
238 
239  is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
240  switch(avctx->pix_fmt) {
241  case AV_PIX_FMT_RGBA64BE:
242  bit_depth = 16;
243  color_type = PNG_COLOR_TYPE_RGB_ALPHA;
244  break;
245  case AV_PIX_FMT_RGB48BE:
246  bit_depth = 16;
247  color_type = PNG_COLOR_TYPE_RGB;
248  break;
249  case AV_PIX_FMT_RGBA:
250  bit_depth = 8;
251  color_type = PNG_COLOR_TYPE_RGB_ALPHA;
252  break;
253  case AV_PIX_FMT_RGB24:
254  bit_depth = 8;
255  color_type = PNG_COLOR_TYPE_RGB;
256  break;
257  case AV_PIX_FMT_GRAY16BE:
258  bit_depth = 16;
259  color_type = PNG_COLOR_TYPE_GRAY;
260  break;
261  case AV_PIX_FMT_GRAY8:
262  bit_depth = 8;
263  color_type = PNG_COLOR_TYPE_GRAY;
264  break;
265  case AV_PIX_FMT_GRAY8A:
266  bit_depth = 8;
267  color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
268  break;
270  bit_depth = 1;
271  color_type = PNG_COLOR_TYPE_GRAY;
272  break;
273  case AV_PIX_FMT_PAL8:
274  bit_depth = 8;
275  color_type = PNG_COLOR_TYPE_PALETTE;
276  break;
277  default:
278  return -1;
279  }
280  bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
281  row_size = (avctx->width * bits_per_pixel + 7) >> 3;
282 
283  s->zstream.zalloc = ff_png_zalloc;
284  s->zstream.zfree = ff_png_zfree;
285  s->zstream.opaque = NULL;
286  compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT ?
287  Z_DEFAULT_COMPRESSION :
288  av_clip(avctx->compression_level, 0, 9);
289  ret = deflateInit2(&s->zstream, compression_level,
290  Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
291  if (ret != Z_OK)
292  return -1;
293 
294  enc_row_size = deflateBound(&s->zstream, row_size);
295  max_packet_size = avctx->height * (int64_t)(enc_row_size +
296  ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
298  if (max_packet_size > INT_MAX)
299  return AVERROR(ENOMEM);
300  if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
301  return ret;
302 
303  s->bytestream_start =
304  s->bytestream = pkt->data;
305  s->bytestream_end = pkt->data + pkt->size;
306 
307  crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
308  if (!crow_base)
309  goto fail;
310  crow_buf = crow_base + 15; // pixel data should be aligned, but there's a control byte before it
311  if (is_progressive) {
312  progressive_buf = av_malloc(row_size + 1);
313  if (!progressive_buf)
314  goto fail;
315  }
316  if (is_progressive) {
317  top_buf = av_malloc(row_size + 1);
318  if (!top_buf)
319  goto fail;
320  }
321 
322  /* write png header */
324  s->bytestream += 8;
325 
326  AV_WB32(s->buf, avctx->width);
327  AV_WB32(s->buf + 4, avctx->height);
328  s->buf[8] = bit_depth;
329  s->buf[9] = color_type;
330  s->buf[10] = 0; /* compression type */
331  s->buf[11] = 0; /* filter type */
332  s->buf[12] = is_progressive; /* interlace type */
333 
334  png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
335 
336  if (s->dpm) {
337  AV_WB32(s->buf, s->dpm);
338  AV_WB32(s->buf + 4, s->dpm);
339  s->buf[8] = 1; /* unit specifier is meter */
340  } else {
341  AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
342  AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
343  s->buf[8] = 0; /* unit specifier is unknown */
344  }
345  png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
346 
347  /* put the palette if needed */
348  if (color_type == PNG_COLOR_TYPE_PALETTE) {
349  int has_alpha, alpha, i;
350  unsigned int v;
351  uint32_t *palette;
352  uint8_t *alpha_ptr;
353 
354  palette = (uint32_t *)p->data[1];
355  ptr = s->buf;
356  alpha_ptr = s->buf + 256 * 3;
357  has_alpha = 0;
358  for(i = 0; i < 256; i++) {
359  v = palette[i];
360  alpha = v >> 24;
361  if (alpha != 0xff)
362  has_alpha = 1;
363  *alpha_ptr++ = alpha;
364  bytestream_put_be24(&ptr, v);
365  }
366  png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
367  if (has_alpha) {
368  png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
369  }
370  }
371 
372  /* now put each row */
373  s->zstream.avail_out = IOBUF_SIZE;
374  s->zstream.next_out = s->buf;
375  if (is_progressive) {
376  int pass;
377 
378  for(pass = 0; pass < NB_PASSES; pass++) {
379  /* NOTE: a pass is completely omitted if no pixels would be
380  output */
381  pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
382  if (pass_row_size > 0) {
383  top = NULL;
384  for(y = 0; y < avctx->height; y++) {
385  if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
386  ptr = p->data[0] + y * p->linesize[0];
387  FFSWAP(uint8_t*, progressive_buf, top_buf);
388  png_get_interlaced_row(progressive_buf, pass_row_size,
389  bits_per_pixel, pass,
390  ptr, avctx->width);
391  crow = png_choose_filter(s, crow_buf, progressive_buf, top, pass_row_size, bits_per_pixel>>3);
392  png_write_row(s, crow, pass_row_size + 1);
393  top = progressive_buf;
394  }
395  }
396  }
397  }
398  } else {
399  top = NULL;
400  for(y = 0; y < avctx->height; y++) {
401  ptr = p->data[0] + y * p->linesize[0];
402  crow = png_choose_filter(s, crow_buf, ptr, top, row_size, bits_per_pixel>>3);
403  png_write_row(s, crow, row_size + 1);
404  top = ptr;
405  }
406  }
407  /* compress last bytes */
408  for(;;) {
409  ret = deflate(&s->zstream, Z_FINISH);
410  if (ret == Z_OK || ret == Z_STREAM_END) {
411  len = IOBUF_SIZE - s->zstream.avail_out;
412  if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
413  png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
414  }
415  s->zstream.avail_out = IOBUF_SIZE;
416  s->zstream.next_out = s->buf;
417  if (ret == Z_STREAM_END)
418  break;
419  } else {
420  goto fail;
421  }
422  }
423  png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
424 
425  pkt->size = s->bytestream - s->bytestream_start;
426  pkt->flags |= AV_PKT_FLAG_KEY;
427  *got_packet = 1;
428  ret = 0;
429 
430  the_end:
431  av_free(crow_base);
432  av_free(progressive_buf);
433  av_free(top_buf);
434  deflateEnd(&s->zstream);
435  return ret;
436  fail:
437  ret = -1;
438  goto the_end;
439 }
440 
442  PNGEncContext *s = avctx->priv_data;
443 
444  switch(avctx->pix_fmt) {
445  case AV_PIX_FMT_RGBA:
446  avctx->bits_per_coded_sample = 32;
447  break;
448  case AV_PIX_FMT_RGB24:
449  avctx->bits_per_coded_sample = 24;
450  break;
451  case AV_PIX_FMT_GRAY8:
452  avctx->bits_per_coded_sample = 0x28;
453  break;
455  avctx->bits_per_coded_sample = 1;
456  break;
457  case AV_PIX_FMT_PAL8:
458  avctx->bits_per_coded_sample = 8;
459  }
460 
462  avctx->coded_frame= &s->picture;
463  ff_dsputil_init(&s->dsp, avctx);
464 
466  if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
468 
469  if (s->dpi && s->dpm) {
470  av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
471  return AVERROR(EINVAL);
472  } else if (s->dpi) {
473  s->dpm = s->dpi * 10000 / 254;
474  }
475 
476  return 0;
477 }
478 
479 #define OFFSET(x) offsetof(PNGEncContext, x)
480 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
481 static const AVOption options[] = {
482  {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
483  {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
484  { NULL }
485 };
486 
487 static const AVClass pngenc_class = {
488  .class_name = "PNG encoder",
489  .item_name = av_default_item_name,
490  .option = options,
491  .version = LIBAVUTIL_VERSION_INT,
492 };
493 
495  .name = "png",
496  .type = AVMEDIA_TYPE_VIDEO,
497  .id = AV_CODEC_ID_PNG,
498  .priv_data_size = sizeof(PNGEncContext),
499  .init = png_enc_init,
500  .encode2 = encode_frame,
502  .pix_fmts = (const enum AVPixelFormat[]){
509  },
510  .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
511  .priv_class = &pngenc_class,
512 };