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