LCOV - code coverage report
Current view: top level - libavcodec - pngdec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 598 950 62.9 %
Date: 2017-12-15 18:13:28 Functions: 21 26 80.8 %

          Line data    Source code
       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/avassert.h"
      25             : #include "libavutil/bprint.h"
      26             : #include "libavutil/imgutils.h"
      27             : #include "libavutil/stereo3d.h"
      28             : #include "libavutil/mastering_display_metadata.h"
      29             : 
      30             : #include "avcodec.h"
      31             : #include "bytestream.h"
      32             : #include "internal.h"
      33             : #include "apng.h"
      34             : #include "png.h"
      35             : #include "pngdsp.h"
      36             : #include "thread.h"
      37             : 
      38             : #include <zlib.h>
      39             : 
      40             : enum PNGHeaderState {
      41             :     PNG_IHDR = 1 << 0,
      42             :     PNG_PLTE = 1 << 1,
      43             : };
      44             : 
      45             : enum PNGImageState {
      46             :     PNG_IDAT     = 1 << 0,
      47             :     PNG_ALLIMAGE = 1 << 1,
      48             : };
      49             : 
      50             : typedef struct PNGDecContext {
      51             :     PNGDSPContext dsp;
      52             :     AVCodecContext *avctx;
      53             : 
      54             :     GetByteContext gb;
      55             :     ThreadFrame previous_picture;
      56             :     ThreadFrame last_picture;
      57             :     ThreadFrame picture;
      58             : 
      59             :     enum PNGHeaderState hdr_state;
      60             :     enum PNGImageState pic_state;
      61             :     int width, height;
      62             :     int cur_w, cur_h;
      63             :     int last_w, last_h;
      64             :     int x_offset, y_offset;
      65             :     int last_x_offset, last_y_offset;
      66             :     uint8_t dispose_op, blend_op;
      67             :     uint8_t last_dispose_op;
      68             :     int bit_depth;
      69             :     int color_type;
      70             :     int compression_type;
      71             :     int interlace_type;
      72             :     int filter_type;
      73             :     int channels;
      74             :     int bits_per_pixel;
      75             :     int bpp;
      76             :     int has_trns;
      77             :     uint8_t transparent_color_be[6];
      78             : 
      79             :     uint8_t *image_buf;
      80             :     int image_linesize;
      81             :     uint32_t palette[256];
      82             :     uint8_t *crow_buf;
      83             :     uint8_t *last_row;
      84             :     unsigned int last_row_size;
      85             :     uint8_t *tmp_row;
      86             :     unsigned int tmp_row_size;
      87             :     uint8_t *buffer;
      88             :     int buffer_size;
      89             :     int pass;
      90             :     int crow_size; /* compressed row size (include filter type) */
      91             :     int row_size; /* decompressed row size */
      92             :     int pass_row_size; /* decompress row size of the current pass */
      93             :     int y;
      94             :     z_stream zstream;
      95             : } PNGDecContext;
      96             : 
      97             : /* Mask to determine which pixels are valid in a pass */
      98             : static const uint8_t png_pass_mask[NB_PASSES] = {
      99             :     0x01, 0x01, 0x11, 0x11, 0x55, 0x55, 0xff,
     100             : };
     101             : 
     102             : /* Mask to determine which y pixels can be written in a pass */
     103             : static const uint8_t png_pass_dsp_ymask[NB_PASSES] = {
     104             :     0xff, 0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
     105             : };
     106             : 
     107             : /* Mask to determine which pixels to overwrite while displaying */
     108             : static const uint8_t png_pass_dsp_mask[NB_PASSES] = {
     109             :     0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff
     110             : };
     111             : 
     112             : /* NOTE: we try to construct a good looking image at each pass. width
     113             :  * is the original image width. We also do pixel format conversion at
     114             :  * this stage */
     115        1408 : static void png_put_interlaced_row(uint8_t *dst, int width,
     116             :                                    int bits_per_pixel, int pass,
     117             :                                    int color_type, const uint8_t *src)
     118             : {
     119             :     int x, mask, dsp_mask, j, src_x, b, bpp;
     120             :     uint8_t *d;
     121             :     const uint8_t *s;
     122             : 
     123        1408 :     mask     = png_pass_mask[pass];
     124        1408 :     dsp_mask = png_pass_dsp_mask[pass];
     125             : 
     126        1408 :     switch (bits_per_pixel) {
     127           0 :     case 1:
     128           0 :         src_x = 0;
     129           0 :         for (x = 0; x < width; x++) {
     130           0 :             j = (x & 7);
     131           0 :             if ((dsp_mask << j) & 0x80) {
     132           0 :                 b = (src[src_x >> 3] >> (7 - (src_x & 7))) & 1;
     133           0 :                 dst[x >> 3] &= 0xFF7F>>j;
     134           0 :                 dst[x >> 3] |= b << (7 - j);
     135             :             }
     136           0 :             if ((mask << j) & 0x80)
     137           0 :                 src_x++;
     138             :         }
     139           0 :         break;
     140           0 :     case 2:
     141           0 :         src_x = 0;
     142           0 :         for (x = 0; x < width; x++) {
     143           0 :             int j2 = 2 * (x & 3);
     144           0 :             j = (x & 7);
     145           0 :             if ((dsp_mask << j) & 0x80) {
     146           0 :                 b = (src[src_x >> 2] >> (6 - 2*(src_x & 3))) & 3;
     147           0 :                 dst[x >> 2] &= 0xFF3F>>j2;
     148           0 :                 dst[x >> 2] |= b << (6 - j2);
     149             :             }
     150           0 :             if ((mask << j) & 0x80)
     151           0 :                 src_x++;
     152             :         }
     153           0 :         break;
     154           0 :     case 4:
     155           0 :         src_x = 0;
     156           0 :         for (x = 0; x < width; x++) {
     157           0 :             int j2 = 4*(x&1);
     158           0 :             j = (x & 7);
     159           0 :             if ((dsp_mask << j) & 0x80) {
     160           0 :                 b = (src[src_x >> 1] >> (4 - 4*(src_x & 1))) & 15;
     161           0 :                 dst[x >> 1] &= 0xFF0F>>j2;
     162           0 :                 dst[x >> 1] |= b << (4 - j2);
     163             :             }
     164           0 :             if ((mask << j) & 0x80)
     165           0 :                 src_x++;
     166             :         }
     167           0 :         break;
     168        1408 :     default:
     169        1408 :         bpp = bits_per_pixel >> 3;
     170        1408 :         d   = dst;
     171        1408 :         s   = src;
     172      181632 :             for (x = 0; x < width; x++) {
     173      180224 :                 j = x & 7;
     174      180224 :                 if ((dsp_mask << j) & 0x80) {
     175      131072 :                     memcpy(d, s, bpp);
     176             :                 }
     177      180224 :                 d += bpp;
     178      180224 :                 if ((mask << j) & 0x80)
     179       61440 :                     s += bpp;
     180             :             }
     181        1408 :         break;
     182             :     }
     183        1408 : }
     184             : 
     185       13000 : void ff_add_png_paeth_prediction(uint8_t *dst, uint8_t *src, uint8_t *top,
     186             :                                  int w, int bpp)
     187             : {
     188             :     int i;
     189     4820674 :     for (i = 0; i < w; i++) {
     190             :         int a, b, c, p, pa, pb, pc;
     191             : 
     192     4807674 :         a = dst[i - bpp];
     193     4807674 :         b = top[i];
     194     4807674 :         c = top[i - bpp];
     195             : 
     196     4807674 :         p  = b - c;
     197     4807674 :         pc = a - c;
     198             : 
     199     4807674 :         pa = abs(p);
     200     4807674 :         pb = abs(pc);
     201     4807674 :         pc = abs(p + pc);
     202             : 
     203     4807674 :         if (pa <= pb && pa <= pc)
     204     2726778 :             p = a;
     205     2080896 :         else if (pb <= pc)
     206     1790946 :             p = b;
     207             :         else
     208      289950 :             p = c;
     209     4807674 :         dst[i] = p + src[i];
     210             :     }
     211       13000 : }
     212             : 
     213             : #define UNROLL1(bpp, op)                                                      \
     214             :     {                                                                         \
     215             :         r = dst[0];                                                           \
     216             :         if (bpp >= 2)                                                         \
     217             :             g = dst[1];                                                       \
     218             :         if (bpp >= 3)                                                         \
     219             :             b = dst[2];                                                       \
     220             :         if (bpp >= 4)                                                         \
     221             :             a = dst[3];                                                       \
     222             :         for (; i <= size - bpp; i += bpp) {                                   \
     223             :             dst[i + 0] = r = op(r, src[i + 0], last[i + 0]);                  \
     224             :             if (bpp == 1)                                                     \
     225             :                 continue;                                                     \
     226             :             dst[i + 1] = g = op(g, src[i + 1], last[i + 1]);                  \
     227             :             if (bpp == 2)                                                     \
     228             :                 continue;                                                     \
     229             :             dst[i + 2] = b = op(b, src[i + 2], last[i + 2]);                  \
     230             :             if (bpp == 3)                                                     \
     231             :                 continue;                                                     \
     232             :             dst[i + 3] = a = op(a, src[i + 3], last[i + 3]);                  \
     233             :         }                                                                     \
     234             :     }
     235             : 
     236             : #define UNROLL_FILTER(op)                                                     \
     237             :     if (bpp == 1) {                                                           \
     238             :         UNROLL1(1, op)                                                        \
     239             :     } else if (bpp == 2) {                                                    \
     240             :         UNROLL1(2, op)                                                        \
     241             :     } else if (bpp == 3) {                                                    \
     242             :         UNROLL1(3, op)                                                        \
     243             :     } else if (bpp == 4) {                                                    \
     244             :         UNROLL1(4, op)                                                        \
     245             :     }                                                                         \
     246             :     for (; i < size; i++) {                                                   \
     247             :         dst[i] = op(dst[i - bpp], src[i], last[i]);                           \
     248             :     }
     249             : 
     250             : /* NOTE: 'dst' can be equal to 'last' */
     251       94072 : static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type,
     252             :                            uint8_t *src, uint8_t *last, int size, int bpp)
     253             : {
     254             :     int i, p, r, g, b, a;
     255             : 
     256       94072 :     switch (filter_type) {
     257       77546 :     case PNG_FILTER_VALUE_NONE:
     258       77546 :         memcpy(dst, src, size);
     259       77546 :         break;
     260        2304 :     case PNG_FILTER_VALUE_SUB:
     261       10819 :         for (i = 0; i < bpp; i++)
     262        8515 :             dst[i] = src[i];
     263        2304 :         if (bpp == 4) {
     264        1573 :             p = *(int *)dst;
     265      272180 :             for (; i < size; i += bpp) {
     266      270607 :                 unsigned s = *(int *)(src + i);
     267      270607 :                 p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080);
     268      270607 :                 *(int *)(dst + i) = p;
     269             :             }
     270             :         } else {
     271             : #define OP_SUB(x, s, l) ((x) + (s))
     272         731 :             UNROLL_FILTER(OP_SUB);
     273             :         }
     274        2304 :         break;
     275        6751 :     case PNG_FILTER_VALUE_UP:
     276        6751 :         dsp->add_bytes_l2(dst, src, last, size);
     277        6751 :         break;
     278         805 :     case PNG_FILTER_VALUE_AVG:
     279        3532 :         for (i = 0; i < bpp; i++) {
     280        2727 :             p      = (last[i] >> 1);
     281        2727 :             dst[i] = p + src[i];
     282             :         }
     283             : #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff)
     284         805 :         UNROLL_FILTER(OP_AVG);
     285         805 :         break;
     286        6666 :     case PNG_FILTER_VALUE_PAETH:
     287       28992 :         for (i = 0; i < bpp; i++) {
     288       22326 :             p      = last[i];
     289       22326 :             dst[i] = p + src[i];
     290             :         }
     291        6666 :         if (bpp > 2 && size > 4) {
     292             :             /* would write off the end of the array if we let it process
     293             :              * the last pixel with bpp=3 */
     294        6596 :             int w = (bpp & 3) ? size - 3 : size;
     295             : 
     296        6596 :             if (w > i) {
     297        6596 :                 dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
     298        6596 :                 i = w;
     299             :             }
     300             :         }
     301        6666 :         ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp);
     302        6666 :         break;
     303             :     }
     304       94072 : }
     305             : 
     306             : /* This used to be called "deloco" in FFmpeg
     307             :  * and is actually an inverse reversible colorspace transformation */
     308             : #define YUV2RGB(NAME, TYPE) \
     309             : static void deloco_ ## NAME(TYPE *dst, int size, int alpha) \
     310             : { \
     311             :     int i; \
     312             :     for (i = 0; i < size; i += 3 + alpha) { \
     313             :         int g = dst [i + 1]; \
     314             :         dst[i + 0] += g; \
     315             :         dst[i + 2] += g; \
     316             :     } \
     317             : }
     318             : 
     319           0 : YUV2RGB(rgb8, uint8_t)
     320           0 : YUV2RGB(rgb16, uint16_t)
     321             : 
     322             : /* process exactly one decompressed row */
     323       94072 : static void png_handle_row(PNGDecContext *s)
     324             : {
     325             :     uint8_t *ptr, *last_row;
     326             :     int got_line;
     327             : 
     328       94072 :     if (!s->interlace_type) {
     329       93592 :         ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
     330       93592 :         if (s->y == 0)
     331         448 :             last_row = s->last_row;
     332             :         else
     333       93144 :             last_row = ptr - s->image_linesize;
     334             : 
     335       93592 :         png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,
     336             :                        last_row, s->row_size, s->bpp);
     337             :         /* loco lags by 1 row so that it doesn't interfere with top prediction */
     338       93592 :         if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {
     339           0 :             if (s->bit_depth == 16) {
     340           0 :                 deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,
     341           0 :                              s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
     342             :             } else {
     343           0 :                 deloco_rgb8(ptr - s->image_linesize, s->row_size,
     344           0 :                             s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
     345             :             }
     346             :         }
     347       93592 :         s->y++;
     348       93592 :         if (s->y == s->cur_h) {
     349         448 :             s->pic_state |= PNG_ALLIMAGE;
     350         448 :             if (s->filter_type == PNG_FILTER_TYPE_LOCO) {
     351           0 :                 if (s->bit_depth == 16) {
     352           0 :                     deloco_rgb16((uint16_t *)ptr, s->row_size / 2,
     353           0 :                                  s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
     354             :                 } else {
     355           0 :                     deloco_rgb8(ptr, s->row_size,
     356           0 :                                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);
     357             :                 }
     358             :             }
     359             :         }
     360             :     } else {
     361         480 :         got_line = 0;
     362             :         for (;;) {
     363        4060 :             ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;
     364        2270 :             if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {
     365             :                 /* if we already read one row, it is time to stop to
     366             :                  * wait for the next one */
     367         958 :                 if (got_line)
     368         478 :                     break;
     369         480 :                 png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,
     370             :                                s->last_row, s->pass_row_size, s->bpp);
     371         480 :                 FFSWAP(uint8_t *, s->last_row, s->tmp_row);
     372         480 :                 FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);
     373         480 :                 got_line = 1;
     374             :             }
     375        1792 :             if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {
     376        1408 :                 png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,
     377        1408 :                                        s->color_type, s->last_row);
     378             :             }
     379        1792 :             s->y++;
     380        1792 :             if (s->y == s->cur_h) {
     381          14 :                 memset(s->last_row, 0, s->row_size);
     382             :                 for (;;) {
     383          14 :                     if (s->pass == NB_PASSES - 1) {
     384           2 :                         s->pic_state |= PNG_ALLIMAGE;
     385           2 :                         goto the_end;
     386             :                     } else {
     387          12 :                         s->pass++;
     388          12 :                         s->y = 0;
     389          12 :                         s->pass_row_size = ff_png_pass_row_size(s->pass,
     390             :                                                                 s->bits_per_pixel,
     391             :                                                                 s->cur_w);
     392          12 :                         s->crow_size = s->pass_row_size + 1;
     393          12 :                         if (s->pass_row_size != 0)
     394          12 :                             break;
     395             :                         /* skip pass if empty row */
     396             :                     }
     397             :                 }
     398             :             }
     399             :         }
     400       94072 : the_end:;
     401             :     }
     402       94072 : }
     403             : 
     404       15613 : static int png_decode_idat(PNGDecContext *s, int length)
     405             : {
     406             :     int ret;
     407       15613 :     s->zstream.avail_in = FFMIN(length, bytestream2_get_bytes_left(&s->gb));
     408       15613 :     s->zstream.next_in  = (unsigned char *)s->gb.buffer;
     409       15613 :     bytestream2_skip(&s->gb, length);
     410             : 
     411             :     /* decode one line if possible */
     412       15613 :     while (s->zstream.avail_in > 0) {
     413      109212 :         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
     414      109212 :         if (ret != Z_OK && ret != Z_STREAM_END) {
     415           0 :             av_log(s->avctx, AV_LOG_ERROR, "inflate returned error %d\n", ret);
     416           0 :             return AVERROR_EXTERNAL;
     417             :         }
     418      109212 :         if (s->zstream.avail_out == 0) {
     419       94072 :             if (!(s->pic_state & PNG_ALLIMAGE)) {
     420       94072 :                 png_handle_row(s);
     421             :             }
     422       94072 :             s->zstream.avail_out = s->crow_size;
     423       94072 :             s->zstream.next_out  = s->crow_buf;
     424             :         }
     425      109212 :         if (ret == Z_STREAM_END && s->zstream.avail_in > 0) {
     426           0 :             av_log(NULL, AV_LOG_WARNING,
     427             :                    "%d undecompressed bytes left in buffer\n", s->zstream.avail_in);
     428           0 :             return 0;
     429             :         }
     430             :     }
     431       15613 :     return 0;
     432             : }
     433             : 
     434           1 : static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
     435             :                        const uint8_t *data_end)
     436             : {
     437             :     z_stream zstream;
     438             :     unsigned char *buf;
     439             :     unsigned buf_size;
     440             :     int ret;
     441             : 
     442           1 :     zstream.zalloc = ff_png_zalloc;
     443           1 :     zstream.zfree  = ff_png_zfree;
     444           1 :     zstream.opaque = NULL;
     445           1 :     if (inflateInit(&zstream) != Z_OK)
     446           0 :         return AVERROR_EXTERNAL;
     447           1 :     zstream.next_in  = (unsigned char *)data;
     448           1 :     zstream.avail_in = data_end - data;
     449           1 :     av_bprint_init(bp, 0, -1);
     450             : 
     451           1 :     while (zstream.avail_in > 0) {
     452           3 :         av_bprint_get_buffer(bp, 2, &buf, &buf_size);
     453           3 :         if (buf_size < 2) {
     454           0 :             ret = AVERROR(ENOMEM);
     455           0 :             goto fail;
     456             :         }
     457           3 :         zstream.next_out  = buf;
     458           3 :         zstream.avail_out = buf_size - 1;
     459           3 :         ret = inflate(&zstream, Z_PARTIAL_FLUSH);
     460           3 :         if (ret != Z_OK && ret != Z_STREAM_END) {
     461           0 :             ret = AVERROR_EXTERNAL;
     462           0 :             goto fail;
     463             :         }
     464           3 :         bp->len += zstream.next_out - buf;
     465           3 :         if (ret == Z_STREAM_END)
     466           1 :             break;
     467             :     }
     468           1 :     inflateEnd(&zstream);
     469           1 :     bp->str[bp->len] = 0;
     470           1 :     return 0;
     471             : 
     472           0 : fail:
     473           0 :     inflateEnd(&zstream);
     474           0 :     av_bprint_finalize(bp, NULL);
     475           0 :     return ret;
     476             : }
     477             : 
     478         226 : static uint8_t *iso88591_to_utf8(const uint8_t *in, size_t size_in)
     479             : {
     480         226 :     size_t extra = 0, i;
     481             :     uint8_t *out, *q;
     482             : 
     483        3938 :     for (i = 0; i < size_in; i++)
     484        3712 :         extra += in[i] >= 0x80;
     485         226 :     if (size_in == SIZE_MAX || extra > SIZE_MAX - size_in - 1)
     486           0 :         return NULL;
     487         226 :     q = out = av_malloc(size_in + extra + 1);
     488         226 :     if (!out)
     489           0 :         return NULL;
     490        3938 :     for (i = 0; i < size_in; i++) {
     491        3712 :         if (in[i] >= 0x80) {
     492           0 :             *(q++) = 0xC0 | (in[i] >> 6);
     493           0 :             *(q++) = 0x80 | (in[i] & 0x3F);
     494             :         } else {
     495        3712 :             *(q++) = in[i];
     496             :         }
     497             :     }
     498         226 :     *(q++) = 0;
     499         226 :     return out;
     500             : }
     501             : 
     502         113 : static int decode_text_chunk(PNGDecContext *s, uint32_t length, int compressed,
     503             :                              AVDictionary **dict)
     504             : {
     505             :     int ret, method;
     506         113 :     const uint8_t *data        = s->gb.buffer;
     507         113 :     const uint8_t *data_end    = data + length;
     508         113 :     const uint8_t *keyword     = data;
     509         113 :     const uint8_t *keyword_end = memchr(keyword, 0, data_end - keyword);
     510         113 :     uint8_t *kw_utf8 = NULL, *text, *txt_utf8 = NULL;
     511             :     unsigned text_len;
     512             :     AVBPrint bp;
     513             : 
     514         113 :     if (!keyword_end)
     515           0 :         return AVERROR_INVALIDDATA;
     516         113 :     data = keyword_end + 1;
     517             : 
     518         113 :     if (compressed) {
     519           0 :         if (data == data_end)
     520           0 :             return AVERROR_INVALIDDATA;
     521           0 :         method = *(data++);
     522           0 :         if (method)
     523           0 :             return AVERROR_INVALIDDATA;
     524           0 :         if ((ret = decode_zbuf(&bp, data, data_end)) < 0)
     525           0 :             return ret;
     526           0 :         text_len = bp.len;
     527           0 :         ret = av_bprint_finalize(&bp, (char **)&text);
     528           0 :         if (ret < 0)
     529           0 :             return ret;
     530             :     } else {
     531         113 :         text = (uint8_t *)data;
     532         113 :         text_len = data_end - text;
     533             :     }
     534             : 
     535         113 :     kw_utf8  = iso88591_to_utf8(keyword, keyword_end - keyword);
     536         113 :     txt_utf8 = iso88591_to_utf8(text, text_len);
     537         113 :     if (text != data)
     538           0 :         av_free(text);
     539         113 :     if (!(kw_utf8 && txt_utf8)) {
     540           0 :         av_free(kw_utf8);
     541           0 :         av_free(txt_utf8);
     542           0 :         return AVERROR(ENOMEM);
     543             :     }
     544             : 
     545         113 :     av_dict_set(dict, kw_utf8, txt_utf8,
     546             :                 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
     547         113 :     return 0;
     548             : }
     549             : 
     550         359 : static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s,
     551             :                              uint32_t length)
     552             : {
     553         359 :     if (length != 13)
     554           0 :         return AVERROR_INVALIDDATA;
     555             : 
     556         359 :     if (s->pic_state & PNG_IDAT) {
     557           0 :         av_log(avctx, AV_LOG_ERROR, "IHDR after IDAT\n");
     558           0 :         return AVERROR_INVALIDDATA;
     559             :     }
     560             : 
     561         359 :     if (s->hdr_state & PNG_IHDR) {
     562           0 :         av_log(avctx, AV_LOG_ERROR, "Multiple IHDR\n");
     563           0 :         return AVERROR_INVALIDDATA;
     564             :     }
     565             : 
     566         359 :     s->width  = s->cur_w = bytestream2_get_be32(&s->gb);
     567         359 :     s->height = s->cur_h = bytestream2_get_be32(&s->gb);
     568         359 :     if (av_image_check_size(s->width, s->height, 0, avctx)) {
     569           0 :         s->cur_w = s->cur_h = s->width = s->height = 0;
     570           0 :         av_log(avctx, AV_LOG_ERROR, "Invalid image size\n");
     571           0 :         return AVERROR_INVALIDDATA;
     572             :     }
     573         359 :     s->bit_depth        = bytestream2_get_byte(&s->gb);
     574         718 :     if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 &&
     575         399 :         s->bit_depth != 8 && s->bit_depth != 16) {
     576           0 :         av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n");
     577           0 :         goto error;
     578             :     }
     579         359 :     s->color_type       = bytestream2_get_byte(&s->gb);
     580         359 :     s->compression_type = bytestream2_get_byte(&s->gb);
     581         359 :     s->filter_type      = bytestream2_get_byte(&s->gb);
     582         359 :     s->interlace_type   = bytestream2_get_byte(&s->gb);
     583         359 :     bytestream2_skip(&s->gb, 4); /* crc */
     584         359 :     s->hdr_state |= PNG_IHDR;
     585         359 :     if (avctx->debug & FF_DEBUG_PICT_INFO)
     586           0 :         av_log(avctx, AV_LOG_DEBUG, "width=%d height=%d depth=%d color_type=%d "
     587             :                 "compression_type=%d filter_type=%d interlace_type=%d\n",
     588             :                 s->width, s->height, s->bit_depth, s->color_type,
     589             :                 s->compression_type, s->filter_type, s->interlace_type);
     590             : 
     591         359 :     return 0;
     592           0 : error:
     593           0 :     s->cur_w = s->cur_h = s->width = s->height = 0;
     594           0 :     s->bit_depth = 8;
     595           0 :     return AVERROR_INVALIDDATA;
     596             : }
     597             : 
     598         333 : static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s)
     599             : {
     600         333 :     if (s->pic_state & PNG_IDAT) {
     601           0 :         av_log(avctx, AV_LOG_ERROR, "pHYs after IDAT\n");
     602           0 :         return AVERROR_INVALIDDATA;
     603             :     }
     604         333 :     avctx->sample_aspect_ratio.num = bytestream2_get_be32(&s->gb);
     605         333 :     avctx->sample_aspect_ratio.den = bytestream2_get_be32(&s->gb);
     606         333 :     if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.den < 0)
     607           0 :         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
     608         333 :     bytestream2_skip(&s->gb, 1); /* unit specifier */
     609         333 :     bytestream2_skip(&s->gb, 4); /* crc */
     610             : 
     611         333 :     return 0;
     612             : }
     613             : 
     614       15613 : static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,
     615             :                              uint32_t length, AVFrame *p)
     616             : {
     617             :     int ret;
     618       15613 :     size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
     619             : 
     620       15613 :     if (!(s->hdr_state & PNG_IHDR)) {
     621           0 :         av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");
     622           0 :         return AVERROR_INVALIDDATA;
     623             :     }
     624       15613 :     if (!(s->pic_state & PNG_IDAT)) {
     625             :         /* init image info */
     626         450 :         ret = ff_set_dimensions(avctx, s->width, s->height);
     627         450 :         if (ret < 0)
     628           0 :             return ret;
     629             : 
     630         450 :         s->channels       = ff_png_get_nb_channels(s->color_type);
     631         450 :         s->bits_per_pixel = s->bit_depth * s->channels;
     632         450 :         s->bpp            = (s->bits_per_pixel + 7) >> 3;
     633         450 :         s->row_size       = (s->cur_w * s->bits_per_pixel + 7) >> 3;
     634             : 
     635         860 :         if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
     636         410 :                 s->color_type == PNG_COLOR_TYPE_RGB) {
     637         309 :             avctx->pix_fmt = AV_PIX_FMT_RGB24;
     638         242 :         } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
     639         101 :                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
     640          54 :             avctx->pix_fmt = AV_PIX_FMT_RGBA;
     641         134 :         } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&
     642          47 :                 s->color_type == PNG_COLOR_TYPE_GRAY) {
     643           4 :             avctx->pix_fmt = AV_PIX_FMT_GRAY8;
     644         123 :         } else if (s->bit_depth == 16 &&
     645          40 :                 s->color_type == PNG_COLOR_TYPE_GRAY) {
     646          16 :             avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;
     647          91 :         } else if (s->bit_depth == 16 &&
     648          24 :                 s->color_type == PNG_COLOR_TYPE_RGB) {
     649          18 :             avctx->pix_fmt = AV_PIX_FMT_RGB48BE;
     650          55 :         } else if (s->bit_depth == 16 &&
     651           6 :                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
     652           4 :             avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
     653          86 :         } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&
     654          41 :                 s->color_type == PNG_COLOR_TYPE_PALETTE) {
     655          41 :             avctx->pix_fmt = AV_PIX_FMT_PAL8;
     656           4 :         } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {
     657           0 :             avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;
     658           6 :         } else if (s->bit_depth == 8 &&
     659           2 :                 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
     660           2 :             avctx->pix_fmt = AV_PIX_FMT_YA8;
     661           4 :         } else if (s->bit_depth == 16 &&
     662           2 :                 s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
     663           2 :             avctx->pix_fmt = AV_PIX_FMT_YA16BE;
     664             :         } else {
     665           0 :             avpriv_report_missing_feature(avctx,
     666             :                                           "Bit depth %d color type %d",
     667             :                                           s->bit_depth, s->color_type);
     668           0 :             return AVERROR_PATCHWELCOME;
     669             :         }
     670             : 
     671         450 :         if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
     672           2 :             switch (avctx->pix_fmt) {
     673           2 :             case AV_PIX_FMT_RGB24:
     674           2 :                 avctx->pix_fmt = AV_PIX_FMT_RGBA;
     675           2 :                 break;
     676             : 
     677           0 :             case AV_PIX_FMT_RGB48BE:
     678           0 :                 avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;
     679           0 :                 break;
     680             : 
     681           0 :             case AV_PIX_FMT_GRAY8:
     682           0 :                 avctx->pix_fmt = AV_PIX_FMT_YA8;
     683           0 :                 break;
     684             : 
     685           0 :             case AV_PIX_FMT_GRAY16BE:
     686           0 :                 avctx->pix_fmt = AV_PIX_FMT_YA16BE;
     687           0 :                 break;
     688             : 
     689           0 :             default:
     690           0 :                 avpriv_request_sample(avctx, "bit depth %d "
     691             :                         "and color type %d with TRNS",
     692             :                         s->bit_depth, s->color_type);
     693           0 :                 return AVERROR_INVALIDDATA;
     694             :             }
     695             : 
     696           2 :             s->bpp += byte_depth;
     697             :         }
     698             : 
     699         450 :         if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
     700           0 :             return ret;
     701         450 :         if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
     702         101 :             ff_thread_release_buffer(avctx, &s->previous_picture);
     703         101 :             if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)
     704           0 :                 return ret;
     705             :         }
     706         450 :         p->pict_type        = AV_PICTURE_TYPE_I;
     707         450 :         p->key_frame        = 1;
     708         450 :         p->interlaced_frame = !!s->interlace_type;
     709             : 
     710         450 :         ff_thread_finish_setup(avctx);
     711             : 
     712             :         /* compute the compressed row size */
     713         450 :         if (!s->interlace_type) {
     714         448 :             s->crow_size = s->row_size + 1;
     715             :         } else {
     716           2 :             s->pass          = 0;
     717           2 :             s->pass_row_size = ff_png_pass_row_size(s->pass,
     718             :                     s->bits_per_pixel,
     719             :                     s->cur_w);
     720           2 :             s->crow_size = s->pass_row_size + 1;
     721             :         }
     722             :         ff_dlog(avctx, "row_size=%d crow_size =%d\n",
     723             :                 s->row_size, s->crow_size);
     724         450 :         s->image_buf      = p->data[0];
     725         450 :         s->image_linesize = p->linesize[0];
     726             :         /* copy the palette if needed */
     727         450 :         if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
     728          41 :             memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));
     729             :         /* empty row is used if differencing to the first row */
     730         450 :         av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);
     731         450 :         if (!s->last_row)
     732           0 :             return AVERROR_INVALIDDATA;
     733         898 :         if (s->interlace_type ||
     734         448 :                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
     735          60 :             av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);
     736          60 :             if (!s->tmp_row)
     737           0 :                 return AVERROR_INVALIDDATA;
     738             :         }
     739             :         /* compressed row */
     740         450 :         av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);
     741         450 :         if (!s->buffer)
     742           0 :             return AVERROR(ENOMEM);
     743             : 
     744             :         /* we want crow_buf+1 to be 16-byte aligned */
     745         450 :         s->crow_buf          = s->buffer + 15;
     746         450 :         s->zstream.avail_out = s->crow_size;
     747         450 :         s->zstream.next_out  = s->crow_buf;
     748             :     }
     749             : 
     750       15613 :     s->pic_state |= PNG_IDAT;
     751             : 
     752             :     /* set image to non-transparent bpp while decompressing */
     753       15613 :     if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
     754          12 :         s->bpp -= byte_depth;
     755             : 
     756       15613 :     ret = png_decode_idat(s, length);
     757             : 
     758       15613 :     if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)
     759          12 :         s->bpp += byte_depth;
     760             : 
     761       15613 :     if (ret < 0)
     762           0 :         return ret;
     763             : 
     764       15613 :     bytestream2_skip(&s->gb, 4); /* crc */
     765             : 
     766       15613 :     return 0;
     767             : }
     768             : 
     769           2 : static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,
     770             :                              uint32_t length)
     771             : {
     772             :     int n, i, r, g, b;
     773             : 
     774           2 :     if ((length % 3) != 0 || length > 256 * 3)
     775           0 :         return AVERROR_INVALIDDATA;
     776             :     /* read the palette */
     777           2 :     n = length / 3;
     778         474 :     for (i = 0; i < n; i++) {
     779         472 :         r = bytestream2_get_byte(&s->gb);
     780         472 :         g = bytestream2_get_byte(&s->gb);
     781         472 :         b = bytestream2_get_byte(&s->gb);
     782         472 :         s->palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | b;
     783             :     }
     784          42 :     for (; i < 256; i++)
     785          40 :         s->palette[i] = (0xFFU << 24);
     786           2 :     s->hdr_state |= PNG_PLTE;
     787           2 :     bytestream2_skip(&s->gb, 4);     /* crc */
     788             : 
     789           2 :     return 0;
     790             : }
     791             : 
     792           4 : static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
     793             :                              uint32_t length)
     794             : {
     795             :     int v, i;
     796             : 
     797           4 :     if (!(s->hdr_state & PNG_IHDR)) {
     798           0 :         av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
     799           0 :         return AVERROR_INVALIDDATA;
     800             :     }
     801             : 
     802           4 :     if (s->pic_state & PNG_IDAT) {
     803           0 :         av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
     804           0 :         return AVERROR_INVALIDDATA;
     805             :     }
     806             : 
     807           4 :     if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
     808           2 :         if (length > 256 || !(s->hdr_state & PNG_PLTE))
     809           0 :             return AVERROR_INVALIDDATA;
     810             : 
     811          36 :         for (i = 0; i < length; i++) {
     812          34 :             unsigned v = bytestream2_get_byte(&s->gb);
     813          34 :             s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
     814             :         }
     815           4 :     } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
     816           4 :         if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
     817           6 :             (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
     818           2 :             s->bit_depth == 1)
     819           0 :             return AVERROR_INVALIDDATA;
     820             : 
     821           8 :         for (i = 0; i < length / 2; i++) {
     822             :             /* only use the least significant bits */
     823           6 :             v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
     824             : 
     825           6 :             if (s->bit_depth > 8)
     826           0 :                 AV_WB16(&s->transparent_color_be[2 * i], v);
     827             :             else
     828           6 :                 s->transparent_color_be[i] = v;
     829             :         }
     830             :     } else {
     831           0 :         return AVERROR_INVALIDDATA;
     832             :     }
     833             : 
     834           4 :     bytestream2_skip(&s->gb, 4); /* crc */
     835           4 :     s->has_trns = 1;
     836             : 
     837           4 :     return 0;
     838             : }
     839             : 
     840           1 : static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)
     841             : {
     842           1 :     int ret, cnt = 0;
     843             :     uint8_t *data, profile_name[82];
     844             :     AVBPrint bp;
     845             :     AVFrameSideData *sd;
     846             : 
     847           1 :     while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);
     848           1 :     if (cnt > 80) {
     849           0 :         av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");
     850           0 :         return AVERROR_INVALIDDATA;
     851             :     }
     852             : 
     853           1 :     length = FFMAX(length - cnt, 0);
     854             : 
     855           1 :     if (bytestream2_get_byte(&s->gb) != 0) {
     856           0 :         av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");
     857           0 :         return AVERROR_INVALIDDATA;
     858             :     }
     859             : 
     860           1 :     length = FFMAX(length - 1, 0);
     861             : 
     862           1 :     if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)
     863           0 :         return ret;
     864             : 
     865           1 :     ret = av_bprint_finalize(&bp, (char **)&data);
     866           1 :     if (ret < 0)
     867           0 :         return ret;
     868             : 
     869           1 :     sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);
     870           1 :     if (!sd) {
     871           0 :         av_free(data);
     872           0 :         return AVERROR(ENOMEM);
     873             :     }
     874             : 
     875           1 :     av_dict_set(&sd->metadata, "name", profile_name, 0);
     876           1 :     memcpy(sd->data, data, bp.len);
     877           1 :     av_free(data);
     878             : 
     879             :     /* ICC compressed data and CRC */
     880           1 :     bytestream2_skip(&s->gb, length + 4);
     881             : 
     882           1 :     return 0;
     883             : }
     884             : 
     885           0 : static void handle_small_bpp(PNGDecContext *s, AVFrame *p)
     886             : {
     887           0 :     if (s->bits_per_pixel == 1 && s->color_type == PNG_COLOR_TYPE_PALETTE) {
     888             :         int i, j, k;
     889           0 :         uint8_t *pd = p->data[0];
     890           0 :         for (j = 0; j < s->height; j++) {
     891           0 :             i = s->width / 8;
     892           0 :             for (k = 7; k >= 1; k--)
     893           0 :                 if ((s->width&7) >= k)
     894           0 :                     pd[8*i + k - 1] = (pd[i]>>8-k) & 1;
     895           0 :             for (i--; i >= 0; i--) {
     896           0 :                 pd[8*i + 7]=  pd[i]     & 1;
     897           0 :                 pd[8*i + 6]= (pd[i]>>1) & 1;
     898           0 :                 pd[8*i + 5]= (pd[i]>>2) & 1;
     899           0 :                 pd[8*i + 4]= (pd[i]>>3) & 1;
     900           0 :                 pd[8*i + 3]= (pd[i]>>4) & 1;
     901           0 :                 pd[8*i + 2]= (pd[i]>>5) & 1;
     902           0 :                 pd[8*i + 1]= (pd[i]>>6) & 1;
     903           0 :                 pd[8*i + 0]=  pd[i]>>7;
     904             :             }
     905           0 :             pd += s->image_linesize;
     906             :         }
     907           0 :     } else if (s->bits_per_pixel == 2) {
     908             :         int i, j;
     909           0 :         uint8_t *pd = p->data[0];
     910           0 :         for (j = 0; j < s->height; j++) {
     911           0 :             i = s->width / 4;
     912           0 :             if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
     913           0 :                 if ((s->width&3) >= 3) pd[4*i + 2]= (pd[i] >> 2) & 3;
     914           0 :                 if ((s->width&3) >= 2) pd[4*i + 1]= (pd[i] >> 4) & 3;
     915           0 :                 if ((s->width&3) >= 1) pd[4*i + 0]=  pd[i] >> 6;
     916           0 :                 for (i--; i >= 0; i--) {
     917           0 :                     pd[4*i + 3]=  pd[i]     & 3;
     918           0 :                     pd[4*i + 2]= (pd[i]>>2) & 3;
     919           0 :                     pd[4*i + 1]= (pd[i]>>4) & 3;
     920           0 :                     pd[4*i + 0]=  pd[i]>>6;
     921             :                 }
     922             :             } else {
     923           0 :                 if ((s->width&3) >= 3) pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
     924           0 :                 if ((s->width&3) >= 2) pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
     925           0 :                 if ((s->width&3) >= 1) pd[4*i + 0]= ( pd[i]>>6     )*0x55;
     926           0 :                 for (i--; i >= 0; i--) {
     927           0 :                     pd[4*i + 3]= ( pd[i]     & 3)*0x55;
     928           0 :                     pd[4*i + 2]= ((pd[i]>>2) & 3)*0x55;
     929           0 :                     pd[4*i + 1]= ((pd[i]>>4) & 3)*0x55;
     930           0 :                     pd[4*i + 0]= ( pd[i]>>6     )*0x55;
     931             :                 }
     932             :             }
     933           0 :             pd += s->image_linesize;
     934             :         }
     935           0 :     } else if (s->bits_per_pixel == 4) {
     936             :         int i, j;
     937           0 :         uint8_t *pd = p->data[0];
     938           0 :         for (j = 0; j < s->height; j++) {
     939           0 :             i = s->width/2;
     940           0 :             if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
     941           0 :                 if (s->width&1) pd[2*i+0]= pd[i]>>4;
     942           0 :                 for (i--; i >= 0; i--) {
     943           0 :                     pd[2*i + 1] = pd[i] & 15;
     944           0 :                     pd[2*i + 0] = pd[i] >> 4;
     945             :                 }
     946             :             } else {
     947           0 :                 if (s->width & 1) pd[2*i + 0]= (pd[i] >> 4) * 0x11;
     948           0 :                 for (i--; i >= 0; i--) {
     949           0 :                     pd[2*i + 1] = (pd[i] & 15) * 0x11;
     950           0 :                     pd[2*i + 0] = (pd[i] >> 4) * 0x11;
     951             :                 }
     952             :             }
     953           0 :             pd += s->image_linesize;
     954             :         }
     955             :     }
     956           0 : }
     957             : 
     958         101 : static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,
     959             :                              uint32_t length)
     960             : {
     961             :     uint32_t sequence_number;
     962             :     int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;
     963             : 
     964         101 :     if (length != 26)
     965           0 :         return AVERROR_INVALIDDATA;
     966             : 
     967         101 :     if (!(s->hdr_state & PNG_IHDR)) {
     968           0 :         av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");
     969           0 :         return AVERROR_INVALIDDATA;
     970             :     }
     971             : 
     972         101 :     s->last_w = s->cur_w;
     973         101 :     s->last_h = s->cur_h;
     974         101 :     s->last_x_offset = s->x_offset;
     975         101 :     s->last_y_offset = s->y_offset;
     976         101 :     s->last_dispose_op = s->dispose_op;
     977             : 
     978         101 :     sequence_number = bytestream2_get_be32(&s->gb);
     979         101 :     cur_w           = bytestream2_get_be32(&s->gb);
     980         101 :     cur_h           = bytestream2_get_be32(&s->gb);
     981         101 :     x_offset        = bytestream2_get_be32(&s->gb);
     982         101 :     y_offset        = bytestream2_get_be32(&s->gb);
     983         101 :     bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */
     984         101 :     dispose_op      = bytestream2_get_byte(&s->gb);
     985         101 :     blend_op        = bytestream2_get_byte(&s->gb);
     986         101 :     bytestream2_skip(&s->gb, 4); /* crc */
     987             : 
     988         110 :     if (sequence_number == 0 &&
     989          18 :         (cur_w != s->width ||
     990          18 :          cur_h != s->height ||
     991           9 :          x_offset != 0 ||
     992         101 :          y_offset != 0) ||
     993         101 :         cur_w <= 0 || cur_h <= 0 ||
     994         202 :         x_offset < 0 || y_offset < 0 ||
     995         202 :         cur_w > s->width - x_offset|| cur_h > s->height - y_offset)
     996           0 :             return AVERROR_INVALIDDATA;
     997             : 
     998         101 :     if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {
     999           0 :         av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);
    1000           0 :         return AVERROR_INVALIDDATA;
    1001             :     }
    1002             : 
    1003         101 :     if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&
    1004             :         dispose_op == APNG_DISPOSE_OP_PREVIOUS) {
    1005             :         // No previous frame to revert to for the first frame
    1006             :         // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND
    1007           0 :         dispose_op = APNG_DISPOSE_OP_BACKGROUND;
    1008             :     }
    1009             : 
    1010         101 :     if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (
    1011           0 :             avctx->pix_fmt == AV_PIX_FMT_RGB24 ||
    1012           0 :             avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||
    1013           0 :             avctx->pix_fmt == AV_PIX_FMT_PAL8 ||
    1014           0 :             avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
    1015           0 :             avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||
    1016           0 :             avctx->pix_fmt == AV_PIX_FMT_MONOBLACK
    1017             :         )) {
    1018             :         // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel
    1019           0 :         blend_op = APNG_BLEND_OP_SOURCE;
    1020             :     }
    1021             : 
    1022         101 :     s->cur_w      = cur_w;
    1023         101 :     s->cur_h      = cur_h;
    1024         101 :     s->x_offset   = x_offset;
    1025         101 :     s->y_offset   = y_offset;
    1026         101 :     s->dispose_op = dispose_op;
    1027         101 :     s->blend_op   = blend_op;
    1028             : 
    1029         101 :     return 0;
    1030             : }
    1031             : 
    1032           0 : static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
    1033             : {
    1034             :     int i, j;
    1035           0 :     uint8_t *pd      = p->data[0];
    1036           0 :     uint8_t *pd_last = s->last_picture.f->data[0];
    1037           0 :     int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
    1038             : 
    1039           0 :     ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
    1040           0 :     for (j = 0; j < s->height; j++) {
    1041           0 :         for (i = 0; i < ls; i++)
    1042           0 :             pd[i] += pd_last[i];
    1043           0 :         pd      += s->image_linesize;
    1044           0 :         pd_last += s->image_linesize;
    1045             :     }
    1046           0 : }
    1047             : 
    1048             : // divide by 255 and round to nearest
    1049             : // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
    1050             : #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
    1051             : 
    1052          39 : static int handle_p_frame_apng(AVCodecContext *avctx, PNGDecContext *s,
    1053             :                                AVFrame *p)
    1054             : {
    1055             :     size_t x, y;
    1056             :     uint8_t *buffer;
    1057             : 
    1058          78 :     if (s->blend_op == APNG_BLEND_OP_OVER &&
    1059          78 :         avctx->pix_fmt != AV_PIX_FMT_RGBA &&
    1060          78 :         avctx->pix_fmt != AV_PIX_FMT_GRAY8A &&
    1061          39 :         avctx->pix_fmt != AV_PIX_FMT_PAL8) {
    1062           0 :         avpriv_request_sample(avctx, "Blending with pixel format %s",
    1063             :                               av_get_pix_fmt_name(avctx->pix_fmt));
    1064           0 :         return AVERROR_PATCHWELCOME;
    1065             :     }
    1066             : 
    1067          39 :     buffer = av_malloc_array(s->image_linesize, s->height);
    1068          39 :     if (!buffer)
    1069           0 :         return AVERROR(ENOMEM);
    1070             : 
    1071             : 
    1072             :     // Do the disposal operation specified by the last frame on the frame
    1073          39 :     if (s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
    1074          39 :         ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
    1075          39 :         memcpy(buffer, s->last_picture.f->data[0], s->image_linesize * s->height);
    1076             : 
    1077          39 :         if (s->last_dispose_op == APNG_DISPOSE_OP_BACKGROUND)
    1078           0 :             for (y = s->last_y_offset; y < s->last_y_offset + s->last_h; ++y)
    1079           0 :                 memset(buffer + s->image_linesize * y + s->bpp * s->last_x_offset, 0, s->bpp * s->last_w);
    1080             : 
    1081          39 :         memcpy(s->previous_picture.f->data[0], buffer, s->image_linesize * s->height);
    1082          39 :         ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
    1083             :     } else {
    1084           0 :         ff_thread_await_progress(&s->previous_picture, INT_MAX, 0);
    1085           0 :         memcpy(buffer, s->previous_picture.f->data[0], s->image_linesize * s->height);
    1086             :     }
    1087             : 
    1088             :     // Perform blending
    1089          39 :     if (s->blend_op == APNG_BLEND_OP_SOURCE) {
    1090           0 :         for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
    1091           0 :             size_t row_start = s->image_linesize * y + s->bpp * s->x_offset;
    1092           0 :             memcpy(buffer + row_start, p->data[0] + row_start, s->bpp * s->cur_w);
    1093             :         }
    1094             :     } else { // APNG_BLEND_OP_OVER
    1095        1918 :         for (y = s->y_offset; y < s->y_offset + s->cur_h; ++y) {
    1096        1879 :             uint8_t *foreground = p->data[0] + s->image_linesize * y + s->bpp * s->x_offset;
    1097        1879 :             uint8_t *background = buffer + s->image_linesize * y + s->bpp * s->x_offset;
    1098      143095 :             for (x = s->x_offset; x < s->x_offset + s->cur_w; ++x, foreground += s->bpp, background += s->bpp) {
    1099             :                 size_t b;
    1100             :                 uint8_t foreground_alpha, background_alpha, output_alpha;
    1101             :                 uint8_t output[10];
    1102             : 
    1103             :                 // Since we might be blending alpha onto alpha, we use the following equations:
    1104             :                 // output_alpha = foreground_alpha + (1 - foreground_alpha) * background_alpha
    1105             :                 // output = (foreground_alpha * foreground + (1 - foreground_alpha) * background_alpha * background) / output_alpha
    1106             : 
    1107      141216 :                 switch (avctx->pix_fmt) {
    1108           0 :                 case AV_PIX_FMT_RGBA:
    1109           0 :                     foreground_alpha = foreground[3];
    1110           0 :                     background_alpha = background[3];
    1111           0 :                     break;
    1112             : 
    1113           0 :                 case AV_PIX_FMT_GRAY8A:
    1114           0 :                     foreground_alpha = foreground[1];
    1115           0 :                     background_alpha = background[1];
    1116           0 :                     break;
    1117             : 
    1118      141216 :                 case AV_PIX_FMT_PAL8:
    1119      141216 :                     foreground_alpha = s->palette[foreground[0]] >> 24;
    1120      141216 :                     background_alpha = s->palette[background[0]] >> 24;
    1121      141216 :                     break;
    1122             :                 }
    1123             : 
    1124      141216 :                 if (foreground_alpha == 0)
    1125      262798 :                     continue;
    1126             : 
    1127       19634 :                 if (foreground_alpha == 255) {
    1128       19634 :                     memcpy(background, foreground, s->bpp);
    1129       19634 :                     continue;
    1130             :                 }
    1131             : 
    1132           0 :                 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
    1133             :                     // TODO: Alpha blending with PAL8 will likely need the entire image converted over to RGBA first
    1134           0 :                     avpriv_request_sample(avctx, "Alpha blending palette samples");
    1135           0 :                     background[0] = foreground[0];
    1136           0 :                     continue;
    1137             :                 }
    1138             : 
    1139           0 :                 output_alpha = foreground_alpha + FAST_DIV255((255 - foreground_alpha) * background_alpha);
    1140             : 
    1141           0 :                 av_assert0(s->bpp <= 10);
    1142             : 
    1143           0 :                 for (b = 0; b < s->bpp - 1; ++b) {
    1144           0 :                     if (output_alpha == 0) {
    1145           0 :                         output[b] = 0;
    1146           0 :                     } else if (background_alpha == 255) {
    1147           0 :                         output[b] = FAST_DIV255(foreground_alpha * foreground[b] + (255 - foreground_alpha) * background[b]);
    1148             :                     } else {
    1149           0 :                         output[b] = (255 * foreground_alpha * foreground[b] + (255 - foreground_alpha) * background_alpha * background[b]) / (255 * output_alpha);
    1150             :                     }
    1151             :                 }
    1152           0 :                 output[b] = output_alpha;
    1153           0 :                 memcpy(background, output, s->bpp);
    1154             :             }
    1155             :         }
    1156             :     }
    1157             : 
    1158             :     // Copy blended buffer into the frame and free
    1159          39 :     memcpy(p->data[0], buffer, s->image_linesize * s->height);
    1160          39 :     av_free(buffer);
    1161             : 
    1162          39 :     return 0;
    1163             : }
    1164             : 
    1165         460 : static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
    1166             :                                AVFrame *p, AVPacket *avpkt)
    1167             : {
    1168         460 :     AVDictionary **metadatap = NULL;
    1169             :     uint32_t tag, length;
    1170         460 :     int decode_next_dat = 0;
    1171             :     int i, ret;
    1172             : 
    1173             :     for (;;) {
    1174       33882 :         length = bytestream2_get_bytes_left(&s->gb);
    1175       17171 :         if (length <= 0) {
    1176             : 
    1177         202 :             if (avctx->codec_id == AV_CODEC_ID_PNG &&
    1178          46 :                 avctx->skip_frame == AVDISCARD_ALL) {
    1179          46 :                 return 0;
    1180             :             }
    1181             : 
    1182         110 :             if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
    1183         110 :                 if (!(s->pic_state & PNG_IDAT))
    1184           9 :                     return 0;
    1185             :                 else
    1186         101 :                     goto exit_loop;
    1187             :             }
    1188           0 :             av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
    1189           0 :             if (   s->pic_state & PNG_ALLIMAGE
    1190           0 :                 && avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
    1191           0 :                 goto exit_loop;
    1192           0 :             ret = AVERROR_INVALIDDATA;
    1193           0 :             goto fail;
    1194             :         }
    1195             : 
    1196       17015 :         length = bytestream2_get_be32(&s->gb);
    1197       17015 :         if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
    1198           1 :             av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
    1199           1 :             ret = AVERROR_INVALIDDATA;
    1200           1 :             goto fail;
    1201             :         }
    1202       17014 :         tag = bytestream2_get_le32(&s->gb);
    1203       17014 :         if (avctx->debug & FF_DEBUG_STARTCODE)
    1204           0 :             av_log(avctx, AV_LOG_DEBUG, "png: tag=%s length=%u\n",
    1205           0 :                    av_fourcc2str(tag), length);
    1206             : 
    1207       30625 :         if (avctx->codec_id == AV_CODEC_ID_PNG &&
    1208       13611 :             avctx->skip_frame == AVDISCARD_ALL) {
    1209         794 :             switch(tag) {
    1210         692 :             case MKTAG('I', 'H', 'D', 'R'):
    1211             :             case MKTAG('p', 'H', 'Y', 's'):
    1212             :             case MKTAG('t', 'E', 'X', 't'):
    1213             :             case MKTAG('I', 'D', 'A', 'T'):
    1214             :             case MKTAG('t', 'R', 'N', 'S'):
    1215         692 :                 break;
    1216         102 :             default:
    1217         102 :                 goto skip_tag;
    1218             :             }
    1219       16220 :         }
    1220             : 
    1221       16912 :         metadatap = &p->metadata;
    1222       16912 :         switch (tag) {
    1223         359 :         case MKTAG('I', 'H', 'D', 'R'):
    1224         359 :             if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
    1225           0 :                 goto fail;
    1226         359 :             break;
    1227         333 :         case MKTAG('p', 'H', 'Y', 's'):
    1228         333 :             if ((ret = decode_phys_chunk(avctx, s)) < 0)
    1229           0 :                 goto fail;
    1230         333 :             break;
    1231         101 :         case MKTAG('f', 'c', 'T', 'L'):
    1232         101 :             if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
    1233           0 :                 goto skip_tag;
    1234         101 :             if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
    1235           0 :                 goto fail;
    1236         101 :             decode_next_dat = 1;
    1237         101 :             break;
    1238        2966 :         case MKTAG('f', 'd', 'A', 'T'):
    1239        2966 :             if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
    1240           0 :                 goto skip_tag;
    1241        2966 :             if (!decode_next_dat) {
    1242           0 :                 ret = AVERROR_INVALIDDATA;
    1243           0 :                 goto fail;
    1244             :             }
    1245        2966 :             bytestream2_get_be32(&s->gb);
    1246        2966 :             length -= 4;
    1247             :             /* fallthrough */
    1248       15613 :         case MKTAG('I', 'D', 'A', 'T'):
    1249       15613 :             if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
    1250           0 :                 goto skip_tag;
    1251       15613 :             if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
    1252           0 :                 goto fail;
    1253       15613 :             break;
    1254           2 :         case MKTAG('P', 'L', 'T', 'E'):
    1255           2 :             if (decode_plte_chunk(avctx, s, length) < 0)
    1256           0 :                 goto skip_tag;
    1257           2 :             break;
    1258           4 :         case MKTAG('t', 'R', 'N', 'S'):
    1259           4 :             if (decode_trns_chunk(avctx, s, length) < 0)
    1260           0 :                 goto skip_tag;
    1261           4 :             break;
    1262         113 :         case MKTAG('t', 'E', 'X', 't'):
    1263         113 :             if (decode_text_chunk(s, length, 0, metadatap) < 0)
    1264           0 :                 av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
    1265         113 :             bytestream2_skip(&s->gb, length + 4);
    1266         113 :             break;
    1267           0 :         case MKTAG('z', 'T', 'X', 't'):
    1268           0 :             if (decode_text_chunk(s, length, 1, metadatap) < 0)
    1269           0 :                 av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
    1270           0 :             bytestream2_skip(&s->gb, length + 4);
    1271           0 :             break;
    1272           0 :         case MKTAG('s', 'T', 'E', 'R'): {
    1273           0 :             int mode = bytestream2_get_byte(&s->gb);
    1274           0 :             AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
    1275           0 :             if (!stereo3d)
    1276           0 :                 goto fail;
    1277             : 
    1278           0 :             if (mode == 0 || mode == 1) {
    1279           0 :                 stereo3d->type  = AV_STEREO3D_SIDEBYSIDE;
    1280           0 :                 stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
    1281             :             } else {
    1282           0 :                  av_log(avctx, AV_LOG_WARNING,
    1283             :                         "Unknown value in sTER chunk (%d)\n", mode);
    1284             :             }
    1285           0 :             bytestream2_skip(&s->gb, 4); /* crc */
    1286           0 :             break;
    1287             :         }
    1288           1 :         case MKTAG('i', 'C', 'C', 'P'): {
    1289           1 :             if (decode_iccp_chunk(s, length, p) < 0)
    1290           0 :                 goto fail;
    1291           1 :             break;
    1292             :         }
    1293           1 :         case MKTAG('c', 'H', 'R', 'M'): {
    1294           1 :             AVMasteringDisplayMetadata *mdm = av_mastering_display_metadata_create_side_data(p);
    1295           1 :             if (!mdm) {
    1296           0 :                 ret = AVERROR(ENOMEM);
    1297           0 :                 goto fail;
    1298             :             }
    1299             : 
    1300           1 :             mdm->white_point[0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
    1301           1 :             mdm->white_point[1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
    1302             : 
    1303             :             /* RGB Primaries */
    1304           4 :             for (i = 0; i < 3; i++) {
    1305           3 :                 mdm->display_primaries[i][0] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
    1306           3 :                 mdm->display_primaries[i][1] = av_make_q(bytestream2_get_be32(&s->gb), 100000);
    1307             :             }
    1308             : 
    1309           1 :             mdm->has_primaries = 1;
    1310           1 :             bytestream2_skip(&s->gb, 4); /* crc */
    1311           1 :             break;
    1312             :         }
    1313          13 :         case MKTAG('g', 'A', 'M', 'A'): {
    1314             :             AVBPrint bp;
    1315             :             char *gamma_str;
    1316          13 :             int num = bytestream2_get_be32(&s->gb);
    1317             : 
    1318          13 :             av_bprint_init(&bp, 0, -1);
    1319          13 :             av_bprintf(&bp, "%i/%i", num, 100000);
    1320          13 :             ret = av_bprint_finalize(&bp, &gamma_str);
    1321          13 :             if (ret < 0)
    1322           0 :                 return ret;
    1323             : 
    1324          13 :             av_dict_set(&p->metadata, "gamma", gamma_str, AV_DICT_DONT_STRDUP_VAL);
    1325             : 
    1326          13 :             bytestream2_skip(&s->gb, 4); /* crc */
    1327          13 :             break;
    1328             :         }
    1329         303 :         case MKTAG('I', 'E', 'N', 'D'):
    1330         303 :             if (!(s->pic_state & PNG_ALLIMAGE))
    1331           0 :                 av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
    1332         303 :             if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
    1333           0 :                 ret = AVERROR_INVALIDDATA;
    1334           0 :                 goto fail;
    1335             :             }
    1336         303 :             bytestream2_skip(&s->gb, 4); /* crc */
    1337         303 :             goto exit_loop;
    1338             :         default:
    1339             :             /* skip tag */
    1340         171 : skip_tag:
    1341         171 :             bytestream2_skip(&s->gb, length + 4);
    1342         171 :             break;
    1343             :         }
    1344             :     }
    1345         404 : exit_loop:
    1346             : 
    1347         707 :     if (avctx->codec_id == AV_CODEC_ID_PNG &&
    1348         303 :         avctx->skip_frame == AVDISCARD_ALL) {
    1349           0 :         return 0;
    1350             :     }
    1351             : 
    1352         404 :     if (s->bits_per_pixel <= 4)
    1353           0 :         handle_small_bpp(s, p);
    1354             : 
    1355             :     /* apply transparency if needed */
    1356         404 :     if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
    1357           1 :         size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
    1358           1 :         size_t raw_bpp = s->bpp - byte_depth;
    1359             :         unsigned x, y;
    1360             : 
    1361           1 :         av_assert0(s->bit_depth > 1);
    1362             : 
    1363         331 :         for (y = 0; y < s->height; ++y) {
    1364         330 :             uint8_t *row = &s->image_buf[s->image_linesize * y];
    1365             : 
    1366             :             /* since we're updating in-place, we have to go from right to left */
    1367      109230 :             for (x = s->width; x > 0; --x) {
    1368      108900 :                 uint8_t *pixel = &row[s->bpp * (x - 1)];
    1369      108900 :                 memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
    1370             : 
    1371      108900 :                 if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
    1372       82906 :                     memset(&pixel[raw_bpp], 0, byte_depth);
    1373             :                 } else {
    1374       25994 :                     memset(&pixel[raw_bpp], 0xff, byte_depth);
    1375             :                 }
    1376             :             }
    1377             :         }
    1378             :     }
    1379             : 
    1380             :     /* handle P-frames only if a predecessor frame is available */
    1381         404 :     if (s->last_picture.f->data[0]) {
    1382         350 :         if (   !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
    1383          39 :             && s->last_picture.f->width == p->width
    1384          39 :             && s->last_picture.f->height== p->height
    1385          39 :             && s->last_picture.f->format== p->format
    1386             :          ) {
    1387          39 :             if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
    1388           0 :                 handle_p_frame_png(s, p);
    1389          39 :             else if (CONFIG_APNG_DECODER &&
    1390          78 :                      avctx->codec_id == AV_CODEC_ID_APNG &&
    1391             :                      (ret = handle_p_frame_apng(avctx, s, p)) < 0)
    1392           0 :                 goto fail;
    1393             :         }
    1394             :     }
    1395         404 :     ff_thread_report_progress(&s->picture, INT_MAX, 0);
    1396         404 :     ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
    1397             : 
    1398         404 :     return 0;
    1399             : 
    1400           1 : fail:
    1401           1 :     ff_thread_report_progress(&s->picture, INT_MAX, 0);
    1402           1 :     ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
    1403           1 :     return ret;
    1404             : }
    1405             : 
    1406             : #if CONFIG_PNG_DECODER
    1407         350 : static int decode_frame_png(AVCodecContext *avctx,
    1408             :                         void *data, int *got_frame,
    1409             :                         AVPacket *avpkt)
    1410             : {
    1411         350 :     PNGDecContext *const s = avctx->priv_data;
    1412         350 :     const uint8_t *buf     = avpkt->data;
    1413         350 :     int buf_size           = avpkt->size;
    1414             :     AVFrame *p;
    1415             :     int64_t sig;
    1416             :     int ret;
    1417             : 
    1418         350 :     ff_thread_release_buffer(avctx, &s->last_picture);
    1419         350 :     FFSWAP(ThreadFrame, s->picture, s->last_picture);
    1420         350 :     p = s->picture.f;
    1421             : 
    1422         350 :     bytestream2_init(&s->gb, buf, buf_size);
    1423             : 
    1424             :     /* check signature */
    1425         350 :     sig = bytestream2_get_be64(&s->gb);
    1426         350 :     if (sig != PNGSIG &&
    1427             :         sig != MNGSIG) {
    1428           0 :         av_log(avctx, AV_LOG_ERROR, "Invalid PNG signature 0x%08"PRIX64".\n", sig);
    1429           0 :         return AVERROR_INVALIDDATA;
    1430             :     }
    1431             : 
    1432         350 :     s->y = s->has_trns = 0;
    1433         350 :     s->hdr_state = 0;
    1434         350 :     s->pic_state = 0;
    1435             : 
    1436             :     /* init the zlib */
    1437         350 :     s->zstream.zalloc = ff_png_zalloc;
    1438         350 :     s->zstream.zfree  = ff_png_zfree;
    1439         350 :     s->zstream.opaque = NULL;
    1440         350 :     ret = inflateInit(&s->zstream);
    1441         350 :     if (ret != Z_OK) {
    1442           0 :         av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
    1443           0 :         return AVERROR_EXTERNAL;
    1444             :     }
    1445             : 
    1446         350 :     if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
    1447           1 :         goto the_end;
    1448             : 
    1449         349 :     if (avctx->skip_frame == AVDISCARD_ALL) {
    1450          46 :         *got_frame = 0;
    1451          46 :         ret = bytestream2_tell(&s->gb);
    1452          46 :         goto the_end;
    1453             :     }
    1454             : 
    1455         303 :     if ((ret = av_frame_ref(data, s->picture.f)) < 0)
    1456           0 :         goto the_end;
    1457             : 
    1458         303 :     *got_frame = 1;
    1459             : 
    1460         303 :     ret = bytestream2_tell(&s->gb);
    1461         350 : the_end:
    1462         350 :     inflateEnd(&s->zstream);
    1463         350 :     s->crow_buf = NULL;
    1464         350 :     return ret;
    1465             : }
    1466             : #endif
    1467             : 
    1468             : #if CONFIG_APNG_DECODER
    1469         101 : static int decode_frame_apng(AVCodecContext *avctx,
    1470             :                         void *data, int *got_frame,
    1471             :                         AVPacket *avpkt)
    1472             : {
    1473         101 :     PNGDecContext *const s = avctx->priv_data;
    1474             :     int ret;
    1475             :     AVFrame *p;
    1476             : 
    1477         101 :     ff_thread_release_buffer(avctx, &s->last_picture);
    1478         101 :     FFSWAP(ThreadFrame, s->picture, s->last_picture);
    1479         101 :     p = s->picture.f;
    1480             : 
    1481         101 :     if (!(s->hdr_state & PNG_IHDR)) {
    1482           9 :         if (!avctx->extradata_size)
    1483           0 :             return AVERROR_INVALIDDATA;
    1484             : 
    1485             :         /* only init fields, there is no zlib use in extradata */
    1486           9 :         s->zstream.zalloc = ff_png_zalloc;
    1487           9 :         s->zstream.zfree  = ff_png_zfree;
    1488             : 
    1489           9 :         bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
    1490           9 :         if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
    1491           0 :             goto end;
    1492             :     }
    1493             : 
    1494             :     /* reset state for a new frame */
    1495         101 :     if ((ret = inflateInit(&s->zstream)) != Z_OK) {
    1496           0 :         av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);
    1497           0 :         ret = AVERROR_EXTERNAL;
    1498           0 :         goto end;
    1499             :     }
    1500         101 :     s->y = 0;
    1501         101 :     s->pic_state = 0;
    1502         101 :     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
    1503         101 :     if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)
    1504           0 :         goto end;
    1505             : 
    1506         101 :     if (!(s->pic_state & PNG_ALLIMAGE))
    1507           0 :         av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");
    1508         101 :     if (!(s->pic_state & (PNG_ALLIMAGE|PNG_IDAT))) {
    1509           0 :         ret = AVERROR_INVALIDDATA;
    1510           0 :         goto end;
    1511             :     }
    1512         101 :     if ((ret = av_frame_ref(data, s->picture.f)) < 0)
    1513           0 :         goto end;
    1514             : 
    1515         101 :     *got_frame = 1;
    1516         101 :     ret = bytestream2_tell(&s->gb);
    1517             : 
    1518         101 : end:
    1519         101 :     inflateEnd(&s->zstream);
    1520         101 :     return ret;
    1521             : }
    1522             : #endif
    1523             : 
    1524             : #if HAVE_THREADS
    1525           0 : static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
    1526             : {
    1527           0 :     PNGDecContext *psrc = src->priv_data;
    1528           0 :     PNGDecContext *pdst = dst->priv_data;
    1529             :     int ret;
    1530             : 
    1531           0 :     if (dst == src)
    1532           0 :         return 0;
    1533             : 
    1534           0 :     ff_thread_release_buffer(dst, &pdst->picture);
    1535           0 :     if (psrc->picture.f->data[0] &&
    1536           0 :         (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)
    1537           0 :         return ret;
    1538           0 :     if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {
    1539           0 :         pdst->width             = psrc->width;
    1540           0 :         pdst->height            = psrc->height;
    1541           0 :         pdst->bit_depth         = psrc->bit_depth;
    1542           0 :         pdst->color_type        = psrc->color_type;
    1543           0 :         pdst->compression_type  = psrc->compression_type;
    1544           0 :         pdst->interlace_type    = psrc->interlace_type;
    1545           0 :         pdst->filter_type       = psrc->filter_type;
    1546           0 :         pdst->cur_w = psrc->cur_w;
    1547           0 :         pdst->cur_h = psrc->cur_h;
    1548           0 :         pdst->x_offset = psrc->x_offset;
    1549           0 :         pdst->y_offset = psrc->y_offset;
    1550           0 :         pdst->has_trns = psrc->has_trns;
    1551           0 :         memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));
    1552             : 
    1553           0 :         pdst->dispose_op = psrc->dispose_op;
    1554             : 
    1555           0 :         memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));
    1556             : 
    1557           0 :         pdst->hdr_state |= psrc->hdr_state;
    1558             : 
    1559           0 :         ff_thread_release_buffer(dst, &pdst->last_picture);
    1560           0 :         if (psrc->last_picture.f->data[0] &&
    1561           0 :             (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)
    1562           0 :             return ret;
    1563             : 
    1564           0 :         ff_thread_release_buffer(dst, &pdst->previous_picture);
    1565           0 :         if (psrc->previous_picture.f->data[0] &&
    1566           0 :             (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)
    1567           0 :             return ret;
    1568             :     }
    1569             : 
    1570           0 :     return 0;
    1571             : }
    1572             : #endif
    1573             : 
    1574         132 : static av_cold int png_dec_init(AVCodecContext *avctx)
    1575             : {
    1576         132 :     PNGDecContext *s = avctx->priv_data;
    1577             : 
    1578         132 :     avctx->color_range = AVCOL_RANGE_JPEG;
    1579             : 
    1580         132 :     s->avctx = avctx;
    1581         132 :     s->previous_picture.f = av_frame_alloc();
    1582         132 :     s->last_picture.f = av_frame_alloc();
    1583         132 :     s->picture.f = av_frame_alloc();
    1584         132 :     if (!s->previous_picture.f || !s->last_picture.f || !s->picture.f) {
    1585           0 :         av_frame_free(&s->previous_picture.f);
    1586           0 :         av_frame_free(&s->last_picture.f);
    1587           0 :         av_frame_free(&s->picture.f);
    1588           0 :         return AVERROR(ENOMEM);
    1589             :     }
    1590             : 
    1591         132 :     if (!avctx->internal->is_copy) {
    1592         100 :         avctx->internal->allocate_progress = 1;
    1593         100 :         ff_pngdsp_init(&s->dsp);
    1594             :     }
    1595             : 
    1596         132 :     return 0;
    1597             : }
    1598             : 
    1599         132 : static av_cold int png_dec_end(AVCodecContext *avctx)
    1600             : {
    1601         132 :     PNGDecContext *s = avctx->priv_data;
    1602             : 
    1603         132 :     ff_thread_release_buffer(avctx, &s->previous_picture);
    1604         132 :     av_frame_free(&s->previous_picture.f);
    1605         132 :     ff_thread_release_buffer(avctx, &s->last_picture);
    1606         132 :     av_frame_free(&s->last_picture.f);
    1607         132 :     ff_thread_release_buffer(avctx, &s->picture);
    1608         132 :     av_frame_free(&s->picture.f);
    1609         132 :     av_freep(&s->buffer);
    1610         132 :     s->buffer_size = 0;
    1611         132 :     av_freep(&s->last_row);
    1612         132 :     s->last_row_size = 0;
    1613         132 :     av_freep(&s->tmp_row);
    1614         132 :     s->tmp_row_size = 0;
    1615             : 
    1616         132 :     return 0;
    1617             : }
    1618             : 
    1619             : #if CONFIG_APNG_DECODER
    1620             : AVCodec ff_apng_decoder = {
    1621             :     .name           = "apng",
    1622             :     .long_name      = NULL_IF_CONFIG_SMALL("APNG (Animated Portable Network Graphics) image"),
    1623             :     .type           = AVMEDIA_TYPE_VIDEO,
    1624             :     .id             = AV_CODEC_ID_APNG,
    1625             :     .priv_data_size = sizeof(PNGDecContext),
    1626             :     .init           = png_dec_init,
    1627             :     .close          = png_dec_end,
    1628             :     .decode         = decode_frame_apng,
    1629             :     .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
    1630             :     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
    1631             :     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
    1632             :     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
    1633             : };
    1634             : #endif
    1635             : 
    1636             : #if CONFIG_PNG_DECODER
    1637             : AVCodec ff_png_decoder = {
    1638             :     .name           = "png",
    1639             :     .long_name      = NULL_IF_CONFIG_SMALL("PNG (Portable Network Graphics) image"),
    1640             :     .type           = AVMEDIA_TYPE_VIDEO,
    1641             :     .id             = AV_CODEC_ID_PNG,
    1642             :     .priv_data_size = sizeof(PNGDecContext),
    1643             :     .init           = png_dec_init,
    1644             :     .close          = png_dec_end,
    1645             :     .decode         = decode_frame_png,
    1646             :     .init_thread_copy = ONLY_IF_THREADS_ENABLED(png_dec_init),
    1647             :     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
    1648             :     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/,
    1649             :     .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM | FF_CODEC_CAP_INIT_THREADSAFE,
    1650             : };
    1651             : #endif

Generated by: LCOV version 1.13