]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngenc.c
opus: Fix typo causing overflow in silk_stabilize_lsf
[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/stereo3d.h"
23
24 #include "avcodec.h"
25 #include "bytestream.h"
26 #include "huffyuvencdsp.h"
27 #include "png.h"
28
29 /* TODO:
30  * - add 2, 4 and 16 bit depth support
31  */
32
33 #include <zlib.h>
34
35 #define IOBUF_SIZE 4096
36
37 typedef struct PNGEncContext {
38     HuffYUVEncDSPContext hdsp;
39
40     uint8_t *bytestream;
41     uint8_t *bytestream_start;
42     uint8_t *bytestream_end;
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,
89                                      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(PNGEncContext *c, 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         c->hdsp.diff_bytes(dst, src, src - bpp, size);
127         memcpy(dst, src, bpp);
128         break;
129     case PNG_FILTER_VALUE_UP:
130         c->hdsp.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, 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, dst + 1, pred, src, top, size, bpp);
171         dst[0] = pred;
172         return dst;
173     }
174 }
175
176 static void convert_from_rgb32(uint8_t *dst, const uint8_t *src, int width)
177 {
178     uint8_t *d;
179     int j;
180     unsigned int v;
181
182     d = dst;
183     for (j = 0; j < width; j++) {
184         v    = ((const uint32_t *) src)[j];
185         d[0] = v >> 16;
186         d[1] = v >> 8;
187         d[2] = v;
188         d[3] = v >> 24;
189         d   += 4;
190     }
191 }
192
193 static void png_write_chunk(uint8_t **f, uint32_t tag,
194                             const uint8_t *buf, int length)
195 {
196     uint32_t crc;
197     uint8_t tagbuf[4];
198
199     bytestream_put_be32(f, length);
200     crc = crc32(0, Z_NULL, 0);
201     AV_WL32(tagbuf, tag);
202     crc = crc32(crc, tagbuf, 4);
203     bytestream_put_be32(f, av_bswap32(tag));
204     if (length > 0) {
205         crc = crc32(crc, buf, length);
206         memcpy(*f, buf, length);
207         *f += length;
208     }
209     bytestream_put_be32(f, crc);
210 }
211
212 /* XXX: do filtering */
213 static int png_write_row(PNGEncContext *s, const uint8_t *data, int size)
214 {
215     int ret;
216
217     s->zstream.avail_in = size;
218     s->zstream.next_in  = data;
219     while (s->zstream.avail_in > 0) {
220         ret = deflate(&s->zstream, Z_NO_FLUSH);
221         if (ret != Z_OK)
222             return -1;
223         if (s->zstream.avail_out == 0) {
224             if (s->bytestream_end - s->bytestream > IOBUF_SIZE + 100)
225                 png_write_chunk(&s->bytestream,
226                                 MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
227             s->zstream.avail_out = IOBUF_SIZE;
228             s->zstream.next_out  = s->buf;
229         }
230     }
231     return 0;
232 }
233
234 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
235                         const AVFrame *pict, int *got_packet)
236 {
237     PNGEncContext *s       = avctx->priv_data;
238     AVFrameSideData *side_data;
239     const AVFrame *const p = pict;
240     int bit_depth, color_type, y, len, row_size, ret, is_progressive;
241     int bits_per_pixel, pass_row_size, enc_row_size, max_packet_size;
242     int compression_level;
243     uint8_t *ptr, *top, *crow_buf, *crow;
244     uint8_t *crow_base       = NULL;
245     uint8_t *progressive_buf = NULL;
246     uint8_t *rgba_buf        = NULL;
247     uint8_t *top_buf         = NULL;
248
249     is_progressive = !!(avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT);
250     switch (avctx->pix_fmt) {
251     case AV_PIX_FMT_RGBA64BE:
252         bit_depth = 16;
253         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
254         break;
255     case AV_PIX_FMT_RGB48BE:
256         bit_depth = 16;
257         color_type = PNG_COLOR_TYPE_RGB;
258         break;
259     case AV_PIX_FMT_RGB32:
260         bit_depth  = 8;
261         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
262         break;
263     case AV_PIX_FMT_RGB24:
264         bit_depth  = 8;
265         color_type = PNG_COLOR_TYPE_RGB;
266         break;
267     case AV_PIX_FMT_GRAY16BE:
268         bit_depth  = 16;
269         color_type = PNG_COLOR_TYPE_GRAY;
270         break;
271     case AV_PIX_FMT_GRAY8:
272         bit_depth  = 8;
273         color_type = PNG_COLOR_TYPE_GRAY;
274         break;
275     case AV_PIX_FMT_MONOBLACK:
276         bit_depth  = 1;
277         color_type = PNG_COLOR_TYPE_GRAY;
278         break;
279     case AV_PIX_FMT_PAL8:
280         bit_depth  = 8;
281         color_type = PNG_COLOR_TYPE_PALETTE;
282         break;
283     default:
284         return -1;
285     }
286     bits_per_pixel = ff_png_get_nb_channels(color_type) * bit_depth;
287     row_size       = (avctx->width * bits_per_pixel + 7) >> 3;
288
289     s->zstream.zalloc = ff_png_zalloc;
290     s->zstream.zfree  = ff_png_zfree;
291     s->zstream.opaque = NULL;
292     compression_level = avctx->compression_level == FF_COMPRESSION_DEFAULT
293                       ? Z_DEFAULT_COMPRESSION
294                       : av_clip(avctx->compression_level, 0, 9);
295     ret = deflateInit2(&s->zstream, compression_level,
296                        Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
297     if (ret != Z_OK)
298         return -1;
299
300     enc_row_size    = deflateBound(&s->zstream, row_size);
301     max_packet_size = avctx->height * (enc_row_size +
302                                        ((enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) * 12)
303                       + AV_INPUT_BUFFER_MIN_SIZE;
304     if (!pkt->data &&
305         (ret = av_new_packet(pkt, max_packet_size)) < 0) {
306         av_log(avctx, AV_LOG_ERROR, "Could not allocate output packet of size %d.\n",
307                max_packet_size);
308         return ret;
309     }
310
311     s->bytestream_start =
312     s->bytestream       = pkt->data;
313     s->bytestream_end   = pkt->data + pkt->size;
314
315     crow_base = av_malloc((row_size + 32) << (s->filter_type == PNG_FILTER_VALUE_MIXED));
316     if (!crow_base)
317         goto fail;
318     // pixel data should be aligned, but there's a control byte before it
319     crow_buf = crow_base + 15;
320     if (is_progressive) {
321         progressive_buf = av_malloc(row_size + 1);
322         if (!progressive_buf)
323             goto fail;
324     }
325     if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
326         rgba_buf = av_malloc(row_size + 1);
327         if (!rgba_buf)
328             goto fail;
329     }
330     if (is_progressive || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
331         top_buf = av_malloc(row_size + 1);
332         if (!top_buf)
333             goto fail;
334     }
335
336     /* write png header */
337     memcpy(s->bytestream, ff_pngsig, 8);
338     s->bytestream += 8;
339
340     AV_WB32(s->buf, avctx->width);
341     AV_WB32(s->buf + 4, avctx->height);
342     s->buf[8]  = bit_depth;
343     s->buf[9]  = color_type;
344     s->buf[10] = 0; /* compression type */
345     s->buf[11] = 0; /* filter type */
346     s->buf[12] = is_progressive; /* interlace type */
347
348     png_write_chunk(&s->bytestream, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
349
350     /* put the palette if needed */
351     if (color_type == PNG_COLOR_TYPE_PALETTE) {
352         int has_alpha, alpha, i;
353         unsigned int v;
354         uint32_t *palette;
355         uint8_t *alpha_ptr;
356
357         palette   = (uint32_t *)p->data[1];
358         ptr       = s->buf;
359         alpha_ptr = s->buf + 256 * 3;
360         has_alpha = 0;
361         for (i = 0; i < 256; i++) {
362             v     = palette[i];
363             alpha = v >> 24;
364             if (alpha && alpha != 0xff)
365                 has_alpha = 1;
366             *alpha_ptr++ = alpha;
367             bytestream_put_be24(&ptr, v);
368         }
369         png_write_chunk(&s->bytestream,
370                         MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
371         if (has_alpha) {
372             png_write_chunk(&s->bytestream,
373                             MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
374         }
375     }
376
377     /* write stereoscopic information */
378     side_data = av_frame_get_side_data(pict, AV_FRAME_DATA_STEREO3D);
379     if (side_data) {
380         AVStereo3D *stereo3d = (AVStereo3D *)side_data->data;
381         uint8_t sm;
382         switch (stereo3d->type) {
383         case AV_STEREO3D_SIDEBYSIDE:
384             sm = !(stereo3d->flags & AV_STEREO3D_FLAG_INVERT);
385             png_write_chunk(&s->bytestream, MKTAG('s', 'T', 'E', 'R'), &sm, 1);
386             break;
387         case AV_STEREO3D_2D:
388             break;
389         default:
390             av_log(avctx, AV_LOG_WARNING,
391                    "Only side-by-side stereo3d flag can be defined within sTER chunk\n");
392             break;
393         }
394     }
395
396     /* now put each row */
397     s->zstream.avail_out = IOBUF_SIZE;
398     s->zstream.next_out  = s->buf;
399     if (is_progressive) {
400         int pass;
401
402         for (pass = 0; pass < NB_PASSES; pass++) {
403             /* NOTE: a pass is completely omitted if no pixels would be
404              * output */
405             pass_row_size = ff_png_pass_row_size(pass, bits_per_pixel, avctx->width);
406             if (pass_row_size > 0) {
407                 top = NULL;
408                 for (y = 0; y < avctx->height; y++)
409                     if ((ff_png_pass_ymask[pass] << (y & 7)) & 0x80) {
410                         ptr = p->data[0] + y * p->linesize[0];
411                         FFSWAP(uint8_t *, progressive_buf, top_buf);
412                         if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
413                             convert_from_rgb32(rgba_buf, ptr, avctx->width);
414                             ptr = rgba_buf;
415                         }
416                         png_get_interlaced_row(progressive_buf, pass_row_size,
417                                                bits_per_pixel, pass,
418                                                ptr, avctx->width);
419                         crow = png_choose_filter(s, crow_buf, progressive_buf,
420                                                  top, pass_row_size, bits_per_pixel >> 3);
421                         png_write_row(s, crow, pass_row_size + 1);
422                         top = progressive_buf;
423                     }
424             }
425         }
426     } else {
427         top = NULL;
428         for (y = 0; y < avctx->height; y++) {
429             ptr = p->data[0] + y * p->linesize[0];
430             if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
431                 FFSWAP(uint8_t *, rgba_buf, top_buf);
432                 convert_from_rgb32(rgba_buf, ptr, avctx->width);
433                 ptr = rgba_buf;
434             }
435             crow = png_choose_filter(s, crow_buf, ptr, top,
436                                      row_size, bits_per_pixel >> 3);
437             png_write_row(s, crow, row_size + 1);
438             top = ptr;
439         }
440     }
441     /* compress last bytes */
442     for (;;) {
443         ret = deflate(&s->zstream, Z_FINISH);
444         if (ret == Z_OK || ret == Z_STREAM_END) {
445             len = IOBUF_SIZE - s->zstream.avail_out;
446             if (len > 0 && s->bytestream_end - s->bytestream > len + 100) {
447                 png_write_chunk(&s->bytestream, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
448             }
449             s->zstream.avail_out = IOBUF_SIZE;
450             s->zstream.next_out  = s->buf;
451             if (ret == Z_STREAM_END)
452                 break;
453         } else {
454             goto fail;
455         }
456     }
457     png_write_chunk(&s->bytestream, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
458
459     pkt->size   = s->bytestream - s->bytestream_start;
460     pkt->flags |= AV_PKT_FLAG_KEY;
461     *got_packet = 1;
462     ret         = 0;
463
464 the_end:
465     av_free(crow_base);
466     av_free(progressive_buf);
467     av_free(rgba_buf);
468     av_free(top_buf);
469     deflateEnd(&s->zstream);
470     return ret;
471 fail:
472     ret = -1;
473     goto the_end;
474 }
475
476 static av_cold int png_enc_init(AVCodecContext *avctx)
477 {
478     PNGEncContext *s = avctx->priv_data;
479
480 #if FF_API_CODED_FRAME
481 FF_DISABLE_DEPRECATION_WARNINGS
482     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
483     avctx->coded_frame->key_frame = 1;
484 FF_ENABLE_DEPRECATION_WARNINGS
485 #endif
486
487     ff_huffyuvencdsp_init(&s->hdsp);
488
489     s->filter_type = av_clip(avctx->prediction_method,
490                              PNG_FILTER_VALUE_NONE,
491                              PNG_FILTER_VALUE_MIXED);
492     if (avctx->pix_fmt == AV_PIX_FMT_MONOBLACK)
493         s->filter_type = PNG_FILTER_VALUE_NONE;
494
495     return 0;
496 }
497
498 AVCodec ff_png_encoder = {
499     .name           = "png",
500     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
501     .type           = AVMEDIA_TYPE_VIDEO,
502     .id             = AV_CODEC_ID_PNG,
503     .priv_data_size = sizeof(PNGEncContext),
504     .init           = png_enc_init,
505     .encode2        = encode_frame,
506     .pix_fmts       = (const enum AVPixelFormat[]) {
507         AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB32, AV_PIX_FMT_PAL8, AV_PIX_FMT_GRAY8,
508         AV_PIX_FMT_RGBA64BE, AV_PIX_FMT_RGB48BE, AV_PIX_FMT_GRAY16BE,
509         AV_PIX_FMT_MONOBLACK, AV_PIX_FMT_NONE
510     },
511 };