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