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 "png.h"
30 #include "pngdsp.h"
31 #include "thread.h"
32 
33 #include <zlib.h>
34 
35 typedef struct PNGDecContext {
38 
42 
43  int state;
44  int width, height;
45  int bit_depth;
50  int channels;
52  int bpp;
53 
56  uint32_t palette[256];
59  unsigned int last_row_size;
61  unsigned int tmp_row_size;
64  int pass;
65  int crow_size; /* compressed row size (include filter type) */
66  int row_size; /* decompressed row size */
67  int pass_row_size; /* decompress row size of the current pass */
68  int y;
69  z_stream zstream;
71 
72 /* Mask to determine which pixels are valid in a pass */
73 static const uint8_t png_pass_mask[NB_PASSES] = {
74  0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
75 };
76 
77 /* Mask to determine which y pixels can be written in a pass */
79  0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
80 };
81 
82 /* Mask to determine which pixels to overwrite while displaying */
84  0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
85 };
86 
87 /* NOTE: we try to construct a good looking image at each pass. width
88  * is the original image width. We also do pixel format conversion at
89  * this stage */
90 static void png_put_interlaced_row(uint8_t *dst, int width,
91  int bits_per_pixel, int pass,
92  int color_type, const uint8_t *src)
93 {
94  int x, mask, dsp_mask, j, src_x, b, bpp;
95  uint8_t *d;
96  const uint8_t *s;
97 
98  mask = png_pass_mask[pass];
99  dsp_mask = png_pass_dsp_mask[pass];
100 
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 
161  int w, int bpp)
162 {
163  int i;
164  for (i = 0; i < w; i++) {
165  int a, b, c, p, pa, pb, pc;
166 
167  a = dst[i - bpp];
168  b = top[i];
169  c = top[i - bpp];
170 
171  p = b - c;
172  pc = a - c;
173 
174  pa = abs(p);
175  pb = abs(pc);
176  pc = abs(p + pc);
177 
178  if (pa <= pb && pa <= pc)
179  p = a;
180  else if (pb <= pc)
181  p = b;
182  else
183  p = c;
184  dst[i] = p + src[i];
185  }
186 }
187 
188 #define UNROLL1(bpp, op) \
189  { \
190  r = dst[0]; \
191  if (bpp >= 2) \
192  g = dst[1]; \
193  if (bpp >= 3) \
194  b = dst[2]; \
195  if (bpp >= 4) \
196  a = dst[3]; \
197  for (; i <= size - bpp; i += bpp) { \
198  dst[i + 0] = r = op(r, src[i + 0], last[i + 0]); \
199  if (bpp == 1) \
200  continue; \
201  dst[i + 1] = g = op(g, src[i + 1], last[i + 1]); \
202  if (bpp == 2) \
203  continue; \
204  dst[i + 2] = b = op(b, src[i + 2], last[i + 2]); \
205  if (bpp == 3) \
206  continue; \
207  dst[i + 3] = a = op(a, src[i + 3], last[i + 3]); \
208  } \
209  }
210 
211 #define UNROLL_FILTER(op) \
212  if (bpp == 1) { \
213  UNROLL1(1, op) \
214  } else if (bpp == 2) { \
215  UNROLL1(2, op) \
216  } else if (bpp == 3) { \
217  UNROLL1(3, op) \
218  } else if (bpp == 4) { \
219  UNROLL1(4, op) \
220  } \
221  for (; i < size; i++) { \
222  dst[i] = op(dst[i - bpp], src[i], last[i]); \
223  }
224 
225 /* NOTE: 'dst' can be equal to 'last' */
226 static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
227  uint8_t *src, uint8_t *last, int size, int bpp)
228 {
229  int i, p, r, g, b, a;
230 
231  switch (filter_type) {
233  memcpy(dst, src, size);
234  break;
236  for (i = 0; i < bpp; i++)
237  dst[i] = src[i];
238  if (bpp == 4) {
239  p = *(int *)dst;
240  for (; i < size; i += bpp) {
241  unsigned s = *(int *)(src + i);
242  p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
243  *(int *)(dst + i) = p;
244  }
245  } else {
246 #define OP_SUB(x, s, l) ((x) + (s))
248  }
249  break;
250  case PNG_FILTER_VALUE_UP:
251  dsp->add_bytes_l2(dst, src, last, size);
252  break;
254  for (i = 0; i < bpp; i++) {
255  p = (last[i] >> 1);
256  dst[i] = p + src[i];
257  }
258 #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
260  break;
262  for (i = 0; i < bpp; i++) {
263  p = last[i];
264  dst[i] = p + src[i];
265  }
266  if (bpp > 2 && size > 4) {
267  /* would write off the end of the array if we let it process
268  * the last pixel with bpp=3 */
269  int w = bpp == 4 ? size : size - 3;
270  if (w > i) {
271  dsp->add_paeth_prediction(dst + i, src + i, last + i, w - i, bpp);
272  i = w;
273  }
274  }
275  ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
276  break;
277  }
278 }
279 
280 /* This used to be called "deloco" in FFmpeg
281  * and is actually an inverse reversible colorspace transformation */
282 #define YUV2RGB(NAME, TYPE) \
283 static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
284 { \
285  int i; \
286  for (i = 0; i < size; i += 3 + alpha) { \
287  int g = dst [i + 1]; \
288  dst[i + 0] += g; \
289  dst[i + 2] += g; \
290  } \
291 }
292 
293 YUV2RGB(rgb8, uint8_t)
294 YUV2RGB(rgb16, uint16_t)
295 
296 /* process exactly one decompressed row */
298 {
299  uint8_t *ptr, *last_row;
300  int got_line;
301 
302  if (!s->interlace_type) {
303  ptr = s->image_buf + s->image_linesize * s->y;
304  if (s->y == 0)
305  last_row = s->last_row;
306  else
307  last_row = ptr - s->image_linesize;
308 
309  png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
310  last_row, s->row_size, s->bpp);
311  /* loco lags by 1 row so that it doesn't interfere with top prediction */
312  if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
313  if (s->bit_depth == 16) {
314  deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
315  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
316  } else {
317  deloco_rgb8(ptr - s->image_linesize, s->row_size,
318  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
319  }
320  }
321  s->y++;
322  if (s->y == s->height) {
323  s->state |= PNG_ALLIMAGE;
324  if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
325  if (s->bit_depth == 16) {
326  deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
327  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
328  } else {
329  deloco_rgb8(ptr, s->row_size,
330  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
331  }
332  }
333  }
334  } else {
335  got_line = 0;
336  for (;;) {
337  ptr = s->image_buf + s->image_linesize * s->y;
338  if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
339  /* if we already read one row, it is time to stop to
340  * wait for the next one */
341  if (got_line)
342  break;
343  png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
344  s->last_row, s->pass_row_size, s->bpp);
345  FFSWAP(uint8_t *, s->last_row, s->tmp_row);
346  FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
347  got_line = 1;
348  }
349  if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
350  png_put_interlaced_row(ptr, s->width, s->bits_per_pixel, s->pass,
351  s->color_type, s->last_row);
352  }
353  s->y++;
354  if (s->y == s->height) {
355  memset(s->last_row, 0, s->row_size);
356  for (;;) {
357  if (s->pass == NB_PASSES - 1) {
358  s->state |= PNG_ALLIMAGE;
359  goto the_end;
360  } else {
361  s->pass++;
362  s->y = 0;
363  s->pass_row_size = ff_png_pass_row_size(s->pass,
364  s->bits_per_pixel,
365  s->width);
366  s->crow_size = s->pass_row_size + 1;
367  if (s->pass_row_size != 0)
368  break;
369  /* skip pass if empty row */
370  }
371  }
372  }
373  }
374 the_end:;
375  }
376 }
377 
379 {
380  int ret;
381  s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
382  s->zstream.next_in = (unsigned char *)s->gb.buffer;
383  bytestream2_skip(&s->gb, length);
384 
385  /* decode one line if possible */
386  while (s->zstream.avail_in > 0) {
387  ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
388  if (ret != Z_OK && ret != Z_STREAM_END) {
389  av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
390  return AVERROR_EXTERNAL;
391  }
392  if (s->zstream.avail_out == 0) {
393  if (!(s->state & PNG_ALLIMAGE)) {
394  png_handle_row(s);
395  }
396  s->zstream.avail_out = s->crow_size;
397  s->zstream.next_out = s->crow_buf;
398  }
399  if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
400  av_log(NULL, AV_LOG_WARNING,
401  "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
402  return 0;
403  }
404  }
405  return 0;
406 }
407 
408 static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
409  const uint8_t *data_end)
410 {
411  z_stream zstream;
412  unsigned char *buf;
413  unsigned buf_size;
414  int ret;
415 
416  zstream.zalloc = ff_png_zalloc;
417  zstream.zfree = ff_png_zfree;
418  zstream.opaque = NULL;
419  if (inflateInit(&zstream) != Z_OK)
420  return AVERROR_EXTERNAL;
421  zstream.next_in = (unsigned char *)data;
422  zstream.avail_in = data_end - data;
423  av_bprint_init(bp, 0, -1);
424 
425  while (zstream.avail_in > 0) {
426  av_bprint_get_buffer(bp, 1, &buf, &buf_size);
427  if (!buf_size) {
428  ret = AVERROR(ENOMEM);
429  goto fail;
430  }
431  zstream.next_out = buf;
432  zstream.avail_out = buf_size;
433  ret = inflate(&zstream, Z_PARTIAL_FLUSH);
434  if (ret != Z_OK && ret != Z_STREAM_END) {
435  ret = AVERROR_EXTERNAL;
436  goto fail;
437  }
438  bp->len += zstream.next_out - buf;
439  if (ret == Z_STREAM_END)
440  break;
441  }
442  inflateEnd(&zstream);
443  bp->str[bp->len] = 0;
444  return 0;
445 
446 fail:
447  inflateEnd(&zstream);
448  av_bprint_finalize(bp, NULL);
449  return ret;
450 }
451 
452 static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
453 {
454  size_t extra = 0, i;
455  uint8_t *out, *q;
456 
457  for (i = 0; i < size_in; i++)
458  extra += in[i] >= 0x80;
459  if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
460  return NULL;
461  q = out = av_malloc(size_in + extra + 1);
462  if (!out)
463  return NULL;
464  for (i = 0; i < size_in; i++) {
465  if (in[i] >= 0x80) {
466  *(q++) = 0xC0 | (in[i] >> 6);
467  *(q++) = 0x80 | (in[i] & 0x3F);
468  } else {
469  *(q++) = in[i];
470  }
471  }
472  *(q++) = 0;
473  return out;
474 }
475 
476 static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
477  AVDictionary **dict)
478 {
479  int ret, method;
480  const uint8_t *data = s->gb.buffer;
481  const uint8_t *data_end = data + length;
482  const uint8_t *keyword = data;
483  const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
484  uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
485  unsigned text_len;
486  AVBPrint bp;
487 
488  if (!keyword_end)
489  return AVERROR_INVALIDDATA;
490  data = keyword_end + 1;
491 
492  if (compressed) {
493  if (data == data_end)
494  return AVERROR_INVALIDDATA;
495  method = *(data++);
496  if (method)
497  return AVERROR_INVALIDDATA;
498  if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
499  return ret;
500  text_len = bp.len;
501  av_bprint_finalize(&bp, (char **)&text);
502  if (!text)
503  return AVERROR(ENOMEM);
504  } else {
505  text = (uint8_t *)data;
506  text_len = data_end - text;
507  }
508 
509  kw_utf8 = iso88591_to_utf8(keyword, keyword_end - keyword);
510  txt_utf8 = iso88591_to_utf8(text, text_len);
511  if (text != data)
512  av_free(text);
513  if (!(kw_utf8 && txt_utf8)) {
514  av_free(kw_utf8);
515  av_free(txt_utf8);
516  return AVERROR(ENOMEM);
517  }
518 
519  av_dict_set(dict, kw_utf8, txt_utf8,
521  return 0;
522 }
523 
525  uint32_t length)
526 {
527  if (length != 13)
528  return AVERROR_INVALIDDATA;
529 
530  if (s->state & PNG_IDAT) {
531  av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
532  return AVERROR_INVALIDDATA;
533  }
534 
535  s->width = bytestream2_get_be32(&s->gb);
536  s->height = bytestream2_get_be32(&s->gb);
537  if (av_image_check_size(s->width, s->height, 0, avctx)) {
538  s->width = s->height = 0;
539  av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
540  return AVERROR_INVALIDDATA;
541  }
542  s->bit_depth = bytestream2_get_byte(&s->gb);
543  s->color_type = bytestream2_get_byte(&s->gb);
544  s->compression_type = bytestream2_get_byte(&s->gb);
545  s->filter_type = bytestream2_get_byte(&s->gb);
546  s->interlace_type = bytestream2_get_byte(&s->gb);
547  bytestream2_skip(&s->gb, 4); /* crc */
548  s->state |= PNG_IHDR;
549  if (avctx->debug & FF_DEBUG_PICT_INFO)
550  av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
551  "compression_type=%d filter_type=%d interlace_type=%d\n",
552  s->width, s->height, s->bit_depth, s->color_type,
554 
555  return 0;
556 }
557 
559 {
560  if (s->state & PNG_IDAT) {
561  av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
562  return AVERROR_INVALIDDATA;
563  }
564  avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
565  avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
566  if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
567  avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
568  bytestream2_skip(&s->gb, 1); /* unit specifier */
569  bytestream2_skip(&s->gb, 4); /* crc */
570 
571  return 0;
572 }
573 
575  uint32_t length, AVFrame *p)
576 {
577  int ret;
578 
579  if (!(s->state & PNG_IHDR)) {
580  av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
581  return AVERROR_INVALIDDATA;
582  }
583  if (!(s->state & PNG_IDAT)) {
584  /* init image info */
585  avctx->width = s->width;
586  avctx->height = s->height;
587 
589  s->bits_per_pixel = s->bit_depth * s->channels;
590  s->bpp = (s->bits_per_pixel + 7) >> 3;
591  s->row_size = (avctx->width * s->bits_per_pixel + 7) >> 3;
592 
593  if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
595  avctx->pix_fmt = AV_PIX_FMT_RGB24;
596  } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
598  avctx->pix_fmt = AV_PIX_FMT_RGBA;
599  } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
601  avctx->pix_fmt = AV_PIX_FMT_GRAY8;
602  } else if (s->bit_depth == 16 &&
604  avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
605  } else if (s->bit_depth == 16 &&
607  avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
608  } else if (s->bit_depth == 16 &&
610  avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
611  } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
613  avctx->pix_fmt = AV_PIX_FMT_PAL8;
614  } else if (s->bit_depth == 1 && s->bits_per_pixel == 1) {
615  avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
616  } else if (s->bit_depth == 8 &&
618  avctx->pix_fmt = AV_PIX_FMT_YA8;
619  } else if (s->bit_depth == 16 &&
621  avctx->pix_fmt = AV_PIX_FMT_YA16BE;
622  } else {
623  av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "
624  "and color type %d\n",
625  s->bit_depth, s->color_type);
626  return AVERROR_INVALIDDATA;
627  }
628 
629  if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
630  return ret;
631  ff_thread_finish_setup(avctx);
632 
634  p->key_frame = 1;
636 
637  /* compute the compressed row size */
638  if (!s->interlace_type) {
639  s->crow_size = s->row_size + 1;
640  } else {
641  s->pass = 0;
643  s->bits_per_pixel,
644  s->width);
645  s->crow_size = s->pass_row_size + 1;
646  }
647  av_dlog(avctx, "row_size=%d crow_size =%d\n",
648  s->row_size, s->crow_size);
649  s->image_buf = p->data[0];
650  s->image_linesize = p->linesize[0];
651  /* copy the palette if needed */
652  if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
653  memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
654  /* empty row is used if differencing to the first row */
656  if (!s->last_row)
657  return AVERROR_INVALIDDATA;
658  if (s->interlace_type ||
661  if (!s->tmp_row)
662  return AVERROR_INVALIDDATA;
663  }
664  /* compressed row */
666  if (!s->buffer)
667  return AVERROR(ENOMEM);
668 
669  /* we want crow_buf+1 to be 16-byte aligned */
670  s->crow_buf = s->buffer + 15;
671  s->zstream.avail_out = s->crow_size;
672  s->zstream.next_out = s->crow_buf;
673  }
674  s->state |= PNG_IDAT;
675  if ((ret = png_decode_idat(s, length)) < 0)
676  return ret;
677  bytestream2_skip(&s->gb, 4); /* crc */
678 
679  return 0;
680 }
681 
683  uint32_t length)
684 {
685  int n, i, r, g, b;
686 
687  if ((length % 3) != 0 || length > 256 * 3)
688  return AVERROR_INVALIDDATA;
689  /* read the palette */
690  n = length / 3;
691  for (i = 0; i < n; i++) {
692  r = bytestream2_get_byte(&s->gb);
693  g = bytestream2_get_byte(&s->gb);
694  b = bytestream2_get_byte(&s->gb);
695  s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
696  }
697  for (; i < 256; i++)
698  s->palette[i] = (0xFFU << 24);
699  s->state |= PNG_PLTE;
700  bytestream2_skip(&s->gb, 4); /* crc */
701 
702  return 0;
703 }
704 
706  uint32_t length)
707 {
708  int v, i;
709 
710  /* read the transparency. XXX: Only palette mode supported */
712  length > 256 ||
713  !(s->state & PNG_PLTE))
714  return AVERROR_INVALIDDATA;
715  for (i = 0; i < length; i++) {
716  v = bytestream2_get_byte(&s->gb);
717  s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
718  }
719  bytestream2_skip(&s->gb, 4); /* crc */
720 
721  return 0;
722 }
723 
725 {
726  if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
727  int i, j, k;
728  uint8_t *pd = p->data[0];
729  for (j = 0; j < s->height; j++) {
730  i = s->width / 8;
731  for (k = 7; k >= 1; k--)
732  if ((s->width&7) >= k)
733  pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
734  for (i--; i >= 0; i--) {
735  pd[8*i + 7]= pd[i] & 1;
736  pd[8*i + 6]= (pd[i]>>1) & 1;
737  pd[8*i + 5]= (pd[i]>>2) & 1;
738  pd[8*i + 4]= (pd[i]>>3) & 1;
739  pd[8*i + 3]= (pd[i]>>4) & 1;
740  pd[8*i + 2]= (pd[i]>>5) & 1;
741  pd[8*i + 1]= (pd[i]>>6) & 1;
742  pd[8*i + 0]= pd[i]>>7;
743  }
744  pd += s->image_linesize;
745  }
746  } else if (s->bits_per_pixel == 2) {
747  int i, j;
748  uint8_t *pd = p->data[0];
749  for (j = 0; j < s->height; j++) {
750  i = s->width / 4;
752  if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
753  if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
754  if ((s->width&3) >= 1) pd[4*i + 0]= pd[i] >> 6;
755  for (i--; i >= 0; i--) {
756  pd[4*i + 3]= pd[i] & 3;
757  pd[4*i + 2]= (pd[i]>>2) & 3;
758  pd[4*i + 1]= (pd[i]>>4) & 3;
759  pd[4*i + 0]= pd[i]>>6;
760  }
761  } else {
762  if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
763  if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
764  if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6 )*0x55;
765  for (i--; i >= 0; i--) {
766  pd[4*i + 3]= ( pd[i] & 3)*0x55;
767  pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
768  pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
769  pd[4*i + 0]= ( pd[i]>>6 )*0x55;
770  }
771  }
772  pd += s->image_linesize;
773  }
774  } else if (s->bits_per_pixel == 4) {
775  int i, j;
776  uint8_t *pd = p->data[0];
777  for (j = 0; j < s->height; j++) {
778  i = s->width/2;
780  if (s->width&1) pd[2*i+0]= pd[i]>>4;
781  for (i--; i >= 0; i--) {
782  pd[2*i + 1] = pd[i] & 15;
783  pd[2*i + 0] = pd[i] >> 4;
784  }
785  } else {
786  if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
787  for (i--; i >= 0; i--) {
788  pd[2*i + 1] = (pd[i] & 15) * 0x11;
789  pd[2*i + 0] = (pd[i] >> 4) * 0x11;
790  }
791  }
792  pd += s->image_linesize;
793  }
794  }
795 }
796 
798  uint32_t length)
799 {
800  uint32_t sequence_number, width, height, x_offset, y_offset;
801 
802  if (length != 26)
803  return AVERROR_INVALIDDATA;
804 
805  sequence_number = bytestream2_get_be32(&s->gb);
806  width = bytestream2_get_be32(&s->gb);
807  height = bytestream2_get_be32(&s->gb);
808  x_offset = bytestream2_get_be32(&s->gb);
809  y_offset = bytestream2_get_be32(&s->gb);
810  bytestream2_skip(&s->gb, 10); /* delay_num (2)
811  * delay_den (2)
812  * dispose_op (1)
813  * blend_op (1)
814  * crc (4)
815  */
816 
817  if (width != s->width || height != s->height ||
818  x_offset != 0 || y_offset != 0) {
819  if (sequence_number == 0)
820  return AVERROR_INVALIDDATA;
821  avpriv_request_sample(avctx, "non key frames");
822  return AVERROR_PATCHWELCOME;
823  }
824 
825  return 0;
826 }
827 
829  AVFrame *p, AVPacket *avpkt)
830 {
831  AVDictionary *metadata = NULL;
832  uint32_t tag, length;
833  int decode_next_dat = 0;
834  int ret = AVERROR_INVALIDDATA;
835 
836  for (;;) {
837  length = bytestream2_get_bytes_left(&s->gb);
838  if (length <= 0) {
839  if (avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
840  if (!(s->state & PNG_IDAT))
841  return 0;
842  else
843  goto exit_loop;
844  }
845  av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
846  if ( s->state & PNG_ALLIMAGE
848  goto exit_loop;
849  goto fail;
850  }
851 
852  length = bytestream2_get_be32(&s->gb);
853  if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
854  av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
855  goto fail;
856  }
857  tag = bytestream2_get_le32(&s->gb);
858  if (avctx->debug & FF_DEBUG_STARTCODE)
859  av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
860  (tag & 0xff),
861  ((tag >> 8) & 0xff),
862  ((tag >> 16) & 0xff),
863  ((tag >> 24) & 0xff), length);
864  switch (tag) {
865  case MKTAG('I', 'H', 'D', 'R'):
866  if (decode_ihdr_chunk(avctx, s, length) < 0)
867  goto fail;
868  break;
869  case MKTAG('p', 'H', 'Y', 's'):
870  if (decode_phys_chunk(avctx, s) < 0)
871  goto fail;
872  break;
873  case MKTAG('f', 'c', 'T', 'L'):
874  if (avctx->codec_id != AV_CODEC_ID_APNG)
875  goto skip_tag;
876  if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
877  goto fail;
878  decode_next_dat = 1;
879  break;
880  case MKTAG('f', 'd', 'A', 'T'):
881  if (avctx->codec_id != AV_CODEC_ID_APNG)
882  goto skip_tag;
883  if (!decode_next_dat)
884  goto fail;
885  bytestream2_get_be32(&s->gb);
886  length -= 4;
887  /* fallthrough */
888  case MKTAG('I', 'D', 'A', 'T'):
889  if (avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
890  goto skip_tag;
891  if (decode_idat_chunk(avctx, s, length, p) < 0)
892  goto fail;
893  break;
894  case MKTAG('P', 'L', 'T', 'E'):
895  if (decode_plte_chunk(avctx, s, length) < 0)
896  goto skip_tag;
897  break;
898  case MKTAG('t', 'R', 'N', 'S'):
899  if (decode_trns_chunk(avctx, s, length) < 0)
900  goto skip_tag;
901  break;
902  case MKTAG('t', 'E', 'X', 't'):
903  if (decode_text_chunk(s, length, 0, &metadata) < 0)
904  av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
905  bytestream2_skip(&s->gb, length + 4);
906  break;
907  case MKTAG('z', 'T', 'X', 't'):
908  if (decode_text_chunk(s, length, 1, &metadata) < 0)
909  av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
910  bytestream2_skip(&s->gb, length + 4);
911  break;
912  case MKTAG('I', 'E', 'N', 'D'):
913  if (!(s->state & PNG_ALLIMAGE))
914  av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
915  if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
916  goto fail;
917  }
918  bytestream2_skip(&s->gb, 4); /* crc */
919  goto exit_loop;
920  default:
921  /* skip tag */
922 skip_tag:
923  bytestream2_skip(&s->gb, length + 4);
924  break;
925  }
926  }
927 exit_loop:
928 
929  if (s->bits_per_pixel <= 4)
930  handle_small_bpp(s, p);
931 
932  /* handle p-frames only if a predecessor frame is available */
933  if (s->last_picture.f->data[0]) {
934  if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
935  && s->last_picture.f->width == p->width
936  && s->last_picture.f->height== p->height
937  && s->last_picture.f->format== p->format
938  ) {
939  int i, j;
940  uint8_t *pd = p->data[0];
941  uint8_t *pd_last = s->last_picture.f->data[0];
942  int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
943 
944  ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
945  for (j = 0; j < s->height; j++) {
946  for (i = 0; i < ls; i++)
947  pd[i] += pd_last[i];
948  pd += s->image_linesize;
949  pd_last += s->image_linesize;
950  }
951  }
952  }
953  ff_thread_report_progress(&s->picture, INT_MAX, 0);
954 
955  av_frame_set_metadata(p, metadata);
956  metadata = NULL;
957  return 0;
958 
959 fail:
960  av_dict_free(&metadata);
961  ff_thread_report_progress(&s->picture, INT_MAX, 0);
962  return ret;
963 }
964 
965 #if CONFIG_PNG_DECODER
966 static int decode_frame_png(AVCodecContext *avctx,
967  void *data, int *got_frame,
968  AVPacket *avpkt)
969 {
970  PNGDecContext *const s = avctx->priv_data;
971  const uint8_t *buf = avpkt->data;
972  int buf_size = avpkt->size;
973  AVFrame *p;
974  int64_t sig;
975  int ret;
976 
979  p = s->picture.f;
980 
981  bytestream2_init(&s->gb, buf, buf_size);
982 
983  /* check signature */
984  sig = bytestream2_get_be64(&s->gb);
985  if (sig != PNGSIG &&
986  sig != MNGSIG) {
987  av_log(avctx, AV_LOG_ERROR, "Missing png signature\n");
988  return AVERROR_INVALIDDATA;
989  }
990 
991  s->y = s->state = 0;
992 
993  /* init the zlib */
994  s->zstream.zalloc = ff_png_zalloc;
995  s->zstream.zfree = ff_png_zfree;
996  s->zstream.opaque = NULL;
997  ret = inflateInit(&s->zstream);
998  if (ret != Z_OK) {
999  av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1000  return AVERROR_EXTERNAL;
1001  }
1002 
1003  if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1004  goto the_end;
1005 
1006  if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1007  return ret;
1008 
1009  *got_frame = 1;
1010 
1011  ret = bytestream2_tell(&s->gb);
1012 the_end:
1013  inflateEnd(&s->zstream);
1014  s->crow_buf = NULL;
1015  return ret;
1016 }
1017 #endif
1018 
1019 #if CONFIG_APNG_DECODER
1020 static int decode_frame_apng(AVCodecContext *avctx,
1021  void *data, int *got_frame,
1022  AVPacket *avpkt)
1023 {
1024  PNGDecContext *const s = avctx->priv_data;
1025  int ret;
1026  AVFrame *p;
1027 
1030  p = s->picture.f;
1031 
1032  if (!(s->state & PNG_IHDR)) {
1033  if (!avctx->extradata_size)
1034  return AVERROR_INVALIDDATA;
1035 
1036  /* only init fields, there is no zlib use in extradata */
1037  s->zstream.zalloc = ff_png_zalloc;
1038  s->zstream.zfree = ff_png_zfree;
1039 
1040  bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
1041  if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1042  goto end;
1043  }
1044 
1045  /* reset state for a new frame */
1046  if ((ret = inflateInit(&s->zstream)) != Z_OK) {
1047  av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
1048  ret = AVERROR_EXTERNAL;
1049  goto end;
1050  }
1051  s->y = 0;
1052  s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);
1053  bytestream2_init(&s->gb, avpkt->data, avpkt->size);
1054  if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
1055  goto end;
1056 
1057  if (!(s->state & PNG_ALLIMAGE))
1058  av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
1059  if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
1060  ret = AVERROR_INVALIDDATA;
1061  goto end;
1062  }
1063  if ((ret = av_frame_ref(data, s->picture.f)) < 0)
1064  goto end;
1065 
1066  *got_frame = 1;
1067  ret = bytestream2_tell(&s->gb);
1068 
1069 end:
1070  inflateEnd(&s->zstream);
1071  return ret;
1072 }
1073 #endif
1074 
1076 {
1077  PNGDecContext *psrc = src->priv_data;
1078  PNGDecContext *pdst = dst->priv_data;
1079 
1080  if (dst == src)
1081  return 0;
1082 
1083  ff_thread_release_buffer(dst, &pdst->picture);
1084  if (psrc->picture.f->data[0])
1085  return ff_thread_ref_frame(&pdst->picture, &psrc->picture);
1086 
1087  return 0;
1088 }
1089 
1091 {
1092  PNGDecContext *s = avctx->priv_data;
1093 
1094  s->avctx = avctx;
1095  s->last_picture.f = av_frame_alloc();
1096  s->picture.f = av_frame_alloc();
1097  if (!s->last_picture.f || !s->picture.f)
1098  return AVERROR(ENOMEM);
1099 
1100  if (!avctx->internal->is_copy) {
1101  avctx->internal->allocate_progress = 1;
1102  ff_pngdsp_init(&s->dsp);
1103  }
1104 
1105  return 0;
1106 }
1107 
1109 {
1110  PNGDecContext *s = avctx->priv_data;
1111 
1114  ff_thread_release_buffer(avctx, &s->picture);
1115  av_frame_free(&s->picture.f);
1116  av_freep(&s->buffer);
1117  s->buffer_size = 0;
1118  av_freep(&s->last_row);
1119  s->last_row_size = 0;
1120  av_freep(&s->tmp_row);
1121  s->tmp_row_size = 0;
1122 
1123  return 0;
1124 }
1125 
1126 #if CONFIG_APNG_DECODER
1127 AVCodec ff_apng_decoder = {
1128  .name = "apng",
1129  .long_name = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
1130  .type = AVMEDIA_TYPE_VIDEO,
1131  .id = AV_CODEC_ID_APNG,
1132  .priv_data_size = sizeof(PNGDecContext),
1133  .init = png_dec_init,
1134  .close = png_dec_end,
1135  .decode = decode_frame_apng,
1137  .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1138  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
1139 };
1140 #endif
1141 
1142 #if CONFIG_PNG_DECODER
1143 AVCodec ff_png_decoder = {
1144  .name = "png",
1145  .long_name = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
1146  .type = AVMEDIA_TYPE_VIDEO,
1147  .id = AV_CODEC_ID_PNG,
1148  .priv_data_size = sizeof(PNGDecContext),
1149  .init = png_dec_init,
1150  .close = png_dec_end,
1151  .decode = decode_frame_png,
1153  .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1154  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS /*| CODEC_CAP_DRAW_HORIZ_BAND*/,
1155 };
1156 #endif