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