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