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"
32 #define IOBUF_SIZE 4096
34 typedef struct PNGEncContext {
39 uint8_t *bytestream_start;
40 uint8_t *bytestream_end;
46 uint8_t buf[IOBUF_SIZE];
47 int dpi; ///< Physical pixel density, in dots per inch, if set
48 int dpm; ///< Physical pixel density, in dots per meter, if set
51 static void png_get_interlaced_row(uint8_t *dst, int row_size,
52 int bits_per_pixel, int pass,
53 const uint8_t *src, int width)
55 int x, mask, dst_x, j, b, bpp;
58 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
61 switch(bits_per_pixel) {
63 memset(dst, 0, row_size);
65 for(x = 0; x < width; x++) {
67 if ((mask << j) & 0x80) {
68 b = (src[x >> 3] >> (7 - j)) & 1;
69 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
75 bpp = bits_per_pixel >> 3;
78 for(x = 0; x < width; x++) {
80 if ((mask << j) & 0x80) {
90 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
93 for(i = 0; i < w; i++) {
94 int a, b, c, p, pa, pb, pc;
107 if (pa <= pb && pa <= pc)
117 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
118 uint8_t *src, uint8_t *top, int size, int bpp)
122 switch(filter_type) {
123 case PNG_FILTER_VALUE_NONE:
124 memcpy(dst, src, size);
126 case PNG_FILTER_VALUE_SUB:
127 dsp->diff_bytes(dst, src, src-bpp, size);
128 memcpy(dst, src, bpp);
130 case PNG_FILTER_VALUE_UP:
131 dsp->diff_bytes(dst, src, top, size);
133 case PNG_FILTER_VALUE_AVG:
134 for(i = 0; i < bpp; i++)
135 dst[i] = src[i] - (top[i] >> 1);
137 dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
139 case PNG_FILTER_VALUE_PAETH:
140 for(i = 0; i < bpp; i++)
141 dst[i] = src[i] - top[i];
142 sub_png_paeth_prediction(dst+i, src+i, top+i, size-i, bpp);
147 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
148 uint8_t *src, uint8_t *top, int size, int bpp)
150 int pred = s->filter_type;
151 av_assert0(bpp || !pred);
153 pred = PNG_FILTER_VALUE_SUB;
154 if(pred == PNG_FILTER_VALUE_MIXED) {
156 int cost, bcost = INT_MAX;
157 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
158 for(pred=0; pred<5; pred++) {
159 png_filter_row(&s->dsp, buf1+1, pred, src, top, size, bpp);
162 for(i=0; i<=size; i++)
163 cost += abs((int8_t)buf1[i]);
166 FFSWAP(uint8_t*, buf1, buf2);
171 png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
177 static void png_write_chunk(uint8_t **f, uint32_t tag,
178 const uint8_t *buf, int length)
183 bytestream_put_be32(f, length);
184 crc = crc32(0, Z_NULL, 0);
185 AV_WL32(tagbuf, tag);
186 crc = crc32(crc, tagbuf, 4);
187 bytestream_put_be32(f, av_bswap32(tag));
189 crc = crc32(crc, buf, length);
190 memcpy(*f, buf, length);
193 bytestream_put_be32(f, crc);
196 /* XXX: do filtering */
197 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
201 s->zstream.avail_in = size;
202 s->zstream.next_in = (uint8_t *)data;
203 while (s->zstream.avail_in > 0) {
204 ret = deflate(&s->zstream, Z_NO_FLUSH);
207 if (s->zstream.avail_out == 0) {
208 if(s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
209 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
210 s->zstream.avail_out = IOBUF_SIZE;
211 s->zstream.next_out = s->buf;
217 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
218 const AVFrame *pict, int *got_packet)
220 PNGEncContext *s = avctx->priv_data;
221 AVFrame * const p= &s->picture;
222 int bit_depth, color_type, y, len, row_size, ret, is_progressive;
223 int bits_per_pixel, pass_row_size, enc_row_size;
224 int64_t max_packet_size;
225 int compression_level;
227 uint8_t *crow_base = NULL, *crow_buf, *crow;
228 uint8_t *progressive_buf = NULL;
229 uint8_t *top_buf = NULL;
232 p->pict_type= AV_PICTURE_TYPE_I;
235 is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
236 switch(avctx->pix_fmt) {
237 case AV_PIX_FMT_RGBA64BE:
239 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
241 case AV_PIX_FMT_RGB48BE:
243 color_type = PNG_COLOR_TYPE_RGB;
245 case AV_PIX_FMT_RGBA:
247 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
249 case AV_PIX_FMT_RGB24:
251 color_type = PNG_COLOR_TYPE_RGB;
253 case AV_PIX_FMT_GRAY16BE:
255 color_type = PNG_COLOR_TYPE_GRAY;
257 case AV_PIX_FMT_GRAY8:
259 color_type = PNG_COLOR_TYPE_GRAY;
261 case AV_PIX_FMT_GRAY8A:
263 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
265 case AV_PIX_FMT_MONOBLACK:
267 color_type = PNG_COLOR_TYPE_GRAY;
269 case AV_PIX_FMT_PAL8:
271 color_type = PNG_COLOR_TYPE_PALETTE;
276 bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
277 row_size = (avctx->width * bits_per_pixel + 7) >> 3;
279 s->zstream.zalloc = ff_png_zalloc;
280 s->zstream.zfree = ff_png_zfree;
281 s->zstream.opaque = NULL;
282 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT ?
283 Z_DEFAULT_COMPRESSION :
284 av_clip(avctx->compression_level, 0, 9);
285 ret = deflateInit2(&s->zstream, compression_level,
286 Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
290 enc_row_size = deflateBound(&s->zstream, row_size);
291 max_packet_size = avctx->height * (int64_t)(enc_row_size +
292 ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
293 + FF_MIN_BUFFER_SIZE;
294 if (max_packet_size > INT_MAX)
295 return AVERROR(ENOMEM);
296 if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
299 s->bytestream_start =
300 s->bytestream = pkt->data;
301 s->bytestream_end = pkt->data + pkt->size;
303 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
306 crow_buf = crow_base + 15; // pixel data should be aligned, but there's a control byte before it
307 if (is_progressive) {
308 progressive_buf = av_malloc(row_size + 1);
309 if (!progressive_buf)
312 if (is_progressive) {
313 top_buf = av_malloc(row_size + 1);
318 /* write png header */
319 AV_WB64(s->bytestream, PNGSIG);
322 AV_WB32(s->buf, avctx->width);
323 AV_WB32(s->buf + 4, avctx->height);
324 s->buf[8] = bit_depth;
325 s->buf[9] = color_type;
326 s->buf[10] = 0; /* compression type */
327 s->buf[11] = 0; /* filter type */
328 s->buf[12] = is_progressive; /* interlace type */
330 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
333 AV_WB32(s->buf, s->dpm);
334 AV_WB32(s->buf + 4, s->dpm);
335 s->buf[8] = 1; /* unit specifier is meter */
337 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
338 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
339 s->buf[8] = 0; /* unit specifier is unknown */
341 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
343 /* put the palette if needed */
344 if (color_type == PNG_COLOR_TYPE_PALETTE) {
345 int has_alpha, alpha, i;
350 palette = (uint32_t *)p->data[1];
352 alpha_ptr = s->buf + 256 * 3;
354 for(i = 0; i < 256; i++) {
359 *alpha_ptr++ = alpha;
360 bytestream_put_be24(&ptr, v);
362 png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
364 png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
368 /* now put each row */
369 s->zstream.avail_out = IOBUF_SIZE;
370 s->zstream.next_out = s->buf;
371 if (is_progressive) {
374 for(pass = 0; pass < NB_PASSES; pass++) {
375 /* NOTE: a pass is completely omitted if no pixels would be
377 pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
378 if (pass_row_size > 0) {
380 for(y = 0; y < avctx->height; y++) {
381 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
382 ptr = p->data[0] + y * p->linesize[0];
383 FFSWAP(uint8_t*, progressive_buf, top_buf);
384 png_get_interlaced_row(progressive_buf, pass_row_size,
385 bits_per_pixel, pass,
387 crow = png_choose_filter(s, crow_buf, progressive_buf, top, pass_row_size, bits_per_pixel>>3);
388 png_write_row(s, crow, pass_row_size + 1);
389 top = progressive_buf;
396 for(y = 0; y < avctx->height; y++) {
397 ptr = p->data[0] + y * p->linesize[0];
398 crow = png_choose_filter(s, crow_buf, ptr, top, row_size, bits_per_pixel>>3);
399 png_write_row(s, crow, row_size + 1);
403 /* compress last bytes */
405 ret = deflate(&s->zstream, Z_FINISH);
406 if (ret == Z_OK || ret == Z_STREAM_END) {
407 len = IOBUF_SIZE - s->zstream.avail_out;
408 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
409 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
411 s->zstream.avail_out = IOBUF_SIZE;
412 s->zstream.next_out = s->buf;
413 if (ret == Z_STREAM_END)
419 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
421 pkt->size = s->bytestream - s->bytestream_start;
422 pkt->flags |= AV_PKT_FLAG_KEY;
428 av_free(progressive_buf);
430 deflateEnd(&s->zstream);
437 static av_cold int png_enc_init(AVCodecContext *avctx){
438 PNGEncContext *s = avctx->priv_data;
440 switch(avctx->pix_fmt) {
441 case AV_PIX_FMT_RGBA:
442 avctx->bits_per_coded_sample = 32;
444 case AV_PIX_FMT_RGB24:
445 avctx->bits_per_coded_sample = 24;
447 case AV_PIX_FMT_GRAY8:
448 avctx->bits_per_coded_sample = 0x28;
450 case AV_PIX_FMT_MONOBLACK:
451 avctx->bits_per_coded_sample = 1;
453 case AV_PIX_FMT_PAL8:
454 avctx->bits_per_coded_sample = 8;
457 avcodec_get_frame_defaults(&s->picture);
458 avctx->coded_frame= &s->picture;
459 ff_dsputil_init(&s->dsp, avctx);
461 s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
462 if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
463 s->filter_type = PNG_FILTER_VALUE_NONE;
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);
469 s->dpm = s->dpi * 10000 / 254;
475 #define OFFSET(x) offsetof(PNGEncContext, x)
476 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
477 static const AVOption options[] = {
478 {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
479 {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
483 static const AVClass pngenc_class = {
484 .class_name = "PNG encoder",
485 .item_name = av_default_item_name,
487 .version = LIBAVUTIL_VERSION_INT,
490 AVCodec ff_png_encoder = {
492 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
493 .type = AVMEDIA_TYPE_VIDEO,
494 .id = AV_CODEC_ID_PNG,
495 .priv_data_size = sizeof(PNGEncContext),
496 .init = png_enc_init,
497 .encode2 = encode_frame,
498 .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
499 .pix_fmts = (const enum AVPixelFormat[]){
500 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
501 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
503 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
505 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
507 .priv_class = &pngenc_class,