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