3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
23 #include "bytestream.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/opt.h"
31 * - add 2, 4 and 16 bit depth support
36 #define IOBUF_SIZE 4096
38 typedef struct PNGEncContext {
43 uint8_t *bytestream_start;
44 uint8_t *bytestream_end;
50 uint8_t buf[IOBUF_SIZE];
51 int dpi; ///< Physical pixel density, in dots per inch, if set
52 int dpm; ///< Physical pixel density, in dots per meter, if set
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)
59 int x, mask, dst_x, j, b, bpp;
62 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
65 switch(bits_per_pixel) {
67 memset(dst, 0, row_size);
69 for(x = 0; x < width; x++) {
71 if ((mask << j) & 0x80) {
72 b = (src[x >> 3] >> (7 - j)) & 1;
73 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
79 bpp = bits_per_pixel >> 3;
82 for(x = 0; x < width; x++) {
84 if ((mask << j) & 0x80) {
94 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
97 for(i = 0; i < w; i++) {
98 int a, b, c, p, pa, pb, pc;
111 if (pa <= pb && pa <= pc)
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)
126 switch(filter_type) {
127 case PNG_FILTER_VALUE_NONE:
128 memcpy(dst, src, size);
130 case PNG_FILTER_VALUE_SUB:
131 dsp->diff_bytes(dst, src, src-bpp, size);
132 memcpy(dst, src, bpp);
134 case PNG_FILTER_VALUE_UP:
135 dsp->diff_bytes(dst, src, top, size);
137 case PNG_FILTER_VALUE_AVG:
138 for(i = 0; i < bpp; i++)
139 dst[i] = src[i] - (top[i] >> 1);
141 dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
143 case PNG_FILTER_VALUE_PAETH:
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);
151 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
152 uint8_t *src, uint8_t *top, int size, int bpp)
154 int pred = s->filter_type;
155 av_assert0(bpp || !pred);
157 pred = PNG_FILTER_VALUE_SUB;
158 if(pred == PNG_FILTER_VALUE_MIXED) {
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);
166 for(i=0; i<=size; i++)
167 cost += abs((int8_t)buf1[i]);
170 FFSWAP(uint8_t*, buf1, buf2);
175 png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
181 static void png_write_chunk(uint8_t **f, uint32_t tag,
182 const uint8_t *buf, int length)
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));
193 crc = crc32(crc, buf, length);
194 memcpy(*f, buf, length);
197 bytestream_put_be32(f, crc);
200 /* XXX: do filtering */
201 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
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);
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;
221 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
222 const AVFrame *pict, int *got_packet)
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;
231 uint8_t *crow_base = NULL, *crow_buf, *crow;
232 uint8_t *progressive_buf = NULL;
233 uint8_t *top_buf = NULL;
236 p->pict_type= AV_PICTURE_TYPE_I;
239 is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
240 switch(avctx->pix_fmt) {
241 case AV_PIX_FMT_RGBA64BE:
243 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
245 case AV_PIX_FMT_RGB48BE:
247 color_type = PNG_COLOR_TYPE_RGB;
249 case AV_PIX_FMT_RGBA:
251 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
253 case AV_PIX_FMT_RGB24:
255 color_type = PNG_COLOR_TYPE_RGB;
257 case AV_PIX_FMT_GRAY16BE:
259 color_type = PNG_COLOR_TYPE_GRAY;
261 case AV_PIX_FMT_GRAY8:
263 color_type = PNG_COLOR_TYPE_GRAY;
265 case AV_PIX_FMT_GRAY8A:
267 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
269 case AV_PIX_FMT_MONOBLACK:
271 color_type = PNG_COLOR_TYPE_GRAY;
273 case AV_PIX_FMT_PAL8:
275 color_type = PNG_COLOR_TYPE_PALETTE;
280 bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
281 row_size = (avctx->width * bits_per_pixel + 7) >> 3;
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);
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)
297 + FF_MIN_BUFFER_SIZE;
298 if (max_packet_size > INT_MAX)
299 return AVERROR(ENOMEM);
300 if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
303 s->bytestream_start =
304 s->bytestream = pkt->data;
305 s->bytestream_end = pkt->data + pkt->size;
307 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
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)
316 if (is_progressive) {
317 top_buf = av_malloc(row_size + 1);
322 /* write png header */
323 AV_WB64(s->bytestream, PNGSIG);
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 */
334 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
337 AV_WB32(s->buf, s->dpm);
338 AV_WB32(s->buf + 4, s->dpm);
339 s->buf[8] = 1; /* unit specifier is meter */
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 */
345 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
347 /* put the palette if needed */
348 if (color_type == PNG_COLOR_TYPE_PALETTE) {
349 int has_alpha, alpha, i;
354 palette = (uint32_t *)p->data[1];
356 alpha_ptr = s->buf + 256 * 3;
358 for(i = 0; i < 256; i++) {
363 *alpha_ptr++ = alpha;
364 bytestream_put_be24(&ptr, v);
366 png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
368 png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
372 /* now put each row */
373 s->zstream.avail_out = IOBUF_SIZE;
374 s->zstream.next_out = s->buf;
375 if (is_progressive) {
378 for(pass = 0; pass < NB_PASSES; pass++) {
379 /* NOTE: a pass is completely omitted if no pixels would be
381 pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
382 if (pass_row_size > 0) {
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,
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;
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);
407 /* compress last bytes */
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);
415 s->zstream.avail_out = IOBUF_SIZE;
416 s->zstream.next_out = s->buf;
417 if (ret == Z_STREAM_END)
423 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
425 pkt->size = s->bytestream - s->bytestream_start;
426 pkt->flags |= AV_PKT_FLAG_KEY;
432 av_free(progressive_buf);
434 deflateEnd(&s->zstream);
441 static av_cold int png_enc_init(AVCodecContext *avctx){
442 PNGEncContext *s = avctx->priv_data;
444 switch(avctx->pix_fmt) {
445 case AV_PIX_FMT_RGBA:
446 avctx->bits_per_coded_sample = 32;
448 case AV_PIX_FMT_RGB24:
449 avctx->bits_per_coded_sample = 24;
451 case AV_PIX_FMT_GRAY8:
452 avctx->bits_per_coded_sample = 0x28;
454 case AV_PIX_FMT_MONOBLACK:
455 avctx->bits_per_coded_sample = 1;
457 case AV_PIX_FMT_PAL8:
458 avctx->bits_per_coded_sample = 8;
461 avcodec_get_frame_defaults(&s->picture);
462 avctx->coded_frame= &s->picture;
463 ff_dsputil_init(&s->dsp, avctx);
465 s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
466 if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
467 s->filter_type = PNG_FILTER_VALUE_NONE;
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);
473 s->dpm = s->dpi * 10000 / 254;
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},
487 static const AVClass pngenc_class = {
488 .class_name = "PNG encoder",
489 .item_name = av_default_item_name,
491 .version = LIBAVUTIL_VERSION_INT,
494 AVCodec ff_png_encoder = {
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,
501 .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
502 .pix_fmts = (const enum AVPixelFormat[]){
503 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
504 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
506 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
508 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
510 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
511 .priv_class = &pngenc_class,