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/libm.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/color_utils.h"
35 #define IOBUF_SIZE 4096
37 typedef struct PNGEncContext {
39 HuffYUVEncDSPContext hdsp;
42 uint8_t *bytestream_start;
43 uint8_t *bytestream_end;
48 uint8_t buf[IOBUF_SIZE];
49 int dpi; ///< Physical pixel density, in dots per inch, if set
50 int dpm; ///< Physical pixel density, in dots per meter, if set
58 static void png_get_interlaced_row(uint8_t *dst, int row_size,
59 int bits_per_pixel, int pass,
60 const uint8_t *src, int width)
62 int x, mask, dst_x, j, b, bpp;
65 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
68 switch (bits_per_pixel) {
70 memset(dst, 0, row_size);
72 for (x = 0; x < width; x++) {
74 if ((mask << j) & 0x80) {
75 b = (src[x >> 3] >> (7 - j)) & 1;
76 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
82 bpp = bits_per_pixel >> 3;
85 for (x = 0; x < width; x++) {
87 if ((mask << j) & 0x80) {
97 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
101 for (i = 0; i < w; i++) {
102 int a, b, c, p, pa, pb, pc;
115 if (pa <= pb && pa <= pc)
125 static void sub_left_prediction(PNGEncContext *c, uint8_t *dst, const uint8_t *src, int bpp, int size)
127 const uint8_t *src1 = src + bpp;
128 const uint8_t *src2 = src;
131 memcpy(dst, src, bpp);
134 unaligned_w = FFMIN(32 - bpp, size);
135 for (x = 0; x < unaligned_w; x++)
136 *dst++ = *src1++ - *src2++;
138 c->hdsp.diff_bytes(dst, src1, src2, size);
141 static void png_filter_row(PNGEncContext *c, uint8_t *dst, int filter_type,
142 uint8_t *src, uint8_t *top, int size, int bpp)
146 switch (filter_type) {
147 case PNG_FILTER_VALUE_NONE:
148 memcpy(dst, src, size);
150 case PNG_FILTER_VALUE_SUB:
151 sub_left_prediction(c, dst, src, bpp, size);
153 case PNG_FILTER_VALUE_UP:
154 c->hdsp.diff_bytes(dst, src, top, size);
156 case PNG_FILTER_VALUE_AVG:
157 for (i = 0; i < bpp; i++)
158 dst[i] = src[i] - (top[i] >> 1);
159 for (; i < size; i++)
160 dst[i] = src[i] - ((src[i - bpp] + top[i]) >> 1);
162 case PNG_FILTER_VALUE_PAETH:
163 for (i = 0; i < bpp; i++)
164 dst[i] = src[i] - top[i];
165 sub_png_paeth_prediction(dst + i, src + i, top + i, size - i, bpp);
170 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
171 uint8_t *src, uint8_t *top, int size, int bpp)
173 int pred = s->filter_type;
174 av_assert0(bpp || !pred);
176 pred = PNG_FILTER_VALUE_SUB;
177 if (pred == PNG_FILTER_VALUE_MIXED) {
179 int cost, bcost = INT_MAX;
180 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
181 for (pred = 0; pred < 5; pred++) {
182 png_filter_row(s, buf1 + 1, pred, src, top, size, bpp);
185 for (i = 0; i <= size; i++)
186 cost += abs((int8_t) buf1[i]);
189 FFSWAP(uint8_t *, buf1, buf2);
194 png_filter_row(s, dst + 1, pred, src, top, size, bpp);
200 static void png_write_chunk(uint8_t **f, uint32_t tag,
201 const uint8_t *buf, int length)
206 bytestream_put_be32(f, length);
207 crc = crc32(0, Z_NULL, 0);
208 AV_WL32(tagbuf, tag);
209 crc = crc32(crc, tagbuf, 4);
210 bytestream_put_be32(f, av_bswap32(tag));
212 crc = crc32(crc, buf, length);
213 memcpy(*f, buf, length);
216 bytestream_put_be32(f, crc);
219 /* XXX: do filtering */
220 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
224 s->zstream.avail_in = size;
225 s->zstream.next_in = data;
226 while (s->zstream.avail_in > 0) {
227 ret = deflate(&s->zstream, Z_NO_FLUSH);
230 if (s->zstream.avail_out == 0) {
231 if (s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
232 png_write_chunk(&s->bytestream,
233 MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
234 s->zstream.avail_out = IOBUF_SIZE;
235 s->zstream.next_out = s->buf;
241 #define AV_WB32_PNG(buf, n) AV_WB32(buf, lrint((n) * 100000))
242 static int png_get_chrm(enum AVColorPrimaries prim, uint8_t *buf)
244 double rx, ry, gx, gy, bx, by, wx = 0.3127, wy = 0.3290;
246 case AVCOL_PRI_BT709:
247 rx = 0.640; ry = 0.330;
248 gx = 0.300; gy = 0.600;
249 bx = 0.150; by = 0.060;
251 case AVCOL_PRI_BT470M:
252 rx = 0.670; ry = 0.330;
253 gx = 0.210; gy = 0.710;
254 bx = 0.140; by = 0.080;
255 wx = 0.310; wy = 0.316;
257 case AVCOL_PRI_BT470BG:
258 rx = 0.640; ry = 0.330;
259 gx = 0.290; gy = 0.600;
260 bx = 0.150; by = 0.060;
262 case AVCOL_PRI_SMPTE170M:
263 case AVCOL_PRI_SMPTE240M:
264 rx = 0.630; ry = 0.340;
265 gx = 0.310; gy = 0.595;
266 bx = 0.155; by = 0.070;
268 case AVCOL_PRI_BT2020:
269 rx = 0.708; ry = 0.292;
270 gx = 0.170; gy = 0.797;
271 bx = 0.131; by = 0.046;
277 AV_WB32_PNG(buf , wx); AV_WB32_PNG(buf + 4 , wy);
278 AV_WB32_PNG(buf + 8 , rx); AV_WB32_PNG(buf + 12, ry);
279 AV_WB32_PNG(buf + 16, gx); AV_WB32_PNG(buf + 20, gy);
280 AV_WB32_PNG(buf + 24, bx); AV_WB32_PNG(buf + 28, by);
284 static int png_get_gama(enum AVColorTransferCharacteristic trc, uint8_t *buf)
286 double gamma = avpriv_get_gamma_from_trc(trc);
290 AV_WB32_PNG(buf, 1.0 / gamma);
294 static int encode_headers(AVCodecContext *avctx, const AVFrame *pict)
296 PNGEncContext *s = avctx->priv_data;
298 /* write png header */
299 AV_WB32(s->buf, avctx->width);
300 AV_WB32(s->buf + 4, avctx->height);
301 s->buf[8] = s->bit_depth;
302 s->buf[9] = s->color_type;
303 s->buf[10] = 0; /* compression type */
304 s->buf[11] = 0; /* filter type */
305 s->buf[12] = s->is_progressive; /* interlace type */
306 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
308 /* write physical information */
310 AV_WB32(s->buf, s->dpm);
311 AV_WB32(s->buf + 4, s->dpm);
312 s->buf[8] = 1; /* unit specifier is meter */
314 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
315 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
316 s->buf[8] = 0; /* unit specifier is unknown */
318 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
320 /* write colorspace information */
321 if (pict->color_primaries == AVCOL_PRI_BT709 &&
322 pict->color_trc == AVCOL_TRC_IEC61966_2_1) {
323 s->buf[0] = 1; /* rendering intent, relative colorimetric by default */
324 png_write_chunk(&s->bytestream, MKTAG('s', 'R', 'G', 'B'), s->buf, 1);
327 if (png_get_chrm(pict->color_primaries, s->buf))
328 png_write_chunk(&s->bytestream, MKTAG('c', 'H', 'R', 'M'), s->buf, 32);
329 if (png_get_gama(pict->color_trc, s->buf))
330 png_write_chunk(&s->bytestream, MKTAG('g', 'A', 'M', 'A'), s->buf, 4);
332 /* put the palette if needed */
333 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
334 int has_alpha, alpha, i;
337 uint8_t *ptr, *alpha_ptr;
339 palette = (uint32_t *)pict->data[1];
341 alpha_ptr = s->buf + 256 * 3;
343 for (i = 0; i < 256; i++) {
348 *alpha_ptr++ = alpha;
349 bytestream_put_be24(&ptr, v);
351 png_write_chunk(&s->bytestream,
352 MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
354 png_write_chunk(&s->bytestream,
355 MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
362 static int encode_frame(AVCodecContext *avctx, const AVFrame *pict)
364 PNGEncContext *s = avctx->priv_data;
365 const AVFrame *const p = pict;
367 int row_size, pass_row_size;
368 uint8_t *ptr, *top, *crow_buf, *crow;
369 uint8_t *crow_base = NULL;
370 uint8_t *progressive_buf = NULL;
371 uint8_t *top_buf = NULL;
373 row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
375 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
377 ret = AVERROR(ENOMEM);
380 // pixel data should be aligned, but there's a control byte before it
381 crow_buf = crow_base + 15;
382 if (s->is_progressive) {
383 progressive_buf = av_malloc(row_size + 1);
384 top_buf = av_malloc(row_size + 1);
385 if (!progressive_buf || !top_buf) {
386 ret = AVERROR(ENOMEM);
392 s->zstream.avail_out = IOBUF_SIZE;
393 s->zstream.next_out = s->buf;
394 if (s->is_progressive) {
397 for (pass = 0; pass < NB_PASSES; pass++) {
398 /* NOTE: a pass is completely omitted if no pixels would be
400 pass_row_size = ff_png_pass_row_size(pass, s->bits_per_pixel, avctx->width);
401 if (pass_row_size > 0) {
403 for (y = 0; y < avctx->height; y++)
404 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
405 ptr = p->data[0] + y * p->linesize[0];
406 FFSWAP(uint8_t *, progressive_buf, top_buf);
407 png_get_interlaced_row(progressive_buf, pass_row_size,
408 s->bits_per_pixel, pass,
410 crow = png_choose_filter(s, crow_buf, progressive_buf,
411 top, pass_row_size, s->bits_per_pixel >> 3);
412 png_write_row(s, crow, pass_row_size + 1);
413 top = progressive_buf;
419 for (y = 0; y < avctx->height; y++) {
420 ptr = p->data[0] + y * p->linesize[0];
421 crow = png_choose_filter(s, crow_buf, ptr, top,
422 row_size, s->bits_per_pixel >> 3);
423 png_write_row(s, crow, row_size + 1);
427 /* compress last bytes */
429 ret = deflate(&s->zstream, Z_FINISH);
430 if (ret == Z_OK || ret == Z_STREAM_END) {
431 len = IOBUF_SIZE - s->zstream.avail_out;
432 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
433 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
435 s->zstream.avail_out = IOBUF_SIZE;
436 s->zstream.next_out = s->buf;
437 if (ret == Z_STREAM_END)
448 av_freep(&crow_base);
449 av_freep(&progressive_buf);
451 deflateReset(&s->zstream);
455 static int encode(AVCodecContext *avctx, AVPacket *pkt,
456 const AVFrame *pict, int *got_packet)
458 PNGEncContext *s = avctx->priv_data;
461 size_t max_packet_size;
463 enc_row_size = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
465 FF_MIN_BUFFER_SIZE + // headers
468 12 * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // IDAT * ceil(enc_row_size / IOBUF_SIZE)
470 if (max_packet_size > INT_MAX)
471 return AVERROR(ENOMEM);
472 ret = ff_alloc_packet2(avctx, pkt, max_packet_size);
476 s->bytestream_start =
477 s->bytestream = pkt->data;
478 s->bytestream_end = pkt->data + pkt->size;
480 AV_WB64(s->bytestream, PNGSIG);
483 ret = encode_headers(avctx, pict);
487 ret = encode_frame(avctx, pict);
491 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
493 pkt->size = s->bytestream - s->bytestream_start;
494 pkt->flags |= AV_PKT_FLAG_KEY;
500 static av_cold int png_enc_init(AVCodecContext *avctx)
502 PNGEncContext *s = avctx->priv_data;
503 int compression_level;
505 switch (avctx->pix_fmt) {
506 case AV_PIX_FMT_RGBA:
507 avctx->bits_per_coded_sample = 32;
509 case AV_PIX_FMT_RGB24:
510 avctx->bits_per_coded_sample = 24;
512 case AV_PIX_FMT_GRAY8:
513 avctx->bits_per_coded_sample = 0x28;
515 case AV_PIX_FMT_MONOBLACK:
516 avctx->bits_per_coded_sample = 1;
518 case AV_PIX_FMT_PAL8:
519 avctx->bits_per_coded_sample = 8;
522 avctx->coded_frame = av_frame_alloc();
523 if (!avctx->coded_frame)
524 return AVERROR(ENOMEM);
526 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
527 avctx->coded_frame->key_frame = 1;
529 ff_huffyuvencdsp_init(&s->hdsp);
531 s->filter_type = av_clip(avctx->prediction_method,
532 PNG_FILTER_VALUE_NONE,
533 PNG_FILTER_VALUE_MIXED);
534 if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
535 s->filter_type = PNG_FILTER_VALUE_NONE;
537 if (s->dpi && s->dpm) {
538 av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
539 return AVERROR(EINVAL);
541 s->dpm = s->dpi * 10000 / 254;
544 s->is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
545 switch (avctx->pix_fmt) {
546 case AV_PIX_FMT_RGBA64BE:
548 s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
550 case AV_PIX_FMT_RGB48BE:
552 s->color_type = PNG_COLOR_TYPE_RGB;
554 case AV_PIX_FMT_RGBA:
556 s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
558 case AV_PIX_FMT_RGB24:
560 s->color_type = PNG_COLOR_TYPE_RGB;
562 case AV_PIX_FMT_GRAY16BE:
564 s->color_type = PNG_COLOR_TYPE_GRAY;
566 case AV_PIX_FMT_GRAY8:
568 s->color_type = PNG_COLOR_TYPE_GRAY;
570 case AV_PIX_FMT_GRAY8A:
572 s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
574 case AV_PIX_FMT_YA16BE:
576 s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
578 case AV_PIX_FMT_MONOBLACK:
580 s->color_type = PNG_COLOR_TYPE_GRAY;
582 case AV_PIX_FMT_PAL8:
584 s->color_type = PNG_COLOR_TYPE_PALETTE;
589 s->bits_per_pixel = ff_png_get_nb_channels(s->color_type) * s->bit_depth;
591 s->zstream.zalloc = ff_png_zalloc;
592 s->zstream.zfree = ff_png_zfree;
593 s->zstream.opaque = NULL;
594 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT
595 ? Z_DEFAULT_COMPRESSION
596 : av_clip(avctx->compression_level, 0, 9);
597 if (deflateInit2(&s->zstream, compression_level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
603 static av_cold int png_enc_close(AVCodecContext *avctx)
605 PNGEncContext *s = avctx->priv_data;
607 deflateEnd(&s->zstream);
608 av_frame_free(&avctx->coded_frame);
612 #define OFFSET(x) offsetof(PNGEncContext, x)
613 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
614 static const AVOption options[] = {
615 {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
616 {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
620 static const AVClass pngenc_class = {
621 .class_name = "PNG encoder",
622 .item_name = av_default_item_name,
624 .version = LIBAVUTIL_VERSION_INT,
627 AVCodec ff_png_encoder = {
629 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
630 .type = AVMEDIA_TYPE_VIDEO,
631 .id = AV_CODEC_ID_PNG,
632 .priv_data_size = sizeof(PNGEncContext),
633 .init = png_enc_init,
634 .close = png_enc_close,
636 .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
637 .pix_fmts = (const enum AVPixelFormat[]) {
638 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
639 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
641 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
642 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
643 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
645 .priv_class = &pngenc_class,