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