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