]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngenc.c
Merge commit '0c00fd80ee4791bd70b634084307fc9f179e0412'
[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 #include "avcodec.h"
22 #include "internal.h"
23 #include "bytestream.h"
24 #include "dsputil.h"
25 #include "png.h"
26
27 #include "libavutil/avassert.h"
28
29 /* TODO:
30  * - add 2, 4 and 16 bit depth support
31  */
32
33 #include <zlib.h>
34
35 //#define DEBUG
36
37 #define IOBUF_SIZE 4096
38
39 typedef struct PNGEncContext {
40     DSPContext dsp;
41
42     uint8_t *bytestream;
43     uint8_t *bytestream_start;
44     uint8_t *bytestream_end;
45     AVFrame picture;
46
47     int filter_type;
48
49     z_stream zstream;
50     uint8_t buf[IOBUF_SIZE];
51 } PNGEncContext;
52
53 static void png_get_interlaced_row(uint8_t *dst, int row_size,
54                                    int bits_per_pixel, int pass,
55                                    const uint8_t *src, int width)
56 {
57     int x, mask, dst_x, j, b, bpp;
58     uint8_t *d;
59     const uint8_t *s;
60
61     mask =  (int[]){0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff}[pass];
62     switch(bits_per_pixel) {
63     case 1:
64         memset(dst, 0, row_size);
65         dst_x = 0;
66         for(x = 0; x < width; x++) {
67             j = (x & 7);
68             if ((mask << j) & 0x80) {
69                 b = (src[x >> 3] >> (7 - j)) & 1;
70                 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
71                 dst_x++;
72             }
73         }
74         break;
75     default:
76         bpp = bits_per_pixel >> 3;
77         d = dst;
78         s = src;
79         for(x = 0; x < width; x++) {
80             j = x & 7;
81             if ((mask << j) & 0x80) {
82                 memcpy(d, s, bpp);
83                 d += bpp;
84             }
85             s += bpp;
86         }
87         break;
88     }
89 }
90
91 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
92 {
93     int i;
94     for(i = 0; i < w; i++) {
95         int a, b, c, p, pa, pb, pc;
96
97         a = src[i - bpp];
98         b = top[i];
99         c = top[i - bpp];
100
101         p = b - c;
102         pc = a - c;
103
104         pa = abs(p);
105         pb = abs(pc);
106         pc = abs(p + pc);
107
108         if (pa <= pb && pa <= pc)
109             p = a;
110         else if (pb <= pc)
111             p = b;
112         else
113             p = c;
114         dst[i] = src[i] - p;
115     }
116 }
117
118 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
119                            uint8_t *src, uint8_t *top, int size, int bpp)
120 {
121     int i;
122
123     switch(filter_type) {
124     case PNG_FILTER_VALUE_NONE:
125         memcpy(dst, src, size);
126         break;
127     case PNG_FILTER_VALUE_SUB:
128         dsp->diff_bytes(dst, src, src-bpp, size);
129         memcpy(dst, src, bpp);
130         break;
131     case PNG_FILTER_VALUE_UP:
132         dsp->diff_bytes(dst, src, top, size);
133         break;
134     case PNG_FILTER_VALUE_AVG:
135         for(i = 0; i < bpp; i++)
136             dst[i] = src[i] - (top[i] >> 1);
137         for(; i < size; i++)
138             dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
139         break;
140     case PNG_FILTER_VALUE_PAETH:
141         for(i = 0; i < bpp; i++)
142             dst[i] = src[i] - top[i];
143         sub_png_paeth_prediction(dst+i, src+i, top+i, size-i, bpp);
144         break;
145     }
146 }
147
148 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
149                                   uint8_t *src, uint8_t *top, int size, int bpp)
150 {
151     int pred = s->filter_type;
152     av_assert0(bpp || !pred);
153     if(!top && pred)
154         pred = PNG_FILTER_VALUE_SUB;
155     if(pred == PNG_FILTER_VALUE_MIXED) {
156         int i;
157         int cost, bcost = INT_MAX;
158         uint8_t *buf1 = dst, *buf2 = dst + size + 16;
159         for(pred=0; pred<5; pred++) {
160             png_filter_row(&s->dsp, buf1+1, pred, src, top, size, bpp);
161             buf1[0] = pred;
162             cost = 0;
163             for(i=0; i<=size; i++)
164                 cost += abs((int8_t)buf1[i]);
165             if(cost < bcost) {
166                 bcost = cost;
167                 FFSWAP(uint8_t*, buf1, buf2);
168             }
169         }
170         return buf2;
171     } else {
172         png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
173         dst[0] = pred;
174         return dst;
175     }
176 }
177
178 static void png_write_chunk(uint8_t **f, uint32_t tag,
179                             const uint8_t *buf, int length)
180 {
181     uint32_t crc;
182     uint8_t tagbuf[4];
183
184     bytestream_put_be32(f, length);
185     crc = crc32(0, Z_NULL, 0);
186     AV_WL32(tagbuf, tag);
187     crc = crc32(crc, tagbuf, 4);
188     bytestream_put_be32(f, av_bswap32(tag));
189     if (length > 0) {
190         crc = crc32(crc, buf, length);
191         memcpy(*f, buf, length);
192         *f += length;
193     }
194     bytestream_put_be32(f, crc);
195 }
196
197 /* XXX: do filtering */
198 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
199 {
200     int ret;
201
202     s->zstream.avail_in = size;
203     s->zstream.next_in = (uint8_t *)data;
204     while (s->zstream.avail_in > 0) {
205         ret = deflate(&s->zstream, Z_NO_FLUSH);
206         if (ret != Z_OK)
207             return -1;
208         if (s->zstream.avail_out == 0) {
209             if(s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
210                 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
211             s->zstream.avail_out = IOBUF_SIZE;
212             s->zstream.next_out = s->buf;
213         }
214     }
215     return 0;
216 }
217
218 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
219                         const AVFrame *pict, int *got_packet)
220 {
221     PNGEncContext *s = avctx->priv_data;
222     AVFrame * const p= &s->picture;
223     int bit_depth, color_type, y, len, row_size, ret, is_progressive;
224     int bits_per_pixel, pass_row_size, enc_row_size;
225     int64_t max_packet_size;
226     int compression_level;
227     uint8_t *ptr, *top;
228     uint8_t *crow_base = NULL, *crow_buf, *crow;
229     uint8_t *progressive_buf = NULL;
230     uint8_t *top_buf = NULL;
231
232     *p = *pict;
233     p->pict_type= AV_PICTURE_TYPE_I;
234     p->key_frame= 1;
235
236     is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
237     switch(avctx->pix_fmt) {
238     case PIX_FMT_RGBA64BE:
239         bit_depth = 16;
240         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
241         break;
242     case PIX_FMT_RGB48BE:
243         bit_depth = 16;
244         color_type = PNG_COLOR_TYPE_RGB;
245         break;
246     case PIX_FMT_RGBA:
247         avctx->bits_per_coded_sample = 32;
248         bit_depth = 8;
249         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
250         break;
251     case PIX_FMT_RGB24:
252         avctx->bits_per_coded_sample = 24;
253         bit_depth = 8;
254         color_type = PNG_COLOR_TYPE_RGB;
255         break;
256     case PIX_FMT_GRAY16BE:
257         bit_depth = 16;
258         color_type = PNG_COLOR_TYPE_GRAY;
259         break;
260     case PIX_FMT_GRAY8:
261         avctx->bits_per_coded_sample = 0x28;
262         bit_depth = 8;
263         color_type = PNG_COLOR_TYPE_GRAY;
264         break;
265     case PIX_FMT_GRAY8A:
266         bit_depth = 8;
267         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
268         break;
269     case PIX_FMT_MONOBLACK:
270         avctx->bits_per_coded_sample =
271         bit_depth = 1;
272         color_type = PNG_COLOR_TYPE_GRAY;
273         break;
274     case PIX_FMT_PAL8:
275         avctx->bits_per_coded_sample =
276         bit_depth = 8;
277         color_type = PNG_COLOR_TYPE_PALETTE;
278         break;
279     default:
280         return -1;
281     }
282     bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
283     row_size = (avctx->width * bits_per_pixel + 7) >> 3;
284
285     s->zstream.zalloc = ff_png_zalloc;
286     s->zstream.zfree = ff_png_zfree;
287     s->zstream.opaque = NULL;
288     compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT ?
289                             Z_DEFAULT_COMPRESSION :
290                             av_clip(avctx->compression_level, 0, 9);
291     ret = deflateInit2(&s->zstream, compression_level,
292                        Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
293     if (ret != Z_OK)
294         return -1;
295
296     enc_row_size    = deflateBound(&s->zstream, row_size);
297     max_packet_size = avctx->height * (int64_t)(enc_row_size +
298                                        ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
299                       + FF_MIN_BUFFER_SIZE;
300     if (max_packet_size > INT_MAX)
301         return AVERROR(ENOMEM);
302     if ((ret = ff_alloc_packet2(avctx, pkt, max_packet_size)) < 0)
303         return ret;
304
305     s->bytestream_start =
306     s->bytestream       = pkt->data;
307     s->bytestream_end   = pkt->data + pkt->size;
308
309     crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
310     if (!crow_base)
311         goto fail;
312     crow_buf = crow_base + 15; // pixel data should be aligned, but there's a control byte before it
313     if (is_progressive) {
314         progressive_buf = av_malloc(row_size + 1);
315         if (!progressive_buf)
316             goto fail;
317     }
318     if (is_progressive) {
319         top_buf = av_malloc(row_size + 1);
320         if (!top_buf)
321             goto fail;
322     }
323
324     /* write png header */
325     AV_WB64(s->bytestream, PNGSIG);
326     s->bytestream += 8;
327
328     AV_WB32(s->buf, avctx->width);
329     AV_WB32(s->buf + 4, avctx->height);
330     s->buf[8] = bit_depth;
331     s->buf[9] = color_type;
332     s->buf[10] = 0; /* compression type */
333     s->buf[11] = 0; /* filter type */
334     s->buf[12] = is_progressive; /* interlace type */
335
336     png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
337
338     /* put the palette if needed */
339     if (color_type == PNG_COLOR_TYPE_PALETTE) {
340         int has_alpha, alpha, i;
341         unsigned int v;
342         uint32_t *palette;
343         uint8_t *alpha_ptr;
344
345         palette = (uint32_t *)p->data[1];
346         ptr = s->buf;
347         alpha_ptr = s->buf + 256 * 3;
348         has_alpha = 0;
349         for(i = 0; i < 256; i++) {
350             v = palette[i];
351             alpha = v >> 24;
352             if (alpha != 0xff)
353                 has_alpha = 1;
354             *alpha_ptr++ = alpha;
355             bytestream_put_be24(&ptr, v);
356         }
357         png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
358         if (has_alpha) {
359             png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
360         }
361     }
362
363     /* now put each row */
364     s->zstream.avail_out = IOBUF_SIZE;
365     s->zstream.next_out = s->buf;
366     if (is_progressive) {
367         int pass;
368
369         for(pass = 0; pass < NB_PASSES; pass++) {
370             /* NOTE: a pass is completely omited if no pixels would be
371                output */
372             pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
373             if (pass_row_size > 0) {
374                 top = NULL;
375                 for(y = 0; y < avctx->height; y++) {
376                     if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
377                         ptr = p->data[0] + y * p->linesize[0];
378                         FFSWAP(uint8_t*, progressive_buf, top_buf);
379                         png_get_interlaced_row(progressive_buf, pass_row_size,
380                                                bits_per_pixel, pass,
381                                                ptr, avctx->width);
382                         crow = png_choose_filter(s, crow_buf, progressive_buf, top, pass_row_size, bits_per_pixel>>3);
383                         png_write_row(s, crow, pass_row_size + 1);
384                         top = progressive_buf;
385                     }
386                 }
387             }
388         }
389     } else {
390         top = NULL;
391         for(y = 0; y < avctx->height; y++) {
392             ptr = p->data[0] + y * p->linesize[0];
393             crow = png_choose_filter(s, crow_buf, ptr, top, row_size, bits_per_pixel>>3);
394             png_write_row(s, crow, row_size + 1);
395             top = ptr;
396         }
397     }
398     /* compress last bytes */
399     for(;;) {
400         ret = deflate(&s->zstream, Z_FINISH);
401         if (ret == Z_OK || ret == Z_STREAM_END) {
402             len = IOBUF_SIZE - s->zstream.avail_out;
403             if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
404                 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
405             }
406             s->zstream.avail_out = IOBUF_SIZE;
407             s->zstream.next_out = s->buf;
408             if (ret == Z_STREAM_END)
409                 break;
410         } else {
411             goto fail;
412         }
413     }
414     png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
415
416     pkt->size   = s->bytestream - s->bytestream_start;
417     pkt->flags |= AV_PKT_FLAG_KEY;
418     *got_packet = 1;
419     ret         = 0;
420
421  the_end:
422     av_free(crow_base);
423     av_free(progressive_buf);
424     av_free(top_buf);
425     deflateEnd(&s->zstream);
426     return ret;
427  fail:
428     ret = -1;
429     goto the_end;
430 }
431
432 static av_cold int png_enc_init(AVCodecContext *avctx){
433     PNGEncContext *s = avctx->priv_data;
434
435     avcodec_get_frame_defaults(&s->picture);
436     avctx->coded_frame= &s->picture;
437     ff_dsputil_init(&s->dsp, avctx);
438
439     s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
440     if(avctx->pix_fmt == PIX_FMT_MONOBLACK)
441         s->filter_type = PNG_FILTER_VALUE_NONE;
442
443     return 0;
444 }
445
446 AVCodec ff_png_encoder = {
447     .name           = "png",
448     .type           = AVMEDIA_TYPE_VIDEO,
449     .id             = AV_CODEC_ID_PNG,
450     .priv_data_size = sizeof(PNGEncContext),
451     .init           = png_enc_init,
452     .encode2        = encode_frame,
453     .pix_fmts       = (const enum PixelFormat[]){
454         PIX_FMT_RGB24, PIX_FMT_RGBA,
455         PIX_FMT_RGB48BE, PIX_FMT_RGBA64BE,
456         PIX_FMT_PAL8,
457         PIX_FMT_GRAY8, PIX_FMT_GRAY8A,
458         PIX_FMT_GRAY16BE,
459         PIX_FMT_MONOBLACK, PIX_FMT_NONE
460     },
461     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
462 };