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"
29 #include "libavutil/avassert.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/libm.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/color_utils.h"
34 #include "libavutil/stereo3d.h"
38 #define IOBUF_SIZE 4096
40 typedef struct APNGFctlChunk {
41 uint32_t sequence_number;
42 uint32_t width, height;
43 uint32_t x_offset, y_offset;
44 uint16_t delay_num, delay_den;
45 uint8_t dispose_op, blend_op;
48 typedef struct PNGEncContext {
50 HuffYUVEncDSPContext hdsp;
53 uint8_t *bytestream_start;
54 uint8_t *bytestream_end;
59 uint8_t buf[IOBUF_SIZE];
60 int dpi; ///< Physical pixel density, in dots per inch, if set
61 int dpm; ///< Physical pixel density, in dots per meter, if set
69 uint32_t palette_checksum; // Used to ensure a single unique palette
70 uint32_t sequence_number;
74 APNGFctlChunk last_frame_fctl;
75 uint8_t *last_frame_packet;
76 size_t last_frame_packet_size;
79 static void png_get_interlaced_row(uint8_t *dst, int row_size,
80 int bits_per_pixel, int pass,
81 const uint8_t *src, int width)
83 int x, mask, dst_x, j, b, bpp;
86 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
89 switch (bits_per_pixel) {
91 memset(dst, 0, row_size);
93 for (x = 0; x < width; x++) {
95 if ((mask << j) & 0x80) {
96 b = (src[x >> 3] >> (7 - j)) & 1;
97 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
103 bpp = bits_per_pixel >> 3;
106 for (x = 0; x < width; x++) {
108 if ((mask << j) & 0x80) {
118 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
122 for (i = 0; i < w; i++) {
123 int a, b, c, p, pa, pb, pc;
136 if (pa <= pb && pa <= pc)
146 static void sub_left_prediction(PNGEncContext *c, uint8_t *dst, const uint8_t *src, int bpp, int size)
148 const uint8_t *src1 = src + bpp;
149 const uint8_t *src2 = src;
152 memcpy(dst, src, bpp);
155 unaligned_w = FFMIN(32 - bpp, size);
156 for (x = 0; x < unaligned_w; x++)
157 *dst++ = *src1++ - *src2++;
159 c->hdsp.diff_bytes(dst, src1, src2, size);
162 static void png_filter_row(PNGEncContext *c, uint8_t *dst, int filter_type,
163 uint8_t *src, uint8_t *top, int size, int bpp)
167 switch (filter_type) {
168 case PNG_FILTER_VALUE_NONE:
169 memcpy(dst, src, size);
171 case PNG_FILTER_VALUE_SUB:
172 sub_left_prediction(c, dst, src, bpp, size);
174 case PNG_FILTER_VALUE_UP:
175 c->hdsp.diff_bytes(dst, src, top, size);
177 case PNG_FILTER_VALUE_AVG:
178 for (i = 0; i < bpp; i++)
179 dst[i] = src[i] - (top[i] >> 1);
180 for (; i < size; i++)
181 dst[i] = src[i] - ((src[i - bpp] + top[i]) >> 1);
183 case PNG_FILTER_VALUE_PAETH:
184 for (i = 0; i < bpp; i++)
185 dst[i] = src[i] - top[i];
186 sub_png_paeth_prediction(dst + i, src + i, top + i, size - i, bpp);
191 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
192 uint8_t *src, uint8_t *top, int size, int bpp)
194 int pred = s->filter_type;
195 av_assert0(bpp || !pred);
197 pred = PNG_FILTER_VALUE_SUB;
198 if (pred == PNG_FILTER_VALUE_MIXED) {
200 int cost, bcost = INT_MAX;
201 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
202 for (pred = 0; pred < 5; pred++) {
203 png_filter_row(s, buf1 + 1, pred, src, top, size, bpp);
206 for (i = 0; i <= size; i++)
207 cost += abs((int8_t) buf1[i]);
210 FFSWAP(uint8_t *, buf1, buf2);
215 png_filter_row(s, dst + 1, pred, src, top, size, bpp);
221 static void png_write_chunk(uint8_t **f, uint32_t tag,
222 const uint8_t *buf, int length)
224 const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
228 bytestream_put_be32(f, length);
229 AV_WL32(tagbuf, tag);
230 crc = av_crc(crc_table, crc, tagbuf, 4);
231 bytestream_put_be32(f, av_bswap32(tag));
233 crc = av_crc(crc_table, crc, buf, length);
234 memcpy(*f, buf, length);
237 bytestream_put_be32(f, ~crc);
240 static void png_write_image_data(AVCodecContext *avctx,
241 const uint8_t *buf, int length)
243 PNGEncContext *s = avctx->priv_data;
244 const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
247 if (avctx->codec_id == AV_CODEC_ID_PNG || avctx->frame_number == 0) {
248 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), buf, length);
252 bytestream_put_be32(&s->bytestream, length + 4);
254 bytestream_put_be32(&s->bytestream, MKBETAG('f', 'd', 'A', 'T'));
255 bytestream_put_be32(&s->bytestream, s->sequence_number);
256 crc = av_crc(crc_table, crc, s->bytestream - 8, 8);
258 crc = av_crc(crc_table, crc, buf, length);
259 memcpy(s->bytestream, buf, length);
260 s->bytestream += length;
262 bytestream_put_be32(&s->bytestream, ~crc);
264 ++s->sequence_number;
267 /* XXX: do filtering */
268 static int png_write_row(AVCodecContext *avctx, const uint8_t *data, int size)
270 PNGEncContext *s = avctx->priv_data;
273 s->zstream.avail_in = size;
274 s->zstream.next_in = data;
275 while (s->zstream.avail_in > 0) {
276 ret = deflate(&s->zstream, Z_NO_FLUSH);
279 if (s->zstream.avail_out == 0) {
280 if (s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
281 png_write_image_data(avctx, s->buf, IOBUF_SIZE);
282 s->zstream.avail_out = IOBUF_SIZE;
283 s->zstream.next_out = s->buf;
289 #define AV_WB32_PNG(buf, n) AV_WB32(buf, lrint((n) * 100000))
290 static int png_get_chrm(enum AVColorPrimaries prim, uint8_t *buf)
292 double rx, ry, gx, gy, bx, by, wx = 0.3127, wy = 0.3290;
294 case AVCOL_PRI_BT709:
295 rx = 0.640; ry = 0.330;
296 gx = 0.300; gy = 0.600;
297 bx = 0.150; by = 0.060;
299 case AVCOL_PRI_BT470M:
300 rx = 0.670; ry = 0.330;
301 gx = 0.210; gy = 0.710;
302 bx = 0.140; by = 0.080;
303 wx = 0.310; wy = 0.316;
305 case AVCOL_PRI_BT470BG:
306 rx = 0.640; ry = 0.330;
307 gx = 0.290; gy = 0.600;
308 bx = 0.150; by = 0.060;
310 case AVCOL_PRI_SMPTE170M:
311 case AVCOL_PRI_SMPTE240M:
312 rx = 0.630; ry = 0.340;
313 gx = 0.310; gy = 0.595;
314 bx = 0.155; by = 0.070;
316 case AVCOL_PRI_BT2020:
317 rx = 0.708; ry = 0.292;
318 gx = 0.170; gy = 0.797;
319 bx = 0.131; by = 0.046;
325 AV_WB32_PNG(buf , wx); AV_WB32_PNG(buf + 4 , wy);
326 AV_WB32_PNG(buf + 8 , rx); AV_WB32_PNG(buf + 12, ry);
327 AV_WB32_PNG(buf + 16, gx); AV_WB32_PNG(buf + 20, gy);
328 AV_WB32_PNG(buf + 24, bx); AV_WB32_PNG(buf + 28, by);
332 static int png_get_gama(enum AVColorTransferCharacteristic trc, uint8_t *buf)
334 double gamma = avpriv_get_gamma_from_trc(trc);
338 AV_WB32_PNG(buf, 1.0 / gamma);
342 static int encode_headers(AVCodecContext *avctx, const AVFrame *pict)
344 AVFrameSideData *side_data;
345 PNGEncContext *s = avctx->priv_data;
347 /* write png header */
348 AV_WB32(s->buf, avctx->width);
349 AV_WB32(s->buf + 4, avctx->height);
350 s->buf[8] = s->bit_depth;
351 s->buf[9] = s->color_type;
352 s->buf[10] = 0; /* compression type */
353 s->buf[11] = 0; /* filter type */
354 s->buf[12] = s->is_progressive; /* interlace type */
355 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
357 /* write physical information */
359 AV_WB32(s->buf, s->dpm);
360 AV_WB32(s->buf + 4, s->dpm);
361 s->buf[8] = 1; /* unit specifier is meter */
363 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
364 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
365 s->buf[8] = 0; /* unit specifier is unknown */
367 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
369 /* write stereoscopic information */
370 side_data = av_frame_get_side_data(pict, AV_FRAME_DATA_STEREO3D);
372 AVStereo3D *stereo3d = (AVStereo3D *)side_data->data;
373 switch (stereo3d->type) {
374 case AV_STEREO3D_SIDEBYSIDE:
375 s->buf[0] = ((stereo3d->flags & AV_STEREO3D_FLAG_INVERT) == 0) ? 1 : 0;
376 png_write_chunk(&s->bytestream, MKTAG('s', 'T', 'E', 'R'), s->buf, 1);
381 av_log(avctx, AV_LOG_WARNING, "Only side-by-side stereo3d flag can be defined within sTER chunk\n");
386 /* write colorspace information */
387 if (pict->color_primaries == AVCOL_PRI_BT709 &&
388 pict->color_trc == AVCOL_TRC_IEC61966_2_1) {
389 s->buf[0] = 1; /* rendering intent, relative colorimetric by default */
390 png_write_chunk(&s->bytestream, MKTAG('s', 'R', 'G', 'B'), s->buf, 1);
393 if (png_get_chrm(pict->color_primaries, s->buf))
394 png_write_chunk(&s->bytestream, MKTAG('c', 'H', 'R', 'M'), s->buf, 32);
395 if (png_get_gama(pict->color_trc, s->buf))
396 png_write_chunk(&s->bytestream, MKTAG('g', 'A', 'M', 'A'), s->buf, 4);
398 /* put the palette if needed */
399 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
400 int has_alpha, alpha, i;
403 uint8_t *ptr, *alpha_ptr;
405 palette = (uint32_t *)pict->data[1];
407 alpha_ptr = s->buf + 256 * 3;
409 for (i = 0; i < 256; i++) {
414 *alpha_ptr++ = alpha;
415 bytestream_put_be24(&ptr, v);
417 png_write_chunk(&s->bytestream,
418 MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
420 png_write_chunk(&s->bytestream,
421 MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
428 static int encode_frame(AVCodecContext *avctx, const AVFrame *pict)
430 PNGEncContext *s = avctx->priv_data;
431 const AVFrame *const p = pict;
433 int row_size, pass_row_size;
434 uint8_t *ptr, *top, *crow_buf, *crow;
435 uint8_t *crow_base = NULL;
436 uint8_t *progressive_buf = NULL;
437 uint8_t *top_buf = NULL;
439 row_size = (pict->width * s->bits_per_pixel + 7) >> 3;
441 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
443 ret = AVERROR(ENOMEM);
446 // pixel data should be aligned, but there's a control byte before it
447 crow_buf = crow_base + 15;
448 if (s->is_progressive) {
449 progressive_buf = av_malloc(row_size + 1);
450 top_buf = av_malloc(row_size + 1);
451 if (!progressive_buf || !top_buf) {
452 ret = AVERROR(ENOMEM);
458 s->zstream.avail_out = IOBUF_SIZE;
459 s->zstream.next_out = s->buf;
460 if (s->is_progressive) {
463 for (pass = 0; pass < NB_PASSES; pass++) {
464 /* NOTE: a pass is completely omitted if no pixels would be
466 pass_row_size = ff_png_pass_row_size(pass, s->bits_per_pixel, pict->width);
467 if (pass_row_size > 0) {
469 for (y = 0; y < pict->height; y++)
470 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
471 ptr = p->data[0] + y * p->linesize[0];
472 FFSWAP(uint8_t *, progressive_buf, top_buf);
473 png_get_interlaced_row(progressive_buf, pass_row_size,
474 s->bits_per_pixel, pass,
476 crow = png_choose_filter(s, crow_buf, progressive_buf,
477 top, pass_row_size, s->bits_per_pixel >> 3);
478 png_write_row(avctx, crow, pass_row_size + 1);
479 top = progressive_buf;
485 for (y = 0; y < pict->height; y++) {
486 ptr = p->data[0] + y * p->linesize[0];
487 crow = png_choose_filter(s, crow_buf, ptr, top,
488 row_size, s->bits_per_pixel >> 3);
489 png_write_row(avctx, crow, row_size + 1);
493 /* compress last bytes */
495 ret = deflate(&s->zstream, Z_FINISH);
496 if (ret == Z_OK || ret == Z_STREAM_END) {
497 len = IOBUF_SIZE - s->zstream.avail_out;
498 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
499 png_write_image_data(avctx, s->buf, len);
501 s->zstream.avail_out = IOBUF_SIZE;
502 s->zstream.next_out = s->buf;
503 if (ret == Z_STREAM_END)
514 av_freep(&crow_base);
515 av_freep(&progressive_buf);
517 deflateReset(&s->zstream);
521 static int encode_png(AVCodecContext *avctx, AVPacket *pkt,
522 const AVFrame *pict, int *got_packet)
524 PNGEncContext *s = avctx->priv_data;
527 size_t max_packet_size;
529 enc_row_size = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
531 AV_INPUT_BUFFER_MIN_SIZE + // headers
534 12 * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // IDAT * ceil(enc_row_size / IOBUF_SIZE)
536 if (max_packet_size > INT_MAX)
537 return AVERROR(ENOMEM);
538 ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
542 s->bytestream_start =
543 s->bytestream = pkt->data;
544 s->bytestream_end = pkt->data + pkt->size;
546 AV_WB64(s->bytestream, PNGSIG);
549 ret = encode_headers(avctx, pict);
553 ret = encode_frame(avctx, pict);
557 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
559 pkt->size = s->bytestream - s->bytestream_start;
560 pkt->flags |= AV_PKT_FLAG_KEY;
566 static int apng_do_inverse_blend(AVFrame *output, const AVFrame *input,
567 APNGFctlChunk *fctl_chunk, uint8_t bpp)
569 // output: background, input: foreground
570 // output the image such that when blended with the background, will produce the foreground
573 unsigned int leftmost_x = input->width;
574 unsigned int rightmost_x = 0;
575 unsigned int topmost_y = input->height;
576 unsigned int bottommost_y = 0;
577 const uint8_t *input_data = input->data[0];
578 uint8_t *output_data = output->data[0];
579 ptrdiff_t input_linesize = input->linesize[0];
580 ptrdiff_t output_linesize = output->linesize[0];
582 // Find bounding box of changes
583 for (y = 0; y < input->height; ++y) {
584 for (x = 0; x < input->width; ++x) {
585 if (!memcmp(input_data + bpp * x, output_data + bpp * x, bpp))
590 if (x >= rightmost_x)
594 if (y >= bottommost_y)
595 bottommost_y = y + 1;
598 input_data += input_linesize;
599 output_data += output_linesize;
602 if (leftmost_x == input->width && rightmost_x == 0) {
604 // APNG does not support empty frames, so we make it a 1x1 frame
605 leftmost_x = topmost_y = 0;
606 rightmost_x = bottommost_y = 1;
609 // Do actual inverse blending
610 if (fctl_chunk->blend_op == APNG_BLEND_OP_SOURCE) {
611 output_data = output->data[0];
612 for (y = topmost_y; y < bottommost_y; ++y) {
614 input->data[0] + input_linesize * y + bpp * leftmost_x,
615 bpp * (rightmost_x - leftmost_x));
616 output_data += output_linesize;
618 } else { // APNG_BLEND_OP_OVER
619 size_t transparent_palette_index;
622 switch (input->format) {
623 case AV_PIX_FMT_RGBA64BE:
624 case AV_PIX_FMT_YA16BE:
625 case AV_PIX_FMT_RGBA:
626 case AV_PIX_FMT_GRAY8A:
629 case AV_PIX_FMT_PAL8:
630 palette = (uint32_t*)input->data[1];
631 for (transparent_palette_index = 0; transparent_palette_index < 256; ++transparent_palette_index)
632 if (palette[transparent_palette_index] >> 24 == 0)
637 // No alpha, so blending not possible
641 for (y = topmost_y; y < bottommost_y; ++y) {
642 uint8_t *foreground = input->data[0] + input_linesize * y + bpp * leftmost_x;
643 uint8_t *background = output->data[0] + output_linesize * y + bpp * leftmost_x;
644 output_data = output->data[0] + output_linesize * (y - topmost_y);
645 for (x = leftmost_x; x < rightmost_x; ++x, foreground += bpp, background += bpp, output_data += bpp) {
646 if (!memcmp(foreground, background, bpp)) {
647 if (input->format == AV_PIX_FMT_PAL8) {
648 if (transparent_palette_index == 256) {
649 // Need fully transparent colour, but none exists
653 *output_data = transparent_palette_index;
655 memset(output_data, 0, bpp);
660 // Check for special alpha values, since full inverse
661 // alpha-on-alpha blending is rarely possible, and when
662 // possible, doesn't compress much better than
663 // APNG_BLEND_OP_SOURCE blending
664 switch (input->format) {
665 case AV_PIX_FMT_RGBA64BE:
666 if (((uint16_t*)foreground)[3] == 0xffff ||
667 ((uint16_t*)background)[3] == 0)
671 case AV_PIX_FMT_YA16BE:
672 if (((uint16_t*)foreground)[1] == 0xffff ||
673 ((uint16_t*)background)[1] == 0)
677 case AV_PIX_FMT_RGBA:
678 if (foreground[3] == 0xff || background[3] == 0)
682 case AV_PIX_FMT_GRAY8A:
683 if (foreground[1] == 0xff || background[1] == 0)
687 case AV_PIX_FMT_PAL8:
688 if (palette[*foreground] >> 24 == 0xff ||
689 palette[*background] >> 24 == 0)
694 memmove(output_data, foreground, bpp);
699 output->width = rightmost_x - leftmost_x;
700 output->height = bottommost_y - topmost_y;
701 fctl_chunk->width = output->width;
702 fctl_chunk->height = output->height;
703 fctl_chunk->x_offset = leftmost_x;
704 fctl_chunk->y_offset = topmost_y;
709 static int apng_encode_frame(AVCodecContext *avctx, const AVFrame *pict,
710 APNGFctlChunk *best_fctl_chunk, APNGFctlChunk *best_last_fctl_chunk)
712 PNGEncContext *s = avctx->priv_data;
716 uint8_t bpp = (s->bits_per_pixel + 7) >> 3;
717 uint8_t *original_bytestream, *original_bytestream_end;
718 uint8_t *temp_bytestream = 0, *temp_bytestream_end;
719 uint32_t best_sequence_number;
720 uint8_t *best_bytestream;
721 size_t best_bytestream_size = SIZE_MAX;
722 APNGFctlChunk last_fctl_chunk = *best_last_fctl_chunk;
723 APNGFctlChunk fctl_chunk = *best_fctl_chunk;
725 if (avctx->frame_number == 0) {
726 best_fctl_chunk->width = pict->width;
727 best_fctl_chunk->height = pict->height;
728 best_fctl_chunk->x_offset = 0;
729 best_fctl_chunk->y_offset = 0;
730 best_fctl_chunk->blend_op = APNG_BLEND_OP_SOURCE;
731 return encode_frame(avctx, pict);
734 diffFrame = av_frame_alloc();
736 return AVERROR(ENOMEM);
738 diffFrame->format = pict->format;
739 diffFrame->width = pict->width;
740 diffFrame->height = pict->height;
741 if ((ret = av_frame_get_buffer(diffFrame, 32)) < 0)
744 original_bytestream = s->bytestream;
745 original_bytestream_end = s->bytestream_end;
747 temp_bytestream = av_malloc(original_bytestream_end - original_bytestream);
748 temp_bytestream_end = temp_bytestream + (original_bytestream_end - original_bytestream);
749 if (!temp_bytestream) {
750 ret = AVERROR(ENOMEM);
754 for (last_fctl_chunk.dispose_op = 0; last_fctl_chunk.dispose_op < 3; ++last_fctl_chunk.dispose_op) {
755 // 0: APNG_DISPOSE_OP_NONE
756 // 1: APNG_DISPOSE_OP_BACKGROUND
757 // 2: APNG_DISPOSE_OP_PREVIOUS
759 for (fctl_chunk.blend_op = 0; fctl_chunk.blend_op < 2; ++fctl_chunk.blend_op) {
760 // 0: APNG_BLEND_OP_SOURCE
761 // 1: APNG_BLEND_OP_OVER
763 uint32_t original_sequence_number = s->sequence_number, sequence_number;
764 uint8_t *bytestream_start = s->bytestream;
765 size_t bytestream_size;
768 if (last_fctl_chunk.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
769 memcpy(diffFrame->data[0], s->last_frame->data[0],
770 s->last_frame->linesize[0] * s->last_frame->height);
772 if (last_fctl_chunk.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
773 for (y = last_fctl_chunk.y_offset; y < last_fctl_chunk.y_offset + last_fctl_chunk.height; ++y) {
774 size_t row_start = s->last_frame->linesize[0] * y + bpp * last_fctl_chunk.x_offset;
775 memset(diffFrame->data[0] + row_start, 0, bpp * last_fctl_chunk.width);
782 memcpy(diffFrame->data[0], s->prev_frame->data[0],
783 s->prev_frame->linesize[0] * s->prev_frame->height);
786 // Do inverse blending
787 if (apng_do_inverse_blend(diffFrame, pict, &fctl_chunk, bpp) < 0)
791 ret = encode_frame(avctx, diffFrame);
792 sequence_number = s->sequence_number;
793 s->sequence_number = original_sequence_number;
794 bytestream_size = s->bytestream - bytestream_start;
795 s->bytestream = bytestream_start;
799 if (bytestream_size < best_bytestream_size) {
800 *best_fctl_chunk = fctl_chunk;
801 *best_last_fctl_chunk = last_fctl_chunk;
803 best_sequence_number = sequence_number;
804 best_bytestream = s->bytestream;
805 best_bytestream_size = bytestream_size;
807 if (best_bytestream == original_bytestream) {
808 s->bytestream = temp_bytestream;
809 s->bytestream_end = temp_bytestream_end;
811 s->bytestream = original_bytestream;
812 s->bytestream_end = original_bytestream_end;
818 s->sequence_number = best_sequence_number;
819 s->bytestream = original_bytestream + best_bytestream_size;
820 s->bytestream_end = original_bytestream_end;
821 if (best_bytestream != original_bytestream)
822 memcpy(original_bytestream, best_bytestream, best_bytestream_size);
827 av_freep(&temp_bytestream);
828 av_frame_free(&diffFrame);
832 static int encode_apng(AVCodecContext *avctx, AVPacket *pkt,
833 const AVFrame *pict, int *got_packet)
835 PNGEncContext *s = avctx->priv_data;
838 size_t max_packet_size;
839 APNGFctlChunk fctl_chunk = {0};
841 if (pict && avctx->codec_id == AV_CODEC_ID_APNG && s->color_type == PNG_COLOR_TYPE_PALETTE) {
842 uint32_t checksum = ~av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), ~0U, pict->data[1], 256 * sizeof(uint32_t));
844 if (avctx->frame_number == 0) {
845 s->palette_checksum = checksum;
846 } else if (checksum != s->palette_checksum) {
847 av_log(avctx, AV_LOG_ERROR,
848 "Input contains more than one unique palette. APNG does not support multiple palettes.\n");
853 enc_row_size = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
855 AV_INPUT_BUFFER_MIN_SIZE + // headers
858 (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE)
860 if (max_packet_size > INT_MAX)
861 return AVERROR(ENOMEM);
863 if (avctx->frame_number == 0) {
865 return AVERROR(EINVAL);
867 s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE);
868 if (!avctx->extradata)
869 return AVERROR(ENOMEM);
871 ret = encode_headers(avctx, pict);
875 avctx->extradata_size = s->bytestream - avctx->extradata;
877 s->last_frame_packet = av_malloc(max_packet_size);
878 if (!s->last_frame_packet)
879 return AVERROR(ENOMEM);
880 } else if (s->last_frame) {
881 ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
885 memcpy(pkt->data, s->last_frame_packet, s->last_frame_packet_size);
886 pkt->size = s->last_frame_packet_size;
887 pkt->pts = pkt->dts = s->last_frame->pts;
891 s->bytestream_start =
892 s->bytestream = s->last_frame_packet;
893 s->bytestream_end = s->bytestream + max_packet_size;
895 // We're encoding the frame first, so we have to do a bit of shuffling around
896 // to have the image data write to the correct place in the buffer
897 fctl_chunk.sequence_number = s->sequence_number;
898 ++s->sequence_number;
899 s->bytestream += 26 + 12;
901 ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl);
905 fctl_chunk.delay_num = 0; // delay filled in during muxing
906 fctl_chunk.delay_den = 0;
908 s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE;
912 uint8_t* last_fctl_chunk_start = pkt->data;
915 AV_WB32(buf + 0, s->last_frame_fctl.sequence_number);
916 AV_WB32(buf + 4, s->last_frame_fctl.width);
917 AV_WB32(buf + 8, s->last_frame_fctl.height);
918 AV_WB32(buf + 12, s->last_frame_fctl.x_offset);
919 AV_WB32(buf + 16, s->last_frame_fctl.y_offset);
920 AV_WB16(buf + 20, s->last_frame_fctl.delay_num);
921 AV_WB16(buf + 22, s->last_frame_fctl.delay_den);
922 buf[24] = s->last_frame_fctl.dispose_op;
923 buf[25] = s->last_frame_fctl.blend_op;
924 png_write_chunk(&last_fctl_chunk_start, MKTAG('f', 'c', 'T', 'L'), buf, 26);
930 if (!s->last_frame) {
931 s->last_frame = av_frame_alloc();
933 return AVERROR(ENOMEM);
934 } else if (s->last_frame_fctl.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
935 if (!s->prev_frame) {
936 s->prev_frame = av_frame_alloc();
938 return AVERROR(ENOMEM);
940 s->prev_frame->format = pict->format;
941 s->prev_frame->width = pict->width;
942 s->prev_frame->height = pict->height;
943 if ((ret = av_frame_get_buffer(s->prev_frame, 32)) < 0)
947 // Do disposal, but not blending
948 memcpy(s->prev_frame->data[0], s->last_frame->data[0],
949 s->last_frame->linesize[0] * s->last_frame->height);
950 if (s->last_frame_fctl.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
952 uint8_t bpp = (s->bits_per_pixel + 7) >> 3;
953 for (y = s->last_frame_fctl.y_offset; y < s->last_frame_fctl.y_offset + s->last_frame_fctl.height; ++y) {
954 size_t row_start = s->last_frame->linesize[0] * y + bpp * s->last_frame_fctl.x_offset;
955 memset(s->prev_frame->data[0] + row_start, 0, bpp * s->last_frame_fctl.width);
960 av_frame_unref(s->last_frame);
961 ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
965 s->last_frame_fctl = fctl_chunk;
966 s->last_frame_packet_size = s->bytestream - s->bytestream_start;
968 av_frame_free(&s->last_frame);
974 static av_cold int png_enc_init(AVCodecContext *avctx)
976 PNGEncContext *s = avctx->priv_data;
977 int compression_level;
979 switch (avctx->pix_fmt) {
980 case AV_PIX_FMT_RGBA:
981 avctx->bits_per_coded_sample = 32;
983 case AV_PIX_FMT_RGB24:
984 avctx->bits_per_coded_sample = 24;
986 case AV_PIX_FMT_GRAY8:
987 avctx->bits_per_coded_sample = 0x28;
989 case AV_PIX_FMT_MONOBLACK:
990 avctx->bits_per_coded_sample = 1;
992 case AV_PIX_FMT_PAL8:
993 avctx->bits_per_coded_sample = 8;
996 #if FF_API_CODED_FRAME
997 FF_DISABLE_DEPRECATION_WARNINGS
998 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
999 avctx->coded_frame->key_frame = 1;
1000 FF_ENABLE_DEPRECATION_WARNINGS
1003 ff_huffyuvencdsp_init(&s->hdsp);
1005 s->filter_type = av_clip(avctx->prediction_method,
1006 PNG_FILTER_VALUE_NONE,
1007 PNG_FILTER_VALUE_MIXED);
1008 if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
1009 s->filter_type = PNG_FILTER_VALUE_NONE;
1011 if (s->dpi && s->dpm) {
1012 av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
1013 return AVERROR(EINVAL);
1014 } else if (s->dpi) {
1015 s->dpm = s->dpi * 10000 / 254;
1018 s->is_progressive = !!(avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT);
1019 switch (avctx->pix_fmt) {
1020 case AV_PIX_FMT_RGBA64BE:
1022 s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1024 case AV_PIX_FMT_RGB48BE:
1026 s->color_type = PNG_COLOR_TYPE_RGB;
1028 case AV_PIX_FMT_RGBA:
1030 s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1032 case AV_PIX_FMT_RGB24:
1034 s->color_type = PNG_COLOR_TYPE_RGB;
1036 case AV_PIX_FMT_GRAY16BE:
1038 s->color_type = PNG_COLOR_TYPE_GRAY;
1040 case AV_PIX_FMT_GRAY8:
1042 s->color_type = PNG_COLOR_TYPE_GRAY;
1044 case AV_PIX_FMT_GRAY8A:
1046 s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1048 case AV_PIX_FMT_YA16BE:
1050 s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1052 case AV_PIX_FMT_MONOBLACK:
1054 s->color_type = PNG_COLOR_TYPE_GRAY;
1056 case AV_PIX_FMT_PAL8:
1058 s->color_type = PNG_COLOR_TYPE_PALETTE;
1063 s->bits_per_pixel = ff_png_get_nb_channels(s->color_type) * s->bit_depth;
1065 s->zstream.zalloc = ff_png_zalloc;
1066 s->zstream.zfree = ff_png_zfree;
1067 s->zstream.opaque = NULL;
1068 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT
1069 ? Z_DEFAULT_COMPRESSION
1070 : av_clip(avctx->compression_level, 0, 9);
1071 if (deflateInit2(&s->zstream, compression_level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
1077 static av_cold int png_enc_close(AVCodecContext *avctx)
1079 PNGEncContext *s = avctx->priv_data;
1081 deflateEnd(&s->zstream);
1082 av_frame_free(&s->last_frame);
1083 av_frame_free(&s->prev_frame);
1084 av_freep(&s->last_frame_packet);
1088 #define OFFSET(x) offsetof(PNGEncContext, x)
1089 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1090 static const AVOption options[] = {
1091 {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
1092 {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
1096 static const AVClass pngenc_class = {
1097 .class_name = "PNG encoder",
1098 .item_name = av_default_item_name,
1100 .version = LIBAVUTIL_VERSION_INT,
1103 static const AVClass apngenc_class = {
1104 .class_name = "APNG encoder",
1105 .item_name = av_default_item_name,
1107 .version = LIBAVUTIL_VERSION_INT,
1110 AVCodec ff_png_encoder = {
1112 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1113 .type = AVMEDIA_TYPE_VIDEO,
1114 .id = AV_CODEC_ID_PNG,
1115 .priv_data_size = sizeof(PNGEncContext),
1116 .init = png_enc_init,
1117 .close = png_enc_close,
1118 .encode2 = encode_png,
1119 .capabilities = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
1120 .pix_fmts = (const enum AVPixelFormat[]) {
1121 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
1122 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
1124 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
1125 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
1126 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
1128 .priv_class = &pngenc_class,
1131 AVCodec ff_apng_encoder = {
1133 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1134 .type = AVMEDIA_TYPE_VIDEO,
1135 .id = AV_CODEC_ID_APNG,
1136 .priv_data_size = sizeof(PNGEncContext),
1137 .init = png_enc_init,
1138 .close = png_enc_close,
1139 .encode2 = encode_apng,
1140 .capabilities = CODEC_CAP_DELAY,
1141 .pix_fmts = (const enum AVPixelFormat[]) {
1142 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
1143 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
1145 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
1146 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
1147 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
1149 .priv_class = &apngenc_class,