]> git.sesse.net Git - ffmpeg/blob - libavformat/png.c
round readed bits up to next 32bits, as orginal huffyuv cant handle less then 32bit...
[ffmpeg] / libavformat / 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 "avformat.h"
20
21 #include <zlib.h>
22
23 //#define DEBUG
24
25 #define PNG_COLOR_MASK_PALETTE    1
26 #define PNG_COLOR_MASK_COLOR      2
27 #define PNG_COLOR_MASK_ALPHA      4
28
29 #define PNG_COLOR_TYPE_GRAY 0
30 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
31 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
32 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
33 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
34
35 #define PNG_FILTER_VALUE_NONE  0
36 #define PNG_FILTER_VALUE_SUB   1
37 #define PNG_FILTER_VALUE_UP    2
38 #define PNG_FILTER_VALUE_AVG   3
39 #define PNG_FILTER_VALUE_PAETH 4
40
41 #define PNG_IHDR      0x0001
42 #define PNG_IDAT      0x0002
43 #define PNG_ALLIMAGE  0x0004
44 #define PNG_PLTE      0x0008
45
46 #define IOBUF_SIZE 4096
47
48 typedef struct PNGDecodeState {
49     int state;
50     int width, height;
51     int bit_depth;
52     int color_type;
53     int compression_type;
54     int interlace_type;
55     int filter_type;
56     int channels;
57     int bits_per_pixel;
58     int bpp;
59     
60     uint8_t *image_buf;
61     int image_linesize;
62     uint32_t palette[256];
63     uint8_t *crow_buf;
64     uint8_t *empty_row;
65     int crow_size; /* compressed row size (include filter type) */
66     int row_size; /* decompressed row size */
67     int y;
68     z_stream zstream;
69 } PNGDecodeState;
70
71 static const uint8_t pngsig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
72
73 static int png_probe(AVProbeData *pd)
74 {
75     if (pd->buf_size >= 8 &&
76         memcmp(pd->buf, pngsig, 8) == 0)
77         return AVPROBE_SCORE_MAX;
78     else
79         return 0;
80 }
81
82 static void *png_zalloc(void *opaque, unsigned int items, unsigned int size)
83 {
84     return av_malloc(items * size);
85 }
86
87 static void png_zfree(void *opaque, void *ptr)
88 {
89     av_free(ptr);
90 }
91
92 /* XXX: optimize */
93 static void png_filter_row(uint8_t *dst, int filter_type, 
94                            uint8_t *src, uint8_t *last, int size, int bpp)
95 {
96     int i, p;
97
98     switch(filter_type) {
99     case PNG_FILTER_VALUE_NONE:
100         memcpy(dst, src, size);
101         break;
102     case PNG_FILTER_VALUE_SUB:
103         for(i = 0; i < bpp; i++) {
104             dst[i] = src[i];
105         }
106         for(i = bpp; i < size; i++) {
107             p = dst[i - bpp];
108             dst[i] = p + src[i];
109         }
110         break;
111     case PNG_FILTER_VALUE_UP:
112         for(i = 0; i < size; i++) {
113             p = last[i];
114             dst[i] = p + src[i];
115         }
116         break;
117     case PNG_FILTER_VALUE_AVG:
118         for(i = 0; i < bpp; i++) {
119             p = (last[i] >> 1);
120             dst[i] = p + src[i];
121         }
122         for(i = bpp; i < size; i++) {
123             p = ((dst[i - bpp] + last[i]) >> 1);
124             dst[i] = p + src[i];
125         }
126         break;
127     case PNG_FILTER_VALUE_PAETH:
128         for(i = 0; i < bpp; i++) {
129             p = last[i];
130             dst[i] = p + src[i];
131         }
132         for(i = bpp; i < size; i++) {
133             int a, b, c, pa, pb, pc;
134
135             a = dst[i - bpp];
136             b = last[i];
137             c = last[i - bpp];
138
139             p = b - c;
140             pc = a - c;
141
142             pa = abs(p);
143             pb = abs(pc);
144             pc = abs(p + pc);
145
146             if (pa <= pb && pa <= pc)
147                 p = a;
148             else if (pb <= pc)
149                 p = b;
150             else
151                 p = c;
152             dst[i] = p + src[i];
153         }
154         break;
155     }
156 }
157
158 static void png_handle_row(PNGDecodeState *s)
159 {
160     uint8_t *ptr, *last_row;
161     ptr = s->image_buf + s->image_linesize * s->y;
162     if (s->y == 0)
163         last_row = s->empty_row;
164     else
165         last_row = ptr - s->image_linesize;
166
167     png_filter_row(ptr, s->crow_buf[0], s->crow_buf + 1, 
168                    last_row, s->row_size, s->bpp);
169 }
170
171 static int png_decode_idat(PNGDecodeState *s, ByteIOContext *f, int length)
172 {
173     uint8_t buf[IOBUF_SIZE];
174     int buf_size;
175     int ret;
176     while (length > 0) {
177         /* read the buffer */
178         buf_size = IOBUF_SIZE;
179         if (buf_size > length)
180             buf_size = length;
181         ret = get_buffer(f, buf, buf_size);
182         if (ret != buf_size)
183             return -1;
184         s->zstream.avail_in = buf_size;
185         s->zstream.next_in = buf;
186         /* decode one line if possible */
187         while (s->zstream.avail_in > 0) {
188             ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
189             if (ret != Z_OK && ret != Z_STREAM_END) {
190                 return -1;
191             }
192             if (s->zstream.avail_out == 0) {
193                 if (s->y < s->height) {
194                     png_handle_row(s);
195                     s->y++;
196                     if (s->y == s->height)
197                         s->state |= PNG_ALLIMAGE;
198                 }
199                 s->zstream.avail_out = s->crow_size;
200                 s->zstream.next_out = s->crow_buf;
201             }
202         }
203         length -= buf_size;
204     }
205     return 0;
206 }
207
208 static int png_read(ByteIOContext *f, 
209                     int (*alloc_cb)(void *opaque, AVImageInfo *info), void *opaque)
210 {
211     AVImageInfo info1, *info = &info1;
212     PNGDecodeState s1, *s = &s1;
213     uint32_t tag, length;
214     int ret, crc;
215     uint8_t buf[8];
216
217     /* check signature */
218     ret = get_buffer(f, buf, 8);
219     if (ret != 8)
220         return -1;
221     if (memcmp(buf, pngsig, 8) != 0)
222         return -1;
223     memset(s, 0, sizeof(PNGDecodeState));
224     /* init the zlib */
225     s->zstream.zalloc = png_zalloc;
226     s->zstream.zfree = png_zfree;
227     s->zstream.opaque = NULL;
228     ret = inflateInit(&s->zstream);
229     if (ret != Z_OK)
230         return -1;
231     for(;;) {
232         if (url_feof(f))
233             goto fail;
234         length = get_be32(f);
235         if (length > 0x7fffffff)
236             goto fail;
237         tag = get_le32(f);
238 #ifdef DEBUG
239         printf("png: tag=%c%c%c%c length=%u\n", 
240                (tag & 0xff),
241                ((tag >> 8) & 0xff),
242                ((tag >> 16) & 0xff),
243                ((tag >> 24) & 0xff), length);
244 #endif
245         switch(tag) {
246         case MKTAG('I', 'H', 'D', 'R'):
247             if (length != 13)
248                 goto fail;
249             s->width = get_be32(f);
250             s->height = get_be32(f);
251             s->bit_depth = get_byte(f);
252             s->color_type = get_byte(f);
253             s->compression_type = get_byte(f);
254             s->filter_type = get_byte(f);
255             s->interlace_type = get_byte(f);
256             crc = get_be32(f);
257             s->state |= PNG_IHDR;
258 #ifdef DEBUG
259             printf("width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n", 
260                    s->width, s->height, s->bit_depth, s->color_type, 
261                    s->compression_type, s->filter_type, s->interlace_type);
262 #endif
263             break;
264         case MKTAG('I', 'D', 'A', 'T'):
265             if (!(s->state & PNG_IHDR))
266                 goto fail;
267             if (!(s->state & PNG_IDAT)) {
268                 /* init image info */
269                 info->width = s->width;
270                 info->height = s->height;
271
272                 s->channels = 1;
273                 if ((s->color_type & (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)) ==
274                     PNG_COLOR_MASK_COLOR)
275                     s->channels = 3;
276                 if (s->color_type & PNG_COLOR_MASK_ALPHA)
277                     s->channels++;
278                 s->bits_per_pixel = s->bit_depth * s->channels;
279                 s->bpp = (s->bits_per_pixel + 7) >> 3;
280                 if (s->bit_depth == 8 && 
281                     s->color_type == PNG_COLOR_TYPE_RGB) {
282                     info->pix_fmt = PIX_FMT_RGB24;
283                     s->row_size = s->width * 3;
284                 } else if (s->bit_depth == 8 && 
285                            s->color_type == PNG_COLOR_TYPE_GRAY) {
286                     info->pix_fmt = PIX_FMT_GRAY8;
287                     s->row_size = s->width;
288                 } else if (s->bit_depth == 1 && 
289                            s->color_type == PNG_COLOR_TYPE_GRAY) {
290                     info->pix_fmt = PIX_FMT_MONOBLACK;
291                     s->row_size = (s->width + 7) >> 3;
292                 } else if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
293                     info->pix_fmt = PIX_FMT_PAL8;
294                     s->row_size = s->width;;
295                 } else {
296                     goto fail;
297                 }
298                 /* compute the compressed row size */
299                 if (!s->interlace_type) {
300                     s->crow_size = s->row_size + 1;
301                 } else {
302                     /* XXX: handle interlacing */
303                     goto fail;
304                 }
305                 ret = alloc_cb(opaque, info);
306                 if (ret) 
307                     goto the_end;
308 #ifdef DEBUG
309                 printf("row_size=%d crow_size =%d\n", 
310                        s->row_size, s->crow_size);
311 #endif
312                 s->image_buf = info->pict.data[0];
313                 s->image_linesize = info->pict.linesize[0];
314                 /* copy the palette if needed */
315                 if (s->color_type == PNG_COLOR_TYPE_PALETTE)
316                     memcpy(info->pict.data[1], s->palette, 256 * sizeof(uint32_t));
317                 /* empty row is used if differencing to the first row */
318                 s->empty_row = av_mallocz(s->row_size);
319                 if (!s->empty_row)
320                     goto fail;
321                 /* compressed row */
322                 s->crow_buf = av_malloc(s->crow_size);
323                 if (!s->crow_buf)
324                     goto fail;
325                 s->zstream.avail_out = s->crow_size;
326                 s->zstream.next_out = s->crow_buf;
327             }
328             s->state |= PNG_IDAT;
329             if (png_decode_idat(s, f, length) < 0)
330                 goto fail;
331             /* skip crc */
332             crc = get_be32(f);
333             break;
334         case MKTAG('P', 'L', 'T', 'E'):
335             {
336                 int n, i, r, g, b;
337                 
338                 if ((length % 3) != 0 || length > 256 * 3)
339                     goto skip_tag;
340                 /* read the palette */
341                 n = length / 3;
342                 for(i=0;i<n;i++) {
343                     r = get_byte(f);
344                     g = get_byte(f);
345                     b = get_byte(f);
346                     s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
347                 }
348                 for(;i<256;i++) {
349                     s->palette[i] = (0xff << 24);
350                 }
351                 s->state |= PNG_PLTE;
352                 crc = get_be32(f);
353             }
354             break;
355         case MKTAG('t', 'R', 'N', 'S'):
356             {
357                 int v, i;
358
359                 /* read the transparency. XXX: Only palette mode supported */
360                 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
361                     length > 256 ||
362                     !(s->state & PNG_PLTE))
363                     goto skip_tag;
364                 for(i=0;i<length;i++) {
365                     v = get_byte(f);
366                     s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
367                 }
368                 crc = get_be32(f);
369             }
370             break;
371         case MKTAG('I', 'E', 'N', 'D'):
372             if (!(s->state & PNG_ALLIMAGE))
373                 goto fail;
374             crc = get_be32(f);
375             goto exit_loop;
376         default:
377             /* skip tag */
378         skip_tag:
379             url_fskip(f, length + 4);
380             break;
381         }
382     }
383  exit_loop:
384     ret = 0;
385  the_end:
386     inflateEnd(&s->zstream);
387     av_free(s->crow_buf);
388     return ret;
389  fail:
390     ret = -1;
391     goto the_end;
392 }
393
394 static void png_write_chunk(ByteIOContext *f, uint32_t tag,
395                             const uint8_t *buf, int length)
396 {
397     uint32_t crc;
398     uint8_t tagbuf[4];
399
400     put_be32(f, length);
401     crc = crc32(0, Z_NULL, 0);
402     tagbuf[0] = tag;
403     tagbuf[1] = tag >> 8;
404     tagbuf[2] = tag >> 16;
405     tagbuf[3] = tag >> 24;
406     crc = crc32(crc, tagbuf, 4);
407     put_le32(f, tag);
408     if (length > 0) {
409         crc = crc32(crc, buf, length);
410         put_buffer(f, buf, length);
411     }
412     put_be32(f, crc);
413 }
414
415 /* XXX: use avcodec generic function ? */
416 static void to_be32(uint8_t *p, uint32_t v)
417 {
418     p[0] = v >> 24;
419     p[1] = v >> 16;
420     p[2] = v >> 8;
421     p[3] = v;
422 }
423
424 static int png_write(ByteIOContext *f, AVImageInfo *info)
425 {
426     int bit_depth, color_type, y, len, row_size, ret;
427     uint8_t *ptr;
428     uint8_t buf[IOBUF_SIZE];
429     uint8_t *crow_buf = NULL;
430     z_stream zstream;
431     
432     switch(info->pix_fmt) {
433     case PIX_FMT_RGB24:
434         bit_depth = 8;
435         color_type = PNG_COLOR_TYPE_RGB;
436         row_size = info->width * 3;
437         break;
438     case PIX_FMT_GRAY8:
439         bit_depth = 8;
440         color_type = PNG_COLOR_TYPE_GRAY;
441         row_size = info->width;
442         break;
443     case PIX_FMT_MONOBLACK:
444         bit_depth = 1;
445         color_type = PNG_COLOR_TYPE_GRAY;
446         row_size = (info->width + 7) >> 3;
447         break;
448     case PIX_FMT_PAL8:
449         bit_depth = 8;
450         color_type = PNG_COLOR_TYPE_PALETTE;
451         row_size = info->width;
452         break;
453     default:
454         return -1;
455     }
456     zstream.zalloc = png_zalloc;
457     zstream.zfree = png_zfree;
458     zstream.opaque = NULL;
459     ret = deflateInit2(&zstream, Z_DEFAULT_COMPRESSION,
460                        Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
461     if (ret != Z_OK)
462         return -1;
463     crow_buf = av_malloc(row_size + 1);
464     if (!crow_buf)
465         goto fail;
466
467     /* write png header */
468     put_buffer(f, pngsig, 8);
469     
470     to_be32(buf, info->width);
471     to_be32(buf + 4, info->height);
472     buf[8] = bit_depth;
473     buf[9] = color_type;
474     buf[10] = 0; /* compression type */
475     buf[11] = 0; /* filter type */
476     buf[12] = 0; /* interlace type */
477     
478     png_write_chunk(f, MKTAG('I', 'H', 'D', 'R'), buf, 13);
479
480     /* put the palette if needed */
481     if (color_type == PNG_COLOR_TYPE_PALETTE) {
482         int has_alpha, alpha, i;
483         unsigned int v;
484         uint32_t *palette;
485         uint8_t *alpha_ptr;
486         
487         palette = (uint32_t *)info->pict.data[1];
488         ptr = buf;
489         alpha_ptr = buf + 256 * 3;
490         has_alpha = 0;
491         for(i = 0; i < 256; i++) {
492             v = palette[i];
493             alpha = v >> 24;
494             if (alpha != 0xff)
495                 has_alpha = 1;
496             *alpha_ptr++ = alpha;
497             ptr[0] = v >> 16;
498             ptr[1] = v >> 8;
499             ptr[2] = v;
500             ptr += 3;
501         }
502         png_write_chunk(f, MKTAG('P', 'L', 'T', 'E'), buf, 256 * 3);
503         if (has_alpha) {
504             png_write_chunk(f, MKTAG('t', 'R', 'N', 'S'), buf + 256 * 3, 256);
505         }
506     }
507
508     /* now put each row */
509     zstream.avail_out = IOBUF_SIZE;
510     zstream.next_out = buf;
511     for(y = 0;y < info->height; y++) {
512         /* XXX: do filtering */
513         ptr = info->pict.data[0] + y * info->pict.linesize[0];
514         memcpy(crow_buf + 1, ptr, row_size);
515         crow_buf[0] = PNG_FILTER_VALUE_NONE;
516         zstream.avail_in = row_size + 1;
517         zstream.next_in = crow_buf;
518         while (zstream.avail_in > 0) {
519             ret = deflate(&zstream, Z_NO_FLUSH);
520             if (ret != Z_OK)
521                 goto fail;
522             if (zstream.avail_out == 0) {
523                 png_write_chunk(f, MKTAG('I', 'D', 'A', 'T'), buf, IOBUF_SIZE);
524                 zstream.avail_out = IOBUF_SIZE;
525                 zstream.next_out = buf;
526             }
527         }
528     }
529     /* compress last bytes */
530     for(;;) {
531         ret = deflate(&zstream, Z_FINISH);
532         if (ret == Z_OK || ret == Z_STREAM_END) {
533             len = IOBUF_SIZE - zstream.avail_out;
534             if (len > 0) {
535                 png_write_chunk(f, MKTAG('I', 'D', 'A', 'T'), buf, len);
536             }
537             zstream.avail_out = IOBUF_SIZE;
538             zstream.next_out = buf;
539             if (ret == Z_STREAM_END)
540                 break;
541         } else {
542             goto fail;
543         }
544     }
545     png_write_chunk(f, MKTAG('I', 'E', 'N', 'D'), NULL, 0);
546
547     put_flush_packet(f);
548     ret = 0;
549  the_end:
550     av_free(crow_buf);
551     deflateEnd(&zstream);
552     return ret;
553  fail:
554     ret = -1;
555     goto the_end;
556 }
557
558 AVImageFormat png_image_format = {
559     "png",
560     "png",
561     png_probe,
562     png_read,
563     (1 << PIX_FMT_RGB24) | (1 << PIX_FMT_GRAY8) | (1 << PIX_FMT_MONOBLACK) | (1 << PIX_FMT_PAL8),
564     png_write,
565 };