]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/pngdec.c
simd and unroll png_filter_row
[frescor/ffmpeg.git] / libavcodec / pngdec.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 "avcodec.h"
22 #include "bytestream.h"
23 #include "png.h"
24 #include "dsputil.h"
25
26 /* TODO:
27  * - add 2, 4 and 16 bit depth support
28  */
29
30 #include <zlib.h>
31
32 //#define DEBUG
33
34 typedef struct PNGDecContext {
35     DSPContext dsp;
36
37     const uint8_t *bytestream;
38     const uint8_t *bytestream_start;
39     const uint8_t *bytestream_end;
40     AVFrame picture;
41
42     int state;
43     int width, height;
44     int bit_depth;
45     int color_type;
46     int compression_type;
47     int interlace_type;
48     int filter_type;
49     int channels;
50     int bits_per_pixel;
51     int bpp;
52
53     uint8_t *image_buf;
54     int image_linesize;
55     uint32_t palette[256];
56     uint8_t *crow_buf;
57     uint8_t *last_row;
58     uint8_t *tmp_row;
59     int pass;
60     int crow_size; /* compressed row size (include filter type) */
61     int row_size; /* decompressed row size */
62     int pass_row_size; /* decompress row size of the current pass */
63     int y;
64     z_stream zstream;
65 } PNGDecContext;
66
67 /* Mask to determine which y pixels can be written in a pass */
68 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
69     0xff, 0xff, 0x0f, 0xcc, 0x33, 0xff, 0x55,
70 };
71
72 /* Mask to determine which pixels to overwrite while displaying */
73 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
74     0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
75 };
76
77 /* NOTE: we try to construct a good looking image at each pass. width
78    is the original image width. We also do pixel format conversion at
79    this stage */
80 static void png_put_interlaced_row(uint8_t *dst, int width,
81                                    int bits_per_pixel, int pass,
82                                    int color_type, const uint8_t *src)
83 {
84     int x, mask, dsp_mask, j, src_x, b, bpp;
85     uint8_t *d;
86     const uint8_t *s;
87
88     mask = ff_png_pass_mask[pass];
89     dsp_mask = png_pass_dsp_mask[pass];
90     switch(bits_per_pixel) {
91     case 1:
92         /* we must initialize the line to zero before writing to it */
93         if (pass == 0)
94             memset(dst, 0, (width + 7) >> 3);
95         src_x = 0;
96         for(x = 0; x < width; x++) {
97             j = (x & 7);
98             if ((dsp_mask << j) & 0x80) {
99                 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
100                 dst[x >> 3] |= b << (7 - j);
101             }
102             if ((mask << j) & 0x80)
103                 src_x++;
104         }
105         break;
106     default:
107         bpp = bits_per_pixel >> 3;
108         d = dst;
109         s = src;
110         if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
111             for(x = 0; x < width; x++) {
112                 j = x & 7;
113                 if ((dsp_mask << j) & 0x80) {
114                     *(uint32_t *)d = (s[3] << 24) | (s[0] << 16) | (s[1] << 8) | s[2];
115                 }
116                 d += bpp;
117                 if ((mask << j) & 0x80)
118                     s += bpp;
119             }
120         } else {
121             for(x = 0; x < width; x++) {
122                 j = x & 7;
123                 if ((dsp_mask << j) & 0x80) {
124                     memcpy(d, s, bpp);
125                 }
126                 d += bpp;
127                 if ((mask << j) & 0x80)
128                     s += bpp;
129             }
130         }
131         break;
132     }
133 }
134
135 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
136 {
137     int i;
138     for(i = 0; i < w; i++) {
139         int a, b, c, p, pa, pb, pc;
140
141         a = dst[i - bpp];
142         b = top[i];
143         c = top[i - bpp];
144
145         p = b - c;
146         pc = a - c;
147
148         pa = abs(p);
149         pb = abs(pc);
150         pc = abs(p + pc);
151
152         if (pa <= pb && pa <= pc)
153             p = a;
154         else if (pb <= pc)
155             p = b;
156         else
157             p = c;
158         dst[i] = p + src[i];
159     }
160 }
161
162 #define UNROLL1(bpp, op) {\
163                  r = dst[0];\
164     if(bpp >= 2) g = dst[1];\
165     if(bpp >= 3) b = dst[2];\
166     if(bpp >= 4) a = dst[3];\
167     for(; i < size; i+=bpp) {\
168         dst[i+0] = r = op(r, src[i+0], last[i+0]);\
169         if(bpp == 1) continue;\
170         dst[i+1] = g = op(g, src[i+1], last[i+1]);\
171         if(bpp == 2) continue;\
172         dst[i+2] = b = op(b, src[i+2], last[i+2]);\
173         if(bpp == 3) continue;\
174         dst[i+3] = a = op(a, src[i+3], last[i+3]);\
175     }\
176 }
177
178 #define UNROLL_FILTER(op)\
179          if(bpp == 1) UNROLL1(1, op)\
180     else if(bpp == 2) UNROLL1(2, op)\
181     else if(bpp == 3) UNROLL1(3, op)\
182     else if(bpp == 4) UNROLL1(4, op)\
183
184 /* NOTE: 'dst' can be equal to 'last' */
185 static void png_filter_row(DSPContext *dsp, uint8_t *dst, int filter_type,
186                            uint8_t *src, uint8_t *last, int size, int bpp)
187 {
188     int i, p, r, g, b, a;
189
190     switch(filter_type) {
191     case PNG_FILTER_VALUE_NONE:
192         memcpy(dst, src, size);
193         break;
194     case PNG_FILTER_VALUE_SUB:
195         for(i = 0; i < bpp; i++) {
196             dst[i] = src[i];
197         }
198         if(bpp == 4) {
199             p = *(int*)dst;
200             for(; i < size; i+=bpp) {
201                 int s = *(int*)(src+i);
202                 p = ((s&0x7f7f7f7f) + (p&0x7f7f7f7f)) ^ ((s^p)&0x80808080);
203                 *(int*)(dst+i) = p;
204             }
205         } else {
206 #define OP_SUB(x,s,l) x+s
207             UNROLL_FILTER(OP_SUB);
208         }
209         break;
210     case PNG_FILTER_VALUE_UP:
211         dsp->add_bytes_l2(dst, src, last, size);
212         break;
213     case PNG_FILTER_VALUE_AVG:
214         for(i = 0; i < bpp; i++) {
215             p = (last[i] >> 1);
216             dst[i] = p + src[i];
217         }
218 #define OP_AVG(x,s,l) (((x + l) >> 1) + s) & 0xff
219         UNROLL_FILTER(OP_AVG);
220         break;
221     case PNG_FILTER_VALUE_PAETH:
222         for(i = 0; i < bpp; i++) {
223             p = last[i];
224             dst[i] = p + src[i];
225         }
226         if(bpp > 1 && size > 4) {
227             // would write off the end of the array if we let it process the last pixel with bpp=3
228             int w = bpp==4 ? size : size-3;
229             dsp->add_png_paeth_prediction(dst+i, src+i, last+i, w-i, bpp);
230             i = w;
231         }
232         ff_add_png_paeth_prediction(dst+i, src+i, last+i, size-i, bpp);
233         break;
234     }
235 }
236
237 static void convert_to_rgb32(uint8_t *dst, const uint8_t *src, int width)
238 {
239     int j;
240     unsigned int r, g, b, a;
241
242     for(j = 0;j < width; j++) {
243         r = src[0];
244         g = src[1];
245         b = src[2];
246         a = src[3];
247         *(uint32_t *)dst = (a << 24) | (r << 16) | (g << 8) | b;
248         dst += 4;
249         src += 4;
250     }
251 }
252
253 /* process exactly one decompressed row */
254 static void png_handle_row(PNGDecContext *s)
255 {
256     uint8_t *ptr, *last_row;
257     int got_line;
258
259     if (!s->interlace_type) {
260         ptr = s->image_buf + s->image_linesize * s->y;
261         /* need to swap bytes correctly for RGB_ALPHA */
262         if (s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
263             png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
264                            s->last_row, s->row_size, s->bpp);
265             memcpy(s->last_row, s->tmp_row, s->row_size);
266             convert_to_rgb32(ptr, s->tmp_row, s->width);
267         } else {
268             /* in normal case, we avoid one copy */
269             if (s->y == 0)
270                 last_row = s->last_row;
271             else
272                 last_row = ptr - s->image_linesize;
273
274             png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
275                            last_row, s->row_size, s->bpp);
276         }
277         s->y++;
278         if (s->y == s->height) {
279             s->state |= PNG_ALLIMAGE;
280         }
281     } else {
282         got_line = 0;
283         for(;;) {
284             ptr = s->image_buf + s->image_linesize * s->y;
285             if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
286                 /* if we already read one row, it is time to stop to
287                    wait for the next one */
288                 if (got_line)
289                     break;
290                 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
291                                s->last_row, s->pass_row_size, s->bpp);
292                 memcpy(s->last_row, s->tmp_row, s->pass_row_size);
293                 got_line = 1;
294             }
295             if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
296                 /* NOTE: RGB32 is handled directly in png_put_interlaced_row */
297                 png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
298                                        s->color_type, s->last_row);
299             }
300             s->y++;
301             if (s->y == s->height) {
302                 for(;;) {
303                     if (s->pass == NB_PASSES - 1) {
304                         s->state |= PNG_ALLIMAGE;
305                         goto the_end;
306                     } else {
307                         s->pass++;
308                         s->y = 0;
309                         s->pass_row_size = ff_png_pass_row_size(s->pass,
310                                                              s->bits_per_pixel,
311                                                              s->width);
312                         s->crow_size = s->pass_row_size + 1;
313                         if (s->pass_row_size != 0)
314                             break;
315                         /* skip pass if empty row */
316                     }
317                 }
318             }
319         }
320     the_end: ;
321     }
322 }
323
324 static int png_decode_idat(PNGDecContext *s, int length)
325 {
326     int ret;
327     s->zstream.avail_in = length;
328     s->zstream.next_in = s->bytestream;
329     s->bytestream += length;
330
331     if(s->bytestream > s->bytestream_end)
332         return -1;
333
334     /* decode one line if possible */
335     while (s->zstream.avail_in > 0) {
336         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
337         if (ret != Z_OK && ret != Z_STREAM_END) {
338             return -1;
339         }
340         if (s->zstream.avail_out == 0) {
341             if (!(s->state & PNG_ALLIMAGE)) {
342                 png_handle_row(s);
343             }
344             s->zstream.avail_out = s->crow_size;
345             s->zstream.next_out = s->crow_buf;
346         }
347     }
348     return 0;
349 }
350
351 static int decode_frame(AVCodecContext *avctx,
352                         void *data, int *data_size,
353                         const uint8_t *buf, int buf_size)
354 {
355     PNGDecContext * const s = avctx->priv_data;
356     AVFrame *picture = data;
357     AVFrame * const p= (AVFrame*)&s->picture;
358     uint32_t tag, length;
359     int ret, crc;
360
361     s->bytestream_start=
362     s->bytestream= buf;
363     s->bytestream_end= buf + buf_size;
364
365     /* check signature */
366     if (memcmp(s->bytestream, ff_pngsig, 8) != 0)
367         return -1;
368     s->bytestream+= 8;
369     s->y=
370     s->state=0;
371 //    memset(s, 0, sizeof(PNGDecContext));
372     /* init the zlib */
373     s->zstream.zalloc = ff_png_zalloc;
374     s->zstream.zfree = ff_png_zfree;
375     s->zstream.opaque = NULL;
376     ret = inflateInit(&s->zstream);
377     if (ret != Z_OK)
378         return -1;
379     for(;;) {
380         int tag32;
381         if (s->bytestream >= s->bytestream_end)
382             goto fail;
383         length = bytestream_get_be32(&s->bytestream);
384         if (length > 0x7fffffff)
385             goto fail;
386         tag32 = bytestream_get_be32(&s->bytestream);
387         tag = bswap_32(tag32);
388 #ifdef DEBUG
389         av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
390                (tag & 0xff),
391                ((tag >> 8) & 0xff),
392                ((tag >> 16) & 0xff),
393                ((tag >> 24) & 0xff), length);
394 #endif
395         switch(tag) {
396         case MKTAG('I', 'H', 'D', 'R'):
397             if (length != 13)
398                 goto fail;
399             s->width = bytestream_get_be32(&s->bytestream);
400             s->height = bytestream_get_be32(&s->bytestream);
401             if(avcodec_check_dimensions(avctx, s->width, s->height)){
402                 s->width= s->height= 0;
403                 goto fail;
404             }
405             s->bit_depth = *s->bytestream++;
406             s->color_type = *s->bytestream++;
407             s->compression_type = *s->bytestream++;
408             s->filter_type = *s->bytestream++;
409             s->interlace_type = *s->bytestream++;
410             crc = bytestream_get_be32(&s->bytestream);
411             s->state |= PNG_IHDR;
412 #ifdef DEBUG
413             av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d compression_type=%d filter_type=%d interlace_type=%d\n",
414                    s->width, s->height, s->bit_depth, s->color_type,
415                    s->compression_type, s->filter_type, s->interlace_type);
416 #endif
417             break;
418         case MKTAG('I', 'D', 'A', 'T'):
419             if (!(s->state & PNG_IHDR))
420                 goto fail;
421             if (!(s->state & PNG_IDAT)) {
422                 /* init image info */
423                 avctx->width = s->width;
424                 avctx->height = s->height;
425
426                 s->channels = ff_png_get_nb_channels(s->color_type);
427                 s->bits_per_pixel = s->bit_depth * s->channels;
428                 s->bpp = (s->bits_per_pixel + 7) >> 3;
429                 s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
430
431                 if (s->bit_depth == 8 &&
432                     s->color_type == PNG_COLOR_TYPE_RGB) {
433                     avctx->pix_fmt = PIX_FMT_RGB24;
434                 } else if (s->bit_depth == 8 &&
435                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
436                     avctx->pix_fmt = PIX_FMT_RGB32;
437                 } else if (s->bit_depth == 8 &&
438                            s->color_type == PNG_COLOR_TYPE_GRAY) {
439                     avctx->pix_fmt = PIX_FMT_GRAY8;
440                 } else if (s->bit_depth == 16 &&
441                            s->color_type == PNG_COLOR_TYPE_GRAY) {
442                     avctx->pix_fmt = PIX_FMT_GRAY16BE;
443                 } else if (s->bit_depth == 1 &&
444                            s->color_type == PNG_COLOR_TYPE_GRAY) {
445                     avctx->pix_fmt = PIX_FMT_MONOBLACK;
446                 } else if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
447                     avctx->pix_fmt = PIX_FMT_PAL8;
448                 } else {
449                     goto fail;
450                 }
451                 if(p->data[0])
452                     avctx->release_buffer(avctx, p);
453
454                 p->reference= 0;
455                 if(avctx->get_buffer(avctx, p) < 0){
456                     av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
457                     goto fail;
458                 }
459                 p->pict_type= FF_I_TYPE;
460                 p->key_frame= 1;
461                 p->interlaced_frame = !!s->interlace_type;
462
463                 /* compute the compressed row size */
464                 if (!s->interlace_type) {
465                     s->crow_size = s->row_size + 1;
466                 } else {
467                     s->pass = 0;
468                     s->pass_row_size = ff_png_pass_row_size(s->pass,
469                                                          s->bits_per_pixel,
470                                                          s->width);
471                     s->crow_size = s->pass_row_size + 1;
472                 }
473 #ifdef DEBUG
474                 av_log(avctx, AV_LOG_DEBUG, "row_size=%d crow_size =%d\n",
475                        s->row_size, s->crow_size);
476 #endif
477                 s->image_buf = p->data[0];
478                 s->image_linesize = p->linesize[0];
479                 /* copy the palette if needed */
480                 if (s->color_type == PNG_COLOR_TYPE_PALETTE)
481                     memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
482                 /* empty row is used if differencing to the first row */
483                 s->last_row = av_mallocz(s->row_size);
484                 if (!s->last_row)
485                     goto fail;
486                 if (s->interlace_type ||
487                     s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
488                     s->tmp_row = av_malloc(s->row_size);
489                     if (!s->tmp_row)
490                         goto fail;
491                 }
492                 /* compressed row */
493                 s->crow_buf = av_malloc(s->row_size + 1);
494                 if (!s->crow_buf)
495                     goto fail;
496                 s->zstream.avail_out = s->crow_size;
497                 s->zstream.next_out = s->crow_buf;
498             }
499             s->state |= PNG_IDAT;
500             if (png_decode_idat(s, length) < 0)
501                 goto fail;
502             /* skip crc */
503             crc = bytestream_get_be32(&s->bytestream);
504             break;
505         case MKTAG('P', 'L', 'T', 'E'):
506             {
507                 int n, i, r, g, b;
508
509                 if ((length % 3) != 0 || length > 256 * 3)
510                     goto skip_tag;
511                 /* read the palette */
512                 n = length / 3;
513                 for(i=0;i<n;i++) {
514                     r = *s->bytestream++;
515                     g = *s->bytestream++;
516                     b = *s->bytestream++;
517                     s->palette[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
518                 }
519                 for(;i<256;i++) {
520                     s->palette[i] = (0xff << 24);
521                 }
522                 s->state |= PNG_PLTE;
523                 crc = bytestream_get_be32(&s->bytestream);
524             }
525             break;
526         case MKTAG('t', 'R', 'N', 'S'):
527             {
528                 int v, i;
529
530                 /* read the transparency. XXX: Only palette mode supported */
531                 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
532                     length > 256 ||
533                     !(s->state & PNG_PLTE))
534                     goto skip_tag;
535                 for(i=0;i<length;i++) {
536                     v = *s->bytestream++;
537                     s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
538                 }
539                 crc = bytestream_get_be32(&s->bytestream);
540             }
541             break;
542         case MKTAG('I', 'E', 'N', 'D'):
543             if (!(s->state & PNG_ALLIMAGE))
544                 goto fail;
545             crc = bytestream_get_be32(&s->bytestream);
546             goto exit_loop;
547         default:
548             /* skip tag */
549         skip_tag:
550             s->bytestream += length + 4;
551             break;
552         }
553     }
554  exit_loop:
555     *picture= *(AVFrame*)&s->picture;
556     *data_size = sizeof(AVPicture);
557
558     ret = s->bytestream - s->bytestream_start;
559  the_end:
560     inflateEnd(&s->zstream);
561     av_freep(&s->crow_buf);
562     av_freep(&s->last_row);
563     av_freep(&s->tmp_row);
564     return ret;
565  fail:
566     ret = -1;
567     goto the_end;
568 }
569
570 static int png_dec_init(AVCodecContext *avctx){
571     PNGDecContext *s = avctx->priv_data;
572
573     avcodec_get_frame_defaults((AVFrame*)&s->picture);
574     avctx->coded_frame= (AVFrame*)&s->picture;
575     dsputil_init(&s->dsp, avctx);
576
577     return 0;
578 }
579
580 AVCodec png_decoder = {
581     "png",
582     CODEC_TYPE_VIDEO,
583     CODEC_ID_PNG,
584     sizeof(PNGDecContext),
585     png_dec_init,
586     NULL,
587     NULL, //decode_end,
588     decode_frame,
589     0 /*CODEC_CAP_DR1*/ /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
590     NULL
591 };