Path: blob/master/thirdparty/libwebp/src/demux/anim_decode.c
9913 views
// Copyright 2015 Google Inc. All Rights Reserved.1//2// Use of this source code is governed by a BSD-style license3// that can be found in the COPYING file in the root of the source4// tree. An additional intellectual property rights grant can be found5// in the file PATENTS. All contributing project authors may6// be found in the AUTHORS file in the root of the source tree.7// -----------------------------------------------------------------------------8//9// AnimDecoder implementation.10//1112#ifdef HAVE_CONFIG_H13#include "src/webp/config.h"14#endif1516#include <assert.h>17#include <string.h>1819#include "src/utils/utils.h"20#include "src/webp/decode.h"21#include "src/webp/demux.h"22#include "src/webp/types.h"2324#define NUM_CHANNELS 42526// Channel extraction from a uint32_t representation of a uint8_t RGBA/BGRA27// buffer.28#ifdef WORDS_BIGENDIAN29#define CHANNEL_SHIFT(i) (24 - (i) * 8)30#else31#define CHANNEL_SHIFT(i) ((i) * 8)32#endif3334typedef void (*BlendRowFunc)(uint32_t* const, const uint32_t* const, int);35static void BlendPixelRowNonPremult(uint32_t* const src,36const uint32_t* const dst, int num_pixels);37static void BlendPixelRowPremult(uint32_t* const src, const uint32_t* const dst,38int num_pixels);3940struct WebPAnimDecoder {41WebPDemuxer* demux_; // Demuxer created from given WebP bitstream.42WebPDecoderConfig config_; // Decoder config.43// Note: we use a pointer to a function blending multiple pixels at a time to44// allow possible inlining of per-pixel blending function.45BlendRowFunc blend_func_; // Pointer to the chose blend row function.46WebPAnimInfo info_; // Global info about the animation.47uint8_t* curr_frame_; // Current canvas (not disposed).48uint8_t* prev_frame_disposed_; // Previous canvas (properly disposed).49int prev_frame_timestamp_; // Previous frame timestamp (milliseconds).50WebPIterator prev_iter_; // Iterator object for previous frame.51int prev_frame_was_keyframe_; // True if previous frame was a keyframe.52int next_frame_; // Index of the next frame to be decoded53// (starting from 1).54};5556static void DefaultDecoderOptions(WebPAnimDecoderOptions* const dec_options) {57dec_options->color_mode = MODE_RGBA;58dec_options->use_threads = 0;59}6061int WebPAnimDecoderOptionsInitInternal(WebPAnimDecoderOptions* dec_options,62int abi_version) {63if (dec_options == NULL ||64WEBP_ABI_IS_INCOMPATIBLE(abi_version, WEBP_DEMUX_ABI_VERSION)) {65return 0;66}67DefaultDecoderOptions(dec_options);68return 1;69}7071WEBP_NODISCARD static int ApplyDecoderOptions(72const WebPAnimDecoderOptions* const dec_options,73WebPAnimDecoder* const dec) {74WEBP_CSP_MODE mode;75WebPDecoderConfig* config = &dec->config_;76assert(dec_options != NULL);7778mode = dec_options->color_mode;79if (mode != MODE_RGBA && mode != MODE_BGRA &&80mode != MODE_rgbA && mode != MODE_bgrA) {81return 0;82}83dec->blend_func_ = (mode == MODE_RGBA || mode == MODE_BGRA)84? &BlendPixelRowNonPremult85: &BlendPixelRowPremult;86if (!WebPInitDecoderConfig(config)) {87return 0;88}89config->output.colorspace = mode;90config->output.is_external_memory = 1;91config->options.use_threads = dec_options->use_threads;92// Note: config->output.u.RGBA is set at the time of decoding each frame.93return 1;94}9596WebPAnimDecoder* WebPAnimDecoderNewInternal(97const WebPData* webp_data, const WebPAnimDecoderOptions* dec_options,98int abi_version) {99WebPAnimDecoderOptions options;100WebPAnimDecoder* dec = NULL;101WebPBitstreamFeatures features;102if (webp_data == NULL ||103WEBP_ABI_IS_INCOMPATIBLE(abi_version, WEBP_DEMUX_ABI_VERSION)) {104return NULL;105}106107// Validate the bitstream before doing expensive allocations. The demuxer may108// be more tolerant than the decoder.109if (WebPGetFeatures(webp_data->bytes, webp_data->size, &features) !=110VP8_STATUS_OK) {111return NULL;112}113114// Note: calloc() so that the pointer members are initialized to NULL.115dec = (WebPAnimDecoder*)WebPSafeCalloc(1ULL, sizeof(*dec));116if (dec == NULL) goto Error;117118if (dec_options != NULL) {119options = *dec_options;120} else {121DefaultDecoderOptions(&options);122}123if (!ApplyDecoderOptions(&options, dec)) goto Error;124125dec->demux_ = WebPDemux(webp_data);126if (dec->demux_ == NULL) goto Error;127128dec->info_.canvas_width = WebPDemuxGetI(dec->demux_, WEBP_FF_CANVAS_WIDTH);129dec->info_.canvas_height = WebPDemuxGetI(dec->demux_, WEBP_FF_CANVAS_HEIGHT);130dec->info_.loop_count = WebPDemuxGetI(dec->demux_, WEBP_FF_LOOP_COUNT);131dec->info_.bgcolor = WebPDemuxGetI(dec->demux_, WEBP_FF_BACKGROUND_COLOR);132dec->info_.frame_count = WebPDemuxGetI(dec->demux_, WEBP_FF_FRAME_COUNT);133134// Note: calloc() because we fill frame with zeroes as well.135dec->curr_frame_ = (uint8_t*)WebPSafeCalloc(136dec->info_.canvas_width * NUM_CHANNELS, dec->info_.canvas_height);137if (dec->curr_frame_ == NULL) goto Error;138dec->prev_frame_disposed_ = (uint8_t*)WebPSafeCalloc(139dec->info_.canvas_width * NUM_CHANNELS, dec->info_.canvas_height);140if (dec->prev_frame_disposed_ == NULL) goto Error;141142WebPAnimDecoderReset(dec);143return dec;144145Error:146WebPAnimDecoderDelete(dec);147return NULL;148}149150int WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec, WebPAnimInfo* info) {151if (dec == NULL || info == NULL) return 0;152*info = dec->info_;153return 1;154}155156// Returns true if the frame covers the full canvas.157static int IsFullFrame(int width, int height, int canvas_width,158int canvas_height) {159return (width == canvas_width && height == canvas_height);160}161162// Clear the canvas to transparent.163WEBP_NODISCARD static int ZeroFillCanvas(uint8_t* buf, uint32_t canvas_width,164uint32_t canvas_height) {165const uint64_t size =166(uint64_t)canvas_width * canvas_height * NUM_CHANNELS * sizeof(*buf);167if (!CheckSizeOverflow(size)) return 0;168memset(buf, 0, (size_t)size);169return 1;170}171172// Clear given frame rectangle to transparent.173static void ZeroFillFrameRect(uint8_t* buf, int buf_stride, int x_offset,174int y_offset, int width, int height) {175int j;176assert(width * NUM_CHANNELS <= buf_stride);177buf += y_offset * buf_stride + x_offset * NUM_CHANNELS;178for (j = 0; j < height; ++j) {179memset(buf, 0, width * NUM_CHANNELS);180buf += buf_stride;181}182}183184// Copy width * height pixels from 'src' to 'dst'.185WEBP_NODISCARD static int CopyCanvas(const uint8_t* src, uint8_t* dst,186uint32_t width, uint32_t height) {187const uint64_t size = (uint64_t)width * height * NUM_CHANNELS;188if (!CheckSizeOverflow(size)) return 0;189assert(src != NULL && dst != NULL);190memcpy(dst, src, (size_t)size);191return 1;192}193194// Returns true if the current frame is a key-frame.195static int IsKeyFrame(const WebPIterator* const curr,196const WebPIterator* const prev,197int prev_frame_was_key_frame,198int canvas_width, int canvas_height) {199if (curr->frame_num == 1) {200return 1;201} else if ((!curr->has_alpha || curr->blend_method == WEBP_MUX_NO_BLEND) &&202IsFullFrame(curr->width, curr->height,203canvas_width, canvas_height)) {204return 1;205} else {206return (prev->dispose_method == WEBP_MUX_DISPOSE_BACKGROUND) &&207(IsFullFrame(prev->width, prev->height, canvas_width,208canvas_height) ||209prev_frame_was_key_frame);210}211}212213214// Blend a single channel of 'src' over 'dst', given their alpha channel values.215// 'src' and 'dst' are assumed to be NOT pre-multiplied by alpha.216static uint8_t BlendChannelNonPremult(uint32_t src, uint8_t src_a,217uint32_t dst, uint8_t dst_a,218uint32_t scale, int shift) {219const uint8_t src_channel = (src >> shift) & 0xff;220const uint8_t dst_channel = (dst >> shift) & 0xff;221const uint32_t blend_unscaled = src_channel * src_a + dst_channel * dst_a;222assert(blend_unscaled < (1ULL << 32) / scale);223return (blend_unscaled * scale) >> CHANNEL_SHIFT(3);224}225226// Blend 'src' over 'dst' assuming they are NOT pre-multiplied by alpha.227static uint32_t BlendPixelNonPremult(uint32_t src, uint32_t dst) {228const uint8_t src_a = (src >> CHANNEL_SHIFT(3)) & 0xff;229230if (src_a == 0) {231return dst;232} else {233const uint8_t dst_a = (dst >> CHANNEL_SHIFT(3)) & 0xff;234// This is the approximate integer arithmetic for the actual formula:235// dst_factor_a = (dst_a * (255 - src_a)) / 255.236const uint8_t dst_factor_a = (dst_a * (256 - src_a)) >> 8;237const uint8_t blend_a = src_a + dst_factor_a;238const uint32_t scale = (1UL << 24) / blend_a;239240const uint8_t blend_r = BlendChannelNonPremult(241src, src_a, dst, dst_factor_a, scale, CHANNEL_SHIFT(0));242const uint8_t blend_g = BlendChannelNonPremult(243src, src_a, dst, dst_factor_a, scale, CHANNEL_SHIFT(1));244const uint8_t blend_b = BlendChannelNonPremult(245src, src_a, dst, dst_factor_a, scale, CHANNEL_SHIFT(2));246assert(src_a + dst_factor_a < 256);247248return ((uint32_t)blend_r << CHANNEL_SHIFT(0)) |249((uint32_t)blend_g << CHANNEL_SHIFT(1)) |250((uint32_t)blend_b << CHANNEL_SHIFT(2)) |251((uint32_t)blend_a << CHANNEL_SHIFT(3));252}253}254255// Blend 'num_pixels' in 'src' over 'dst' assuming they are NOT pre-multiplied256// by alpha.257static void BlendPixelRowNonPremult(uint32_t* const src,258const uint32_t* const dst, int num_pixels) {259int i;260for (i = 0; i < num_pixels; ++i) {261const uint8_t src_alpha = (src[i] >> CHANNEL_SHIFT(3)) & 0xff;262if (src_alpha != 0xff) {263src[i] = BlendPixelNonPremult(src[i], dst[i]);264}265}266}267268// Individually multiply each channel in 'pix' by 'scale'.269static WEBP_INLINE uint32_t ChannelwiseMultiply(uint32_t pix, uint32_t scale) {270uint32_t mask = 0x00FF00FF;271uint32_t rb = ((pix & mask) * scale) >> 8;272uint32_t ag = ((pix >> 8) & mask) * scale;273return (rb & mask) | (ag & ~mask);274}275276// Blend 'src' over 'dst' assuming they are pre-multiplied by alpha.277static uint32_t BlendPixelPremult(uint32_t src, uint32_t dst) {278const uint8_t src_a = (src >> CHANNEL_SHIFT(3)) & 0xff;279return src + ChannelwiseMultiply(dst, 256 - src_a);280}281282// Blend 'num_pixels' in 'src' over 'dst' assuming they are pre-multiplied by283// alpha.284static void BlendPixelRowPremult(uint32_t* const src, const uint32_t* const dst,285int num_pixels) {286int i;287for (i = 0; i < num_pixels; ++i) {288const uint8_t src_alpha = (src[i] >> CHANNEL_SHIFT(3)) & 0xff;289if (src_alpha != 0xff) {290src[i] = BlendPixelPremult(src[i], dst[i]);291}292}293}294295// Returns two ranges (<left, width> pairs) at row 'canvas_y', that belong to296// 'src' but not 'dst'. A point range is empty if the corresponding width is 0.297static void FindBlendRangeAtRow(const WebPIterator* const src,298const WebPIterator* const dst, int canvas_y,299int* const left1, int* const width1,300int* const left2, int* const width2) {301const int src_max_x = src->x_offset + src->width;302const int dst_max_x = dst->x_offset + dst->width;303const int dst_max_y = dst->y_offset + dst->height;304assert(canvas_y >= src->y_offset && canvas_y < (src->y_offset + src->height));305*left1 = -1;306*width1 = 0;307*left2 = -1;308*width2 = 0;309310if (canvas_y < dst->y_offset || canvas_y >= dst_max_y ||311src->x_offset >= dst_max_x || src_max_x <= dst->x_offset) {312*left1 = src->x_offset;313*width1 = src->width;314return;315}316317if (src->x_offset < dst->x_offset) {318*left1 = src->x_offset;319*width1 = dst->x_offset - src->x_offset;320}321322if (src_max_x > dst_max_x) {323*left2 = dst_max_x;324*width2 = src_max_x - dst_max_x;325}326}327328int WebPAnimDecoderGetNext(WebPAnimDecoder* dec,329uint8_t** buf_ptr, int* timestamp_ptr) {330WebPIterator iter;331uint32_t width;332uint32_t height;333int is_key_frame;334int timestamp;335BlendRowFunc blend_row;336337if (dec == NULL || buf_ptr == NULL || timestamp_ptr == NULL) return 0;338if (!WebPAnimDecoderHasMoreFrames(dec)) return 0;339340width = dec->info_.canvas_width;341height = dec->info_.canvas_height;342blend_row = dec->blend_func_;343344// Get compressed frame.345if (!WebPDemuxGetFrame(dec->demux_, dec->next_frame_, &iter)) {346return 0;347}348timestamp = dec->prev_frame_timestamp_ + iter.duration;349350// Initialize.351is_key_frame = IsKeyFrame(&iter, &dec->prev_iter_,352dec->prev_frame_was_keyframe_, width, height);353if (is_key_frame) {354if (!ZeroFillCanvas(dec->curr_frame_, width, height)) {355goto Error;356}357} else {358if (!CopyCanvas(dec->prev_frame_disposed_, dec->curr_frame_,359width, height)) {360goto Error;361}362}363364// Decode.365{366const uint8_t* in = iter.fragment.bytes;367const size_t in_size = iter.fragment.size;368const uint32_t stride = width * NUM_CHANNELS; // at most 25 + 2 bits369const uint64_t out_offset = (uint64_t)iter.y_offset * stride +370(uint64_t)iter.x_offset * NUM_CHANNELS; // 53b371const uint64_t size = (uint64_t)iter.height * stride; // at most 25 + 27b372WebPDecoderConfig* const config = &dec->config_;373WebPRGBABuffer* const buf = &config->output.u.RGBA;374if ((size_t)size != size) goto Error;375buf->stride = (int)stride;376buf->size = (size_t)size;377buf->rgba = dec->curr_frame_ + out_offset;378379if (WebPDecode(in, in_size, config) != VP8_STATUS_OK) {380goto Error;381}382}383384// During the decoding of current frame, we may have set some pixels to be385// transparent (i.e. alpha < 255). However, the value of each of these386// pixels should have been determined by blending it against the value of387// that pixel in the previous frame if blending method of is WEBP_MUX_BLEND.388if (iter.frame_num > 1 && iter.blend_method == WEBP_MUX_BLEND &&389!is_key_frame) {390if (dec->prev_iter_.dispose_method == WEBP_MUX_DISPOSE_NONE) {391int y;392// Blend transparent pixels with pixels in previous canvas.393for (y = 0; y < iter.height; ++y) {394const size_t offset =395(iter.y_offset + y) * width + iter.x_offset;396blend_row((uint32_t*)dec->curr_frame_ + offset,397(uint32_t*)dec->prev_frame_disposed_ + offset, iter.width);398}399} else {400int y;401assert(dec->prev_iter_.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND);402// We need to blend a transparent pixel with its value just after403// initialization. That is, blend it with:404// * Fully transparent pixel if it belongs to prevRect <-- No-op.405// * The pixel in the previous canvas otherwise <-- Need alpha-blending.406for (y = 0; y < iter.height; ++y) {407const int canvas_y = iter.y_offset + y;408int left1, width1, left2, width2;409FindBlendRangeAtRow(&iter, &dec->prev_iter_, canvas_y, &left1, &width1,410&left2, &width2);411if (width1 > 0) {412const size_t offset1 = canvas_y * width + left1;413blend_row((uint32_t*)dec->curr_frame_ + offset1,414(uint32_t*)dec->prev_frame_disposed_ + offset1, width1);415}416if (width2 > 0) {417const size_t offset2 = canvas_y * width + left2;418blend_row((uint32_t*)dec->curr_frame_ + offset2,419(uint32_t*)dec->prev_frame_disposed_ + offset2, width2);420}421}422}423}424425// Update info of the previous frame and dispose it for the next iteration.426dec->prev_frame_timestamp_ = timestamp;427WebPDemuxReleaseIterator(&dec->prev_iter_);428dec->prev_iter_ = iter;429dec->prev_frame_was_keyframe_ = is_key_frame;430if (!CopyCanvas(dec->curr_frame_, dec->prev_frame_disposed_, width, height)) {431goto Error;432}433if (dec->prev_iter_.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND) {434ZeroFillFrameRect(dec->prev_frame_disposed_, width * NUM_CHANNELS,435dec->prev_iter_.x_offset, dec->prev_iter_.y_offset,436dec->prev_iter_.width, dec->prev_iter_.height);437}438++dec->next_frame_;439440// All OK, fill in the values.441*buf_ptr = dec->curr_frame_;442*timestamp_ptr = timestamp;443return 1;444445Error:446WebPDemuxReleaseIterator(&iter);447return 0;448}449450int WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec) {451if (dec == NULL) return 0;452return (dec->next_frame_ <= (int)dec->info_.frame_count);453}454455void WebPAnimDecoderReset(WebPAnimDecoder* dec) {456if (dec != NULL) {457dec->prev_frame_timestamp_ = 0;458WebPDemuxReleaseIterator(&dec->prev_iter_);459memset(&dec->prev_iter_, 0, sizeof(dec->prev_iter_));460dec->prev_frame_was_keyframe_ = 0;461dec->next_frame_ = 1;462}463}464465const WebPDemuxer* WebPAnimDecoderGetDemuxer(const WebPAnimDecoder* dec) {466if (dec == NULL) return NULL;467return dec->demux_;468}469470void WebPAnimDecoderDelete(WebPAnimDecoder* dec) {471if (dec != NULL) {472WebPDemuxReleaseIterator(&dec->prev_iter_);473WebPDemuxDelete(dec->demux_);474WebPSafeFree(dec->curr_frame_);475WebPSafeFree(dec->prev_frame_disposed_);476WebPSafeFree(dec);477}478}479480481