Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

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