]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngenc.c
Merge commit '11c9bd633f635f07a762be1ecd672de55daf4edc'
[ffmpeg] / libavcodec / pngenc.c
1 /*
2  * PNG image format
3  * Copyright (c) 2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include "avcodec.h"
23 #include "internal.h"
24 #include "bytestream.h"
25 #include "huffyuvencdsp.h"
26 #include "png.h"
27 #include "apng.h"
28
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"
35
36 #include <zlib.h>
37
38 #define IOBUF_SIZE 4096
39
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;
46 } APNGFctlChunk;
47
48 typedef struct PNGEncContext {
49     AVClass *class;
50     HuffYUVEncDSPContext hdsp;
51
52     uint8_t *bytestream;
53     uint8_t *bytestream_start;
54     uint8_t *bytestream_end;
55
56     int filter_type;
57
58     z_stream zstream;
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
62
63     int is_progressive;
64     int bit_depth;
65     int color_type;
66     int bits_per_pixel;
67
68     // APNG
69     uint32_t palette_checksum;   // Used to ensure a single unique palette
70     uint32_t sequence_number;
71
72     AVFrame *prev_frame;
73     AVFrame *last_frame;
74     APNGFctlChunk last_frame_fctl;
75     uint8_t *last_frame_packet;
76     size_t last_frame_packet_size;
77 } PNGEncContext;
78
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)
82 {
83     int x, mask, dst_x, j, b, bpp;
84     uint8_t *d;
85     const uint8_t *s;
86     static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
87
88     mask = masks[pass];
89     switch (bits_per_pixel) {
90     case 1:
91         memset(dst, 0, row_size);
92         dst_x = 0;
93         for (x = 0; x < width; x++) {
94             j = (x & 7);
95             if ((mask << j) & 0x80) {
96                 b = (src[x >> 3] >> (7 - j)) & 1;
97                 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
98                 dst_x++;
99             }
100         }
101         break;
102     default:
103         bpp = bits_per_pixel >> 3;
104         d = dst;
105         s = src;
106         for (x = 0; x < width; x++) {
107             j = x & 7;
108             if ((mask << j) & 0x80) {
109                 memcpy(d, s, bpp);
110                 d += bpp;
111             }
112             s += bpp;
113         }
114         break;
115     }
116 }
117
118 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
119                                      int w, int bpp)
120 {
121     int i;
122     for (i = 0; i < w; i++) {
123         int a, b, c, p, pa, pb, pc;
124
125         a = src[i - bpp];
126         b = top[i];
127         c = top[i - bpp];
128
129         p  = b - c;
130         pc = a - c;
131
132         pa = abs(p);
133         pb = abs(pc);
134         pc = abs(p + pc);
135
136         if (pa <= pb && pa <= pc)
137             p = a;
138         else if (pb <= pc)
139             p = b;
140         else
141             p = c;
142         dst[i] = src[i] - p;
143     }
144 }
145
146 static void sub_left_prediction(PNGEncContext *c, uint8_t *dst, const uint8_t *src, int bpp, int size)
147 {
148     const uint8_t *src1 = src + bpp;
149     const uint8_t *src2 = src;
150     int x, unaligned_w;
151
152     memcpy(dst, src, bpp);
153     dst += bpp;
154     size -= bpp;
155     unaligned_w = FFMIN(32 - bpp, size);
156     for (x = 0; x < unaligned_w; x++)
157         *dst++ = *src1++ - *src2++;
158     size -= unaligned_w;
159     c->hdsp.diff_bytes(dst, src1, src2, size);
160 }
161
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)
164 {
165     int i;
166
167     switch (filter_type) {
168     case PNG_FILTER_VALUE_NONE:
169         memcpy(dst, src, size);
170         break;
171     case PNG_FILTER_VALUE_SUB:
172         sub_left_prediction(c, dst, src, bpp, size);
173         break;
174     case PNG_FILTER_VALUE_UP:
175         c->hdsp.diff_bytes(dst, src, top, size);
176         break;
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);
182         break;
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);
187         break;
188     }
189 }
190
191 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
192                                   uint8_t *src, uint8_t *top, int size, int bpp)
193 {
194     int pred = s->filter_type;
195     av_assert0(bpp || !pred);
196     if (!top && pred)
197         pred = PNG_FILTER_VALUE_SUB;
198     if (pred == PNG_FILTER_VALUE_MIXED) {
199         int i;
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);
204             buf1[0] = pred;
205             cost = 0;
206             for (i = 0; i <= size; i++)
207                 cost += abs((int8_t) buf1[i]);
208             if (cost < bcost) {
209                 bcost = cost;
210                 FFSWAP(uint8_t *, buf1, buf2);
211             }
212         }
213         return buf2;
214     } else {
215         png_filter_row(s, dst + 1, pred, src, top, size, bpp);
216         dst[0] = pred;
217         return dst;
218     }
219 }
220
221 static void png_write_chunk(uint8_t **f, uint32_t tag,
222                             const uint8_t *buf, int length)
223 {
224     const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
225     uint32_t crc = ~0U;
226     uint8_t tagbuf[4];
227
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));
232     if (length > 0) {
233         crc = av_crc(crc_table, crc, buf, length);
234         memcpy(*f, buf, length);
235         *f += length;
236     }
237     bytestream_put_be32(f, ~crc);
238 }
239
240 static void png_write_image_data(AVCodecContext *avctx,
241                                  const uint8_t *buf, int length)
242 {
243     PNGEncContext *s = avctx->priv_data;
244     const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
245     uint32_t crc = ~0U;
246
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);
249         return;
250     }
251
252     bytestream_put_be32(&s->bytestream, length + 4);
253
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);
257
258     crc = av_crc(crc_table, crc, buf, length);
259     memcpy(s->bytestream, buf, length);
260     s->bytestream += length;
261
262     bytestream_put_be32(&s->bytestream, ~crc);
263
264     ++s->sequence_number;
265 }
266
267 /* XXX: do filtering */
268 static int png_write_row(AVCodecContext *avctx, const uint8_t *data, int size)
269 {
270     PNGEncContext *s = avctx->priv_data;
271     int ret;
272
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);
277         if (ret != Z_OK)
278             return -1;
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;
284         }
285     }
286     return 0;
287 }
288
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)
291 {
292     double rx, ry, gx, gy, bx, by, wx = 0.3127, wy = 0.3290;
293     switch (prim) {
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;
298             break;
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;
304             break;
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;
309             break;
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;
315             break;
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;
320             break;
321         default:
322             return 0;
323     }
324
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);
329     return 1;
330 }
331
332 static int png_get_gama(enum AVColorTransferCharacteristic trc, uint8_t *buf)
333 {
334     double gamma = avpriv_get_gamma_from_trc(trc);
335     if (gamma <= 1e-6)
336         return 0;
337
338     AV_WB32_PNG(buf, 1.0 / gamma);
339     return 1;
340 }
341
342 static int encode_headers(AVCodecContext *avctx, const AVFrame *pict)
343 {
344     AVFrameSideData *side_data;
345     PNGEncContext *s = avctx->priv_data;
346
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);
356
357     /* write physical information */
358     if (s->dpm) {
359       AV_WB32(s->buf, s->dpm);
360       AV_WB32(s->buf + 4, s->dpm);
361       s->buf[8] = 1; /* unit specifier is meter */
362     } else {
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 */
366     }
367     png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
368
369     /* write stereoscopic information */
370     side_data = av_frame_get_side_data(pict, AV_FRAME_DATA_STEREO3D);
371     if (side_data) {
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);
377                 break;
378             case AV_STEREO3D_2D:
379                 break;
380             default:
381                 av_log(avctx, AV_LOG_WARNING, "Only side-by-side stereo3d flag can be defined within sTER chunk\n");
382                 break;
383         }
384     }
385
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);
391     }
392
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);
397
398     /* put the palette if needed */
399     if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
400         int has_alpha, alpha, i;
401         unsigned int v;
402         uint32_t *palette;
403         uint8_t *ptr, *alpha_ptr;
404
405         palette   = (uint32_t *)pict->data[1];
406         ptr       = s->buf;
407         alpha_ptr = s->buf + 256 * 3;
408         has_alpha = 0;
409         for (i = 0; i < 256; i++) {
410             v     = palette[i];
411             alpha = v >> 24;
412             if (alpha != 0xff)
413                 has_alpha = 1;
414             *alpha_ptr++ = alpha;
415             bytestream_put_be24(&ptr, v);
416         }
417         png_write_chunk(&s->bytestream,
418                         MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
419         if (has_alpha) {
420             png_write_chunk(&s->bytestream,
421                             MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
422         }
423     }
424
425     return 0;
426 }
427
428 static int encode_frame(AVCodecContext *avctx, const AVFrame *pict)
429 {
430     PNGEncContext *s       = avctx->priv_data;
431     const AVFrame *const p = pict;
432     int y, len, ret;
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;
438
439     row_size = (pict->width * s->bits_per_pixel + 7) >> 3;
440
441     crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
442     if (!crow_base) {
443         ret = AVERROR(ENOMEM);
444         goto the_end;
445     }
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);
453             goto the_end;
454         }
455     }
456
457     /* put each row */
458     s->zstream.avail_out = IOBUF_SIZE;
459     s->zstream.next_out  = s->buf;
460     if (s->is_progressive) {
461         int pass;
462
463         for (pass = 0; pass < NB_PASSES; pass++) {
464             /* NOTE: a pass is completely omitted if no pixels would be
465              * output */
466             pass_row_size = ff_png_pass_row_size(pass, s->bits_per_pixel, pict->width);
467             if (pass_row_size > 0) {
468                 top = NULL;
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,
475                                                ptr, pict->width);
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;
480                     }
481             }
482         }
483     } else {
484         top = NULL;
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);
490             top = ptr;
491         }
492     }
493     /* compress last bytes */
494     for (;;) {
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);
500             }
501             s->zstream.avail_out = IOBUF_SIZE;
502             s->zstream.next_out  = s->buf;
503             if (ret == Z_STREAM_END)
504                 break;
505         } else {
506             ret = -1;
507             goto the_end;
508         }
509     }
510
511     ret = 0;
512
513 the_end:
514     av_freep(&crow_base);
515     av_freep(&progressive_buf);
516     av_freep(&top_buf);
517     deflateReset(&s->zstream);
518     return ret;
519 }
520
521 static int encode_png(AVCodecContext *avctx, AVPacket *pkt,
522                       const AVFrame *pict, int *got_packet)
523 {
524     PNGEncContext *s = avctx->priv_data;
525     int ret;
526     int enc_row_size;
527     size_t max_packet_size;
528
529     enc_row_size    = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
530     max_packet_size =
531         AV_INPUT_BUFFER_MIN_SIZE + // headers
532         avctx->height * (
533             enc_row_size +
534             12 * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // IDAT * ceil(enc_row_size / IOBUF_SIZE)
535         );
536     if (max_packet_size > INT_MAX)
537         return AVERROR(ENOMEM);
538     ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
539     if (ret < 0)
540         return ret;
541
542     s->bytestream_start =
543     s->bytestream       = pkt->data;
544     s->bytestream_end   = pkt->data + pkt->size;
545
546     AV_WB64(s->bytestream, PNGSIG);
547     s->bytestream += 8;
548
549     ret = encode_headers(avctx, pict);
550     if (ret < 0)
551         return ret;
552
553     ret = encode_frame(avctx, pict);
554     if (ret < 0)
555         return ret;
556
557     png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
558
559     pkt->size = s->bytestream - s->bytestream_start;
560     pkt->flags |= AV_PKT_FLAG_KEY;
561     *got_packet = 1;
562
563     return 0;
564 }
565
566 static int apng_do_inverse_blend(AVFrame *output, const AVFrame *input,
567                                   APNGFctlChunk *fctl_chunk, uint8_t bpp)
568 {
569     // output: background, input: foreground
570     // output the image such that when blended with the background, will produce the foreground
571
572     unsigned int x, y;
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];
581
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))
586                 continue;
587
588             if (x < leftmost_x)
589                 leftmost_x = x;
590             if (x >= rightmost_x)
591                 rightmost_x = x + 1;
592             if (y < topmost_y)
593                 topmost_y = y;
594             if (y >= bottommost_y)
595                 bottommost_y = y + 1;
596         }
597
598         input_data += input_linesize;
599         output_data += output_linesize;
600     }
601
602     if (leftmost_x == input->width && rightmost_x == 0) {
603         // Empty frame
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;
607     }
608
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) {
613             memcpy(output_data,
614                    input->data[0] + input_linesize * y + bpp * leftmost_x,
615                    bpp * (rightmost_x - leftmost_x));
616             output_data += output_linesize;
617         }
618     } else { // APNG_BLEND_OP_OVER
619         size_t transparent_palette_index;
620         uint32_t *palette;
621
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:
627             break;
628
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)
633                     break;
634             break;
635
636         default:
637             // No alpha, so blending not possible
638             return -1;
639         }
640
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
650                             return -1;
651                         }
652
653                         *output_data = transparent_palette_index;
654                     } else {
655                         memset(output_data, 0, bpp);
656                     }
657                     continue;
658                 }
659
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)
668                         break;
669                     return -1;
670
671                 case AV_PIX_FMT_YA16BE:
672                     if (((uint16_t*)foreground)[1] == 0xffff ||
673                         ((uint16_t*)background)[1] == 0)
674                         break;
675                     return -1;
676
677                 case AV_PIX_FMT_RGBA:
678                     if (foreground[3] == 0xff || background[3] == 0)
679                         break;
680                     return -1;
681
682                 case AV_PIX_FMT_GRAY8A:
683                     if (foreground[1] == 0xff || background[1] == 0)
684                         break;
685                     return -1;
686
687                 case AV_PIX_FMT_PAL8:
688                     if (palette[*foreground] >> 24 == 0xff ||
689                         palette[*background] >> 24 == 0)
690                         break;
691                     return -1;
692                 }
693
694                 memmove(output_data, foreground, bpp);
695             }
696         }
697     }
698
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;
705
706     return 0;
707 }
708
709 static int apng_encode_frame(AVCodecContext *avctx, const AVFrame *pict,
710                              APNGFctlChunk *best_fctl_chunk, APNGFctlChunk *best_last_fctl_chunk)
711 {
712     PNGEncContext *s = avctx->priv_data;
713     int ret;
714     unsigned int y;
715     AVFrame* diffFrame;
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;
724
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);
732     }
733
734     diffFrame = av_frame_alloc();
735     if (!diffFrame)
736         return AVERROR(ENOMEM);
737
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)
742         goto fail;
743
744     original_bytestream = s->bytestream;
745     original_bytestream_end = s->bytestream_end;
746
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);
751         goto fail;
752     }
753
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
758
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
762
763             uint32_t original_sequence_number = s->sequence_number, sequence_number;
764             uint8_t *bytestream_start = s->bytestream;
765             size_t bytestream_size;
766
767             // Do disposal
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);
771
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);
776                     }
777                 }
778             } else {
779                 if (!s->prev_frame)
780                     continue;
781
782                 memcpy(diffFrame->data[0], s->prev_frame->data[0],
783                        s->prev_frame->linesize[0] * s->prev_frame->height);
784             }
785
786             // Do inverse blending
787             if (apng_do_inverse_blend(diffFrame, pict, &fctl_chunk, bpp) < 0)
788                 continue;
789
790             // Do encoding
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;
796             if (ret < 0)
797                 goto fail;
798
799             if (bytestream_size < best_bytestream_size) {
800                 *best_fctl_chunk = fctl_chunk;
801                 *best_last_fctl_chunk = last_fctl_chunk;
802
803                 best_sequence_number = sequence_number;
804                 best_bytestream = s->bytestream;
805                 best_bytestream_size = bytestream_size;
806
807                 if (best_bytestream == original_bytestream) {
808                     s->bytestream = temp_bytestream;
809                     s->bytestream_end = temp_bytestream_end;
810                 } else {
811                     s->bytestream = original_bytestream;
812                     s->bytestream_end = original_bytestream_end;
813                 }
814             }
815         }
816     }
817
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);
823
824     ret = 0;
825
826 fail:
827     av_freep(&temp_bytestream);
828     av_frame_free(&diffFrame);
829     return ret;
830 }
831
832 static int encode_apng(AVCodecContext *avctx, AVPacket *pkt,
833                        const AVFrame *pict, int *got_packet)
834 {
835     PNGEncContext *s = avctx->priv_data;
836     int ret;
837     int enc_row_size;
838     size_t max_packet_size;
839     APNGFctlChunk fctl_chunk = {0};
840
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));
843
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");
849             return -1;
850         }
851     }
852
853     enc_row_size    = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
854     max_packet_size =
855         AV_INPUT_BUFFER_MIN_SIZE + // headers
856         avctx->height * (
857             enc_row_size +
858             (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE)
859         );
860     if (max_packet_size > INT_MAX)
861         return AVERROR(ENOMEM);
862
863     if (avctx->frame_number == 0) {
864         if (!pict)
865             return AVERROR(EINVAL);
866
867         s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE);
868         if (!avctx->extradata)
869             return AVERROR(ENOMEM);
870
871         ret = encode_headers(avctx, pict);
872         if (ret < 0)
873             return ret;
874
875         avctx->extradata_size = s->bytestream - avctx->extradata;
876
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);
882         if (ret < 0)
883             return ret;
884
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;
888     }
889
890     if (pict) {
891         s->bytestream_start =
892         s->bytestream       = s->last_frame_packet;
893         s->bytestream_end   = s->bytestream + max_packet_size;
894
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;
900
901         ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl);
902         if (ret < 0)
903             return ret;
904
905         fctl_chunk.delay_num = 0; // delay filled in during muxing
906         fctl_chunk.delay_den = 0;
907     } else {
908         s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE;
909     }
910
911     if (s->last_frame) {
912         uint8_t* last_fctl_chunk_start = pkt->data;
913         uint8_t buf[26];
914
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);
925
926         *got_packet = 1;
927     }
928
929     if (pict) {
930         if (!s->last_frame) {
931             s->last_frame = av_frame_alloc();
932             if (!s->last_frame)
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();
937                 if (!s->prev_frame)
938                     return AVERROR(ENOMEM);
939
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)
944                     return ret;
945             }
946
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) {
951                 uint32_t y;
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);
956                 }
957             }
958         }
959
960         av_frame_unref(s->last_frame);
961         ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
962         if (ret < 0)
963             return ret;
964
965         s->last_frame_fctl = fctl_chunk;
966         s->last_frame_packet_size = s->bytestream - s->bytestream_start;
967     } else {
968         av_frame_free(&s->last_frame);
969     }
970
971     return 0;
972 }
973
974 static av_cold int png_enc_init(AVCodecContext *avctx)
975 {
976     PNGEncContext *s = avctx->priv_data;
977     int compression_level;
978
979     switch (avctx->pix_fmt) {
980     case AV_PIX_FMT_RGBA:
981         avctx->bits_per_coded_sample = 32;
982         break;
983     case AV_PIX_FMT_RGB24:
984         avctx->bits_per_coded_sample = 24;
985         break;
986     case AV_PIX_FMT_GRAY8:
987         avctx->bits_per_coded_sample = 0x28;
988         break;
989     case AV_PIX_FMT_MONOBLACK:
990         avctx->bits_per_coded_sample = 1;
991         break;
992     case AV_PIX_FMT_PAL8:
993         avctx->bits_per_coded_sample = 8;
994     }
995
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
1001 #endif
1002
1003     ff_huffyuvencdsp_init(&s->hdsp);
1004
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;
1010
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;
1016     }
1017
1018     s->is_progressive = !!(avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT);
1019     switch (avctx->pix_fmt) {
1020     case AV_PIX_FMT_RGBA64BE:
1021         s->bit_depth = 16;
1022         s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1023         break;
1024     case AV_PIX_FMT_RGB48BE:
1025         s->bit_depth = 16;
1026         s->color_type = PNG_COLOR_TYPE_RGB;
1027         break;
1028     case AV_PIX_FMT_RGBA:
1029         s->bit_depth  = 8;
1030         s->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1031         break;
1032     case AV_PIX_FMT_RGB24:
1033         s->bit_depth  = 8;
1034         s->color_type = PNG_COLOR_TYPE_RGB;
1035         break;
1036     case AV_PIX_FMT_GRAY16BE:
1037         s->bit_depth  = 16;
1038         s->color_type = PNG_COLOR_TYPE_GRAY;
1039         break;
1040     case AV_PIX_FMT_GRAY8:
1041         s->bit_depth  = 8;
1042         s->color_type = PNG_COLOR_TYPE_GRAY;
1043         break;
1044     case AV_PIX_FMT_GRAY8A:
1045         s->bit_depth = 8;
1046         s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1047         break;
1048     case AV_PIX_FMT_YA16BE:
1049         s->bit_depth = 16;
1050         s->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1051         break;
1052     case AV_PIX_FMT_MONOBLACK:
1053         s->bit_depth  = 1;
1054         s->color_type = PNG_COLOR_TYPE_GRAY;
1055         break;
1056     case AV_PIX_FMT_PAL8:
1057         s->bit_depth  = 8;
1058         s->color_type = PNG_COLOR_TYPE_PALETTE;
1059         break;
1060     default:
1061         return -1;
1062     }
1063     s->bits_per_pixel = ff_png_get_nb_channels(s->color_type) * s->bit_depth;
1064
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)
1072         return -1;
1073
1074     return 0;
1075 }
1076
1077 static av_cold int png_enc_close(AVCodecContext *avctx)
1078 {
1079     PNGEncContext *s = avctx->priv_data;
1080
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);
1085     return 0;
1086 }
1087
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},
1093     { NULL }
1094 };
1095
1096 static const AVClass pngenc_class = {
1097     .class_name = "PNG encoder",
1098     .item_name  = av_default_item_name,
1099     .option     = options,
1100     .version    = LIBAVUTIL_VERSION_INT,
1101 };
1102
1103 static const AVClass apngenc_class = {
1104     .class_name = "APNG encoder",
1105     .item_name  = av_default_item_name,
1106     .option     = options,
1107     .version    = LIBAVUTIL_VERSION_INT,
1108 };
1109
1110 AVCodec ff_png_encoder = {
1111     .name           = "png",
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,
1123         AV_PIX_FMT_PAL8,
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
1127     },
1128     .priv_class     = &pngenc_class,
1129 };
1130
1131 AVCodec ff_apng_encoder = {
1132     .name           = "apng",
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,
1144         AV_PIX_FMT_PAL8,
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
1148     },
1149     .priv_class     = &apngenc_class,
1150 };