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
38 #define IOBUF_SIZE 4096
40 typedef struct PNGEncContext {
45 uint8_t *bytestream_start;
46 uint8_t *bytestream_end;
52 uint8_t buf[IOBUF_SIZE];
53 int dpi; ///< Physical pixel density, in dots per inch, if set
54 int dpm; ///< Physical pixel density, in dots per meter, if set
57 static void png_get_interlaced_row(uint8_t *dst, int row_size,
58 int bits_per_pixel, int pass,
59 const uint8_t *src, int width)
61 int x, mask, dst_x, j, b, bpp;
64 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
67 switch(bits_per_pixel) {
69 memset(dst, 0, row_size);
71 for(x = 0; x < width; x++) {
73 if ((mask << j) & 0x80) {
74 b = (src[x >> 3] >> (7 - j)) & 1;
75 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
81 bpp = bits_per_pixel >> 3;
84 for(x = 0; x < width; x++) {
86 if ((mask << j) & 0x80) {
96 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
99 for(i = 0; i < w; i++) {
100 int a, b, c, p, pa, pb, pc;
113 if (pa <= pb && pa <= pc)
123 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
124 uint8_t *src, uint8_t *top, int size, int bpp)
128 switch(filter_type) {
129 case PNG_FILTER_VALUE_NONE:
130 memcpy(dst, src, size);
132 case PNG_FILTER_VALUE_SUB:
133 dsp->diff_bytes(dst, src, src-bpp, size);
134 memcpy(dst, src, bpp);
136 case PNG_FILTER_VALUE_UP:
137 dsp->diff_bytes(dst, src, top, size);
139 case PNG_FILTER_VALUE_AVG:
140 for(i = 0; i < bpp; i++)
141 dst[i] = src[i] - (top[i] >> 1);
143 dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
145 case PNG_FILTER_VALUE_PAETH:
146 for(i = 0; i < bpp; i++)
147 dst[i] = src[i] - top[i];
148 sub_png_paeth_prediction(dst+i, src+i, top+i, size-i, bpp);
153 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
154 uint8_t *src, uint8_t *top, int size, int bpp)
156 int pred = s->filter_type;
157 av_assert0(bpp || !pred);
159 pred = PNG_FILTER_VALUE_SUB;
160 if(pred == PNG_FILTER_VALUE_MIXED) {
162 int cost, bcost = INT_MAX;
163 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
164 for(pred=0; pred<5; pred++) {
165 png_filter_row(&s->dsp, buf1+1, pred, src, top, size, bpp);
168 for(i=0; i<=size; i++)
169 cost += abs((int8_t)buf1[i]);
172 FFSWAP(uint8_t*, buf1, buf2);
177 png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
183 static void png_write_chunk(uint8_t **f, uint32_t tag,
184 const uint8_t *buf, int length)
189 bytestream_put_be32(f, length);
190 crc = crc32(0, Z_NULL, 0);
191 AV_WL32(tagbuf, tag);
192 crc = crc32(crc, tagbuf, 4);
193 bytestream_put_be32(f, av_bswap32(tag));
195 crc = crc32(crc, buf, length);
196 memcpy(*f, buf, length);
199 bytestream_put_be32(f, crc);
202 /* XXX: do filtering */
203 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
207 s->zstream.avail_in = size;
208 s->zstream.next_in = (uint8_t *)data;
209 while (s->zstream.avail_in > 0) {
210 ret = deflate(&s->zstream, Z_NO_FLUSH);
213 if (s->zstream.avail_out == 0) {
214 if(s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
215 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
216 s->zstream.avail_out = IOBUF_SIZE;
217 s->zstream.next_out = s->buf;
223 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
224 const AVFrame *pict, int *got_packet)
226 PNGEncContext *s = avctx->priv_data;
227 AVFrame * const p= &s->picture;
228 int bit_depth, color_type, y, len, row_size, ret, is_progressive;
229 int bits_per_pixel, pass_row_size, enc_row_size;
230 int64_t max_packet_size;
231 int compression_level;
233 uint8_t *crow_base = NULL, *crow_buf, *crow;
234 uint8_t *progressive_buf = NULL;
235 uint8_t *top_buf = NULL;
238 p->pict_type= AV_PICTURE_TYPE_I;
241 is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
242 switch(avctx->pix_fmt) {
243 case AV_PIX_FMT_RGBA64BE:
245 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
247 case AV_PIX_FMT_RGB48BE:
249 color_type = PNG_COLOR_TYPE_RGB;
251 case AV_PIX_FMT_RGBA:
253 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
255 case AV_PIX_FMT_RGB24:
257 color_type = PNG_COLOR_TYPE_RGB;
259 case AV_PIX_FMT_GRAY16BE:
261 color_type = PNG_COLOR_TYPE_GRAY;
263 case AV_PIX_FMT_GRAY8:
265 color_type = PNG_COLOR_TYPE_GRAY;
267 case AV_PIX_FMT_GRAY8A:
269 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
271 case AV_PIX_FMT_MONOBLACK:
273 color_type = PNG_COLOR_TYPE_GRAY;
275 case AV_PIX_FMT_PAL8:
277 color_type = PNG_COLOR_TYPE_PALETTE;
282 bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
283 row_size = (avctx->width * bits_per_pixel + 7) >> 3;
285 s->zstream.zalloc = ff_png_zalloc;
286 s->zstream.zfree = ff_png_zfree;
287 s->zstream.opaque = NULL;
288 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT ?
289 Z_DEFAULT_COMPRESSION :
290 av_clip(avctx->compression_level, 0, 9);
291 ret = deflateInit2(&s->zstream, compression_level,
292 Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
296 enc_row_size = deflateBound(&s->zstream, row_size);
297 max_packet_size = avctx->height * (int64_t)(enc_row_size +
298 ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
299 + FF_MIN_BUFFER_SIZE;
300 if (max_packet_size > INT_MAX)
301 return AVERROR(ENOMEM);
302 if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
305 s->bytestream_start =
306 s->bytestream = pkt->data;
307 s->bytestream_end = pkt->data + pkt->size;
309 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
312 crow_buf = crow_base + 15; // pixel data should be aligned, but there's a control byte before it
313 if (is_progressive) {
314 progressive_buf = av_malloc(row_size + 1);
315 if (!progressive_buf)
318 if (is_progressive) {
319 top_buf = av_malloc(row_size + 1);
324 /* write png header */
325 AV_WB64(s->bytestream, PNGSIG);
328 AV_WB32(s->buf, avctx->width);
329 AV_WB32(s->buf + 4, avctx->height);
330 s->buf[8] = bit_depth;
331 s->buf[9] = color_type;
332 s->buf[10] = 0; /* compression type */
333 s->buf[11] = 0; /* filter type */
334 s->buf[12] = is_progressive; /* interlace type */
336 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
339 AV_WB32(s->buf, s->dpm);
340 AV_WB32(s->buf + 4, s->dpm);
341 s->buf[8] = 1; /* unit specifier is meter */
343 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
344 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
345 s->buf[8] = 0; /* unit specifier is unknown */
347 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
349 /* put the palette if needed */
350 if (color_type == PNG_COLOR_TYPE_PALETTE) {
351 int has_alpha, alpha, i;
356 palette = (uint32_t *)p->data[1];
358 alpha_ptr = s->buf + 256 * 3;
360 for(i = 0; i < 256; i++) {
365 *alpha_ptr++ = alpha;
366 bytestream_put_be24(&ptr, v);
368 png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
370 png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
374 /* now put each row */
375 s->zstream.avail_out = IOBUF_SIZE;
376 s->zstream.next_out = s->buf;
377 if (is_progressive) {
380 for(pass = 0; pass < NB_PASSES; pass++) {
381 /* NOTE: a pass is completely omitted if no pixels would be
383 pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
384 if (pass_row_size > 0) {
386 for(y = 0; y < avctx->height; y++) {
387 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
388 ptr = p->data[0] + y * p->linesize[0];
389 FFSWAP(uint8_t*, progressive_buf, top_buf);
390 png_get_interlaced_row(progressive_buf, pass_row_size,
391 bits_per_pixel, pass,
393 crow = png_choose_filter(s, crow_buf, progressive_buf, top, pass_row_size, bits_per_pixel>>3);
394 png_write_row(s, crow, pass_row_size + 1);
395 top = progressive_buf;
402 for(y = 0; y < avctx->height; y++) {
403 ptr = p->data[0] + y * p->linesize[0];
404 crow = png_choose_filter(s, crow_buf, ptr, top, row_size, bits_per_pixel>>3);
405 png_write_row(s, crow, row_size + 1);
409 /* compress last bytes */
411 ret = deflate(&s->zstream, Z_FINISH);
412 if (ret == Z_OK || ret == Z_STREAM_END) {
413 len = IOBUF_SIZE - s->zstream.avail_out;
414 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
415 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
417 s->zstream.avail_out = IOBUF_SIZE;
418 s->zstream.next_out = s->buf;
419 if (ret == Z_STREAM_END)
425 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
427 pkt->size = s->bytestream - s->bytestream_start;
428 pkt->flags |= AV_PKT_FLAG_KEY;
434 av_free(progressive_buf);
436 deflateEnd(&s->zstream);
443 static av_cold int png_enc_init(AVCodecContext *avctx){
444 PNGEncContext *s = avctx->priv_data;
446 switch(avctx->pix_fmt) {
447 case AV_PIX_FMT_RGBA:
448 avctx->bits_per_coded_sample = 32;
450 case AV_PIX_FMT_RGB24:
451 avctx->bits_per_coded_sample = 24;
453 case AV_PIX_FMT_GRAY8:
454 avctx->bits_per_coded_sample = 0x28;
456 case AV_PIX_FMT_MONOBLACK:
457 avctx->bits_per_coded_sample = 1;
459 case AV_PIX_FMT_PAL8:
460 avctx->bits_per_coded_sample = 8;
463 avcodec_get_frame_defaults(&s->picture);
464 avctx->coded_frame= &s->picture;
465 ff_dsputil_init(&s->dsp, avctx);
467 s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
468 if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
469 s->filter_type = PNG_FILTER_VALUE_NONE;
471 if (s->dpi && s->dpm) {
472 av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
473 return AVERROR(EINVAL);
475 s->dpm = s->dpi * 10000 / 254;
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},
489 static const AVClass pngenc_class = {
490 .class_name = "PNG encoder",
491 .item_name = av_default_item_name,
493 .version = LIBAVUTIL_VERSION_INT,
496 AVCodec ff_png_encoder = {
498 .type = AVMEDIA_TYPE_VIDEO,
499 .id = AV_CODEC_ID_PNG,
500 .priv_data_size = sizeof(PNGEncContext),
501 .init = png_enc_init,
502 .encode2 = encode_frame,
503 .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
504 .pix_fmts = (const enum AVPixelFormat[]){
505 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
506 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
508 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
510 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
512 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
513 .priv_class = &pngenc_class,