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"
34 #define IOBUF_SIZE 4096
36 typedef struct PNGEncContext {
38 HuffYUVEncDSPContext hdsp;
41 uint8_t *bytestream_start;
42 uint8_t *bytestream_end;
47 uint8_t buf[IOBUF_SIZE];
48 int dpi; ///< Physical pixel density, in dots per inch, if set
49 int dpm; ///< Physical pixel density, in dots per meter, if set
52 static void png_get_interlaced_row(uint8_t *dst, int row_size,
53 int bits_per_pixel, int pass,
54 const uint8_t *src, int width)
56 int x, mask, dst_x, j, b, bpp;
59 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
62 switch (bits_per_pixel) {
64 memset(dst, 0, row_size);
66 for (x = 0; x < width; x++) {
68 if ((mask << j) & 0x80) {
69 b = (src[x >> 3] >> (7 - j)) & 1;
70 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
76 bpp = bits_per_pixel >> 3;
79 for (x = 0; x < width; x++) {
81 if ((mask << j) & 0x80) {
91 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
95 for (i = 0; i < w; i++) {
96 int a, b, c, p, pa, pb, pc;
109 if (pa <= pb && pa <= pc)
119 static void sub_left_prediction(PNGEncContext *c, uint8_t *dst, const uint8_t *src, int bpp, int size)
121 const uint8_t *src1 = src + bpp;
122 const uint8_t *src2 = src;
125 memcpy(dst, src, bpp);
128 unaligned_w = FFMIN(32 - bpp, size);
129 for (x = 0; x < unaligned_w; x++)
130 *dst++ = *src1++ - *src2++;
132 c->hdsp.diff_bytes(dst, src1, src2, size);
135 static void png_filter_row(PNGEncContext *c, uint8_t *dst, int filter_type,
136 uint8_t *src, uint8_t *top, int size, int bpp)
140 switch (filter_type) {
141 case PNG_FILTER_VALUE_NONE:
142 memcpy(dst, src, size);
144 case PNG_FILTER_VALUE_SUB:
145 sub_left_prediction(c, dst, src, bpp, size);
147 case PNG_FILTER_VALUE_UP:
148 c->hdsp.diff_bytes(dst, src, top, size);
150 case PNG_FILTER_VALUE_AVG:
151 for (i = 0; i < bpp; i++)
152 dst[i] = src[i] - (top[i] >> 1);
153 for (; i < size; i++)
154 dst[i] = src[i] - ((src[i - bpp] + top[i]) >> 1);
156 case PNG_FILTER_VALUE_PAETH:
157 for (i = 0; i < bpp; i++)
158 dst[i] = src[i] - top[i];
159 sub_png_paeth_prediction(dst + i, src + i, top + i, size - i, bpp);
164 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
165 uint8_t *src, uint8_t *top, int size, int bpp)
167 int pred = s->filter_type;
168 av_assert0(bpp || !pred);
170 pred = PNG_FILTER_VALUE_SUB;
171 if (pred == PNG_FILTER_VALUE_MIXED) {
173 int cost, bcost = INT_MAX;
174 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
175 for (pred = 0; pred < 5; pred++) {
176 png_filter_row(s, buf1 + 1, pred, src, top, size, bpp);
179 for (i = 0; i <= size; i++)
180 cost += abs((int8_t) buf1[i]);
183 FFSWAP(uint8_t *, buf1, buf2);
188 png_filter_row(s, dst + 1, pred, src, top, size, bpp);
194 static void png_write_chunk(uint8_t **f, uint32_t tag,
195 const uint8_t *buf, int length)
200 bytestream_put_be32(f, length);
201 crc = crc32(0, Z_NULL, 0);
202 AV_WL32(tagbuf, tag);
203 crc = crc32(crc, tagbuf, 4);
204 bytestream_put_be32(f, av_bswap32(tag));
206 crc = crc32(crc, buf, length);
207 memcpy(*f, buf, length);
210 bytestream_put_be32(f, crc);
213 /* XXX: do filtering */
214 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
218 s->zstream.avail_in = size;
219 s->zstream.next_in = data;
220 while (s->zstream.avail_in > 0) {
221 ret = deflate(&s->zstream, Z_NO_FLUSH);
224 if (s->zstream.avail_out == 0) {
225 if (s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
226 png_write_chunk(&s->bytestream,
227 MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
228 s->zstream.avail_out = IOBUF_SIZE;
229 s->zstream.next_out = s->buf;
235 #define AV_WB32_PNG(buf, n) (AV_WB32(buf, lrint((n) * 100000)))
236 static int png_get_chrm(enum AVColorPrimaries prim, uint8_t *buf)
238 double rx, ry, gx, gy, bx, by, wx = 0.3127, wy = 0.3290;
240 case AVCOL_PRI_BT709:
241 rx = 0.640; ry = 0.330;
242 gx = 0.300; gy = 0.600;
243 bx = 0.150; by = 0.060;
245 case AVCOL_PRI_BT470M:
246 rx = 0.670; ry = 0.330;
247 gx = 0.210; gy = 0.710;
248 bx = 0.140; by = 0.080;
249 wx = 0.310; wy = 0.316;
251 case AVCOL_PRI_BT470BG:
252 rx = 0.640; ry = 0.330;
253 gx = 0.290; gy = 0.600;
254 bx = 0.150; by = 0.060;
256 case AVCOL_PRI_SMPTE170M:
257 case AVCOL_PRI_SMPTE240M:
258 rx = 0.630; ry = 0.340;
259 gx = 0.310; gy = 0.595;
260 bx = 0.155; by = 0.070;
262 case AVCOL_PRI_BT2020:
263 rx = 0.708; ry = 0.292;
264 gx = 0.170; gy = 0.797;
265 bx = 0.131; by = 0.046;
271 AV_WB32_PNG(buf , wx); AV_WB32_PNG(buf + 4 , wy);
272 AV_WB32_PNG(buf + 8 , rx); AV_WB32_PNG(buf + 12, ry);
273 AV_WB32_PNG(buf + 16, gx); AV_WB32_PNG(buf + 20, gy);
274 AV_WB32_PNG(buf + 24, bx); AV_WB32_PNG(buf + 28, by);
278 static int png_get_gama(enum AVColorTransferCharacteristic trc, uint8_t *buf)
282 case AVCOL_TRC_BT709:
283 case AVCOL_TRC_SMPTE170M:
284 case AVCOL_TRC_SMPTE240M:
285 case AVCOL_TRC_BT1361_ECG:
286 case AVCOL_TRC_BT2020_10:
287 case AVCOL_TRC_BT2020_12:
288 /* these share a segmented TRC, but gamma 1.961 is a close
289 approximation, and also more correct for decoding content */
292 case AVCOL_TRC_GAMMA22:
293 case AVCOL_TRC_IEC61966_2_1:
296 case AVCOL_TRC_GAMMA28:
299 case AVCOL_TRC_LINEAR:
306 AV_WB32_PNG(buf, 1.0 / gamma);
310 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
311 const AVFrame *pict, int *got_packet)
313 PNGEncContext *s = avctx->priv_data;
314 const AVFrame *const p = pict;
315 int bit_depth, color_type, y, len, row_size, ret, is_progressive;
316 int bits_per_pixel, pass_row_size, enc_row_size;
317 int64_t max_packet_size;
318 int compression_level;
319 uint8_t *ptr, *top, *crow_buf, *crow;
320 uint8_t *crow_base = NULL;
321 uint8_t *progressive_buf = NULL;
322 uint8_t *top_buf = NULL;
324 is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
325 switch (avctx->pix_fmt) {
326 case AV_PIX_FMT_RGBA64BE:
328 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
330 case AV_PIX_FMT_RGB48BE:
332 color_type = PNG_COLOR_TYPE_RGB;
334 case AV_PIX_FMT_RGBA:
336 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
338 case AV_PIX_FMT_RGB24:
340 color_type = PNG_COLOR_TYPE_RGB;
342 case AV_PIX_FMT_GRAY16BE:
344 color_type = PNG_COLOR_TYPE_GRAY;
346 case AV_PIX_FMT_GRAY8:
348 color_type = PNG_COLOR_TYPE_GRAY;
350 case AV_PIX_FMT_GRAY8A:
352 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
354 case AV_PIX_FMT_YA16BE:
356 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
358 case AV_PIX_FMT_MONOBLACK:
360 color_type = PNG_COLOR_TYPE_GRAY;
362 case AV_PIX_FMT_PAL8:
364 color_type = PNG_COLOR_TYPE_PALETTE;
369 bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
370 row_size = (avctx->width * bits_per_pixel + 7) >> 3;
372 s->zstream.zalloc = ff_png_zalloc;
373 s->zstream.zfree = ff_png_zfree;
374 s->zstream.opaque = NULL;
375 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT
376 ? Z_DEFAULT_COMPRESSION
377 : av_clip(avctx->compression_level, 0, 9);
378 ret = deflateInit2(&s->zstream, compression_level,
379 Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
383 enc_row_size = deflateBound(&s->zstream, row_size);
384 max_packet_size = avctx->height * (int64_t)(enc_row_size +
385 ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
386 + FF_MIN_BUFFER_SIZE;
387 if (max_packet_size > INT_MAX)
388 return AVERROR(ENOMEM);
389 if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
392 s->bytestream_start =
393 s->bytestream = pkt->data;
394 s->bytestream_end = pkt->data + pkt->size;
396 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
399 // pixel data should be aligned, but there's a control byte before it
400 crow_buf = crow_base + 15;
401 if (is_progressive) {
402 progressive_buf = av_malloc(row_size + 1);
403 if (!progressive_buf)
406 if (is_progressive) {
407 top_buf = av_malloc(row_size + 1);
412 /* write png header */
413 AV_WB64(s->bytestream, PNGSIG);
416 AV_WB32(s->buf, avctx->width);
417 AV_WB32(s->buf + 4, avctx->height);
418 s->buf[8] = bit_depth;
419 s->buf[9] = color_type;
420 s->buf[10] = 0; /* compression type */
421 s->buf[11] = 0; /* filter type */
422 s->buf[12] = is_progressive; /* interlace type */
424 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
427 AV_WB32(s->buf, s->dpm);
428 AV_WB32(s->buf + 4, s->dpm);
429 s->buf[8] = 1; /* unit specifier is meter */
431 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
432 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
433 s->buf[8] = 0; /* unit specifier is unknown */
435 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
437 /* write colorspace information */
438 if (pict->color_primaries == AVCOL_PRI_BT709 &&
439 pict->color_trc == AVCOL_TRC_IEC61966_2_1) {
440 s->buf[0] = 1; /* rendering intent, relative colorimetric by default */
441 png_write_chunk(&s->bytestream, MKTAG('s', 'R', 'G', 'B'), s->buf, 1);
444 if (png_get_chrm(pict->color_primaries, s->buf))
445 png_write_chunk(&s->bytestream, MKTAG('c', 'H', 'R', 'M'), s->buf, 32);
446 if (png_get_gama(pict->color_trc, s->buf))
447 png_write_chunk(&s->bytestream, MKTAG('g', 'A', 'M', 'A'), s->buf, 4);
449 /* put the palette if needed */
450 if (color_type == PNG_COLOR_TYPE_PALETTE) {
451 int has_alpha, alpha, i;
456 palette = (uint32_t *)p->data[1];
458 alpha_ptr = s->buf + 256 * 3;
460 for (i = 0; i < 256; i++) {
465 *alpha_ptr++ = alpha;
466 bytestream_put_be24(&ptr, v);
468 png_write_chunk(&s->bytestream,
469 MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
471 png_write_chunk(&s->bytestream,
472 MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
476 /* now put each row */
477 s->zstream.avail_out = IOBUF_SIZE;
478 s->zstream.next_out = s->buf;
479 if (is_progressive) {
482 for (pass = 0; pass < NB_PASSES; pass++) {
483 /* NOTE: a pass is completely omitted if no pixels would be
485 pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
486 if (pass_row_size > 0) {
488 for (y = 0; y < avctx->height; y++)
489 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
490 ptr = p->data[0] + y * p->linesize[0];
491 FFSWAP(uint8_t *, progressive_buf, top_buf);
492 png_get_interlaced_row(progressive_buf, pass_row_size,
493 bits_per_pixel, pass,
495 crow = png_choose_filter(s, crow_buf, progressive_buf,
496 top, pass_row_size, bits_per_pixel >> 3);
497 png_write_row(s, crow, pass_row_size + 1);
498 top = progressive_buf;
504 for (y = 0; y < avctx->height; y++) {
505 ptr = p->data[0] + y * p->linesize[0];
506 crow = png_choose_filter(s, crow_buf, ptr, top,
507 row_size, bits_per_pixel >> 3);
508 png_write_row(s, crow, row_size + 1);
512 /* compress last bytes */
514 ret = deflate(&s->zstream, Z_FINISH);
515 if (ret == Z_OK || ret == Z_STREAM_END) {
516 len = IOBUF_SIZE - s->zstream.avail_out;
517 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
518 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
520 s->zstream.avail_out = IOBUF_SIZE;
521 s->zstream.next_out = s->buf;
522 if (ret == Z_STREAM_END)
528 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
530 pkt->size = s->bytestream - s->bytestream_start;
531 pkt->flags |= AV_PKT_FLAG_KEY;
537 av_free(progressive_buf);
539 deflateEnd(&s->zstream);
546 static av_cold int png_enc_init(AVCodecContext *avctx)
548 PNGEncContext *s = avctx->priv_data;
550 switch (avctx->pix_fmt) {
551 case AV_PIX_FMT_RGBA:
552 avctx->bits_per_coded_sample = 32;
554 case AV_PIX_FMT_RGB24:
555 avctx->bits_per_coded_sample = 24;
557 case AV_PIX_FMT_GRAY8:
558 avctx->bits_per_coded_sample = 0x28;
560 case AV_PIX_FMT_MONOBLACK:
561 avctx->bits_per_coded_sample = 1;
563 case AV_PIX_FMT_PAL8:
564 avctx->bits_per_coded_sample = 8;
567 avctx->coded_frame = av_frame_alloc();
568 if (!avctx->coded_frame)
569 return AVERROR(ENOMEM);
571 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
572 avctx->coded_frame->key_frame = 1;
574 ff_huffyuvencdsp_init(&s->hdsp);
576 s->filter_type = av_clip(avctx->prediction_method,
577 PNG_FILTER_VALUE_NONE,
578 PNG_FILTER_VALUE_MIXED);
579 if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
580 s->filter_type = PNG_FILTER_VALUE_NONE;
582 if (s->dpi && s->dpm) {
583 av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
584 return AVERROR(EINVAL);
586 s->dpm = s->dpi * 10000 / 254;
592 static av_cold int png_enc_close(AVCodecContext *avctx)
594 av_frame_free(&avctx->coded_frame);
598 #define OFFSET(x) offsetof(PNGEncContext, x)
599 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
600 static const AVOption options[] = {
601 {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
602 {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
606 static const AVClass pngenc_class = {
607 .class_name = "PNG encoder",
608 .item_name = av_default_item_name,
610 .version = LIBAVUTIL_VERSION_INT,
613 AVCodec ff_png_encoder = {
615 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
616 .type = AVMEDIA_TYPE_VIDEO,
617 .id = AV_CODEC_ID_PNG,
618 .priv_data_size = sizeof(PNGEncContext),
619 .init = png_enc_init,
620 .close = png_enc_close,
621 .encode2 = encode_frame,
622 .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
623 .pix_fmts = (const enum AVPixelFormat[]) {
624 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
625 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
627 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
628 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
629 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
631 .priv_class = &pngenc_class,