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