FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
pngdec.c
Go to the documentation of this file.
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 "apng.h"
30 #include "png.h"
31 #include "pngdsp.h"
32 #include "thread.h"
33 
34 #include <zlib.h>
35 
36 typedef struct PNGDecContext {
39 
44 
45  int state;
46  int width, height;
47  int cur_w, cur_h;
50  int bit_depth;
55  int channels;
57  int bpp;
58 
59  int frame_id;
62  uint32_t palette[256];
65  unsigned int last_row_size;
67  unsigned int tmp_row_size;
70  int pass;
71  int crow_size; /* compressed row size (include filter type) */
72  int row_size; /* decompressed row size */
73  int pass_row_size; /* decompress row size of the current pass */
74  int y;
75  z_stream zstream;
77 
78 /* Mask to determine which pixels are valid in a pass */
79 static const uint8_t png_pass_mask[NB_PASSES] = {
80  0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
81 };
82 
83 /* Mask to determine which y pixels can be written in a pass */
85  0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
86 };
87 
88 /* Mask to determine which pixels to overwrite while displaying */
90  0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
91 };
92 
93 /* NOTE: we try to construct a good looking image at each pass. width
94  * is the original image width. We also do pixel format conversion at
95  * this stage */
96 static void png_put_interlaced_row(uint8_t *dst, int width,
97  int bits_per_pixel, int pass,
98  int color_type, const uint8_t *src)
99 {
100  int x, mask, dsp_mask, j, src_x, b, bpp;
101  uint8_t *d;
102  const uint8_t *s;
103 
104  mask = png_pass_mask[pass];
105  dsp_mask = png_pass_dsp_mask[pass];
106 
107  switch (bits_per_pixel) {
108  case 1:
109  src_x = 0;
110  for (x = 0; x < width; x++) {
111  j = (x & 7);
112  if ((dsp_mask << j) & 0x80) {
113  b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
114  dst[x >> 3] &= 0xFF7F>>j;
115  dst[x >> 3] |= b << (7 - j);
116  }
117  if ((mask << j) & 0x80)
118  src_x++;
119  }
120  break;
121  case 2:
122  src_x = 0;
123  for (x = 0; x < width; x++) {
124  int j2 = 2 * (x & 3);
125  j = (x & 7);
126  if ((dsp_mask << j) & 0x80) {
127  b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
128  dst[x >> 2] &= 0xFF3F>>j2;
129  dst[x >> 2] |= b << (6 - j2);
130  }
131  if ((mask << j) & 0x80)
132  src_x++;
133  }
134  break;
135  case 4:
136  src_x = 0;
137  for (x = 0; x < width; x++) {
138  int j2 = 4*(x&1);
139  j = (x & 7);
140  if ((dsp_mask << j) & 0x80) {
141  b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
142  dst[x >> 1] &= 0xFF0F>>j2;
143  dst[x >> 1] |= b << (4 - j2);
144  }
145  if ((mask << j) & 0x80)
146  src_x++;
147  }
148  break;
149  default:
150  bpp = bits_per_pixel >> 3;
151  d = dst;
152  s = src;
153  for (x = 0; x < width; x++) {
154  j = x & 7;
155  if ((dsp_mask << j) & 0x80) {
156  memcpy(d, s, bpp);
157  }
158  d += bpp;
159  if ((mask << j) & 0x80)
160  s += bpp;
161  }
162  break;
163  }
164 }
165 
167  int w, int bpp)
168 {
169  int i;
170  for (i = 0; i < w; i++) {
171  int a, b, c, p, pa, pb, pc;
172 
173  a = dst[i - bpp];
174  b = top[i];
175  c = top[i - bpp];
176 
177  p = b - c;
178  pc = a - c;
179 
180  pa = abs(p);
181  pb = abs(pc);
182  pc = abs(p + pc);
183 
184  if (pa <= pb && pa <= pc)
185  p = a;
186  else if (pb <= pc)
187  p = b;
188  else
189  p = c;
190  dst[i] = p + src[i];
191  }
192 }
193 
194 #define UNROLL1(bpp, op) \
195  { \
196  r = dst[0]; \
197  if (bpp >= 2) \
198  g = dst[1]; \
199  if (bpp >= 3) \
200  b = dst[2]; \
201  if (bpp >= 4) \
202  a = dst[3]; \
203  for (; i <= size - bpp; i += bpp) { \
204  dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
205  if (bpp == 1) \
206  continue; \
207  dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
208  if (bpp == 2) \
209  continue; \
210  dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
211  if (bpp == 3) \
212  continue; \
213  dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
214  } \
215  }
216 
217 #define UNROLL_FILTER(op) \
218  if (bpp == 1) { \
219  UNROLL1(1, op) \
220  } else if (bpp == 2) { \
221  UNROLL1(2, op) \
222  } else if (bpp == 3) { \
223  UNROLL1(3, op) \
224  } else if (bpp == 4) { \
225  UNROLL1(4, op) \
226  } \
227  for (; i < size; i++) { \
228  dst[i] = op(dst[i - bpp], src[i], last[i]); \
229  }
230 
231 /* NOTE: 'dst' can be equal to 'last' */
232 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
233  uint8_t *src, uint8_t *last, int size, int bpp)
234 {
235  int i, p, r, g, b, a;
236 
237  switch (filter_type) {
239  memcpy(dst, src, size);
240  break;
242  for (i = 0; i < bpp; i++)
243  dst[i] = src[i];
244  if (bpp == 4) {
245  p = *(int *)dst;
246  for (; i < size; i += bpp) {
247  unsigned s = *(int *)(src + i);
248  p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
249  *(int *)(dst + i) = p;
250  }
251  } else {
252 #define OP_SUB(x, s, l) ((x) + (s))
254  }
255  break;
256  case PNG_FILTER_VALUE_UP:
257  dsp->add_bytes_l2(dst, src, last, size);
258  break;
260  for (i = 0; i < bpp; i++) {
261  p = (last[i] >> 1);
262  dst[i] = p + src[i];
263  }
264 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
266  break;
268  for (i = 0; i < bpp; i++) {
269  p = last[i];
270  dst[i] = p + src[i];
271  }
272  if (bpp > 2 && size > 4) {
273  /* would write off the end of the array if we let it process
274  * the last pixel with bpp=3 */
275  int w = (bpp & 3) ? size - 3 : size;
276 
277  if (w > i) {
278  dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
279  i = w;
280  }
281  }
282  ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
283  break;
284  }
285 }
286 
287 /* This used to be called "deloco" in FFmpeg
288  * and is actually an inverse reversible colorspace transformation */
289 #define YUV2RGB(NAME, TYPE) \
290 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
291 { \
292  int i; \
293  for (i = 0; i < size; i += 3 + alpha) { \
294  int g = dst [i + 1]; \
295  dst[i + 0] += g; \
296  dst[i + 2] += g; \
297  } \
298 }
299 
300 YUV2RGB(rgb8, uint8_t)
301 YUV2RGB(rgb16, uint16_t)
302 
303 /* process exactly one decompressed row */
305 {
306  uint8_t *ptr, *last_row;
307  int got_line;
308 
309  if (!s->interlace_type) {
310  ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
311  if (s->y == 0)
312  last_row = s->last_row;
313  else
314  last_row = ptr - s->image_linesize;
315 
316  png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
317  last_row, s->row_size, s->bpp);
318  /* loco lags by 1 row so that it doesn't interfere with top prediction */
319  if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
320  if (s->bit_depth == 16) {
321  deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
322  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
323  } else {
324  deloco_rgb8(ptr - s->image_linesize, s->row_size,
325  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
326  }
327  }
328  s->y++;
329  if (s->y == s->cur_h) {
330  s->state |= PNG_ALLIMAGE;
331  if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
332  if (s->bit_depth == 16) {
333  deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
334  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
335  } else {
336  deloco_rgb8(ptr, s->row_size,
337  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
338  }
339  }
340  }
341  } else {
342  got_line = 0;
343  for (;;) {
344  ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
345  if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
346  /* if we already read one row, it is time to stop to
347  * wait for the next one */
348  if (got_line)
349  break;
350  png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
351  s->last_row, s->pass_row_size, s->bpp);
352  FFSWAP(uint8_t *, s->last_row, s->tmp_row);
353  FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
354  got_line = 1;
355  }
356  if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
357  png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
358  s->color_type, s->last_row);
359  }
360  s->y++;
361  if (s->y == s->cur_h) {
362  memset(s->last_row, 0, s->row_size);
363  for (;;) {
364  if (s->pass == NB_PASSES - 1) {
365  s->state |= PNG_ALLIMAGE;
366  goto the_end;
367  } else {
368  s->pass++;
369  s->y = 0;
370  s->pass_row_size = ff_png_pass_row_size(s->pass,
371  s->bits_per_pixel,
372  s->cur_w);
373  s->crow_size = s->pass_row_size + 1;
374  if (s->pass_row_size != 0)
375  break;
376  /* skip pass if empty row */
377  }
378  }
379  }
380  }
381 the_end:;
382  }
383 }
384 
386 {
387  int ret;
388  s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
389  s->zstream.next_in = (unsigned char *)s->gb.buffer;
390  bytestream2_skip(&s->gb, length);
391 
392  /* decode one line if possible */
393  while (s->zstream.avail_in > 0) {
394  ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
395  if (ret != Z_OK && ret != Z_STREAM_END) {
396  av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
397  return AVERROR_EXTERNAL;
398  }
399  if (s->zstream.avail_out == 0) {
400  if (!(s->state & PNG_ALLIMAGE)) {
401  png_handle_row(s);
402  }
403  s->zstream.avail_out = s->crow_size;
404  s->zstream.next_out = s->crow_buf;
405  }
406  if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
407  av_log(NULL, AV_LOG_WARNING,
408  "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
409  return 0;
410  }
411  }
412  return 0;
413 }
414 
415 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
416  const uint8_t *data_end)
417 {
418  z_stream zstream;
419  unsigned char *buf;
420  unsigned buf_size;
421  int ret;
422 
423  zstream.zalloc = ff_png_zalloc;
424  zstream.zfree = ff_png_zfree;
425  zstream.opaque = NULL;
426  if (inflateInit(&zstream) != Z_OK)
427  return AVERROR_EXTERNAL;
428  zstream.next_in = (unsigned char *)data;
429  zstream.avail_in = data_end - data;
430  av_bprint_init(bp, 0, -1);
431 
432  while (zstream.avail_in > 0) {
433  av_bprint_get_buffer(bp, 1, &buf, &buf_size);
434  if (!buf_size) {
435  ret = AVERROR(ENOMEM);
436  goto fail;
437  }
438  zstream.next_out = buf;
439  zstream.avail_out = buf_size;
440  ret = inflate(&zstream, Z_PARTIAL_FLUSH);
441  if (ret != Z_OK && ret != Z_STREAM_END) {
442  ret = AVERROR_EXTERNAL;
443  goto fail;
444  }
445  bp->len += zstream.next_out - buf;
446  if (ret == Z_STREAM_END)
447  break;
448  }
449  inflateEnd(&zstream);
450  bp->str[bp->len] = 0;
451  return 0;
452 
453 fail:
454  inflateEnd(&zstream);
455  av_bprint_finalize(bp, NULL);
456  return ret;
457 }
458 
459 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
460 {
461  size_t extra = 0, i;
462  uint8_t *out, *q;
463 
464  for (i = 0; i < size_in; i++)
465  extra += in[i] >= 0x80;
466  if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
467  return NULL;
468  q = out = av_malloc(size_in + extra + 1);
469  if (!out)
470  return NULL;
471  for (i = 0; i < size_in; i++) {
472  if (in[i] >= 0x80) {
473  *(q++) = 0xC0 | (in[i] >> 6);
474  *(q++) = 0x80 | (in[i] & 0x3F);
475  } else {
476  *(q++) = in[i];
477  }
478  }
479  *(q++) = 0;
480  return out;
481 }
482 
483 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
484  AVDictionary **dict)
485 {
486  int ret, method;
487  const uint8_t *data = s->gb.buffer;
488  const uint8_t *data_end = data + length;
489  const uint8_t *keyword = data;
490  const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
491  uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
492  unsigned text_len;
493  AVBPrint bp;
494 
495  if (!keyword_end)
496  return AVERROR_INVALIDDATA;
497  data = keyword_end + 1;
498 
499  if (compressed) {
500  if (data == data_end)
501  return AVERROR_INVALIDDATA;
502  method = *(data++);
503  if (method)
504  return AVERROR_INVALIDDATA;
505  if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
506  return ret;
507  text_len = bp.len;
508  av_bprint_finalize(&bp, (char **)&text);
509  if (!text)
510  return AVERROR(ENOMEM);
511  } else {
512  text = (uint8_t *)data;
513  text_len = data_end - text;
514  }
515 
516  kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
517  txt_utf8 = iso88591_to_utf8(text, text_len);
518  if (text != data)
519  av_free(text);
520  if (!(kw_utf8 && txt_utf8)) {
521  av_free(kw_utf8);
522  av_free(txt_utf8);
523  return AVERROR(ENOMEM);
524  }
525 
526  av_dict_set(dict, kw_utf8, txt_utf8,
528  return 0;
529 }
530 
532  uint32_t length)
533 {
534  if (length != 13)
535  return AVERROR_INVALIDDATA;
536 
537  if (s->state & PNG_IDAT) {
538  av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
539  return AVERROR_INVALIDDATA;
540  }
541 
542  s->width = s->cur_w = bytestream2_get_be32(&s->gb);
543  s->height = s->cur_h = bytestream2_get_be32(&s->gb);
544  if (av_image_check_size(s->width, s->height, 0, avctx)) {
545  s->width = s->height = 0;
546  av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
547  return AVERROR_INVALIDDATA;
548  }
549  s->bit_depth = bytestream2_get_byte(&s->gb);
550  s->color_type = bytestream2_get_byte(&s->gb);
551  s->compression_type = bytestream2_get_byte(&s->gb);
552  s->filter_type = bytestream2_get_byte(&s->gb);
553  s->interlace_type = bytestream2_get_byte(&s->gb);
554  bytestream2_skip(&s->gb, 4); /* crc */
555  s->state |= PNG_IHDR;
556  if (avctx->debug & FF_DEBUG_PICT_INFO)
557  av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
558  "compression_type=%d filter_type=%d interlace_type=%d\n",
559  s->width, s->height, s->bit_depth, s->color_type,
561 
562  return 0;
563 }
564 
566 {
567  if (s->state & PNG_IDAT) {
568  av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
569  return AVERROR_INVALIDDATA;
570  }
571  avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
572  avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
573  if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
574  avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
575  bytestream2_skip(&s->gb, 1); /* unit specifier */
576  bytestream2_skip(&s->gb, 4); /* crc */
577 
578  return 0;
579 }
580 
582  uint32_t length, AVFrame *p)
583 {
584  int ret;
585 
586  if (!(s->state & PNG_IHDR)) {
587  av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
588  return AVERROR_INVALIDDATA;
589  }
590  if (!(s->state & PNG_IDAT)) {
591  /* init image info */
592  avctx->width = s->width;
593  avctx->height = s->height;
594 
596  s->bits_per_pixel = s->bit_depth * s->channels;
597  s->bpp = (s->bits_per_pixel + 7) >> 3;
598  s->row_size = (s->cur_w * s->bits_per_pixel + 7) >> 3;
599 
600  if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
602  avctx->pix_fmt = AV_PIX_FMT_RGB24;
603  } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
605  avctx->pix_fmt = AV_PIX_FMT_RGBA;
606  } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
608  avctx->pix_fmt = AV_PIX_FMT_GRAY8;
609  } else if (s->bit_depth == 16 &&
611  avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
612  } else if (s->bit_depth == 16 &&
614  avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
615  } else if (s->bit_depth == 16 &&
617  avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
618  } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
620  avctx->pix_fmt = AV_PIX_FMT_PAL8;
621  } else if (s->bit_depth == 1 && s->bits_per_pixel == 1) {
622  avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
623  } else if (s->bit_depth == 8 &&
625  avctx->pix_fmt = AV_PIX_FMT_YA8;
626  } else if (s->bit_depth == 16 &&
628  avctx->pix_fmt = AV_PIX_FMT_YA16BE;
629  } else {
630  av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
631  "and color type %d\n",
632  s->bit_depth, s->color_type);
633  return AVERROR_INVALIDDATA;
634  }
635 
636  if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
637  return ret;
638  ff_thread_finish_setup(avctx);
639 
641  p->key_frame = 1;
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;
650  s->bits_per_pixel,
651  s->cur_w);
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 */
663  if (!s->last_row)
664  return AVERROR_INVALIDDATA;
665  if (s->interlace_type ||
668  if (!s->tmp_row)
669  return AVERROR_INVALIDDATA;
670  }
671  /* compressed row */
673  if (!s->buffer)
674  return AVERROR(ENOMEM);
675 
676  /* we want crow_buf+1 to be 16-byte aligned */
677  s->crow_buf = s->buffer + 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 ((ret = png_decode_idat(s, length)) < 0)
683  return ret;
684  bytestream2_skip(&s->gb, 4); /* crc */
685 
686  return 0;
687 }
688 
690  uint32_t length)
691 {
692  int n, i, r, g, b;
693 
694  if ((length % 3) != 0 || length > 256 * 3)
695  return AVERROR_INVALIDDATA;
696  /* read the palette */
697  n = length / 3;
698  for (i = 0; i < n; i++) {
699  r = bytestream2_get_byte(&s->gb);
700  g = bytestream2_get_byte(&s->gb);
701  b = bytestream2_get_byte(&s->gb);
702  s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
703  }
704  for (; i < 256; i++)
705  s->palette[i] = (0xFFU << 24);
706  s->state |= PNG_PLTE;
707  bytestream2_skip(&s->gb, 4); /* crc */
708 
709  return 0;
710 }
711 
713  uint32_t length)
714 {
715  int v, i;
716 
717  /* read the transparency. XXX: Only palette mode supported */
719  length > 256 ||
720  !(s->state & PNG_PLTE))
721  return AVERROR_INVALIDDATA;
722  for (i = 0; i < length; i++) {
723  v = bytestream2_get_byte(&s->gb);
724  s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
725  }
726  bytestream2_skip(&s->gb, 4); /* crc */
727 
728  return 0;
729 }
730 
732 {
733  if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
734  int i, j, k;
735  uint8_t *pd = p->data[0];
736  for (j = 0; j < s->height; j++) {
737  i = s->width / 8;
738  for (k = 7; k >= 1; k--)
739  if ((s->width&7) >= k)
740  pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
741  for (i--; i >= 0; i--) {
742  pd[8*i + 7]= pd[i] & 1;
743  pd[8*i + 6]= (pd[i]>>1) & 1;
744  pd[8*i + 5]= (pd[i]>>2) & 1;
745  pd[8*i + 4]= (pd[i]>>3) & 1;
746  pd[8*i + 3]= (pd[i]>>4) & 1;
747  pd[8*i + 2]= (pd[i]>>5) & 1;
748  pd[8*i + 1]= (pd[i]>>6) & 1;
749  pd[8*i + 0]= pd[i]>>7;
750  }
751  pd += s->image_linesize;
752  }
753  } else if (s->bits_per_pixel == 2) {
754  int i, j;
755  uint8_t *pd = p->data[0];
756  for (j = 0; j < s->height; j++) {
757  i = s->width / 4;
759  if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
760  if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
761  if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
762  for (i--; i >= 0; i--) {
763  pd[4*i + 3]= pd[i] & 3;
764  pd[4*i + 2]= (pd[i]>>2) & 3;
765  pd[4*i + 1]= (pd[i]>>4) & 3;
766  pd[4*i + 0]= pd[i]>>6;
767  }
768  } else {
769  if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
770  if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
771  if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
772  for (i--; i >= 0; i--) {
773  pd[4*i + 3]= ( pd[i] & 3)*0x55;
774  pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
775  pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
776  pd[4*i + 0]= ( pd[i]>>6 )*0x55;
777  }
778  }
779  pd += s->image_linesize;
780  }
781  } else if (s->bits_per_pixel == 4) {
782  int i, j;
783  uint8_t *pd = p->data[0];
784  for (j = 0; j < s->height; j++) {
785  i = s->width/2;
787  if (s->width&1) pd[2*i+0]= pd[i]>>4;
788  for (i--; i >= 0; i--) {
789  pd[2*i + 1] = pd[i] & 15;
790  pd[2*i + 0] = pd[i] >> 4;
791  }
792  } else {
793  if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
794  for (i--; i >= 0; i--) {
795  pd[2*i + 1] = (pd[i] & 15) * 0x11;
796  pd[2*i + 0] = (pd[i] >> 4) * 0x11;
797  }
798  }
799  pd += s->image_linesize;
800  }
801  }
802 }
803 
805  uint32_t length)
806 {
807  uint32_t sequence_number;
808 
809  if (length != 26)
810  return AVERROR_INVALIDDATA;
811 
812  sequence_number = bytestream2_get_be32(&s->gb);
813  s->cur_w = bytestream2_get_be32(&s->gb);
814  s->cur_h = bytestream2_get_be32(&s->gb);
815  s->x_offset = bytestream2_get_be32(&s->gb);
816  s->y_offset = bytestream2_get_be32(&s->gb);
817  bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
818  s->dispose_op = bytestream2_get_byte(&s->gb);
819  s->blend_op = bytestream2_get_byte(&s->gb);
820  bytestream2_skip(&s->gb, 4); /* crc */
821 
822  if (sequence_number == 0 &&
823  (s->cur_w != s->width ||
824  s->cur_h != s->height ||
825  s->x_offset != 0 ||
826  s->y_offset != 0) ||
827  s->cur_w <= 0 || s->cur_h <= 0 ||
828  s->x_offset < 0 || s->y_offset < 0 ||
829  s->cur_w > s->width - s->x_offset|| s->cur_h > s->height - s->y_offset)
830  return AVERROR_INVALIDDATA;
831 
832  /* always (re)start with a clean frame */
833  if (sequence_number == 0) {
835  s->frame_id = 0;
836  } else {
837  s->frame_id++;
838  if (s->frame_id == 1 && s->dispose_op == APNG_DISPOSE_OP_PREVIOUS)
839  /* previous for the second frame is the first frame */
841  }
842 
843  return 0;
844 }
845 
847 {
848  int i, j;
849  uint8_t *pd = p->data[0];
850  uint8_t *pd_last = s->last_picture.f->data[0];
851  int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
852 
853  ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
854  for (j = 0; j < s->height; j++) {
855  for (i = 0; i < ls; i++)
856  pd[i] += pd_last[i];
857  pd += s->image_linesize;
858  pd_last += s->image_linesize;
859  }
860 }
861 
862 // divide by 255 and round to nearest
863 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
864 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
865 
867  AVFrame *p)
868 {
869  int i, j;
870  uint8_t *pd = p->data[0];
871  uint8_t *pd_last = s->last_picture.f->data[0];
872  uint8_t *pd_last_region = s->dispose_op == APNG_DISPOSE_OP_PREVIOUS ?
873  s->previous_picture.f->data[0] : s->last_picture.f->data[0];
874  int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
875 
876  if (ls < 0)
877  return ls;
878 
879  if (s->blend_op == APNG_BLEND_OP_OVER &&
880  avctx->pix_fmt != AV_PIX_FMT_RGBA && avctx->pix_fmt != AV_PIX_FMT_ARGB) {
881  avpriv_request_sample(avctx, "Blending with pixel format %s",
882  av_get_pix_fmt_name(avctx->pix_fmt));
883  return AVERROR_PATCHWELCOME;
884  }
885 
886  ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
889 
890  for (j = 0; j < s->y_offset; j++) {
891  memcpy(pd, pd_last, ls);
892  pd += s->image_linesize;
893  pd_last += s->image_linesize;
894  }
895 
897  uint8_t ri, gi, bi, ai;
898 
899  pd_last_region += s->y_offset * s->image_linesize;
900  if (avctx->pix_fmt == AV_PIX_FMT_RGBA) {
901  ri = 0;
902  gi = 1;
903  bi = 2;
904  ai = 3;
905  } else {
906  ri = 3;
907  gi = 2;
908  bi = 1;
909  ai = 0;
910  }
911 
912  for (j = s->y_offset; j < s->y_offset + s->cur_h; j++) {
913  i = s->x_offset * s->bpp;
914  if (i)
915  memcpy(pd, pd_last, i);
916  for (; i < (s->x_offset + s->cur_w) * s->bpp; i += s->bpp) {
917  uint8_t alpha = pd[i+ai];
918 
919  /* output = alpha * foreground + (1-alpha) * background */
920  switch (alpha) {
921  case 0:
922  pd[i+ri] = pd_last_region[i+ri];
923  pd[i+gi] = pd_last_region[i+gi];
924  pd[i+bi] = pd_last_region[i+bi];
925  pd[i+ai] = 0xff;
926  break;
927  case 255:
928  break;
929  default:
930  pd[i+ri] = FAST_DIV255(alpha * pd[i+ri] + (255 - alpha) * pd_last_region[i+ri]);
931  pd[i+gi] = FAST_DIV255(alpha * pd[i+gi] + (255 - alpha) * pd_last_region[i+gi]);
932  pd[i+bi] = FAST_DIV255(alpha * pd[i+bi] + (255 - alpha) * pd_last_region[i+bi]);
933  pd[i+ai] = 0xff;
934  break;
935  }
936  }
937  if (ls - i)
938  memcpy(pd+i, pd_last+i, ls - i);
939  pd += s->image_linesize;
940  pd_last += s->image_linesize;
941  pd_last_region += s->image_linesize;
942  }
943  } else {
944  for (j = s->y_offset; j < s->y_offset + s->cur_h; j++) {
945  int end_offset = (s->x_offset + s->cur_w) * s->bpp;
946  int end_len = ls - end_offset;
947  if (s->x_offset)
948  memcpy(pd, pd_last, s->x_offset * s->bpp);
949  if (end_len)
950  memcpy(pd+end_offset, pd_last+end_offset, end_len);
951  pd += s->image_linesize;
952  pd_last += s->image_linesize;
953  }
954  }
955 
956  for (j = s->y_offset + s->cur_h; j < s->height; j++) {
957  memcpy(pd, pd_last, ls);
958  pd += s->image_linesize;
959  pd_last += s->image_linesize;
960  }
961 
962  return 0;
963 }
964 
966  AVFrame *p, AVPacket *avpkt)
967 {
968  AVDictionary *metadata = NULL;
969  uint32_t tag, length;
970  int decode_next_dat = 0;
971  int ret = AVERROR_INVALIDDATA;
972  AVFrame *ref;
973 
974  for (;;) {
975  length = bytestream2_get_bytes_left(&s->gb);
976  if (length <= 0) {
977  if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
978  if (!(s->state & PNG_IDAT))
979  return 0;
980  else
981  goto exit_loop;
982  }
983  av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
984  if ( s->state & PNG_ALLIMAGE
986  goto exit_loop;
987  goto fail;
988  }
989 
990  length = bytestream2_get_be32(&s->gb);
991  if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
992  av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
993  goto fail;
994  }
995  tag = bytestream2_get_le32(&s->gb);
996  if (avctx->debug & FF_DEBUG_STARTCODE)
997  av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
998  (tag & 0xff),
999  ((tag >> 8) & 0xff),
1000  ((tag >> 16) & 0xff),
1001  ((tag >> 24) & 0xff), length);
1002  switch (tag) {
1003  case MKTAG('I', 'H', 'D', 'R'):
1004  if (decode_ihdr_chunk(avctx, s, length) < 0)
1005  goto fail;
1006  break;
1007  case MKTAG('p', 'H', 'Y', 's'):
1008  if (decode_phys_chunk(avctx, s) < 0)
1009  goto fail;
1010  break;
1011  case MKTAG('f', 'c', 'T', 'L'):
1012  if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1013  goto skip_tag;
1014  if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
1015  goto fail;
1016  decode_next_dat = 1;
1017  break;
1018  case MKTAG('f', 'd', 'A', 'T'):
1019  if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
1020  goto skip_tag;
1021  if (!decode_next_dat)
1022  goto fail;
1023  bytestream2_get_be32(&s->gb);
1024  length -= 4;
1025  /* fallthrough */
1026  case MKTAG('I', 'D', 'A', 'T'):
1027  if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
1028  goto skip_tag;
1029  if (decode_idat_chunk(avctx, s, length, p) < 0)
1030  goto fail;
1031  break;
1032  case MKTAG('P', 'L', 'T', 'E'):
1033  if (decode_plte_chunk(avctx, s, length) < 0)
1034  goto skip_tag;
1035  break;
1036  case MKTAG('t', 'R', 'N', 'S'):
1037  if (decode_trns_chunk(avctx, s, length) < 0)
1038  goto skip_tag;
1039  break;
1040  case MKTAG('t', 'E', 'X', 't'):
1041  if (decode_text_chunk(s, length, 0, &metadata) < 0)
1042  av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
1043  bytestream2_skip(&s->gb, length + 4);
1044  break;
1045  case MKTAG('z', 'T', 'X', 't'):
1046  if (decode_text_chunk(s, length, 1, &metadata) < 0)
1047  av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
1048  bytestream2_skip(&s->gb, length + 4);
1049  break;
1050  case MKTAG('I', 'E', 'N', 'D'):
1051  if (!(s->state & PNG_ALLIMAGE))
1052  av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
1053  if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1054  goto fail;
1055  }
1056  bytestream2_skip(&s->gb, 4); /* crc */
1057  goto exit_loop;
1058  default:
1059  /* skip tag */
1060 skip_tag:
1061  bytestream2_skip(&s->gb, length + 4);
1062  break;
1063  }
1064  }
1065 exit_loop:
1066 
1067  if (s->bits_per_pixel <= 4)
1068  handle_small_bpp(s, p);
1069 
1070  /* handle p-frames only if a predecessor frame is available */
1071  ref = s->dispose_op == APNG_DISPOSE_OP_PREVIOUS ?
1072  s->previous_picture.f : s->last_picture.f;
1073  if (ref->data[0]) {
1074  if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
1075  && ref->width == p->width
1076  && ref->height== p->height
1077  && ref->format== p->format
1078  ) {
1079  if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
1080  handle_p_frame_png(s, p);
1081  else if (CONFIG_APNG_DECODER &&
1082  avctx->codec_id == AV_CODEC_ID_APNG &&
1083  (ret = handle_p_frame_apng(avctx, s, p)) < 0)
1084  goto fail;
1085  }
1086  }
1087  ff_thread_report_progress(&s->picture, INT_MAX, 0);
1088 
1089  av_frame_set_metadata(p, metadata);
1090  metadata = NULL;
1091  return 0;
1092 
1093 fail:
1094  av_dict_free(&metadata);
1095  ff_thread_report_progress(&s->picture, INT_MAX, 0);
1096  return ret;
1097 }
1098 
1099 #if CONFIG_PNG_DECODER
1100 static int decode_frame_png(AVCodecContext *avctx,
1101  void *data, int *got_frame,
1102  AVPacket *avpkt)
1103 {
1104  PNGDecContext *const s = avctx->priv_data;
1105  const uint8_t *buf = avpkt->data;
1106  int buf_size = avpkt->size;
1107  AVFrame *p;
1108  int64_t sig;
1109  int ret;
1110 
1113  p = s->picture.f;
1114 
1115  bytestream2_init(&s->gb, buf, buf_size);
1116 
1117  /* check signature */
1118  sig = bytestream2_get_be64(&s->gb);
1119  if (sig != PNGSIG &&
1120  sig != MNGSIG) {
1121  av_log(avctx, AV_LOG_ERROR, "Missing png signature\n");
1122  return AVERROR_INVALIDDATA;
1123  }
1124 
1125  s->y = s->state = 0;
1126 
1127  /* init the zlib */
1128  s->zstream.zalloc = ff_png_zalloc;
1129  s->zstream.zfree = ff_png_zfree;
1130  s->zstream.opaque = NULL;
1131  ret = inflateInit(&s->zstream);
1132  if (ret != Z_OK) {
1133  av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1134  return AVERROR_EXTERNAL;
1135  }
1136 
1137  if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1138  goto the_end;
1139 
1140  if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1141  return ret;
1142 
1143  *got_frame = 1;
1144 
1145  ret = bytestream2_tell(&s->gb);
1146 the_end:
1147  inflateEnd(&s->zstream);
1148  s->crow_buf = NULL;
1149  return ret;
1150 }
1151 #endif
1152 
1153 #if CONFIG_APNG_DECODER
1154 static int decode_frame_apng(AVCodecContext *avctx,
1155  void *data, int *got_frame,
1156  AVPacket *avpkt)
1157 {
1158  PNGDecContext *const s = avctx->priv_data;
1159  int ret;
1160  AVFrame *p;
1161  ThreadFrame tmp;
1162 
1164  tmp = s->previous_picture;
1166  s->last_picture = s->picture;
1167  s->picture = tmp;
1168  p = s->picture.f;
1169 
1170  if (!(s->state & PNG_IHDR)) {
1171  if (!avctx->extradata_size)
1172  return AVERROR_INVALIDDATA;
1173 
1174  /* only init fields, there is no zlib use in extradata */
1175  s->zstream.zalloc = ff_png_zalloc;
1176  s->zstream.zfree = ff_png_zfree;
1177 
1178  bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1179  if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1180  goto end;
1181  }
1182 
1183  /* reset state for a new frame */
1184  if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1185  av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1186  ret = AVERROR_EXTERNAL;
1187  goto end;
1188  }
1189  s->y = 0;
1190  s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
1191  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1192  if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1193  goto end;
1194 
1195  if (!(s->state & PNG_ALLIMAGE))
1196  av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1197  if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1198  ret = AVERROR_INVALIDDATA;
1199  goto end;
1200  }
1201  if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1202  goto end;
1203 
1204  *got_frame = 1;
1205  ret = bytestream2_tell(&s->gb);
1206 
1207 end:
1208  inflateEnd(&s->zstream);
1209  return ret;
1210 }
1211 #endif
1212 
1214 {
1215  PNGDecContext *psrc = src->priv_data;
1216  PNGDecContext *pdst = dst->priv_data;
1217  int ret;
1218 
1219  if (dst == src)
1220  return 0;
1221 
1222  pdst->frame_id = psrc->frame_id;
1223 
1224  ff_thread_release_buffer(dst, &pdst->picture);
1225  if (psrc->picture.f->data[0] &&
1226  (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
1227  return ret;
1228  if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
1230  if (psrc->last_picture.f->data[0])
1231  return ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture);
1232  }
1233 
1234  return 0;
1235 }
1236 
1238 {
1239  PNGDecContext *s = avctx->priv_data;
1240 
1241  s->avctx = avctx;
1243  s->last_picture.f = av_frame_alloc();
1244  s->picture.f = av_frame_alloc();
1245  if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
1248  av_frame_free(&s->picture.f);
1249  return AVERROR(ENOMEM);
1250  }
1251 
1252  if (!avctx->internal->is_copy) {
1253  avctx->internal->allocate_progress = 1;
1254  ff_pngdsp_init(&s->dsp);
1255  }
1256 
1257  return 0;
1258 }
1259 
1261 {
1262  PNGDecContext *s = avctx->priv_data;
1263 
1268  ff_thread_release_buffer(avctx, &s->picture);
1269  av_frame_free(&s->picture.f);
1270  av_freep(&s->buffer);
1271  s->buffer_size = 0;
1272  av_freep(&s->last_row);
1273  s->last_row_size = 0;
1274  av_freep(&s->tmp_row);
1275  s->tmp_row_size = 0;
1276 
1277  return 0;
1278 }
1279 
1280 #if CONFIG_APNG_DECODER
1281 AVCodec ff_apng_decoder = {
1282  .name = "apng",
1283  .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1284  .type = AVMEDIA_TYPE_VIDEO,
1285  .id = AV_CODEC_ID_APNG,
1286  .priv_data_size = sizeof(PNGDecContext),
1287  .init = png_dec_init,
1288  .close = png_dec_end,
1289  .decode = decode_frame_apng,
1291  .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1292  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
1293 };
1294 #endif
1295 
1296 #if CONFIG_PNG_DECODER
1297 AVCodec ff_png_decoder = {
1298  .name = "png",
1299  .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1300  .type = AVMEDIA_TYPE_VIDEO,
1301  .id = AV_CODEC_ID_PNG,
1302  .priv_data_size = sizeof(PNGDecContext),
1303  .init = png_dec_init,
1304  .close = png_dec_end,
1305  .decode = decode_frame_png,
1307  .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1308  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
1309 };
1310 #endif