]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngenc.c
Merge commit 'b1803c79dcd6d0a345fa1cbe18dd8e2149717121'
[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 #include "libavutil/opt.h"
29
30 /* TODO:
31  * - add 2, 4 and 16 bit depth support
32  */
33
34 #include <zlib.h>
35
36 //#define DEBUG
37
38 #define IOBUF_SIZE 4096
39
40 typedef struct PNGEncContext {
41     AVClass *class;
42     DSPContext dsp;
43
44     uint8_t *bytestream;
45     uint8_t *bytestream_start;
46     uint8_t *bytestream_end;
47     AVFrame picture;
48
49     int filter_type;
50
51     z_stream zstream;
52     uint8_t buf[IOBUF_SIZE];
53     int dpi;                     ///< Physical pixel density, in dots per inch, if set
54     int dpm;                     ///< Physical pixel density, in dots per meter, if set
55 } PNGEncContext;
56
57 static void png_get_interlaced_row(uint8_t *dst, int row_size,
58                                    int bits_per_pixel, int pass,
59                                    const uint8_t *src, int width)
60 {
61     int x, mask, dst_x, j, b, bpp;
62     uint8_t *d;
63     const uint8_t *s;
64     static const int masks[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
65
66     mask = masks[pass];
67     switch(bits_per_pixel) {
68     case 1:
69         memset(dst, 0, row_size);
70         dst_x = 0;
71         for(x = 0; x < width; x++) {
72             j = (x & 7);
73             if ((mask << j) & 0x80) {
74                 b = (src[x >> 3] >> (7 - j)) & 1;
75                 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
76                 dst_x++;
77             }
78         }
79         break;
80     default:
81         bpp = bits_per_pixel >> 3;
82         d = dst;
83         s = src;
84         for(x = 0; x < width; x++) {
85             j = x & 7;
86             if ((mask << j) & 0x80) {
87                 memcpy(d, s, bpp);
88                 d += bpp;
89             }
90             s += bpp;
91         }
92         break;
93     }
94 }
95
96 static void sub_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
97 {
98     int i;
99     for(i = 0; i < w; i++) {
100         int a, b, c, p, pa, pb, pc;
101
102         a = src[i - bpp];
103         b = top[i];
104         c = top[i - bpp];
105
106         p = b - c;
107         pc = a - c;
108
109         pa = abs(p);
110         pb = abs(pc);
111         pc = abs(p + pc);
112
113         if (pa <= pb && pa <= pc)
114             p = a;
115         else if (pb <= pc)
116             p = b;
117         else
118             p = c;
119         dst[i] = src[i] - p;
120     }
121 }
122
123 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
124                            uint8_t *src, uint8_t *top, int size, int bpp)
125 {
126     int i;
127
128     switch(filter_type) {
129     case PNG_FILTER_VALUE_NONE:
130         memcpy(dst, src, size);
131         break;
132     case PNG_FILTER_VALUE_SUB:
133         dsp->diff_bytes(dst, src, src-bpp, size);
134         memcpy(dst, src, bpp);
135         break;
136     case PNG_FILTER_VALUE_UP:
137         dsp->diff_bytes(dst, src, top, size);
138         break;
139     case PNG_FILTER_VALUE_AVG:
140         for(i = 0; i < bpp; i++)
141             dst[i] = src[i] - (top[i] >> 1);
142         for(; i < size; i++)
143             dst[i] = src[i] - ((src[i-bpp] + top[i]) >> 1);
144         break;
145     case PNG_FILTER_VALUE_PAETH:
146         for(i = 0; i < bpp; i++)
147             dst[i] = src[i] - top[i];
148         sub_png_paeth_prediction(dst+i, src+i, top+i, size-i, bpp);
149         break;
150     }
151 }
152
153 static uint8_t *png_choose_filter(PNGEncContext *s, uint8_t *dst,
154                                   uint8_t *src, uint8_t *top, int size, int bpp)
155 {
156     int pred = s->filter_type;
157     av_assert0(bpp || !pred);
158     if(!top && pred)
159         pred = PNG_FILTER_VALUE_SUB;
160     if(pred == PNG_FILTER_VALUE_MIXED) {
161         int i;
162         int cost, bcost = INT_MAX;
163         uint8_t *buf1 = dst, *buf2 = dst + size + 16;
164         for(pred=0; pred<5; pred++) {
165             png_filter_row(&s->dsp, buf1+1, pred, src, top, size, bpp);
166             buf1[0] = pred;
167             cost = 0;
168             for(i=0; i<=size; i++)
169                 cost += abs((int8_t)buf1[i]);
170             if(cost < bcost) {
171                 bcost = cost;
172                 FFSWAP(uint8_t*, buf1, buf2);
173             }
174         }
175         return buf2;
176     } else {
177         png_filter_row(&s->dsp, dst+1, pred, src, top, size, bpp);
178         dst[0] = pred;
179         return dst;
180     }
181 }
182
183 static void png_write_chunk(uint8_t **f, uint32_t tag,
184                             const uint8_t *buf, int length)
185 {
186     uint32_t crc;
187     uint8_t tagbuf[4];
188
189     bytestream_put_be32(f, length);
190     crc = crc32(0, Z_NULL, 0);
191     AV_WL32(tagbuf, tag);
192     crc = crc32(crc, tagbuf, 4);
193     bytestream_put_be32(f, av_bswap32(tag));
194     if (length > 0) {
195         crc = crc32(crc, buf, length);
196         memcpy(*f, buf, length);
197         *f += length;
198     }
199     bytestream_put_be32(f, crc);
200 }
201
202 /* XXX: do filtering */
203 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
204 {
205     int ret;
206
207     s->zstream.avail_in = size;
208     s->zstream.next_in = (uint8_t *)data;
209     while (s->zstream.avail_in > 0) {
210         ret = deflate(&s->zstream, Z_NO_FLUSH);
211         if (ret != Z_OK)
212             return -1;
213         if (s->zstream.avail_out == 0) {
214             if(s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
215                 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
216             s->zstream.avail_out = IOBUF_SIZE;
217             s->zstream.next_out = s->buf;
218         }
219     }
220     return 0;
221 }
222
223 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
224                         const AVFrame *pict, int *got_packet)
225 {
226     PNGEncContext *s = avctx->priv_data;
227     AVFrame * const p= &s->picture;
228     int bit_depth, color_type, y, len, row_size, ret, is_progressive;
229     int bits_per_pixel, pass_row_size, enc_row_size;
230     int64_t max_packet_size;
231     int compression_level;
232     uint8_t *ptr, *top;
233     uint8_t *crow_base = NULL, *crow_buf, *crow;
234     uint8_t *progressive_buf = NULL;
235     uint8_t *top_buf = NULL;
236
237     *p = *pict;
238     p->pict_type= AV_PICTURE_TYPE_I;
239     p->key_frame= 1;
240
241     is_progressive = !!(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
242     switch(avctx->pix_fmt) {
243     case AV_PIX_FMT_RGBA64BE:
244         bit_depth = 16;
245         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
246         break;
247     case AV_PIX_FMT_RGB48BE:
248         bit_depth = 16;
249         color_type = PNG_COLOR_TYPE_RGB;
250         break;
251     case AV_PIX_FMT_RGBA:
252         bit_depth = 8;
253         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
254         break;
255     case AV_PIX_FMT_RGB24:
256         bit_depth = 8;
257         color_type = PNG_COLOR_TYPE_RGB;
258         break;
259     case AV_PIX_FMT_GRAY16BE:
260         bit_depth = 16;
261         color_type = PNG_COLOR_TYPE_GRAY;
262         break;
263     case AV_PIX_FMT_GRAY8:
264         bit_depth = 8;
265         color_type = PNG_COLOR_TYPE_GRAY;
266         break;
267     case AV_PIX_FMT_GRAY8A:
268         bit_depth = 8;
269         color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
270         break;
271     case AV_PIX_FMT_MONOBLACK:
272         bit_depth = 1;
273         color_type = PNG_COLOR_TYPE_GRAY;
274         break;
275     case AV_PIX_FMT_PAL8:
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     if (s->dpm) {
339       AV_WB32(s->buf, s->dpm);
340       AV_WB32(s->buf + 4, s->dpm);
341       s->buf[8] = 1; /* unit specifier is meter */
342     } else {
343       AV_WB32(s->buf, avctx->sample_aspect_ratio.num);
344       AV_WB32(s->buf + 4, avctx->sample_aspect_ratio.den);
345       s->buf[8] = 0; /* unit specifier is unknown */
346     }
347     png_write_chunk(&s->bytestream, MKTAG('p', 'H', 'Y', 's'), s->buf, 9);
348
349     /* put the palette if needed */
350     if (color_type == PNG_COLOR_TYPE_PALETTE) {
351         int has_alpha, alpha, i;
352         unsigned int v;
353         uint32_t *palette;
354         uint8_t *alpha_ptr;
355
356         palette = (uint32_t *)p->data[1];
357         ptr = s->buf;
358         alpha_ptr = s->buf + 256 * 3;
359         has_alpha = 0;
360         for(i = 0; i < 256; i++) {
361             v = palette[i];
362             alpha = v >> 24;
363             if (alpha != 0xff)
364                 has_alpha = 1;
365             *alpha_ptr++ = alpha;
366             bytestream_put_be24(&ptr, v);
367         }
368         png_write_chunk(&s->bytestream, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
369         if (has_alpha) {
370             png_write_chunk(&s->bytestream, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
371         }
372     }
373
374     /* now put each row */
375     s->zstream.avail_out = IOBUF_SIZE;
376     s->zstream.next_out = s->buf;
377     if (is_progressive) {
378         int pass;
379
380         for(pass = 0; pass < NB_PASSES; pass++) {
381             /* NOTE: a pass is completely omitted if no pixels would be
382                output */
383             pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
384             if (pass_row_size > 0) {
385                 top = NULL;
386                 for(y = 0; y < avctx->height; y++) {
387                     if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
388                         ptr = p->data[0] + y * p->linesize[0];
389                         FFSWAP(uint8_t*, progressive_buf, top_buf);
390                         png_get_interlaced_row(progressive_buf, pass_row_size,
391                                                bits_per_pixel, pass,
392                                                ptr, avctx->width);
393                         crow = png_choose_filter(s, crow_buf, progressive_buf, top, pass_row_size, bits_per_pixel>>3);
394                         png_write_row(s, crow, pass_row_size + 1);
395                         top = progressive_buf;
396                     }
397                 }
398             }
399         }
400     } else {
401         top = NULL;
402         for(y = 0; y < avctx->height; y++) {
403             ptr = p->data[0] + y * p->linesize[0];
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(top_buf);
436     deflateEnd(&s->zstream);
437     return ret;
438  fail:
439     ret = -1;
440     goto the_end;
441 }
442
443 static av_cold int png_enc_init(AVCodecContext *avctx){
444     PNGEncContext *s = avctx->priv_data;
445
446     switch(avctx->pix_fmt) {
447     case AV_PIX_FMT_RGBA:
448         avctx->bits_per_coded_sample = 32;
449         break;
450     case AV_PIX_FMT_RGB24:
451         avctx->bits_per_coded_sample = 24;
452         break;
453     case AV_PIX_FMT_GRAY8:
454         avctx->bits_per_coded_sample = 0x28;
455         break;
456     case AV_PIX_FMT_MONOBLACK:
457         avctx->bits_per_coded_sample = 1;
458         break;
459     case AV_PIX_FMT_PAL8:
460         avctx->bits_per_coded_sample = 8;
461     }
462
463     avcodec_get_frame_defaults(&s->picture);
464     avctx->coded_frame= &s->picture;
465     ff_dsputil_init(&s->dsp, avctx);
466
467     s->filter_type = av_clip(avctx->prediction_method, PNG_FILTER_VALUE_NONE, PNG_FILTER_VALUE_MIXED);
468     if(avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
469         s->filter_type = PNG_FILTER_VALUE_NONE;
470
471     if (s->dpi && s->dpm) {
472       av_log(avctx, AV_LOG_ERROR, "Only one of 'dpi' or 'dpm' options should be set\n");
473       return AVERROR(EINVAL);
474     } else if (s->dpi) {
475       s->dpm = s->dpi * 10000 / 254;
476     }
477
478     return 0;
479 }
480
481 #define OFFSET(x) offsetof(PNGEncContext, x)
482 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
483 static const AVOption options[] = {
484     {"dpi", "Set image resolution (in dots per inch)",  OFFSET(dpi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
485     {"dpm", "Set image resolution (in dots per meter)", OFFSET(dpm), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0x10000, VE},
486     { NULL }
487 };
488
489 static const AVClass pngenc_class = {
490     .class_name = "PNG encoder",
491     .item_name  = av_default_item_name,
492     .option     = options,
493     .version    = LIBAVUTIL_VERSION_INT,
494 };
495
496 AVCodec ff_png_encoder = {
497     .name           = "png",
498     .type           = AVMEDIA_TYPE_VIDEO,
499     .id             = AV_CODEC_ID_PNG,
500     .priv_data_size = sizeof(PNGEncContext),
501     .init           = png_enc_init,
502     .encode2        = encode_frame,
503     .capabilities   = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
504     .pix_fmts       = (const enum AVPixelFormat[]){
505         AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA,
506         AV_PIX_FMT_RGB48BE, AV_PIX_FMT_RGBA64BE,
507         AV_PIX_FMT_PAL8,
508         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY8A,
509         AV_PIX_FMT_GRAY16BE,
510         AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
511     },
512     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
513     .priv_class     = &pngenc_class,
514 };