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"
37 #define IOBUF_SIZE 4096
39 typedef struct APNGFctlChunk {
40 uint32_t sequence_number;
41 uint32_t width, height;
42 uint32_t x_offset, y_offset;
43 uint16_t delay_num, delay_den;
44 uint8_t dispose_op, blend_op;
47 typedef struct PNGEncContext {
49 HuffYUVEncDSPContext hdsp;
52 uint8_t *bytestream_start;
53 uint8_t *bytestream_end;
58 uint8_t buf[IOBUF_SIZE];
59 int dpi; ///< Physical pixel density, in dots per inch, if set
60 int dpm; ///< Physical pixel density, in dots per meter, if set
68 uint32_t palette_checksum; // Used to ensure a single unique palette
69 uint32_t sequence_number;
73 APNGFctlChunk last_frame_fctl;
74 uint8_t *last_frame_packet;
75 size_t last_frame_packet_size;
78 static void png_get_interlaced_row(uint8_t *dst, int row_size,
79 int bits_per_pixel, int pass,
80 const uint8_t *src, int width)
82 int x, mask, dst_x, j, b, bpp;
85 static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
88 switch (bits_per_pixel) {
90 memset(dst, 0, row_size);
92 for (x = 0; x < width; x++) {
94 if ((mask << j) & 0x80) {
95 b = (src[x >> 3] >> (7 - j)) & 1;
96 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
102 bpp = bits_per_pixel >> 3;
105 for (x = 0; x < width; x++) {
107 if ((mask << j) & 0x80) {
117 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
121 for (i = 0; i < w; i++) {
122 int a, b, c, p, pa, pb, pc;
135 if (pa <= pb && pa <= pc)
145 static void sub_left_prediction(PNGEncContext *c, uint8_t *dst, const uint8_t *src, int bpp, int size)
147 const uint8_t *src1 = src + bpp;
148 const uint8_t *src2 = src;
151 memcpy(dst, src, bpp);
154 unaligned_w = FFMIN(32 - bpp, size);
155 for (x = 0; x < unaligned_w; x++)
156 *dst++ = *src1++ - *src2++;
158 c->hdsp.diff_bytes(dst, src1, src2, size);
161 static void png_filter_row(PNGEncContext *c, uint8_t *dst, int filter_type,
162 uint8_t *src, uint8_t *top, int size, int bpp)
166 switch (filter_type) {
167 case PNG_FILTER_VALUE_NONE:
168 memcpy(dst, src, size);
170 case PNG_FILTER_VALUE_SUB:
171 sub_left_prediction(c, dst, src, bpp, size);
173 case PNG_FILTER_VALUE_UP:
174 c->hdsp.diff_bytes(dst, src, top, size);
176 case PNG_FILTER_VALUE_AVG:
177 for (i = 0; i < bpp; i++)
178 dst[i] = src[i] - (top[i] >> 1);
179 for (; i < size; i++)
180 dst[i] = src[i] - ((src[i - bpp] + top[i]) >> 1);
182 case PNG_FILTER_VALUE_PAETH:
183 for (i = 0; i < bpp; i++)
184 dst[i] = src[i] - top[i];
185 sub_png_paeth_prediction(dst + i, src + i, top + i, size - i, bpp);
190 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
191 uint8_t *src, uint8_t *top, int size, int bpp)
193 int pred = s->filter_type;
194 av_assert0(bpp || !pred);
196 pred = PNG_FILTER_VALUE_SUB;
197 if (pred == PNG_FILTER_VALUE_MIXED) {
199 int cost, bcost = INT_MAX;
200 uint8_t *buf1 = dst, *buf2 = dst + size + 16;
201 for (pred = 0; pred < 5; pred++) {
202 png_filter_row(s, buf1 + 1, pred, src, top, size, bpp);
205 for (i = 0; i <= size; i++)
206 cost += abs((int8_t) buf1[i]);
209 FFSWAP(uint8_t *, buf1, buf2);
214 png_filter_row(s, dst + 1, pred, src, top, size, bpp);
220 static void png_write_chunk(uint8_t **f, uint32_t tag,
221 const uint8_t *buf, int length)
223 const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
227 bytestream_put_be32(f, length);
228 AV_WL32(tagbuf, tag);
229 crc = av_crc(crc_table, crc, tagbuf, 4);
230 bytestream_put_be32(f, av_bswap32(tag));
232 crc = av_crc(crc_table, crc, buf, length);
233 memcpy(*f, buf, length);
236 bytestream_put_be32(f, ~crc);
239 static void png_write_image_data(AVCodecContext *avctx,
240 const uint8_t *buf, int length)
242 PNGEncContext *s = avctx->priv_data;
243 const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
246 if (avctx->codec_id == AV_CODEC_ID_PNG || avctx->frame_number == 0) {
247 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), buf, length);
251 bytestream_put_be32(&s->bytestream, length + 4);
253 bytestream_put_be32(&s->bytestream, MKBETAG('f', 'd', 'A', 'T'));
254 bytestream_put_be32(&s->bytestream, s->sequence_number);
255 crc = av_crc(crc_table, crc, s->bytestream - 8, 8);
257 crc = av_crc(crc_table, crc, buf, length);
258 memcpy(s->bytestream, buf, length);
259 s->bytestream += length;
261 bytestream_put_be32(&s->bytestream, ~crc);
263 ++s->sequence_number;
266 /* XXX: do filtering */
267 static int png_write_row(AVCodecContext *avctx, const uint8_t *data, int size)
269 PNGEncContext *s = avctx->priv_data;
272 s->zstream.avail_in = size;
273 s->zstream.next_in = data;
274 while (s->zstream.avail_in > 0) {
275 ret = deflate(&s->zstream, Z_NO_FLUSH);
278 if (s->zstream.avail_out == 0) {
279 if (s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
280 png_write_image_data(avctx, s->buf, IOBUF_SIZE);
281 s->zstream.avail_out = IOBUF_SIZE;
282 s->zstream.next_out = s->buf;
288 #define AV_WB32_PNG(buf, n) AV_WB32(buf, lrint((n) * 100000))
289 static int png_get_chrm(enum AVColorPrimaries prim, uint8_t *buf)
291 double rx, ry, gx, gy, bx, by, wx = 0.3127, wy = 0.3290;
293 case AVCOL_PRI_BT709:
294 rx = 0.640; ry = 0.330;
295 gx = 0.300; gy = 0.600;
296 bx = 0.150; by = 0.060;
298 case AVCOL_PRI_BT470M:
299 rx = 0.670; ry = 0.330;
300 gx = 0.210; gy = 0.710;
301 bx = 0.140; by = 0.080;
302 wx = 0.310; wy = 0.316;
304 case AVCOL_PRI_BT470BG:
305 rx = 0.640; ry = 0.330;
306 gx = 0.290; gy = 0.600;
307 bx = 0.150; by = 0.060;
309 case AVCOL_PRI_SMPTE170M:
310 case AVCOL_PRI_SMPTE240M:
311 rx = 0.630; ry = 0.340;
312 gx = 0.310; gy = 0.595;
313 bx = 0.155; by = 0.070;
315 case AVCOL_PRI_BT2020:
316 rx = 0.708; ry = 0.292;
317 gx = 0.170; gy = 0.797;
318 bx = 0.131; by = 0.046;
324 AV_WB32_PNG(buf , wx); AV_WB32_PNG(buf + 4 , wy);
325 AV_WB32_PNG(buf + 8 , rx); AV_WB32_PNG(buf + 12, ry);
326 AV_WB32_PNG(buf + 16, gx); AV_WB32_PNG(buf + 20, gy);
327 AV_WB32_PNG(buf + 24, bx); AV_WB32_PNG(buf + 28, by);
331 static int png_get_gama(enum AVColorTransferCharacteristic trc, uint8_t *buf)
333 double gamma = avpriv_get_gamma_from_trc(trc);
337 AV_WB32_PNG(buf, 1.0 / gamma);
341 static int encode_headers(AVCodecContext *avctx, const AVFrame *pict)
343 PNGEncContext *s = avctx->priv_data;
345 /* write png header */
346 AV_WB32(s->buf, avctx->width);
347 AV_WB32(s->buf + 4, avctx->height);
348 s->buf[8] = s->bit_depth;
349 s->buf[9] = s->color_type;
350 s->buf[10] = 0; /* compression type */
351 s->buf[11] = 0; /* filter type */
352 s->buf[12] = s->is_progressive; /* interlace type */
353 png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
355 /* write physical information */
357 AV_WB32(s->buf, s->dpm);
358 AV_WB32(s->buf + 4, s->dpm);
359 s->buf[8] = 1; /* unit specifier is meter */
361 AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
362 AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
363 s->buf[8] = 0; /* unit specifier is unknown */
365 png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
367 /* write colorspace information */
368 if (pict->color_primaries == AVCOL_PRI_BT709 &&
369 pict->color_trc == AVCOL_TRC_IEC61966_2_1) {
370 s->buf[0] = 1; /* rendering intent, relative colorimetric by default */
371 png_write_chunk(&s->bytestream, MKTAG('s', 'R', 'G', 'B'), s->buf, 1);
374 if (png_get_chrm(pict->color_primaries, s->buf))
375 png_write_chunk(&s->bytestream, MKTAG('c', 'H', 'R', 'M'), s->buf, 32);
376 if (png_get_gama(pict->color_trc, s->buf))
377 png_write_chunk(&s->bytestream, MKTAG('g', 'A', 'M', 'A'), s->buf, 4);
379 /* put the palette if needed */
380 if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
381 int has_alpha, alpha, i;
384 uint8_t *ptr, *alpha_ptr;
386 palette = (uint32_t *)pict->data[1];
388 alpha_ptr = s->buf + 256 * 3;
390 for (i = 0; i < 256; i++) {
395 *alpha_ptr++ = alpha;
396 bytestream_put_be24(&ptr, v);
398 png_write_chunk(&s->bytestream,
399 MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
401 png_write_chunk(&s->bytestream,
402 MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
409 static int encode_frame(AVCodecContext *avctx, const AVFrame *pict)
411 PNGEncContext *s = avctx->priv_data;
412 const AVFrame *const p = pict;
414 int row_size, pass_row_size;
415 uint8_t *ptr, *top, *crow_buf, *crow;
416 uint8_t *crow_base = NULL;
417 uint8_t *progressive_buf = NULL;
418 uint8_t *top_buf = NULL;
420 row_size = (pict->width * s->bits_per_pixel + 7) >> 3;
422 crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
424 ret = AVERROR(ENOMEM);
427 // pixel data should be aligned, but there's a control byte before it
428 crow_buf = crow_base + 15;
429 if (s->is_progressive) {
430 progressive_buf = av_malloc(row_size + 1);
431 top_buf = av_malloc(row_size + 1);
432 if (!progressive_buf || !top_buf) {
433 ret = AVERROR(ENOMEM);
439 s->zstream.avail_out = IOBUF_SIZE;
440 s->zstream.next_out = s->buf;
441 if (s->is_progressive) {
444 for (pass = 0; pass < NB_PASSES; pass++) {
445 /* NOTE: a pass is completely omitted if no pixels would be
447 pass_row_size = ff_png_pass_row_size(pass, s->bits_per_pixel, pict->width);
448 if (pass_row_size > 0) {
450 for (y = 0; y < pict->height; y++)
451 if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
452 ptr = p->data[0] + y * p->linesize[0];
453 FFSWAP(uint8_t *, progressive_buf, top_buf);
454 png_get_interlaced_row(progressive_buf, pass_row_size,
455 s->bits_per_pixel, pass,
457 crow = png_choose_filter(s, crow_buf, progressive_buf,
458 top, pass_row_size, s->bits_per_pixel >> 3);
459 png_write_row(avctx, crow, pass_row_size + 1);
460 top = progressive_buf;
466 for (y = 0; y < pict->height; y++) {
467 ptr = p->data[0] + y * p->linesize[0];
468 crow = png_choose_filter(s, crow_buf, ptr, top,
469 row_size, s->bits_per_pixel >> 3);
470 png_write_row(avctx, crow, row_size + 1);
474 /* compress last bytes */
476 ret = deflate(&s->zstream, Z_FINISH);
477 if (ret == Z_OK || ret == Z_STREAM_END) {
478 len = IOBUF_SIZE - s->zstream.avail_out;
479 if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
480 png_write_image_data(avctx, s->buf, len);
482 s->zstream.avail_out = IOBUF_SIZE;
483 s->zstream.next_out = s->buf;
484 if (ret == Z_STREAM_END)
495 av_freep(&crow_base);
496 av_freep(&progressive_buf);
498 deflateReset(&s->zstream);
502 static int encode_png(AVCodecContext *avctx, AVPacket *pkt,
503 const AVFrame *pict, int *got_packet)
505 PNGEncContext *s = avctx->priv_data;
508 size_t max_packet_size;
510 enc_row_size = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
512 AV_INPUT_BUFFER_MIN_SIZE + // headers
515 12 * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // IDAT * ceil(enc_row_size / IOBUF_SIZE)
517 if (max_packet_size > INT_MAX)
518 return AVERROR(ENOMEM);
519 ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
523 s->bytestream_start =
524 s->bytestream = pkt->data;
525 s->bytestream_end = pkt->data + pkt->size;
527 AV_WB64(s->bytestream, PNGSIG);
530 ret = encode_headers(avctx, pict);
534 ret = encode_frame(avctx, pict);
538 png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
540 pkt->size = s->bytestream - s->bytestream_start;
541 pkt->flags |= AV_PKT_FLAG_KEY;
547 static int apng_do_inverse_blend(AVFrame *output, const AVFrame *input,
548 APNGFctlChunk *fctl_chunk, uint8_t bpp)
550 // output: background, input: foreground
551 // output the image such that when blended with the background, will produce the foreground
554 unsigned int leftmost_x = input->width;
555 unsigned int rightmost_x = 0;
556 unsigned int topmost_y = input->height;
557 unsigned int bottommost_y = 0;
558 const uint8_t *input_data = input->data[0];
559 uint8_t *output_data = output->data[0];
560 ptrdiff_t input_linesize = input->linesize[0];
561 ptrdiff_t output_linesize = output->linesize[0];
563 // Find bounding box of changes
564 for (y = 0; y < input->height; ++y) {
565 for (x = 0; x < input->width; ++x) {
566 if (!memcmp(input_data + bpp * x, output_data + bpp * x, bpp))
571 if (x >= rightmost_x)
575 if (y >= bottommost_y)
576 bottommost_y = y + 1;
579 input_data += input_linesize;
580 output_data += output_linesize;
583 if (leftmost_x == input->width && rightmost_x == 0) {
585 // APNG does not support empty frames, so we make it a 1x1 frame
586 leftmost_x = topmost_y = 0;
587 rightmost_x = bottommost_y = 1;
590 // Do actual inverse blending
591 if (fctl_chunk->blend_op == APNG_BLEND_OP_SOURCE) {
592 output_data = output->data[0];
593 for (y = topmost_y; y < bottommost_y; ++y) {
595 input->data[0] + input_linesize * y + bpp * leftmost_x,
596 bpp * (rightmost_x - leftmost_x));
597 output_data += output_linesize;
599 } else { // APNG_BLEND_OP_OVER
600 size_t transparent_palette_index;
603 switch (input->format) {
604 case AV_PIX_FMT_RGBA64BE:
605 case AV_PIX_FMT_YA16BE:
606 case AV_PIX_FMT_RGBA:
607 case AV_PIX_FMT_GRAY8A:
610 case AV_PIX_FMT_PAL8:
611 palette = (uint32_t*)input->data[1];
612 for (transparent_palette_index = 0; transparent_palette_index < 256; ++transparent_palette_index)
613 if (palette[transparent_palette_index] >> 24 == 0)
618 // No alpha, so blending not possible
622 for (y = topmost_y; y < bottommost_y; ++y) {
623 uint8_t *foreground = input->data[0] + input_linesize * y + bpp * leftmost_x;
624 uint8_t *background = output->data[0] + output_linesize * y + bpp * leftmost_x;
625 output_data = output->data[0] + output_linesize * (y - topmost_y);
626 for (x = leftmost_x; x < rightmost_x; ++x, foreground += bpp, background += bpp, output_data += bpp) {
627 if (!memcmp(foreground, background, bpp)) {
628 if (input->format == AV_PIX_FMT_PAL8) {
629 if (transparent_palette_index == 256) {
630 // Need fully transparent colour, but none exists
634 *output_data = transparent_palette_index;
636 memset(output_data, 0, bpp);
641 // Check for special alpha values, since full inverse
642 // alpha-on-alpha blending is rarely possible, and when
643 // possible, doesn't compress much better than
644 // APNG_BLEND_OP_SOURCE blending
645 switch (input->format) {
646 case AV_PIX_FMT_RGBA64BE:
647 if (((uint16_t*)foreground)[3] == 0xffff ||
648 ((uint16_t*)background)[3] == 0)
652 case AV_PIX_FMT_YA16BE:
653 if (((uint16_t*)foreground)[1] == 0xffff ||
654 ((uint16_t*)background)[1] == 0)
658 case AV_PIX_FMT_RGBA:
659 if (foreground[3] == 0xff || background[3] == 0)
663 case AV_PIX_FMT_GRAY8A:
664 if (foreground[1] == 0xff || background[1] == 0)
668 case AV_PIX_FMT_PAL8:
669 if (palette[*foreground] >> 24 == 0xff ||
670 palette[*background] >> 24 == 0)
675 memmove(output_data, foreground, bpp);
680 output->width = rightmost_x - leftmost_x;
681 output->height = bottommost_y - topmost_y;
682 fctl_chunk->width = output->width;
683 fctl_chunk->height = output->height;
684 fctl_chunk->x_offset = leftmost_x;
685 fctl_chunk->y_offset = topmost_y;
690 static int apng_encode_frame(AVCodecContext *avctx, const AVFrame *pict,
691 APNGFctlChunk *best_fctl_chunk, APNGFctlChunk *best_last_fctl_chunk)
693 PNGEncContext *s = avctx->priv_data;
697 uint8_t bpp = (s->bits_per_pixel + 7) >> 3;
698 uint8_t *original_bytestream, *original_bytestream_end;
699 uint8_t *temp_bytestream = 0, *temp_bytestream_end;
700 uint32_t best_sequence_number;
701 uint8_t *best_bytestream;
702 size_t best_bytestream_size = SIZE_MAX;
703 APNGFctlChunk last_fctl_chunk = *best_last_fctl_chunk;
704 APNGFctlChunk fctl_chunk = *best_fctl_chunk;
706 if (avctx->frame_number == 0) {
707 best_fctl_chunk->width = pict->width;
708 best_fctl_chunk->height = pict->height;
709 best_fctl_chunk->x_offset = 0;
710 best_fctl_chunk->y_offset = 0;
711 best_fctl_chunk->blend_op = APNG_BLEND_OP_SOURCE;
712 return encode_frame(avctx, pict);
715 diffFrame = av_frame_alloc();
717 return AVERROR(ENOMEM);
719 diffFrame->format = pict->format;
720 diffFrame->width = pict->width;
721 diffFrame->height = pict->height;
722 if ((ret = av_frame_get_buffer(diffFrame, 32)) < 0)
725 original_bytestream = s->bytestream;
726 original_bytestream_end = s->bytestream_end;
728 temp_bytestream = av_malloc(original_bytestream_end - original_bytestream);
729 temp_bytestream_end = temp_bytestream + (original_bytestream_end - original_bytestream);
730 if (!temp_bytestream) {
731 ret = AVERROR(ENOMEM);
735 for (last_fctl_chunk.dispose_op = 0; last_fctl_chunk.dispose_op < 3; ++last_fctl_chunk.dispose_op) {
736 // 0: APNG_DISPOSE_OP_NONE
737 // 1: APNG_DISPOSE_OP_BACKGROUND
738 // 2: APNG_DISPOSE_OP_PREVIOUS
740 for (fctl_chunk.blend_op = 0; fctl_chunk.blend_op < 2; ++fctl_chunk.blend_op) {
741 // 0: APNG_BLEND_OP_SOURCE
742 // 1: APNG_BLEND_OP_OVER
744 uint32_t original_sequence_number = s->sequence_number, sequence_number;
745 uint8_t *bytestream_start = s->bytestream;
746 size_t bytestream_size;
749 if (last_fctl_chunk.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
750 memcpy(diffFrame->data[0], s->last_frame->data[0],
751 s->last_frame->linesize[0] * s->last_frame->height);
753 if (last_fctl_chunk.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
754 for (y = last_fctl_chunk.y_offset; y < last_fctl_chunk.y_offset + last_fctl_chunk.height; ++y) {
755 size_t row_start = s->last_frame->linesize[0] * y + bpp * last_fctl_chunk.x_offset;
756 memset(diffFrame->data[0] + row_start, 0, bpp * last_fctl_chunk.width);
763 memcpy(diffFrame->data[0], s->prev_frame->data[0],
764 s->prev_frame->linesize[0] * s->prev_frame->height);
767 // Do inverse blending
768 if (apng_do_inverse_blend(diffFrame, pict, &fctl_chunk, bpp) < 0)
772 ret = encode_frame(avctx, diffFrame);
773 sequence_number = s->sequence_number;
774 s->sequence_number = original_sequence_number;
775 bytestream_size = s->bytestream - bytestream_start;
776 s->bytestream = bytestream_start;
780 if (bytestream_size < best_bytestream_size) {
781 *best_fctl_chunk = fctl_chunk;
782 *best_last_fctl_chunk = last_fctl_chunk;
784 best_sequence_number = sequence_number;
785 best_bytestream = s->bytestream;
786 best_bytestream_size = bytestream_size;
788 if (best_bytestream == original_bytestream) {
789 s->bytestream = temp_bytestream;
790 s->bytestream_end = temp_bytestream_end;
792 s->bytestream = original_bytestream;
793 s->bytestream_end = original_bytestream_end;
799 s->sequence_number = best_sequence_number;
800 s->bytestream = original_bytestream + best_bytestream_size;
801 s->bytestream_end = original_bytestream_end;
802 if (best_bytestream != original_bytestream)
803 memcpy(original_bytestream, best_bytestream, best_bytestream_size);
808 av_freep(&temp_bytestream);
809 av_frame_free(&diffFrame);
813 static int encode_apng(AVCodecContext *avctx, AVPacket *pkt,
814 const AVFrame *pict, int *got_packet)
816 PNGEncContext *s = avctx->priv_data;
819 size_t max_packet_size;
820 APNGFctlChunk fctl_chunk = {0};
822 if (pict && avctx->codec_id == AV_CODEC_ID_APNG && s->color_type == PNG_COLOR_TYPE_PALETTE) {
823 uint32_t checksum = ~av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), ~0U, pict->data[1], 256 * sizeof(uint32_t));
825 if (avctx->frame_number == 0) {
826 s->palette_checksum = checksum;
827 } else if (checksum != s->palette_checksum) {
828 av_log(avctx, AV_LOG_ERROR,
829 "Input contains more than one unique palette. APNG does not support multiple palettes.\n");
834 enc_row_size = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
836 AV_INPUT_BUFFER_MIN_SIZE + // headers
839 (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE)
841 if (max_packet_size > INT_MAX)
842 return AVERROR(ENOMEM);
844 if (avctx->frame_number == 0) {
846 return AVERROR(EINVAL);
848 s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE);
849 if (!avctx->extradata)
850 return AVERROR(ENOMEM);
852 ret = encode_headers(avctx, pict);
856 avctx->extradata_size = s->bytestream - avctx->extradata;
858 s->last_frame_packet = av_malloc(max_packet_size);
859 if (!s->last_frame_packet)
860 return AVERROR(ENOMEM);
861 } else if (s->last_frame) {
862 ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
866 memcpy(pkt->data, s->last_frame_packet, s->last_frame_packet_size);
867 pkt->size = s->last_frame_packet_size;
868 pkt->pts = pkt->dts = s->last_frame->pts;
872 s->bytestream_start =
873 s->bytestream = s->last_frame_packet;
874 s->bytestream_end = s->bytestream + max_packet_size;
876 // We're encoding the frame first, so we have to do a bit of shuffling around
877 // to have the image data write to the correct place in the buffer
878 fctl_chunk.sequence_number = s->sequence_number;
879 ++s->sequence_number;
880 s->bytestream += 26 + 12;
882 ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl);
886 fctl_chunk.delay_num = 0; // delay filled in during muxing
887 fctl_chunk.delay_den = 0;
889 s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE;
893 uint8_t* last_fctl_chunk_start = pkt->data;
896 AV_WB32(buf + 0, s->last_frame_fctl.sequence_number);
897 AV_WB32(buf + 4, s->last_frame_fctl.width);
898 AV_WB32(buf + 8, s->last_frame_fctl.height);
899 AV_WB32(buf + 12, s->last_frame_fctl.x_offset);
900 AV_WB32(buf + 16, s->last_frame_fctl.y_offset);
901 AV_WB16(buf + 20, s->last_frame_fctl.delay_num);
902 AV_WB16(buf + 22, s->last_frame_fctl.delay_den);
903 buf[24] = s->last_frame_fctl.dispose_op;
904 buf[25] = s->last_frame_fctl.blend_op;
905 png_write_chunk(&last_fctl_chunk_start, MKTAG('f', 'c', 'T', 'L'), buf, 26);
911 if (!s->last_frame) {
912 s->last_frame = av_frame_alloc();
914 return AVERROR(ENOMEM);
915 } else if (s->last_frame_fctl.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
916 if (!s->prev_frame) {
917 s->prev_frame = av_frame_alloc();
919 return AVERROR(ENOMEM);
921 s->prev_frame->format = pict->format;
922 s->prev_frame->width = pict->width;
923 s->prev_frame->height = pict->height;
924 if ((ret = av_frame_get_buffer(s->prev_frame, 32)) < 0)
928 // Do disposal, but not blending
929 memcpy(s->prev_frame->data[0], s->last_frame->data[0],
930 s->last_frame->linesize[0] * s->last_frame->height);
931 if (s->last_frame_fctl.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
933 uint8_t bpp = (s->bits_per_pixel + 7) >> 3;
934 for (y = s->last_frame_fctl.y_offset; y < s->last_frame_fctl.y_offset + s->last_frame_fctl.height; ++y) {
935 size_t row_start = s->last_frame->linesize[0] * y + bpp * s->last_frame_fctl.x_offset;
936 memset(s->prev_frame->data[0] + row_start, 0, bpp * s->last_frame_fctl.width);
941 av_frame_unref(s->last_frame);
942 ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
946 s->last_frame_fctl = fctl_chunk;
947 s->last_frame_packet_size = s->bytestream - s->bytestream_start;
949 av_frame_free(&s->last_frame);
955 static av_cold int png_enc_init(AVCodecContext *avctx)
957 PNGEncContext *s = avctx->priv_data;
958 int compression_level;
960 switch (avctx->pix_fmt) {
961 case AV_PIX_FMT_RGBA:
962 avctx->bits_per_coded_sample = 32;
964 case AV_PIX_FMT_RGB24:
965 avctx->bits_per_coded_sample = 24;
967 case AV_PIX_FMT_GRAY8:
968 avctx->bits_per_coded_sample = 0x28;
970 case AV_PIX_FMT_MONOBLACK:
971 avctx->bits_per_coded_sample = 1;
973 case AV_PIX_FMT_PAL8:
974 avctx->bits_per_coded_sample = 8;
977 #if FF_API_CODED_FRAME
978 FF_DISABLE_DEPRECATION_WARNINGS
979 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
980 avctx->coded_frame->key_frame = 1;
981 FF_ENABLE_DEPRECATION_WARNINGS
984 ff_huffyuvencdsp_init(&s->hdsp);
986 s->filter_type = av_clip(avctx->prediction_method,
987 PNG_FILTER_VALUE_NONE,
988 PNG_FILTER_VALUE_MIXED);
989 if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
990 s->filter_type = PNG_FILTER_VALUE_NONE;
992 if (s->dpi && s->dpm) {
993 av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
994 return AVERROR(EINVAL);
996 s->dpm = s->dpi * 10000 / 254;
999 s->is_progressive = !!(avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT);
1000 switch (avctx->pix_fmt) {
1001 case AV_PIX_FMT_RGBA64BE:
1003 s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1005 case AV_PIX_FMT_RGB48BE:
1007 s->color_type = PNG_COLOR_TYPE_RGB;
1009 case AV_PIX_FMT_RGBA:
1011 s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1013 case AV_PIX_FMT_RGB24:
1015 s->color_type = PNG_COLOR_TYPE_RGB;
1017 case AV_PIX_FMT_GRAY16BE:
1019 s->color_type = PNG_COLOR_TYPE_GRAY;
1021 case AV_PIX_FMT_GRAY8:
1023 s->color_type = PNG_COLOR_TYPE_GRAY;
1025 case AV_PIX_FMT_GRAY8A:
1027 s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1029 case AV_PIX_FMT_YA16BE:
1031 s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1033 case AV_PIX_FMT_MONOBLACK:
1035 s->color_type = PNG_COLOR_TYPE_GRAY;
1037 case AV_PIX_FMT_PAL8:
1039 s->color_type = PNG_COLOR_TYPE_PALETTE;
1044 s->bits_per_pixel = ff_png_get_nb_channels(s->color_type) * s->bit_depth;
1046 s->zstream.zalloc = ff_png_zalloc;
1047 s->zstream.zfree = ff_png_zfree;
1048 s->zstream.opaque = NULL;
1049 compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT
1050 ? Z_DEFAULT_COMPRESSION
1051 : av_clip(avctx->compression_level, 0, 9);
1052 if (deflateInit2(&s->zstream, compression_level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
1058 static av_cold int png_enc_close(AVCodecContext *avctx)
1060 PNGEncContext *s = avctx->priv_data;
1062 deflateEnd(&s->zstream);
1063 av_frame_free(&s->last_frame);
1064 av_frame_free(&s->prev_frame);
1065 av_freep(&s->last_frame_packet);
1069 #define OFFSET(x) offsetof(PNGEncContext, x)
1070 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1071 static const AVOption options[] = {
1072 {"dpi", "Set image resolution (in dots per inch)", OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
1073 {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
1077 static const AVClass pngenc_class = {
1078 .class_name = "PNG encoder",
1079 .item_name = av_default_item_name,
1081 .version = LIBAVUTIL_VERSION_INT,
1084 static const AVClass apngenc_class = {
1085 .class_name = "APNG encoder",
1086 .item_name = av_default_item_name,
1088 .version = LIBAVUTIL_VERSION_INT,
1091 AVCodec ff_png_encoder = {
1093 .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1094 .type = AVMEDIA_TYPE_VIDEO,
1095 .id = AV_CODEC_ID_PNG,
1096 .priv_data_size = sizeof(PNGEncContext),
1097 .init = png_enc_init,
1098 .close = png_enc_close,
1099 .encode2 = encode_png,
1100 .capabilities = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
1101 .pix_fmts = (const enum AVPixelFormat[]) {
1102 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
1103 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
1105 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
1106 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
1107 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
1109 .priv_class = &pngenc_class,
1112 AVCodec ff_apng_encoder = {
1114 .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1115 .type = AVMEDIA_TYPE_VIDEO,
1116 .id = AV_CODEC_ID_APNG,
1117 .priv_data_size = sizeof(PNGEncContext),
1118 .init = png_enc_init,
1119 .close = png_enc_close,
1120 .encode2 = encode_apng,
1121 .capabilities = CODEC_CAP_DELAY,
1122 .pix_fmts = (const enum AVPixelFormat[]) {
1123 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
1124 AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
1126 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
1127 AV_PIX_FMT_GRAY16BE, AV_PIX_FMT_YA16BE,
1128 AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
1130 .priv_class = &apngenc_class,