]> git.sesse.net Git - ffmpeg/blob - libavcodec/pngdec.c
Merge commit '12db891dcd57b305d6e3c1e22ea8204dc26edda1'
[ffmpeg] / 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
22 //#define DEBUG
23
24 #include "libavutil/bprint.h"
25 #include "libavutil/imgutils.h"
26 #include "avcodec.h"
27 #include "bytestream.h"
28 #include "internal.h"
29 #include "png.h"
30 #include "pngdsp.h"
31
32 /* TODO:
33  * - add 16 bit depth support
34  */
35
36 #include <zlib.h>
37
38 typedef struct PNGDecContext {
39     PNGDSPContext dsp;
40     AVCodecContext *avctx;
41
42     GetByteContext gb;
43     AVFrame *prev;
44
45     int state;
46     int width, height;
47     int bit_depth;
48     int color_type;
49     int compression_type;
50     int interlace_type;
51     int filter_type;
52     int channels;
53     int bits_per_pixel;
54     int bpp;
55
56     uint8_t *image_buf;
57     int image_linesize;
58     uint32_t palette[256];
59     uint8_t *crow_buf;
60     uint8_t *last_row;
61     uint8_t *tmp_row;
62     int pass;
63     int crow_size; /* compressed row size (include filter type) */
64     int row_size; /* decompressed row size */
65     int pass_row_size; /* decompress row size of the current pass */
66     int y;
67     z_stream zstream;
68 } PNGDecContext;
69
70 /* Mask to determine which pixels are valid in a pass */
71 static const uint8_t png_pass_mask[NB_PASSES] = {
72     0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
73 };
74
75 /* Mask to determine which y pixels can be written in a pass */
76 static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
77     0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
78 };
79
80 /* Mask to determine which pixels to overwrite while displaying */
81 static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
82     0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
83 };
84
85 /* NOTE: we try to construct a good looking image at each pass. width
86    is the original image width. We also do pixel format conversion at
87    this stage */
88 static void png_put_interlaced_row(uint8_t *dst, int width,
89                                    int bits_per_pixel, int pass,
90                                    int color_type, const uint8_t *src)
91 {
92     int x, mask, dsp_mask, j, src_x, b, bpp;
93     uint8_t *d;
94     const uint8_t *s;
95
96     mask     = png_pass_mask[pass];
97     dsp_mask = png_pass_dsp_mask[pass];
98
99     switch (bits_per_pixel) {
100     case 1:
101         src_x = 0;
102         for (x = 0; x < width; x++) {
103             j = (x & 7);
104             if ((dsp_mask << j) & 0x80) {
105                 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
106                 dst[x >> 3] &= 0xFF7F>>j;
107                 dst[x >> 3] |= b << (7 - j);
108             }
109             if ((mask << j) & 0x80)
110                 src_x++;
111         }
112         break;
113     case 2:
114         src_x = 0;
115         for (x = 0; x < width; x++) {
116             int j2 = 2 * (x & 3);
117             j = (x & 7);
118             if ((dsp_mask << j) & 0x80) {
119                 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
120                 dst[x >> 2] &= 0xFF3F>>j2;
121                 dst[x >> 2] |= b << (6 - j2);
122             }
123             if ((mask << j) & 0x80)
124                 src_x++;
125         }
126         break;
127     case 4:
128         src_x = 0;
129         for (x = 0; x < width; x++) {
130             int j2 = 4*(x&1);
131             j = (x & 7);
132             if ((dsp_mask << j) & 0x80) {
133                 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
134                 dst[x >> 1] &= 0xFF0F>>j2;
135                 dst[x >> 1] |= b << (4 - j2);
136             }
137             if ((mask << j) & 0x80)
138                 src_x++;
139         }
140         break;
141     default:
142         bpp = bits_per_pixel >> 3;
143         d   = dst;
144         s   = src;
145             for (x = 0; x < width; x++) {
146                 j = x & 7;
147                 if ((dsp_mask << j) & 0x80) {
148                     memcpy(d, s, bpp);
149                 }
150                 d += bpp;
151                 if ((mask << j) & 0x80)
152                     s += bpp;
153             }
154         break;
155     }
156 }
157
158 void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)
159 {
160     int i;
161     for (i = 0; i < w; i++) {
162         int a, b, c, p, pa, pb, pc;
163
164         a = dst[i - bpp];
165         b = top[i];
166         c = top[i - bpp];
167
168         p  = b - c;
169         pc = a - c;
170
171         pa = abs(p);
172         pb = abs(pc);
173         pc = abs(p + pc);
174
175         if (pa <= pb && pa <= pc)
176             p = a;
177         else if (pb <= pc)
178             p = b;
179         else
180             p = c;
181         dst[i] = p + src[i];
182     }
183 }
184
185 #define UNROLL1(bpp, op) {\
186                  r = dst[0];\
187     if(bpp >= 2) g = dst[1];\
188     if(bpp >= 3) b = dst[2];\
189     if(bpp >= 4) a = dst[3];\
190     for(; i <= size - bpp; i+=bpp) {\
191         dst[i+0] = r = op(r, src[i+0], last[i+0]);\
192         if(bpp == 1) continue;\
193         dst[i+1] = g = op(g, src[i+1], last[i+1]);\
194         if(bpp == 2) continue;\
195         dst[i+2] = b = op(b, src[i+2], last[i+2]);\
196         if(bpp == 3) continue;\
197         dst[i+3] = a = op(a, src[i+3], last[i+3]);\
198     }\
199 }
200
201 #define UNROLL_FILTER(op)\
202          if(bpp == 1) UNROLL1(1, op)\
203     else if(bpp == 2) UNROLL1(2, op)\
204     else if(bpp == 3) UNROLL1(3, op)\
205     else if(bpp == 4) UNROLL1(4, op)\
206     for (; i < size; i++) {\
207         dst[i] = op(dst[i-bpp], src[i], last[i]);\
208     }\
209
210 /* NOTE: 'dst' can be equal to 'last' */
211 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
212                            uint8_t *src, uint8_t *last, int size, int bpp)
213 {
214     int i, p, r, g, b, a;
215
216     switch (filter_type) {
217     case PNG_FILTER_VALUE_NONE:
218         memcpy(dst, src, size);
219         break;
220     case PNG_FILTER_VALUE_SUB:
221         for (i = 0; i < bpp; i++) {
222             dst[i] = src[i];
223         }
224         if (bpp == 4) {
225             p = *(int*)dst;
226             for (; i < size; i += bpp) {
227                 int s = *(int*)(src + i);
228                 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
229                 *(int*)(dst + i) = p;
230             }
231         } else {
232 #define OP_SUB(x,s,l) x+s
233             UNROLL_FILTER(OP_SUB);
234         }
235         break;
236     case PNG_FILTER_VALUE_UP:
237         dsp->add_bytes_l2(dst, src, last, size);
238         break;
239     case PNG_FILTER_VALUE_AVG:
240         for (i = 0; i < bpp; i++) {
241             p = (last[i] >> 1);
242             dst[i] = p + src[i];
243         }
244 #define OP_AVG(x,s,l) (((x + l) >> 1) + s) & 0xff
245         UNROLL_FILTER(OP_AVG);
246         break;
247     case PNG_FILTER_VALUE_PAETH:
248         for (i = 0; i < bpp; i++) {
249             p = last[i];
250             dst[i] = p + src[i];
251         }
252         if (bpp > 2 && size > 4) {
253             // would write off the end of the array if we let it process the last pixel with bpp=3
254             int w = bpp == 4 ? size : size - 3;
255             dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
256             i = w;
257         }
258         ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
259         break;
260     }
261 }
262
263 /* This used to be called "deloco" in FFmpeg
264  * and is actually an inverse reversible colorspace transformation */
265 #define YUV2RGB(NAME, TYPE) \
266 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
267 { \
268     int i; \
269     for (i = 0; i < size; i += 3 + alpha) { \
270         int g = dst [i+1]; \
271         dst[i+0] += g; \
272         dst[i+2] += g; \
273     } \
274 }
275
276 YUV2RGB(rgb8, uint8_t)
277 YUV2RGB(rgb16, uint16_t)
278
279 /* process exactly one decompressed row */
280 static void png_handle_row(PNGDecContext *s)
281 {
282     uint8_t *ptr, *last_row;
283     int got_line;
284
285     if (!s->interlace_type) {
286         ptr = s->image_buf + s->image_linesize * s->y;
287             if (s->y == 0)
288                 last_row = s->last_row;
289             else
290                 last_row = ptr - s->image_linesize;
291
292             png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
293                            last_row, s->row_size, s->bpp);
294         /* loco lags by 1 row so that it doesn't interfere with top prediction */
295         if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
296             if (s->bit_depth == 16) {
297                 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
298                              s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
299             } else {
300                 deloco_rgb8(ptr - s->image_linesize, s->row_size,
301                             s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
302             }
303         }
304         s->y++;
305         if (s->y == s->height) {
306             s->state |= PNG_ALLIMAGE;
307             if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
308                 if (s->bit_depth == 16) {
309                     deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
310                                  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
311                 } else {
312                     deloco_rgb8(ptr, s->row_size,
313                                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
314                 }
315             }
316         }
317     } else {
318         got_line = 0;
319         for (;;) {
320             ptr = s->image_buf + s->image_linesize * s->y;
321             if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
322                 /* if we already read one row, it is time to stop to
323                    wait for the next one */
324                 if (got_line)
325                     break;
326                 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
327                                s->last_row, s->pass_row_size, s->bpp);
328                 FFSWAP(uint8_t*, s->last_row, s->tmp_row);
329                 got_line = 1;
330             }
331             if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
332                 png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
333                                        s->color_type, s->last_row);
334             }
335             s->y++;
336             if (s->y == s->height) {
337                 memset(s->last_row, 0, s->row_size);
338                 for (;;) {
339                     if (s->pass == NB_PASSES - 1) {
340                         s->state |= PNG_ALLIMAGE;
341                         goto the_end;
342                     } else {
343                         s->pass++;
344                         s->y = 0;
345                         s->pass_row_size = ff_png_pass_row_size(s->pass,
346                                                              s->bits_per_pixel,
347                                                              s->width);
348                         s->crow_size = s->pass_row_size + 1;
349                         if (s->pass_row_size != 0)
350                             break;
351                         /* skip pass if empty row */
352                     }
353                 }
354             }
355         }
356     the_end: ;
357     }
358 }
359
360 static int png_decode_idat(PNGDecContext *s, int length)
361 {
362     int ret;
363     s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
364     s->zstream.next_in  = (unsigned char *)s->gb.buffer;
365     bytestream2_skip(&s->gb, length);
366
367     /* decode one line if possible */
368     while (s->zstream.avail_in > 0) {
369         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
370         if (ret != Z_OK && ret != Z_STREAM_END) {
371             av_log(s->avctx, AV_LOG_ERROR, "inflate returned %d\n", ret);
372             return -1;
373         }
374         if (s->zstream.avail_out == 0) {
375             if (!(s->state & PNG_ALLIMAGE)) {
376                 png_handle_row(s);
377             }
378             s->zstream.avail_out = s->crow_size;
379             s->zstream.next_out  = s->crow_buf;
380         }
381     }
382     return 0;
383 }
384
385 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
386                        const uint8_t *data_end)
387 {
388     z_stream zstream;
389     unsigned char *buf;
390     unsigned buf_size;
391     int ret;
392
393     zstream.zalloc = ff_png_zalloc;
394     zstream.zfree  = ff_png_zfree;
395     zstream.opaque = NULL;
396     if (inflateInit(&zstream) != Z_OK)
397         return AVERROR_EXTERNAL;
398     zstream.next_in  = (unsigned char *)data;
399     zstream.avail_in = data_end - data;
400     av_bprint_init(bp, 0, -1);
401
402     while (zstream.avail_in > 0) {
403         av_bprint_get_buffer(bp, 1, &buf, &buf_size);
404         if (!buf_size) {
405             ret = AVERROR(ENOMEM);
406             goto fail;
407         }
408         zstream.next_out  = buf;
409         zstream.avail_out = buf_size;
410         ret = inflate(&zstream, Z_PARTIAL_FLUSH);
411         if (ret != Z_OK && ret != Z_STREAM_END) {
412             ret = AVERROR_EXTERNAL;
413             goto fail;
414         }
415         bp->len += zstream.next_out - buf;
416         if (ret == Z_STREAM_END)
417             break;
418     }
419     inflateEnd(&zstream);
420     bp->str[bp->len] = 0;
421     return 0;
422
423 fail:
424     inflateEnd(&zstream);
425     av_bprint_finalize(bp, NULL);
426     return ret;
427 }
428
429 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
430 {
431     size_t extra = 0, i;
432     uint8_t *out, *q;
433
434     for (i = 0; i < size_in; i++)
435         extra += in[i] >= 0x80;
436     if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
437         return NULL;
438     q = out = av_malloc(size_in + extra + 1);
439     if (!out)
440         return NULL;
441     for (i = 0; i < size_in; i++) {
442         if (in[i] >= 0x80) {
443             *(q++) = 0xC0 | (in[i] >> 6);
444             *(q++) = 0x80 | (in[i] & 0x3F);
445         } else {
446             *(q++) = in[i];
447         }
448     }
449     *(q++) = 0;
450     return out;
451 }
452
453 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
454                              AVDictionary **dict)
455 {
456     int ret, method;
457     const uint8_t *data        = s->gb.buffer;
458     const uint8_t *data_end    = data + length;
459     const uint8_t *keyword     = data;
460     const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
461     uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
462     unsigned text_len;
463     AVBPrint bp;
464
465     if (!keyword_end)
466         return AVERROR_INVALIDDATA;
467     data = keyword_end + 1;
468
469     if (compressed) {
470         if (data == data_end)
471             return AVERROR_INVALIDDATA;
472         method = *(data++);
473         if (method)
474             return AVERROR_INVALIDDATA;
475         if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
476             return ret;
477         text_len = bp.len;
478         av_bprint_finalize(&bp, (char **)&text);
479         if (!text)
480             return AVERROR(ENOMEM);
481     } else {
482         text = (uint8_t *)data;
483         text_len = data_end - text;
484     }
485
486     kw_utf8  = iso88591_to_utf8(keyword, keyword_end - keyword);
487     txt_utf8 = iso88591_to_utf8(text, text_len);
488     if (text != data)
489         av_free(text);
490     if (!(kw_utf8 && txt_utf8)) {
491         av_free(kw_utf8);
492         av_free(txt_utf8);
493         return AVERROR(ENOMEM);
494     }
495
496     av_dict_set(dict, kw_utf8, txt_utf8,
497                 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
498     return 0;
499 }
500
501 static int decode_frame(AVCodecContext *avctx,
502                         void *data, int *got_frame,
503                         AVPacket *avpkt)
504 {
505     PNGDecContext * const s = avctx->priv_data;
506     const uint8_t *buf      = avpkt->data;
507     int buf_size            = avpkt->size;
508     AVFrame *p              = data;
509     AVDictionary *metadata  = NULL;
510     uint8_t *crow_buf_base  = NULL;
511     uint32_t tag, length;
512     int64_t sig;
513     int ret;
514
515     bytestream2_init(&s->gb, buf, buf_size);
516
517     /* check signature */
518     sig = bytestream2_get_be64(&s->gb);
519     if (sig != PNGSIG &&
520         sig != MNGSIG) {
521         av_log(avctx, AV_LOG_ERROR, "Missing png signature\n");
522         return -1;
523     }
524
525     s->y = s->state = 0;
526
527     /* init the zlib */
528     s->zstream.zalloc = ff_png_zalloc;
529     s->zstream.zfree  = ff_png_zfree;
530     s->zstream.opaque = NULL;
531     ret = inflateInit(&s->zstream);
532     if (ret != Z_OK) {
533         av_log(avctx, AV_LOG_ERROR, "inflateInit returned %d\n", ret);
534         return -1;
535     }
536     for (;;) {
537         if (bytestream2_get_bytes_left(&s->gb) <= 0) {
538             av_log(avctx, AV_LOG_ERROR, "No bytes left\n");
539             goto fail;
540         }
541
542         length = bytestream2_get_be32(&s->gb);
543         if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb))  {
544             av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
545             goto fail;
546         }
547         tag = bytestream2_get_le32(&s->gb);
548         if (avctx->debug & FF_DEBUG_STARTCODE)
549             av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
550                 (tag & 0xff),
551                 ((tag >> 8) & 0xff),
552                 ((tag >> 16) & 0xff),
553                 ((tag >> 24) & 0xff), length);
554         switch (tag) {
555         case MKTAG('I', 'H', 'D', 'R'):
556             if (length != 13)
557                 goto fail;
558             s->width  = bytestream2_get_be32(&s->gb);
559             s->height = bytestream2_get_be32(&s->gb);
560             if (av_image_check_size(s->width, s->height, 0, avctx)) {
561                 s->width = s->height = 0;
562                 av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
563                 goto fail;
564             }
565             s->bit_depth        = bytestream2_get_byte(&s->gb);
566             s->color_type       = bytestream2_get_byte(&s->gb);
567             s->compression_type = bytestream2_get_byte(&s->gb);
568             s->filter_type      = bytestream2_get_byte(&s->gb);
569             s->interlace_type   = bytestream2_get_byte(&s->gb);
570             bytestream2_skip(&s->gb, 4); /* crc */
571             s->state |= PNG_IHDR;
572             if (avctx->debug & FF_DEBUG_PICT_INFO)
573                 av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
574                     "compression_type=%d filter_type=%d interlace_type=%d\n",
575                     s->width, s->height, s->bit_depth, s->color_type,
576                     s->compression_type, s->filter_type, s->interlace_type);
577             break;
578         case MKTAG('p', 'H', 'Y', 's'):
579             if (s->state & PNG_IDAT) {
580                 av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
581                 goto fail;
582             }
583             avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
584             avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
585             if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
586                 avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
587             bytestream2_skip(&s->gb, 1); /* unit specifier */
588             bytestream2_skip(&s->gb, 4); /* crc */
589             break;
590         case MKTAG('I', 'D', 'A', 'T'):
591             if (!(s->state & PNG_IHDR)) {
592                 av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
593                 goto fail;
594             }
595             if (!(s->state & PNG_IDAT)) {
596                 /* init image info */
597                 avctx->width  = s->width;
598                 avctx->height = s->height;
599
600                 s->channels       = ff_png_get_nb_channels(s->color_type);
601                 s->bits_per_pixel = s->bit_depth * s->channels;
602                 s->bpp            = (s->bits_per_pixel + 7) >> 3;
603                 s->row_size       = (avctx->width * s->bits_per_pixel + 7) >> 3;
604
605                 if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
606                     s->color_type == PNG_COLOR_TYPE_RGB) {
607                     avctx->pix_fmt = AV_PIX_FMT_RGB24;
608                 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
609                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
610                     avctx->pix_fmt = AV_PIX_FMT_RGBA;
611                 } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
612                            s->color_type == PNG_COLOR_TYPE_GRAY) {
613                     avctx->pix_fmt = AV_PIX_FMT_GRAY8;
614                 } else if (s->bit_depth == 16 &&
615                            s->color_type == PNG_COLOR_TYPE_GRAY) {
616                     avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
617                 } else if (s->bit_depth == 16 &&
618                            s->color_type == PNG_COLOR_TYPE_RGB) {
619                     avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
620                 } else if (s->bit_depth == 16 &&
621                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
622                     avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
623                 } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
624                            s->color_type == PNG_COLOR_TYPE_PALETTE) {
625                     avctx->pix_fmt = AV_PIX_FMT_PAL8;
626                 } else if (s->bit_depth == 1) {
627                     avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
628                 } else if (s->bit_depth == 8 &&
629                            s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
630                     avctx->pix_fmt = AV_PIX_FMT_Y400A;
631                 } else {
632                     av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
633                                                 "and color type %d\n",
634                                                  s->bit_depth, s->color_type);
635                     goto fail;
636                 }
637
638                 if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0)
639                     goto fail;
640                 p->pict_type        = AV_PICTURE_TYPE_I;
641                 p->key_frame        = 1;
642                 p->interlaced_frame = !!s->interlace_type;
643
644                 /* compute the compressed row size */
645                 if (!s->interlace_type) {
646                     s->crow_size = s->row_size + 1;
647                 } else {
648                     s->pass = 0;
649                     s->pass_row_size = ff_png_pass_row_size(s->pass,
650                                                          s->bits_per_pixel,
651                                                          s->width);
652                     s->crow_size = s->pass_row_size + 1;
653                 }
654                 av_dlog(avctx, "row_size=%d crow_size =%d\n",
655                         s->row_size, s->crow_size);
656                 s->image_buf      = p->data[0];
657                 s->image_linesize = p->linesize[0];
658                 /* copy the palette if needed */
659                 if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
660                     memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
661                 /* empty row is used if differencing to the first row */
662                 s->last_row = av_mallocz(s->row_size);
663                 if (!s->last_row)
664                     goto fail;
665                 if (s->interlace_type ||
666                     s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
667                     s->tmp_row = av_malloc(s->row_size);
668                     if (!s->tmp_row)
669                         goto fail;
670                 }
671                 /* compressed row */
672                 crow_buf_base = av_malloc(s->row_size + 16);
673                 if (!crow_buf_base)
674                     goto fail;
675
676                 /* we want crow_buf+1 to be 16-byte aligned */
677                 s->crow_buf          = crow_buf_base + 15;
678                 s->zstream.avail_out = s->crow_size;
679                 s->zstream.next_out  = s->crow_buf;
680             }
681             s->state |= PNG_IDAT;
682             if (png_decode_idat(s, length) < 0)
683                 goto fail;
684             bytestream2_skip(&s->gb, 4); /* crc */
685             break;
686         case MKTAG('P', 'L', 'T', 'E'):
687             {
688                 int n, i, r, g, b;
689
690                 if ((length % 3) != 0 || length > 256 * 3)
691                     goto skip_tag;
692                 /* read the palette */
693                 n = length / 3;
694                 for (i = 0; i < n; i++) {
695                     r = bytestream2_get_byte(&s->gb);
696                     g = bytestream2_get_byte(&s->gb);
697                     b = bytestream2_get_byte(&s->gb);
698                     s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
699                 }
700                 for (; i < 256; i++) {
701                     s->palette[i] = (0xFFU << 24);
702                 }
703                 s->state |= PNG_PLTE;
704                 bytestream2_skip(&s->gb, 4); /* crc */
705             }
706             break;
707         case MKTAG('t', 'R', 'N', 'S'):
708             {
709                 int v, i;
710
711                 /* read the transparency. XXX: Only palette mode supported */
712                 if (s->color_type != PNG_COLOR_TYPE_PALETTE ||
713                     length > 256 ||
714                     !(s->state & PNG_PLTE))
715                     goto skip_tag;
716                 for (i = 0; i < length; i++) {
717                     v = bytestream2_get_byte(&s->gb);
718                     s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
719                 }
720                 bytestream2_skip(&s->gb, 4); /* crc */
721             }
722             break;
723         case MKTAG('t', 'E', 'X', 't'):
724             if (decode_text_chunk(s, length, 0, &metadata) < 0)
725                 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
726             bytestream2_skip(&s->gb, length + 4);
727             break;
728         case MKTAG('z', 'T', 'X', 't'):
729             if (decode_text_chunk(s, length, 1, &metadata) < 0)
730                 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
731             bytestream2_skip(&s->gb, length + 4);
732             break;
733         case MKTAG('I', 'E', 'N', 'D'):
734             if (!(s->state & PNG_ALLIMAGE))
735                 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
736             if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
737                 goto fail;
738             }
739             bytestream2_skip(&s->gb, 4); /* crc */
740             goto exit_loop;
741         default:
742             /* skip tag */
743         skip_tag:
744             bytestream2_skip(&s->gb, length + 4);
745             break;
746         }
747     }
748  exit_loop:
749
750     if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE){
751         int i, j, k;
752         uint8_t *pd = p->data[0];
753         for (j = 0; j < s->height; j++) {
754             i = s->width / 8;
755             for (k = 7; k >= 1; k--)
756                 if ((s->width&7) >= k)
757                     pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
758             for (i--; i >= 0; i--) {
759                 pd[8*i + 7]=  pd[i]     & 1;
760                 pd[8*i + 6]= (pd[i]>>1) & 1;
761                 pd[8*i + 5]= (pd[i]>>2) & 1;
762                 pd[8*i + 4]= (pd[i]>>3) & 1;
763                 pd[8*i + 3]= (pd[i]>>4) & 1;
764                 pd[8*i + 2]= (pd[i]>>5) & 1;
765                 pd[8*i + 1]= (pd[i]>>6) & 1;
766                 pd[8*i + 0]=  pd[i]>>7;
767             }
768             pd += s->image_linesize;
769         }
770     }
771     if (s->bits_per_pixel == 2){
772         int i, j;
773         uint8_t *pd = p->data[0];
774         for (j = 0; j < s->height; j++) {
775             i = s->width / 4;
776             if (s->color_type == PNG_COLOR_TYPE_PALETTE){
777                 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
778                 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
779                 if ((s->width&3) >= 1) pd[4*i + 0]=  pd[i] >> 6;
780                 for (i--; i >= 0; i--) {
781                     pd[4*i + 3]=  pd[i]     & 3;
782                     pd[4*i + 2]= (pd[i]>>2) & 3;
783                     pd[4*i + 1]= (pd[i]>>4) & 3;
784                     pd[4*i + 0]=  pd[i]>>6;
785                 }
786             } else {
787                 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
788                 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
789                 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6     )*0x55;
790                 for (i--; i >= 0; i--) {
791                     pd[4*i + 3]= ( pd[i]     & 3)*0x55;
792                     pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
793                     pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
794                     pd[4*i + 0]= ( pd[i]>>6     )*0x55;
795                 }
796             }
797             pd += s->image_linesize;
798         }
799     }
800     if (s->bits_per_pixel == 4){
801         int i, j;
802         uint8_t *pd = p->data[0];
803         for (j = 0; j < s->height; j++) {
804             i = s->width/2;
805             if (s->color_type == PNG_COLOR_TYPE_PALETTE){
806                 if (s->width&1) pd[2*i+0]= pd[i]>>4;
807                 for (i--; i >= 0; i--) {
808                 pd[2*i + 1] = pd[i] & 15;
809                 pd[2*i + 0] = pd[i] >> 4;
810             }
811             } else {
812                 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
813                 for (i--; i >= 0; i--) {
814                     pd[2*i + 1] = (pd[i] & 15) * 0x11;
815                     pd[2*i + 0] = (pd[i] >> 4) * 0x11;
816                 }
817             }
818             pd += s->image_linesize;
819         }
820     }
821
822      /* handle p-frames only if a predecessor frame is available */
823      if (s->prev->data[0]) {
824          if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
825             && s->prev->width == p->width
826             && s->prev->height== p->height
827             && s->prev->format== p->format
828          ) {
829             int i, j;
830             uint8_t *pd      = p->data[0];
831             uint8_t *pd_last = s->prev->data[0];
832
833             for (j = 0; j < s->height; j++) {
834                 for (i = 0; i < s->width * s->bpp; i++) {
835                     pd[i] += pd_last[i];
836                 }
837                 pd      += s->image_linesize;
838                 pd_last += s->image_linesize;
839             }
840         }
841     }
842
843     av_frame_set_metadata(p, metadata);
844     metadata   = NULL;
845
846     av_frame_unref(s->prev);
847      if ((ret = av_frame_ref(s->prev, p)) < 0)
848          goto fail;
849
850     *got_frame = 1;
851
852     ret = bytestream2_tell(&s->gb);
853  the_end:
854     inflateEnd(&s->zstream);
855     av_free(crow_buf_base);
856     s->crow_buf = NULL;
857     av_freep(&s->last_row);
858     av_freep(&s->tmp_row);
859     return ret;
860  fail:
861     av_dict_free(&metadata);
862     ret = -1;
863     goto the_end;
864 }
865
866 static av_cold int png_dec_init(AVCodecContext *avctx)
867 {
868     PNGDecContext *s = avctx->priv_data;
869
870     s->prev = av_frame_alloc();
871     if (!s->prev)
872         return AVERROR(ENOMEM);
873
874     ff_pngdsp_init(&s->dsp);
875
876     s->avctx = avctx;
877
878     return 0;
879 }
880
881 static av_cold int png_dec_end(AVCodecContext *avctx)
882 {
883     PNGDecContext *s = avctx->priv_data;
884
885     av_frame_free(&s->prev);
886
887     return 0;
888 }
889
890 AVCodec ff_png_decoder = {
891     .name           = "png",
892     .type           = AVMEDIA_TYPE_VIDEO,
893     .id             = AV_CODEC_ID_PNG,
894     .priv_data_size = sizeof(PNGDecContext),
895     .init           = png_dec_init,
896     .close          = png_dec_end,
897     .decode         = decode_frame,
898     .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
899     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
900 };