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
24 #include "bytestream.h"
25 #include "huffyuvencdsp.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/opt.h"
33 #define IOBUF_SIZE 4096
35 typedef struct PNGEncContext {
37 HuffYUVEncDSPContext hdsp;
40 uint8_t *bytestream_start;
41 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,
94 for (i = 0; i < w; i++) {
95 int a, b, c, p, pa, pb, pc;
108 if (pa <= pb && pa <= pc)
118 static void sub_left_prediction(PNGEncContext *c, uint8_t *dst, const uint8_t *src, int bpp, int size)
120 const uint8_t *src1 = src + bpp;
121 const uint8_t *src2 = src;
124 memcpy(dst, src, bpp);
127 unaligned_w = FFMIN(32 - bpp, size);
128 for (x = 0; x < unaligned_w; x++)
129 *dst++ = *src1++ - *src2++;
131 c->hdsp.diff_bytes(dst, src1, src2, size);
134 static void png_filter_row(PNGEncContext *c, uint8_t *dst, int filter_type,
135 uint8_t *src, uint8_t *top, int size, int bpp)
139 switch (filter_type) {
140 case PNG_FILTER_VALUE_NONE:
141 memcpy(dst, src, size);
143 case PNG_FILTER_VALUE_SUB:
144 sub_left_prediction(c, dst, src, bpp, size);
146 case PNG_FILTER_VALUE_UP:
147 c->hdsp.diff_bytes(dst, src, top, size);
149 case PNG_FILTER_VALUE_AVG:
150 for (i = 0; i < bpp; i++)
151 dst[i] = src[i] - (top[i] >> 1);
152 for (; i < size; i++)
153 dst[i] = src[i] - ((src[i - bpp] + top[i]) >> 1);
155 case PNG_FILTER_VALUE_PAETH:
156 for (i = 0; i < bpp; i++)
157 dst[i] = src[i] - top[i];
158 sub_png_paeth_prediction(dst + i, src + i, top + i, size - i, bpp);
163 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
164 uint8_t *src, uint8_t *top, int size, int bpp)
166 int pred = s->filter_type;
167 av_assert0(bpp || !pred);
169 pred = PNG_FILTER_VALUE_SUB;
170 if (pred == PNG_FILTER_VALUE_MIXED) {
172 int cost, bcost = INT_MAX;
173 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
174 for (pred = 0; pred < 5; pred++) {
175 png_filter_row(s, buf1 + 1, pred, src, top, size, bpp);
178 for (i = 0; i <= size; i++)
179 cost += abs((int8_t) buf1[i]);
182 FFSWAP(uint8_t *, buf1, buf2);
187 png_filter_row(s, dst + 1, pred, src, top, size, bpp);
193 static void png_write_chunk(uint8_t **f, uint32_t tag,
194 const uint8_t *buf, int length)
199 bytestream_put_be32(f, length);
200 crc = crc32(0, Z_NULL, 0);
201 AV_WL32(tagbuf, tag);
202 crc = crc32(crc, tagbuf, 4);
203 bytestream_put_be32(f, av_bswap32(tag));
205 crc = crc32(crc, buf, length);
206 memcpy(*f, buf, length);
209 bytestream_put_be32(f, crc);
212 /* XXX: do filtering */
213 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
217 s->zstream.avail_in = size;
218 s->zstream.next_in = data;
219 while (s->zstream.avail_in > 0) {
220 ret = deflate(&s->zstream, Z_NO_FLUSH);
223 if (s->zstream.avail_out == 0) {
224 if (s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
225 png_write_chunk(&s->bytestream,
226 MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
227 s->zstream.avail_out = IOBUF_SIZE;
228 s->zstream.next_out = s->buf;
234 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
235 const AVFrame *pict, int *got_packet)
237 PNGEncContext *s = avctx->priv_data;
238 const AVFrame *const p = pict;
239 int bit_depth, color_type, y, len, row_size, ret, is_progressive;
240 int bits_per_pixel, pass_row_size, enc_row_size;
241 int64_t max_packet_size;
242 int compression_level;
243 uint8_t *ptr, *top, *crow_buf, *crow;
244 uint8_t *crow_base = NULL;
245 uint8_t *progressive_buf = NULL;
246 uint8_t *top_buf = NULL;
248 is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
249 switch (avctx->pix_fmt) {
250 case AV_PIX_FMT_RGBA64BE:
252 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
254 case AV_PIX_FMT_RGB48BE:
256 color_type = PNG_COLOR_TYPE_RGB;
258 case AV_PIX_FMT_RGBA:
260 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
262 case AV_PIX_FMT_RGB24:
264 color_type = PNG_COLOR_TYPE_RGB;
266 case AV_PIX_FMT_GRAY16BE:
268 color_type = PNG_COLOR_TYPE_GRAY;
270 case AV_PIX_FMT_GRAY8:
272 color_type = PNG_COLOR_TYPE_GRAY;
274 case AV_PIX_FMT_GRAY8A:
276 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
278 case AV_PIX_FMT_YA16BE:
280 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
282 case AV_PIX_FMT_MONOBLACK:
284 color_type = PNG_COLOR_TYPE_GRAY;
286 case AV_PIX_FMT_PAL8:
288 color_type = PNG_COLOR_TYPE_PALETTE;
293 bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
294 row_size = (avctx->width * bits_per_pixel + 7) >> 3;
296 s->zstream.zalloc = ff_png_zalloc;
297 s->zstream.zfree = ff_png_zfree;
298 s->zstream.opaque = NULL;
299 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT
300 ? Z_DEFAULT_COMPRESSION
301 : av_clip(avctx->compression_level, 0, 9);
302 ret = deflateInit2(&s->zstream, compression_level,
303 Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
307 enc_row_size = deflateBound(&s->zstream, row_size);
308 max_packet_size = avctx->height * (int64_t)(enc_row_size +
309 ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
310 + FF_MIN_BUFFER_SIZE;
311 if (max_packet_size > INT_MAX)
312 return AVERROR(ENOMEM);
313 if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
316 s->bytestream_start =
317 s->bytestream = pkt->data;
318 s->bytestream_end = pkt->data + pkt->size;
320 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
323 // pixel data should be aligned, but there's a control byte before it
324 crow_buf = crow_base + 15;
325 if (is_progressive) {
326 progressive_buf = av_malloc(row_size + 1);
327 if (!progressive_buf)
330 if (is_progressive) {
331 top_buf = av_malloc(row_size + 1);
336 /* write png header */
337 AV_WB64(s->bytestream, PNGSIG);
340 AV_WB32(s->buf, avctx->width);
341 AV_WB32(s->buf + 4, avctx->height);
342 s->buf[8] = bit_depth;
343 s->buf[9] = color_type;
344 s->buf[10] = 0; /* compression type */
345 s->buf[11] = 0; /* filter type */
346 s->buf[12] = is_progressive; /* interlace type */
348 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
351 AV_WB32(s->buf, s->dpm);
352 AV_WB32(s->buf + 4, s->dpm);
353 s->buf[8] = 1; /* unit specifier is meter */
355 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
356 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
357 s->buf[8] = 0; /* unit specifier is unknown */
359 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
361 /* put the palette if needed */
362 if (color_type == PNG_COLOR_TYPE_PALETTE) {
363 int has_alpha, alpha, i;
368 palette = (uint32_t *)p->data[1];
370 alpha_ptr = s->buf + 256 * 3;
372 for (i = 0; i < 256; i++) {
377 *alpha_ptr++ = alpha;
378 bytestream_put_be24(&ptr, v);
380 png_write_chunk(&s->bytestream,
381 MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
383 png_write_chunk(&s->bytestream,
384 MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
388 /* now put each row */
389 s->zstream.avail_out = IOBUF_SIZE;
390 s->zstream.next_out = s->buf;
391 if (is_progressive) {
394 for (pass = 0; pass < NB_PASSES; pass++) {
395 /* NOTE: a pass is completely omitted if no pixels would be
397 pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
398 if (pass_row_size > 0) {
400 for (y = 0; y < avctx->height; y++)
401 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
402 ptr = p->data[0] + y * p->linesize[0];
403 FFSWAP(uint8_t *, progressive_buf, top_buf);
404 png_get_interlaced_row(progressive_buf, pass_row_size,
405 bits_per_pixel, pass,
407 crow = png_choose_filter(s, crow_buf, progressive_buf,
408 top, pass_row_size, bits_per_pixel >> 3);
409 png_write_row(s, crow, pass_row_size + 1);
410 top = progressive_buf;
416 for (y = 0; y < avctx->height; y++) {
417 ptr = p->data[0] + y * p->linesize[0];
418 crow = png_choose_filter(s, crow_buf, ptr, top,
419 row_size, bits_per_pixel >> 3);
420 png_write_row(s, crow, row_size + 1);
424 /* compress last bytes */
426 ret = deflate(&s->zstream, Z_FINISH);
427 if (ret == Z_OK || ret == Z_STREAM_END) {
428 len = IOBUF_SIZE - s->zstream.avail_out;
429 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
430 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
432 s->zstream.avail_out = IOBUF_SIZE;
433 s->zstream.next_out = s->buf;
434 if (ret == Z_STREAM_END)
440 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
442 pkt->size = s->bytestream - s->bytestream_start;
443 pkt->flags |= AV_PKT_FLAG_KEY;
449 av_free(progressive_buf);
451 deflateEnd(&s->zstream);
458 static av_cold int png_enc_init(AVCodecContext *avctx)
460 PNGEncContext *s = avctx->priv_data;
462 switch (avctx->pix_fmt) {
463 case AV_PIX_FMT_RGBA:
464 avctx->bits_per_coded_sample = 32;
466 case AV_PIX_FMT_RGB24:
467 avctx->bits_per_coded_sample = 24;
469 case AV_PIX_FMT_GRAY8:
470 avctx->bits_per_coded_sample = 0x28;
472 case AV_PIX_FMT_MONOBLACK:
473 avctx->bits_per_coded_sample = 1;
475 case AV_PIX_FMT_PAL8:
476 avctx->bits_per_coded_sample = 8;
479 avctx->coded_frame = av_frame_alloc();
480 if (!avctx->coded_frame)
481 return AVERROR(ENOMEM);
483 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
484 avctx->coded_frame->key_frame = 1;
486 ff_huffyuvencdsp_init(&s->hdsp);
488 s->filter_type = av_clip(avctx->prediction_method,
489 PNG_FILTER_VALUE_NONE,
490 PNG_FILTER_VALUE_MIXED);
491 if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
492 s->filter_type = PNG_FILTER_VALUE_NONE;
494 if (s->dpi && s->dpm) {
495 av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
496 return AVERROR(EINVAL);
498 s->dpm = s->dpi * 10000 / 254;
504 static av_cold int png_enc_close(AVCodecContext *avctx)
506 av_frame_free(&avctx->coded_frame);
510 #define OFFSET(x) offsetof(PNGEncContext, x)
511 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
512 static const AVOption options[] = {
513 {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
514 {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
518 static const AVClass pngenc_class = {
519 .class_name = "PNG encoder",
520 .item_name = av_default_item_name,
522 .version = LIBAVUTIL_VERSION_INT,
525 AVCodec ff_png_encoder = {
527 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
528 .type = AVMEDIA_TYPE_VIDEO,
529 .id = AV_CODEC_ID_PNG,
530 .priv_data_size = sizeof(PNGEncContext),
531 .init = png_enc_init,
532 .close = png_enc_close,
533 .encode2 = encode_frame,
534 .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
535 .pix_fmts = (const enum AVPixelFormat[]) {
536 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
537 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
539 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
540 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
541 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
543 .priv_class = &pngenc_class,