]> git.sesse.net Git - ffmpeg/blob - libavformat/png.c
Segmentation fault fix when no video device is specified.
[ffmpeg] / libavformat / png.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 "avformat.h"
22
23 /* TODO:
24  * - add 2, 4 and 16 bit depth support
25  * - use filters when generating a png (better compression)
26  */
27
28 #ifdef CONFIG_ZLIB
29 #include <zlib.h>
30
31 //#define DEBUG
32
33 #define PNG_COLOR_MASK_PALETTE    1
34 #define PNG_COLOR_MASK_COLOR      2
35 #define PNG_COLOR_MASK_ALPHA      4
36
37 #define PNG_COLOR_TYPE_GRAY 0
38 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
39 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
40 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
41 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
42
43 #define PNG_FILTER_VALUE_NONE  0
44 #define PNG_FILTER_VALUE_SUB   1
45 #define PNG_FILTER_VALUE_UP    2
46 #define PNG_FILTER_VALUE_AVG   3
47 #define PNG_FILTER_VALUE_PAETH 4
48
49 #define PNG_IHDR      0x0001
50 #define PNG_IDAT      0x0002
51 #define PNG_ALLIMAGE  0x0004
52 #define PNG_PLTE      0x0008
53
54 #define NB_PASSES 7
55
56 #define IOBUF_SIZE 4096
57
58 typedef struct PNGDecodeState {
59     int state;
60     int width, height;
61     int bit_depth;
62     int color_type;
63     int compression_type;
64     int interlace_type;
65     int filter_type;
66     int channels;
67     int bits_per_pixel;
68     int bpp;
69
70     uint8_t *image_buf;
71     int image_linesize;
72     uint32_t palette[256];
73     uint8_t *crow_buf;
74     uint8_t *last_row;
75     uint8_t *tmp_row;
76     int pass;
77     int crow_size; /* compressed row size (include filter type) */
78     int row_size; /* decompressed row size */
79     int pass_row_size; /* decompress row size of the current pass */
80     int y;
81     z_stream zstream;
82 } PNGDecodeState;
83
84 static const uint8_t pngsig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
85
86 /* Mask to determine which y pixels are valid in a pass */
87 static const uint8_t png_pass_ymask[NB_PASSES] = {
88     0x80, 0x80, 0x08, 0x88, 0x22, 0xaa, 0x55,
89 };
90
91 /* Mask to determine which y pixels can be written in a pass */
92 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
93     0xff, 0xff, 0x0f, 0xcc, 0x33, 0xff, 0x55,
94 };
95
96 /* minimum x value */
97 static const uint8_t png_pass_xmin[NB_PASSES] = {
98     0, 4, 0, 2, 0, 1, 0
99 };
100
101 /* x shift to get row width */
102 static const uint8_t png_pass_xshift[NB_PASSES] = {
103     3, 3, 2, 2, 1, 1, 0
104 };
105
106 /* Mask to determine which pixels are valid in a pass */
107 static const uint8_t png_pass_mask[NB_PASSES] = {
108     0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff
109 };
110
111 /* Mask to determine which pixels to overwrite while displaying */
112 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
113     0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
114 };
115
116 static int png_probe(AVProbeData *pd)
117 {
118     if (pd->buf_size >= 8 &&
119         memcmp(pd->buf, pngsig, 8) == 0)
120         return AVPROBE_SCORE_MAX;
121     else
122         return 0;
123 }
124
125 static void *png_zalloc(void *opaque, unsigned int items, unsigned int size)
126 {
127     return av_malloc(items * size);
128 }
129
130 static void png_zfree(void *opaque, void *ptr)
131 {
132     av_free(ptr);
133 }
134
135 static int png_get_nb_channels(int color_type)
136 {
137     int channels;
138     channels = 1;
139     if ((color_type & (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)) ==
140         PNG_COLOR_MASK_COLOR)
141         channels = 3;
142     if (color_type & PNG_COLOR_MASK_ALPHA)
143         channels++;
144     return channels;
145 }
146
147 /* compute the row size of an interleaved pass */
148 static int png_pass_row_size(int pass, int bits_per_pixel, int width)
149 {
150     int shift, xmin, pass_width;
151
152     xmin = png_pass_xmin[pass];
153     if (width <= xmin)
154         return 0;
155     shift = png_pass_xshift[pass];
156     pass_width = (width - xmin + (1 << shift) - 1) >> shift;
157     return (pass_width * bits_per_pixel + 7) >> 3;
158 }
159
160 /* NOTE: we try to construct a good looking image at each pass. width
161    is the original image width. We also do pixel format convertion at
162    this stage */
163 static void png_put_interlaced_row(uint8_t *dst, int width,
164                                    int bits_per_pixel, int pass,
165                                    int color_type, const uint8_t *src)
166 {
167     int x, mask, dsp_mask, j, src_x, b, bpp;
168     uint8_t *d;
169     const uint8_t *s;
170
171     mask = png_pass_mask[pass];
172     dsp_mask = png_pass_dsp_mask[pass];
173     switch(bits_per_pixel) {
174     case 1:
175         /* we must intialize the line to zero before writing to it */
176         if (pass == 0)
177             memset(dst, 0, (width + 7) >> 3);
178         src_x = 0;
179         for(x = 0; x < width; x++) {
180             j = (x & 7);
181             if ((dsp_mask << j) & 0x80) {
182                 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
183                 dst[x >> 3] |= b << (7 - j);
184             }
185             if ((mask << j) & 0x80)
186                 src_x++;
187         }
188         break;
189     default:
190         bpp = bits_per_pixel >> 3;
191         d = dst;
192         s = src;
193         if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
194             for(x = 0; x < width; x++) {
195                 j = x & 7;
196                 if ((dsp_mask << j) & 0x80) {
197                     *(uint32_t *)d = (s[3] << 24) | (s[0] << 16) | (s[1] << 8) | s[2];
198                 }
199                 d += bpp;
200                 if ((mask << j) & 0x80)
201                     s += bpp;
202             }
203         } else {
204             for(x = 0; x < width; x++) {
205                 j = x & 7;
206                 if ((dsp_mask << j) & 0x80) {
207                     memcpy(d, s, bpp);
208                 }
209                 d += bpp;
210                 if ((mask << j) & 0x80)
211                     s += bpp;
212             }
213         }
214         break;
215     }
216 }
217
218 static void png_get_interlaced_row(uint8_t *dst, int row_size,
219                                    int bits_per_pixel, int pass,
220                                    const uint8_t *src, int width)
221 {
222     int x, mask, dst_x, j, b, bpp;
223     uint8_t *d;
224     const uint8_t *s;
225
226     mask = png_pass_mask[pass];
227     switch(bits_per_pixel) {
228     case 1:
229         memset(dst, 0, row_size);
230         dst_x = 0;
231         for(x = 0; x < width; x++) {
232             j = (x & 7);
233             if ((mask << j) & 0x80) {
234                 b = (src[x >> 3] >> (7 - j)) & 1;
235                 dst[dst_x >> 3] |= b << (7 - (dst_x & 7));
236                 dst_x++;
237             }
238         }
239         break;
240     default:
241         bpp = bits_per_pixel >> 3;
242         d = dst;
243         s = src;
244         for(x = 0; x < width; x++) {
245             j = x & 7;
246             if ((mask << j) & 0x80) {
247                 memcpy(d, s, bpp);
248                 d += bpp;
249             }
250             s += bpp;
251         }
252         break;
253     }
254 }
255
256 /* XXX: optimize */
257 /* NOTE: 'dst' can be equal to 'last' */
258 static void png_filter_row(uint8_t *dst, int filter_type,
259                            uint8_t *src, uint8_t *last, int size, int bpp)
260 {
261     int i, p;
262
263     switch(filter_type) {
264     case PNG_FILTER_VALUE_NONE:
265         memcpy(dst, src, size);
266         break;
267     case PNG_FILTER_VALUE_SUB:
268         for(i = 0; i < bpp; i++) {
269             dst[i] = src[i];
270         }
271         for(i = bpp; i < size; i++) {
272             p = dst[i - bpp];
273             dst[i] = p + src[i];
274         }
275         break;
276     case PNG_FILTER_VALUE_UP:
277         for(i = 0; i < size; i++) {
278             p = last[i];
279             dst[i] = p + src[i];
280         }
281         break;
282     case PNG_FILTER_VALUE_AVG:
283         for(i = 0; i < bpp; i++) {
284             p = (last[i] >> 1);
285             dst[i] = p + src[i];
286         }
287         for(i = bpp; i < size; i++) {
288             p = ((dst[i - bpp] + last[i]) >> 1);
289             dst[i] = p + src[i];
290         }
291         break;
292     case PNG_FILTER_VALUE_PAETH:
293         for(i = 0; i < bpp; i++) {
294             p = last[i];
295             dst[i] = p + src[i];
296         }
297         for(i = bpp; i < size; i++) {
298             int a, b, c, pa, pb, pc;
299
300             a = dst[i - bpp];
301             b = last[i];
302             c = last[i - bpp];
303
304             p = b - c;
305             pc = a - c;
306
307             pa = abs(p);
308             pb = abs(pc);
309             pc = abs(p + pc);
310
311             if (pa <= pb && pa <= pc)
312                 p = a;
313             else if (pb <= pc)
314                 p = b;
315             else
316                 p = c;
317             dst[i] = p + src[i];
318         }
319         break;
320     }
321 }
322
323 static void convert_from_rgba32(uint8_t *dst, const uint8_t *src, int width)
324 {
325     uint8_t *d;
326     int j;
327     unsigned int v;
328
329     d = dst;
330     for(j = 0; j < width; j++) {
331         v = ((const uint32_t *)src)[j];
332         d[0] = v >> 16;
333         d[1] = v >> 8;
334         d[2] = v;
335         d[3] = v >> 24;
336         d += 4;
337     }
338 }
339
340 static void convert_to_rgba32(uint8_t *dst, const uint8_t *src, int width)
341 {
342     int j;
343     unsigned int r, g, b, a;
344
345     for(j = 0;j < width; j++) {
346         r = src[0];
347         g = src[1];
348         b = src[2];
349         a = src[3];
350         *(uint32_t *)dst = (a << 24) | (r << 16) | (g << 8) | b;
351         dst += 4;
352         src += 4;
353     }
354 }
355
356 /* process exactly one decompressed row */
357 static void png_handle_row(PNGDecodeState *s)
358 {
359     uint8_t *ptr, *last_row;
360     int got_line;
361
362     if (!s->interlace_type) {
363         ptr = s->image_buf + s->image_linesize * s->y;
364         /* need to swap bytes correctly for RGB_ALPHA */
365         if (s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
366             png_filter_row(s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
367                            s->last_row, s->row_size, s->bpp);
368             memcpy(s->last_row, s->tmp_row, s->row_size);
369             convert_to_rgba32(ptr, s->tmp_row, s->width);
370         } else {
371             /* in normal case, we avoid one copy */
372             if (s->y == 0)
373                 last_row = s->last_row;
374             else
375                 last_row = ptr - s->image_linesize;
376
377             png_filter_row(ptr, s->crow_buf[0], s->crow_buf + 1,
378                            last_row, s->row_size, s->bpp);
379         }
380         s->y++;
381         if (s->y == s->height) {
382             s->state |= PNG_ALLIMAGE;
383         }
384     } else {
385         got_line = 0;
386         for(;;) {
387             ptr = s->image_buf + s->image_linesize * s->y;
388             if ((png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
389                 /* if we already read one row, it is time to stop to
390                    wait for the next one */
391                 if (got_line)
392                     break;
393                 png_filter_row(s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
394                                s->last_row, s->pass_row_size, s->bpp);
395                 memcpy(s->last_row, s->tmp_row, s->pass_row_size);
396                 got_line = 1;
397             }
398             if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
399                 /* NOTE: rgba32 is handled directly in png_put_interlaced_row */
400                 png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
401                                        s->color_type, s->last_row);
402             }
403             s->y++;
404             if (s->y == s->height) {
405                 for(;;) {
406                     if (s->pass == NB_PASSES - 1) {
407                         s->state |= PNG_ALLIMAGE;
408                         goto the_end;
409                     } else {
410                         s->pass++;
411                         s->y = 0;
412                         s->pass_row_size = png_pass_row_size(s->pass,
413                                                              s->bits_per_pixel,
414                                                              s->width);
415                         s->crow_size = s->pass_row_size + 1;
416                         if (s->pass_row_size != 0)
417                             break;
418                         /* skip pass if empty row */
419                     }
420                 }
421             }
422         }
423     the_end: ;
424     }
425 }
426
427 static int png_decode_idat(PNGDecodeState *s, ByteIOContext *f, int length)
428 {
429     uint8_t buf[IOBUF_SIZE];
430     int buf_size;
431     int ret;
432     while (length > 0) {
433         /* read the buffer */
434         buf_size = IOBUF_SIZE;
435         if (buf_size > length)
436             buf_size = length;
437         ret = get_buffer(f, buf, buf_size);
438         if (ret != buf_size)
439             return -1;
440         s->zstream.avail_in = buf_size;
441         s->zstream.next_in = buf;
442         /* decode one line if possible */
443         while (s->zstream.avail_in > 0) {
444             ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
445             if (ret != Z_OK && ret != Z_STREAM_END) {
446                 return -1;
447             }
448             if (s->zstream.avail_out == 0) {
449                 if (!(s->state & PNG_ALLIMAGE)) {
450                     png_handle_row(s);
451                 }
452                 s->zstream.avail_out = s->crow_size;
453                 s->zstream.next_out = s->crow_buf;
454             }
455         }
456         length -= buf_size;
457     }
458     return 0;
459 }
460
461 static int png_read(ByteIOContext *f,
462                     int (*alloc_cb)(void *opaque, AVImageInfo *info), void *opaque)
463 {
464     AVImageInfo info1, *info = &info1;
465     PNGDecodeState s1, *s = &s1;
466     uint32_t tag, length;
467     int ret, crc;
468     uint8_t buf[8];
469
470     /* check signature */
471     ret = get_buffer(f, buf, 8);
472     if (ret != 8)
473         return -1;
474     if (memcmp(buf, pngsig, 8) != 0)
475         return -1;
476     memset(s, 0, sizeof(PNGDecodeState));
477     /* init the zlib */
478     s->zstream.zalloc = png_zalloc;
479     s->zstream.zfree = png_zfree;
480     s->zstream.opaque = NULL;
481     ret = inflateInit(&s->zstream);
482     if (ret != Z_OK)
483         return -1;
484     for(;;) {
485         if (url_feof(f))
486             goto fail;
487         length = get_be32(f);
488         if (length > 0x7fffffff)
489             goto fail;
490         tag = get_le32(f);
491 #ifdef DEBUG
492         printf("png: tag=%c%c%c%c length=%u\n",
493                (tag & 0xff),
494                ((tag >> 8) & 0xff),
495                ((tag >> 16) & 0xff),
496                ((tag >> 24) & 0xff), length);
497 #endif
498         switch(tag) {
499         case MKTAG('I', 'H', 'D', 'R'):
500             if (length != 13)
501                 goto fail;
502             s->width = get_be32(f);
503             s->height = get_be32(f);
504             s->bit_depth = get_byte(f);
505             s->color_type = get_byte(f);
506             s->compression_type = get_byte(f);
507             s->filter_type = get_byte(f);
508             s->interlace_type = get_byte(f);
509             crc = get_be32(f);
510             s->state |= PNG_IHDR;
511 #ifdef DEBUG
512             printf("width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
513                    s->width, s->height, s->bit_depth, s->color_type,
514                    s->compression_type, s->filter_type, s->interlace_type);
515 #endif
516             break;
517         case MKTAG('I', 'D', 'A', 'T'):
518             if (!(s->state & PNG_IHDR))
519                 goto fail;
520             if (!(s->state & PNG_IDAT)) {
521                 /* init image info */
522                 info->width = s->width;
523                 info->height = s->height;
524                 info->interleaved = (s->interlace_type != 0);
525
526                 s->channels = png_get_nb_channels(s->color_type);
527                 s->bits_per_pixel = s->bit_depth * s->channels;
528                 s->bpp = (s->bits_per_pixel + 7) >> 3;
529                 s->row_size = (info->width * s->bits_per_pixel + 7) >> 3;
530
531                 if (s->bit_depth == 8 &&
532                     s->color_type == PNG_COLOR_TYPE_RGB) {
533                     info->pix_fmt = PIX_FMT_RGB24;
534                 } else if (s->bit_depth == 8 &&
535                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
536                     info->pix_fmt = PIX_FMT_RGBA32;
537                 } else if (s->bit_depth == 8 &&
538                            s->color_type == PNG_COLOR_TYPE_GRAY) {
539                     info->pix_fmt = PIX_FMT_GRAY8;
540                 } else if (s->bit_depth == 1 &&
541                            s->color_type == PNG_COLOR_TYPE_GRAY) {
542                     info->pix_fmt = PIX_FMT_MONOBLACK;
543                 } else if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
544                     info->pix_fmt = PIX_FMT_PAL8;
545                 } else {
546                     goto fail;
547                 }
548                 ret = alloc_cb(opaque, info);
549                 if (ret)
550                     goto the_end;
551
552                 /* compute the compressed row size */
553                 if (!s->interlace_type) {
554                     s->crow_size = s->row_size + 1;
555                 } else {
556                     s->pass = 0;
557                     s->pass_row_size = png_pass_row_size(s->pass,
558                                                          s->bits_per_pixel,
559                                                          s->width);
560                     s->crow_size = s->pass_row_size + 1;
561                 }
562 #ifdef DEBUG
563                 printf("row_size=%d crow_size =%d\n",
564                        s->row_size, s->crow_size);
565 #endif
566                 s->image_buf = info->pict.data[0];
567                 s->image_linesize = info->pict.linesize[0];
568                 /* copy the palette if needed */
569                 if (s->color_type == PNG_COLOR_TYPE_PALETTE)
570                     memcpy(info->pict.data[1], s->palette, 256 * sizeof(uint32_t));
571                 /* empty row is used if differencing to the first row */
572                 s->last_row = av_mallocz(s->row_size);
573                 if (!s->last_row)
574                     goto fail;
575                 if (s->interlace_type ||
576                     s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
577                     s->tmp_row = av_malloc(s->row_size);
578                     if (!s->tmp_row)
579                         goto fail;
580                 }
581                 /* compressed row */
582                 s->crow_buf = av_malloc(s->row_size + 1);
583                 if (!s->crow_buf)
584                     goto fail;
585                 s->zstream.avail_out = s->crow_size;
586                 s->zstream.next_out = s->crow_buf;
587             }
588             s->state |= PNG_IDAT;
589             if (png_decode_idat(s, f, length) < 0)
590                 goto fail;
591             /* skip crc */
592             crc = get_be32(f);
593             break;
594         case MKTAG('P', 'L', 'T', 'E'):
595             {
596                 int n, i, r, g, b;
597
598                 if ((length % 3) != 0 || length > 256 * 3)
599                     goto skip_tag;
600                 /* read the palette */
601                 n = length / 3;
602                 for(i=0;i<n;i++) {
603                     r = get_byte(f);
604                     g = get_byte(f);
605                     b = get_byte(f);
606                     s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
607                 }
608                 for(;i<256;i++) {
609                     s->palette[i] = (0xff << 24);
610                 }
611                 s->state |= PNG_PLTE;
612                 crc = get_be32(f);
613             }
614             break;
615         case MKTAG('t', 'R', 'N', 'S'):
616             {
617                 int v, i;
618
619                 /* read the transparency. XXX: Only palette mode supported */
620                 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
621                     length > 256 ||
622                     !(s->state & PNG_PLTE))
623                     goto skip_tag;
624                 for(i=0;i<length;i++) {
625                     v = get_byte(f);
626                     s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
627                 }
628                 crc = get_be32(f);
629             }
630             break;
631         case MKTAG('I', 'E', 'N', 'D'):
632             if (!(s->state & PNG_ALLIMAGE))
633                 goto fail;
634             crc = get_be32(f);
635             goto exit_loop;
636         default:
637             /* skip tag */
638         skip_tag:
639             url_fskip(f, length + 4);
640             break;
641         }
642     }
643  exit_loop:
644     ret = 0;
645  the_end:
646     inflateEnd(&s->zstream);
647     av_free(s->crow_buf);
648     av_free(s->last_row);
649     av_free(s->tmp_row);
650     return ret;
651  fail:
652     ret = -1;
653     goto the_end;
654 }
655
656 static void png_write_chunk(ByteIOContext *f, uint32_t tag,
657                             const uint8_t *buf, int length)
658 {
659     uint32_t crc;
660     uint8_t tagbuf[4];
661
662     put_be32(f, length);
663     crc = crc32(0, Z_NULL, 0);
664     tagbuf[0] = tag;
665     tagbuf[1] = tag >> 8;
666     tagbuf[2] = tag >> 16;
667     tagbuf[3] = tag >> 24;
668     crc = crc32(crc, tagbuf, 4);
669     put_le32(f, tag);
670     if (length > 0) {
671         crc = crc32(crc, buf, length);
672         put_buffer(f, buf, length);
673     }
674     put_be32(f, crc);
675 }
676
677 /* XXX: use avcodec generic function ? */
678 static void to_be32(uint8_t *p, uint32_t v)
679 {
680     p[0] = v >> 24;
681     p[1] = v >> 16;
682     p[2] = v >> 8;
683     p[3] = v;
684 }
685
686 typedef struct PNGEncodeState {
687     ByteIOContext *f;
688     z_stream zstream;
689     uint8_t buf[IOBUF_SIZE];
690 } PNGEncodeState;
691
692
693 /* XXX: do filtering */
694 static int png_write_row(PNGEncodeState *s, const uint8_t *data, int size)
695 {
696     int ret;
697
698     s->zstream.avail_in = size;
699     s->zstream.next_in = (uint8_t *)data;
700     while (s->zstream.avail_in > 0) {
701         ret = deflate(&s->zstream, Z_NO_FLUSH);
702         if (ret != Z_OK)
703             return -1;
704         if (s->zstream.avail_out == 0) {
705             png_write_chunk(s->f, MKTAG('I', 'D', 'A', 'T'), s->buf, IOBUF_SIZE);
706             s->zstream.avail_out = IOBUF_SIZE;
707             s->zstream.next_out = s->buf;
708         }
709     }
710     return 0;
711 }
712
713 static int png_write(ByteIOContext *f, AVImageInfo *info)
714 {
715     PNGEncodeState s1, *s = &s1;
716     int bit_depth, color_type, y, len, row_size, ret, is_progressive;
717     int bits_per_pixel, pass_row_size;
718     uint8_t *ptr;
719     uint8_t *crow_buf = NULL;
720     uint8_t *tmp_buf = NULL;
721
722     s->f = f;
723     is_progressive = info->interleaved;
724     switch(info->pix_fmt) {
725     case PIX_FMT_RGBA32:
726         bit_depth = 8;
727         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
728         break;
729     case PIX_FMT_RGB24:
730         bit_depth = 8;
731         color_type = PNG_COLOR_TYPE_RGB;
732         break;
733     case PIX_FMT_GRAY8:
734         bit_depth = 8;
735         color_type = PNG_COLOR_TYPE_GRAY;
736         break;
737     case PIX_FMT_MONOBLACK:
738         bit_depth = 1;
739         color_type = PNG_COLOR_TYPE_GRAY;
740         break;
741     case PIX_FMT_PAL8:
742         bit_depth = 8;
743         color_type = PNG_COLOR_TYPE_PALETTE;
744         break;
745     default:
746         return -1;
747     }
748     bits_per_pixel = png_get_nb_channels(color_type) * bit_depth;
749     row_size = (info->width * bits_per_pixel + 7) >> 3;
750
751     s->zstream.zalloc = png_zalloc;
752     s->zstream.zfree = png_zfree;
753     s->zstream.opaque = NULL;
754     ret = deflateInit2(&s->zstream, Z_DEFAULT_COMPRESSION,
755                        Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
756     if (ret != Z_OK)
757         return -1;
758     crow_buf = av_malloc(row_size + 1);
759     if (!crow_buf)
760         goto fail;
761     if (is_progressive) {
762         tmp_buf = av_malloc(row_size + 1);
763         if (!tmp_buf)
764             goto fail;
765     }
766
767     /* write png header */
768     put_buffer(f, pngsig, 8);
769
770     to_be32(s->buf, info->width);
771     to_be32(s->buf + 4, info->height);
772     s->buf[8] = bit_depth;
773     s->buf[9] = color_type;
774     s->buf[10] = 0; /* compression type */
775     s->buf[11] = 0; /* filter type */
776     s->buf[12] = is_progressive; /* interlace type */
777
778     png_write_chunk(f, MKTAG('I', 'H', 'D', 'R'), s->buf, 13);
779
780     /* put the palette if needed */
781     if (color_type == PNG_COLOR_TYPE_PALETTE) {
782         int has_alpha, alpha, i;
783         unsigned int v;
784         uint32_t *palette;
785         uint8_t *alpha_ptr;
786
787         palette = (uint32_t *)info->pict.data[1];
788         ptr = s->buf;
789         alpha_ptr = s->buf + 256 * 3;
790         has_alpha = 0;
791         for(i = 0; i < 256; i++) {
792             v = palette[i];
793             alpha = v >> 24;
794             if (alpha != 0xff)
795                 has_alpha = 1;
796             *alpha_ptr++ = alpha;
797             ptr[0] = v >> 16;
798             ptr[1] = v >> 8;
799             ptr[2] = v;
800             ptr += 3;
801         }
802         png_write_chunk(f, MKTAG('P', 'L', 'T', 'E'), s->buf, 256 * 3);
803         if (has_alpha) {
804             png_write_chunk(f, MKTAG('t', 'R', 'N', 'S'), s->buf + 256 * 3, 256);
805         }
806     }
807
808     /* now put each row */
809     s->zstream.avail_out = IOBUF_SIZE;
810     s->zstream.next_out = s->buf;
811     if (is_progressive) {
812         uint8_t *ptr1;
813         int pass;
814
815         for(pass = 0; pass < NB_PASSES; pass++) {
816             /* NOTE: a pass is completely omited if no pixels would be
817                output */
818             pass_row_size = png_pass_row_size(pass, bits_per_pixel, info->width);
819             if (pass_row_size > 0) {
820                 for(y = 0; y < info->height; y++) {
821                     if ((png_pass_ymask[pass] << (y & 7)) & 0x80) {
822                         ptr = info->pict.data[0] + y * info->pict.linesize[0];
823                         if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
824                             convert_from_rgba32(tmp_buf, ptr, info->width);
825                             ptr1 = tmp_buf;
826                         } else {
827                             ptr1 = ptr;
828                         }
829                         png_get_interlaced_row(crow_buf + 1, pass_row_size,
830                                                bits_per_pixel, pass,
831                                                ptr1, info->width);
832                         crow_buf[0] = PNG_FILTER_VALUE_NONE;
833                         png_write_row(s, crow_buf, pass_row_size + 1);
834                     }
835                 }
836             }
837         }
838     } else {
839         for(y = 0; y < info->height; y++) {
840             ptr = info->pict.data[0] + y * info->pict.linesize[0];
841             if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
842                 convert_from_rgba32(crow_buf + 1, ptr, info->width);
843             else
844                 memcpy(crow_buf + 1, ptr, row_size);
845             crow_buf[0] = PNG_FILTER_VALUE_NONE;
846             png_write_row(s, crow_buf, row_size + 1);
847         }
848     }
849     /* compress last bytes */
850     for(;;) {
851         ret = deflate(&s->zstream, Z_FINISH);
852         if (ret == Z_OK || ret == Z_STREAM_END) {
853             len = IOBUF_SIZE - s->zstream.avail_out;
854             if (len > 0) {
855                 png_write_chunk(f, MKTAG('I', 'D', 'A', 'T'), s->buf, len);
856             }
857             s->zstream.avail_out = IOBUF_SIZE;
858             s->zstream.next_out = s->buf;
859             if (ret == Z_STREAM_END)
860                 break;
861         } else {
862             goto fail;
863         }
864     }
865     png_write_chunk(f, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
866
867     put_flush_packet(f);
868     ret = 0;
869  the_end:
870     av_free(crow_buf);
871     av_free(tmp_buf);
872     deflateEnd(&s->zstream);
873     return ret;
874  fail:
875     ret = -1;
876     goto the_end;
877 }
878
879 AVImageFormat png_image_format = {
880     "png",
881     "png",
882     png_probe,
883     png_read,
884     (1 << PIX_FMT_RGBA32) | (1 << PIX_FMT_RGB24) | (1 << PIX_FMT_GRAY8) |
885     (1 << PIX_FMT_MONOBLACK) | (1 << PIX_FMT_PAL8),
886     png_write,
887     AVIMAGE_INTERLEAVED,
888 };
889 #endif