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