Path: blob/master/thirdparty/libwebp/src/demux/demux.c
9913 views
// Copyright 2012 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// WebP container demux.10//1112#ifdef HAVE_CONFIG_H13#include "src/webp/config.h"14#endif1516#include <assert.h>17#include <stdlib.h>18#include <string.h>1920#include "src/utils/utils.h"21#include "src/webp/decode.h" // WebPGetFeatures22#include "src/webp/demux.h"23#include "src/webp/format_constants.h"2425#define DMUX_MAJ_VERSION 126#define DMUX_MIN_VERSION 527#define DMUX_REV_VERSION 02829typedef struct {30size_t start_; // start location of the data31size_t end_; // end location32size_t riff_end_; // riff chunk end location, can be > end_.33size_t buf_size_; // size of the buffer34const uint8_t* buf_;35} MemBuffer;3637typedef struct {38size_t offset_;39size_t size_;40} ChunkData;4142typedef struct Frame {43int x_offset_, y_offset_;44int width_, height_;45int has_alpha_;46int duration_;47WebPMuxAnimDispose dispose_method_;48WebPMuxAnimBlend blend_method_;49int frame_num_;50int complete_; // img_components_ contains a full image.51ChunkData img_components_[2]; // 0=VP8{,L} 1=ALPH52struct Frame* next_;53} Frame;5455typedef struct Chunk {56ChunkData data_;57struct Chunk* next_;58} Chunk;5960struct WebPDemuxer {61MemBuffer mem_;62WebPDemuxState state_;63int is_ext_format_;64uint32_t feature_flags_;65int canvas_width_, canvas_height_;66int loop_count_;67uint32_t bgcolor_;68int num_frames_;69Frame* frames_;70Frame** frames_tail_;71Chunk* chunks_; // non-image chunks72Chunk** chunks_tail_;73};7475typedef enum {76PARSE_OK,77PARSE_NEED_MORE_DATA,78PARSE_ERROR79} ParseStatus;8081typedef struct ChunkParser {82uint8_t id[4];83ParseStatus (*parse)(WebPDemuxer* const dmux);84int (*valid)(const WebPDemuxer* const dmux);85} ChunkParser;8687static ParseStatus ParseSingleImage(WebPDemuxer* const dmux);88static ParseStatus ParseVP8X(WebPDemuxer* const dmux);89static int IsValidSimpleFormat(const WebPDemuxer* const dmux);90static int IsValidExtendedFormat(const WebPDemuxer* const dmux);9192static const ChunkParser kMasterChunks[] = {93{ { 'V', 'P', '8', ' ' }, ParseSingleImage, IsValidSimpleFormat },94{ { 'V', 'P', '8', 'L' }, ParseSingleImage, IsValidSimpleFormat },95{ { 'V', 'P', '8', 'X' }, ParseVP8X, IsValidExtendedFormat },96{ { '0', '0', '0', '0' }, NULL, NULL },97};9899//------------------------------------------------------------------------------100101int WebPGetDemuxVersion(void) {102return (DMUX_MAJ_VERSION << 16) | (DMUX_MIN_VERSION << 8) | DMUX_REV_VERSION;103}104105// -----------------------------------------------------------------------------106// MemBuffer107108static int RemapMemBuffer(MemBuffer* const mem,109const uint8_t* data, size_t size) {110if (size < mem->buf_size_) return 0; // can't remap to a shorter buffer!111112mem->buf_ = data;113mem->end_ = mem->buf_size_ = size;114return 1;115}116117static int InitMemBuffer(MemBuffer* const mem,118const uint8_t* data, size_t size) {119memset(mem, 0, sizeof(*mem));120return RemapMemBuffer(mem, data, size);121}122123// Return the remaining data size available in 'mem'.124static WEBP_INLINE size_t MemDataSize(const MemBuffer* const mem) {125return (mem->end_ - mem->start_);126}127128// Return true if 'size' exceeds the end of the RIFF chunk.129static WEBP_INLINE int SizeIsInvalid(const MemBuffer* const mem, size_t size) {130return (size > mem->riff_end_ - mem->start_);131}132133static WEBP_INLINE void Skip(MemBuffer* const mem, size_t size) {134mem->start_ += size;135}136137static WEBP_INLINE void Rewind(MemBuffer* const mem, size_t size) {138mem->start_ -= size;139}140141static WEBP_INLINE const uint8_t* GetBuffer(MemBuffer* const mem) {142return mem->buf_ + mem->start_;143}144145// Read from 'mem' and skip the read bytes.146static WEBP_INLINE uint8_t ReadByte(MemBuffer* const mem) {147const uint8_t byte = mem->buf_[mem->start_];148Skip(mem, 1);149return byte;150}151152static WEBP_INLINE int ReadLE16s(MemBuffer* const mem) {153const uint8_t* const data = mem->buf_ + mem->start_;154const int val = GetLE16(data);155Skip(mem, 2);156return val;157}158159static WEBP_INLINE int ReadLE24s(MemBuffer* const mem) {160const uint8_t* const data = mem->buf_ + mem->start_;161const int val = GetLE24(data);162Skip(mem, 3);163return val;164}165166static WEBP_INLINE uint32_t ReadLE32(MemBuffer* const mem) {167const uint8_t* const data = mem->buf_ + mem->start_;168const uint32_t val = GetLE32(data);169Skip(mem, 4);170return val;171}172173// -----------------------------------------------------------------------------174// Secondary chunk parsing175176static void AddChunk(WebPDemuxer* const dmux, Chunk* const chunk) {177*dmux->chunks_tail_ = chunk;178chunk->next_ = NULL;179dmux->chunks_tail_ = &chunk->next_;180}181182// Add a frame to the end of the list, ensuring the last frame is complete.183// Returns true on success, false otherwise.184static int AddFrame(WebPDemuxer* const dmux, Frame* const frame) {185const Frame* const last_frame = *dmux->frames_tail_;186if (last_frame != NULL && !last_frame->complete_) return 0;187188*dmux->frames_tail_ = frame;189frame->next_ = NULL;190dmux->frames_tail_ = &frame->next_;191return 1;192}193194static void SetFrameInfo(size_t start_offset, size_t size,195int frame_num, int complete,196const WebPBitstreamFeatures* const features,197Frame* const frame) {198frame->img_components_[0].offset_ = start_offset;199frame->img_components_[0].size_ = size;200frame->width_ = features->width;201frame->height_ = features->height;202frame->has_alpha_ |= features->has_alpha;203frame->frame_num_ = frame_num;204frame->complete_ = complete;205}206207// Store image bearing chunks to 'frame'. 'min_size' is an optional size208// requirement, it may be zero.209static ParseStatus StoreFrame(int frame_num, uint32_t min_size,210MemBuffer* const mem, Frame* const frame) {211int alpha_chunks = 0;212int image_chunks = 0;213int done = (MemDataSize(mem) < CHUNK_HEADER_SIZE ||214MemDataSize(mem) < min_size);215ParseStatus status = PARSE_OK;216217if (done) return PARSE_NEED_MORE_DATA;218219do {220const size_t chunk_start_offset = mem->start_;221const uint32_t fourcc = ReadLE32(mem);222const uint32_t payload_size = ReadLE32(mem);223uint32_t payload_size_padded;224size_t payload_available;225size_t chunk_size;226227if (payload_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;228229payload_size_padded = payload_size + (payload_size & 1);230payload_available = (payload_size_padded > MemDataSize(mem))231? MemDataSize(mem) : payload_size_padded;232chunk_size = CHUNK_HEADER_SIZE + payload_available;233if (SizeIsInvalid(mem, payload_size_padded)) return PARSE_ERROR;234if (payload_size_padded > MemDataSize(mem)) status = PARSE_NEED_MORE_DATA;235236switch (fourcc) {237case MKFOURCC('A', 'L', 'P', 'H'):238if (alpha_chunks == 0) {239++alpha_chunks;240frame->img_components_[1].offset_ = chunk_start_offset;241frame->img_components_[1].size_ = chunk_size;242frame->has_alpha_ = 1;243frame->frame_num_ = frame_num;244Skip(mem, payload_available);245} else {246goto Done;247}248break;249case MKFOURCC('V', 'P', '8', 'L'):250if (alpha_chunks > 0) return PARSE_ERROR; // VP8L has its own alpha251// fall through252case MKFOURCC('V', 'P', '8', ' '):253if (image_chunks == 0) {254// Extract the bitstream features, tolerating failures when the data255// is incomplete.256WebPBitstreamFeatures features;257const VP8StatusCode vp8_status =258WebPGetFeatures(mem->buf_ + chunk_start_offset, chunk_size,259&features);260if (status == PARSE_NEED_MORE_DATA &&261vp8_status == VP8_STATUS_NOT_ENOUGH_DATA) {262return PARSE_NEED_MORE_DATA;263} else if (vp8_status != VP8_STATUS_OK) {264// We have enough data, and yet WebPGetFeatures() failed.265return PARSE_ERROR;266}267++image_chunks;268SetFrameInfo(chunk_start_offset, chunk_size, frame_num,269status == PARSE_OK, &features, frame);270Skip(mem, payload_available);271} else {272goto Done;273}274break;275Done:276default:277// Restore fourcc/size when moving up one level in parsing.278Rewind(mem, CHUNK_HEADER_SIZE);279done = 1;280break;281}282283if (mem->start_ == mem->riff_end_) {284done = 1;285} else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {286status = PARSE_NEED_MORE_DATA;287}288} while (!done && status == PARSE_OK);289290return status;291}292293// Creates a new Frame if 'actual_size' is within bounds and 'mem' contains294// enough data ('min_size') to parse the payload.295// Returns PARSE_OK on success with *frame pointing to the new Frame.296// Returns PARSE_NEED_MORE_DATA with insufficient data, PARSE_ERROR otherwise.297static ParseStatus NewFrame(const MemBuffer* const mem,298uint32_t min_size, uint32_t actual_size,299Frame** frame) {300if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;301if (actual_size < min_size) return PARSE_ERROR;302if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;303304*frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(**frame));305return (*frame == NULL) ? PARSE_ERROR : PARSE_OK;306}307308// Parse a 'ANMF' chunk and any image bearing chunks that immediately follow.309// 'frame_chunk_size' is the previously validated, padded chunk size.310static ParseStatus ParseAnimationFrame(311WebPDemuxer* const dmux, uint32_t frame_chunk_size) {312const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);313const uint32_t anmf_payload_size = frame_chunk_size - ANMF_CHUNK_SIZE;314int added_frame = 0;315int bits;316MemBuffer* const mem = &dmux->mem_;317Frame* frame;318size_t start_offset;319ParseStatus status =320NewFrame(mem, ANMF_CHUNK_SIZE, frame_chunk_size, &frame);321if (status != PARSE_OK) return status;322323frame->x_offset_ = 2 * ReadLE24s(mem);324frame->y_offset_ = 2 * ReadLE24s(mem);325frame->width_ = 1 + ReadLE24s(mem);326frame->height_ = 1 + ReadLE24s(mem);327frame->duration_ = ReadLE24s(mem);328bits = ReadByte(mem);329frame->dispose_method_ =330(bits & 1) ? WEBP_MUX_DISPOSE_BACKGROUND : WEBP_MUX_DISPOSE_NONE;331frame->blend_method_ = (bits & 2) ? WEBP_MUX_NO_BLEND : WEBP_MUX_BLEND;332if (frame->width_ * (uint64_t)frame->height_ >= MAX_IMAGE_AREA) {333WebPSafeFree(frame);334return PARSE_ERROR;335}336337// Store a frame only if the animation flag is set there is some data for338// this frame is available.339start_offset = mem->start_;340status = StoreFrame(dmux->num_frames_ + 1, anmf_payload_size, mem, frame);341if (status != PARSE_ERROR && mem->start_ - start_offset > anmf_payload_size) {342status = PARSE_ERROR;343}344if (status != PARSE_ERROR && is_animation && frame->frame_num_ > 0) {345added_frame = AddFrame(dmux, frame);346if (added_frame) {347++dmux->num_frames_;348} else {349status = PARSE_ERROR;350}351}352353if (!added_frame) WebPSafeFree(frame);354return status;355}356357// General chunk storage, starting with the header at 'start_offset', allowing358// the user to request the payload via a fourcc string. 'size' includes the359// header and the unpadded payload size.360// Returns true on success, false otherwise.361static int StoreChunk(WebPDemuxer* const dmux,362size_t start_offset, uint32_t size) {363Chunk* const chunk = (Chunk*)WebPSafeCalloc(1ULL, sizeof(*chunk));364if (chunk == NULL) return 0;365366chunk->data_.offset_ = start_offset;367chunk->data_.size_ = size;368AddChunk(dmux, chunk);369return 1;370}371372// -----------------------------------------------------------------------------373// Primary chunk parsing374375static ParseStatus ReadHeader(MemBuffer* const mem) {376const size_t min_size = RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE;377uint32_t riff_size;378379// Basic file level validation.380if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;381if (memcmp(GetBuffer(mem), "RIFF", CHUNK_SIZE_BYTES) ||382memcmp(GetBuffer(mem) + CHUNK_HEADER_SIZE, "WEBP", CHUNK_SIZE_BYTES)) {383return PARSE_ERROR;384}385386riff_size = GetLE32(GetBuffer(mem) + TAG_SIZE);387if (riff_size < CHUNK_HEADER_SIZE) return PARSE_ERROR;388if (riff_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;389390// There's no point in reading past the end of the RIFF chunk391mem->riff_end_ = riff_size + CHUNK_HEADER_SIZE;392if (mem->buf_size_ > mem->riff_end_) {393mem->buf_size_ = mem->end_ = mem->riff_end_;394}395396Skip(mem, RIFF_HEADER_SIZE);397return PARSE_OK;398}399400static ParseStatus ParseSingleImage(WebPDemuxer* const dmux) {401const size_t min_size = CHUNK_HEADER_SIZE;402MemBuffer* const mem = &dmux->mem_;403Frame* frame;404ParseStatus status;405int image_added = 0;406407if (dmux->frames_ != NULL) return PARSE_ERROR;408if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;409if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;410411frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));412if (frame == NULL) return PARSE_ERROR;413414// For the single image case we allow parsing of a partial frame, so no415// minimum size is imposed here.416status = StoreFrame(1, 0, &dmux->mem_, frame);417if (status != PARSE_ERROR) {418const int has_alpha = !!(dmux->feature_flags_ & ALPHA_FLAG);419// Clear any alpha when the alpha flag is missing.420if (!has_alpha && frame->img_components_[1].size_ > 0) {421frame->img_components_[1].offset_ = 0;422frame->img_components_[1].size_ = 0;423frame->has_alpha_ = 0;424}425426// Use the frame width/height as the canvas values for non-vp8x files.427// Also, set ALPHA_FLAG if this is a lossless image with alpha.428if (!dmux->is_ext_format_ && frame->width_ > 0 && frame->height_ > 0) {429dmux->state_ = WEBP_DEMUX_PARSED_HEADER;430dmux->canvas_width_ = frame->width_;431dmux->canvas_height_ = frame->height_;432dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;433}434if (!AddFrame(dmux, frame)) {435status = PARSE_ERROR; // last frame was left incomplete436} else {437image_added = 1;438dmux->num_frames_ = 1;439}440}441442if (!image_added) WebPSafeFree(frame);443return status;444}445446static ParseStatus ParseVP8XChunks(WebPDemuxer* const dmux) {447const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);448MemBuffer* const mem = &dmux->mem_;449int anim_chunks = 0;450ParseStatus status = PARSE_OK;451452do {453int store_chunk = 1;454const size_t chunk_start_offset = mem->start_;455const uint32_t fourcc = ReadLE32(mem);456const uint32_t chunk_size = ReadLE32(mem);457uint32_t chunk_size_padded;458459if (chunk_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;460461chunk_size_padded = chunk_size + (chunk_size & 1);462if (SizeIsInvalid(mem, chunk_size_padded)) return PARSE_ERROR;463464switch (fourcc) {465case MKFOURCC('V', 'P', '8', 'X'): {466return PARSE_ERROR;467}468case MKFOURCC('A', 'L', 'P', 'H'):469case MKFOURCC('V', 'P', '8', ' '):470case MKFOURCC('V', 'P', '8', 'L'): {471// check that this isn't an animation (all frames should be in an ANMF).472if (anim_chunks > 0 || is_animation) return PARSE_ERROR;473474Rewind(mem, CHUNK_HEADER_SIZE);475status = ParseSingleImage(dmux);476break;477}478case MKFOURCC('A', 'N', 'I', 'M'): {479if (chunk_size_padded < ANIM_CHUNK_SIZE) return PARSE_ERROR;480481if (MemDataSize(mem) < chunk_size_padded) {482status = PARSE_NEED_MORE_DATA;483} else if (anim_chunks == 0) {484++anim_chunks;485dmux->bgcolor_ = ReadLE32(mem);486dmux->loop_count_ = ReadLE16s(mem);487Skip(mem, chunk_size_padded - ANIM_CHUNK_SIZE);488} else {489store_chunk = 0;490goto Skip;491}492break;493}494case MKFOURCC('A', 'N', 'M', 'F'): {495if (anim_chunks == 0) return PARSE_ERROR; // 'ANIM' precedes frames.496status = ParseAnimationFrame(dmux, chunk_size_padded);497break;498}499case MKFOURCC('I', 'C', 'C', 'P'): {500store_chunk = !!(dmux->feature_flags_ & ICCP_FLAG);501goto Skip;502}503case MKFOURCC('E', 'X', 'I', 'F'): {504store_chunk = !!(dmux->feature_flags_ & EXIF_FLAG);505goto Skip;506}507case MKFOURCC('X', 'M', 'P', ' '): {508store_chunk = !!(dmux->feature_flags_ & XMP_FLAG);509goto Skip;510}511Skip:512default: {513if (chunk_size_padded <= MemDataSize(mem)) {514if (store_chunk) {515// Store only the chunk header and unpadded size as only the payload516// will be returned to the user.517if (!StoreChunk(dmux, chunk_start_offset,518CHUNK_HEADER_SIZE + chunk_size)) {519return PARSE_ERROR;520}521}522Skip(mem, chunk_size_padded);523} else {524status = PARSE_NEED_MORE_DATA;525}526}527}528529if (mem->start_ == mem->riff_end_) {530break;531} else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {532status = PARSE_NEED_MORE_DATA;533}534} while (status == PARSE_OK);535536return status;537}538539static ParseStatus ParseVP8X(WebPDemuxer* const dmux) {540MemBuffer* const mem = &dmux->mem_;541uint32_t vp8x_size;542543if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;544545dmux->is_ext_format_ = 1;546Skip(mem, TAG_SIZE); // VP8X547vp8x_size = ReadLE32(mem);548if (vp8x_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;549if (vp8x_size < VP8X_CHUNK_SIZE) return PARSE_ERROR;550vp8x_size += vp8x_size & 1;551if (SizeIsInvalid(mem, vp8x_size)) return PARSE_ERROR;552if (MemDataSize(mem) < vp8x_size) return PARSE_NEED_MORE_DATA;553554dmux->feature_flags_ = ReadByte(mem);555Skip(mem, 3); // Reserved.556dmux->canvas_width_ = 1 + ReadLE24s(mem);557dmux->canvas_height_ = 1 + ReadLE24s(mem);558if (dmux->canvas_width_ * (uint64_t)dmux->canvas_height_ >= MAX_IMAGE_AREA) {559return PARSE_ERROR; // image final dimension is too large560}561Skip(mem, vp8x_size - VP8X_CHUNK_SIZE); // skip any trailing data.562dmux->state_ = WEBP_DEMUX_PARSED_HEADER;563564if (SizeIsInvalid(mem, CHUNK_HEADER_SIZE)) return PARSE_ERROR;565if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;566567return ParseVP8XChunks(dmux);568}569570// -----------------------------------------------------------------------------571// Format validation572573static int IsValidSimpleFormat(const WebPDemuxer* const dmux) {574const Frame* const frame = dmux->frames_;575if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;576577if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;578if (dmux->state_ == WEBP_DEMUX_DONE && frame == NULL) return 0;579580if (frame->width_ <= 0 || frame->height_ <= 0) return 0;581return 1;582}583584// If 'exact' is true, check that the image resolution matches the canvas.585// If 'exact' is false, check that the x/y offsets do not exceed the canvas.586static int CheckFrameBounds(const Frame* const frame, int exact,587int canvas_width, int canvas_height) {588if (exact) {589if (frame->x_offset_ != 0 || frame->y_offset_ != 0) {590return 0;591}592if (frame->width_ != canvas_width || frame->height_ != canvas_height) {593return 0;594}595} else {596if (frame->x_offset_ < 0 || frame->y_offset_ < 0) return 0;597if (frame->width_ + frame->x_offset_ > canvas_width) return 0;598if (frame->height_ + frame->y_offset_ > canvas_height) return 0;599}600return 1;601}602603static int IsValidExtendedFormat(const WebPDemuxer* const dmux) {604const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);605const Frame* f = dmux->frames_;606607if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;608609if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;610if (dmux->loop_count_ < 0) return 0;611if (dmux->state_ == WEBP_DEMUX_DONE && dmux->frames_ == NULL) return 0;612if (dmux->feature_flags_ & ~ALL_VALID_FLAGS) return 0; // invalid bitstream613614while (f != NULL) {615const int cur_frame_set = f->frame_num_;616617// Check frame properties.618for (; f != NULL && f->frame_num_ == cur_frame_set; f = f->next_) {619const ChunkData* const image = f->img_components_;620const ChunkData* const alpha = f->img_components_ + 1;621622if (!is_animation && f->frame_num_ > 1) return 0;623624if (f->complete_) {625if (alpha->size_ == 0 && image->size_ == 0) return 0;626// Ensure alpha precedes image bitstream.627if (alpha->size_ > 0 && alpha->offset_ > image->offset_) {628return 0;629}630631if (f->width_ <= 0 || f->height_ <= 0) return 0;632} else {633// There shouldn't be a partial frame in a complete file.634if (dmux->state_ == WEBP_DEMUX_DONE) return 0;635636// Ensure alpha precedes image bitstream.637if (alpha->size_ > 0 && image->size_ > 0 &&638alpha->offset_ > image->offset_) {639return 0;640}641// There shouldn't be any frames after an incomplete one.642if (f->next_ != NULL) return 0;643}644645if (f->width_ > 0 && f->height_ > 0 &&646!CheckFrameBounds(f, !is_animation,647dmux->canvas_width_, dmux->canvas_height_)) {648return 0;649}650}651}652return 1;653}654655// -----------------------------------------------------------------------------656// WebPDemuxer object657658static void InitDemux(WebPDemuxer* const dmux, const MemBuffer* const mem) {659dmux->state_ = WEBP_DEMUX_PARSING_HEADER;660dmux->loop_count_ = 1;661dmux->bgcolor_ = 0xFFFFFFFF; // White background by default.662dmux->canvas_width_ = -1;663dmux->canvas_height_ = -1;664dmux->frames_tail_ = &dmux->frames_;665dmux->chunks_tail_ = &dmux->chunks_;666dmux->mem_ = *mem;667}668669static ParseStatus CreateRawImageDemuxer(MemBuffer* const mem,670WebPDemuxer** demuxer) {671WebPBitstreamFeatures features;672const VP8StatusCode status =673WebPGetFeatures(mem->buf_, mem->buf_size_, &features);674*demuxer = NULL;675if (status != VP8_STATUS_OK) {676return (status == VP8_STATUS_NOT_ENOUGH_DATA) ? PARSE_NEED_MORE_DATA677: PARSE_ERROR;678}679680{681WebPDemuxer* const dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));682Frame* const frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));683if (dmux == NULL || frame == NULL) goto Error;684InitDemux(dmux, mem);685SetFrameInfo(0, mem->buf_size_, 1 /*frame_num*/, 1 /*complete*/, &features,686frame);687if (!AddFrame(dmux, frame)) goto Error;688dmux->state_ = WEBP_DEMUX_DONE;689dmux->canvas_width_ = frame->width_;690dmux->canvas_height_ = frame->height_;691dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;692dmux->num_frames_ = 1;693assert(IsValidSimpleFormat(dmux));694*demuxer = dmux;695return PARSE_OK;696697Error:698WebPSafeFree(dmux);699WebPSafeFree(frame);700return PARSE_ERROR;701}702}703704WebPDemuxer* WebPDemuxInternal(const WebPData* data, int allow_partial,705WebPDemuxState* state, int version) {706const ChunkParser* parser;707int partial;708ParseStatus status = PARSE_ERROR;709MemBuffer mem;710WebPDemuxer* dmux;711712if (state != NULL) *state = WEBP_DEMUX_PARSE_ERROR;713714if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_DEMUX_ABI_VERSION)) return NULL;715if (data == NULL || data->bytes == NULL || data->size == 0) return NULL;716717if (!InitMemBuffer(&mem, data->bytes, data->size)) return NULL;718status = ReadHeader(&mem);719if (status != PARSE_OK) {720// If parsing of the webp file header fails attempt to handle a raw721// VP8/VP8L frame. Note 'allow_partial' is ignored in this case.722if (status == PARSE_ERROR) {723status = CreateRawImageDemuxer(&mem, &dmux);724if (status == PARSE_OK) {725if (state != NULL) *state = WEBP_DEMUX_DONE;726return dmux;727}728}729if (state != NULL) {730*state = (status == PARSE_NEED_MORE_DATA) ? WEBP_DEMUX_PARSING_HEADER731: WEBP_DEMUX_PARSE_ERROR;732}733return NULL;734}735736partial = (mem.buf_size_ < mem.riff_end_);737if (!allow_partial && partial) return NULL;738739dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));740if (dmux == NULL) return NULL;741InitDemux(dmux, &mem);742743status = PARSE_ERROR;744for (parser = kMasterChunks; parser->parse != NULL; ++parser) {745if (!memcmp(parser->id, GetBuffer(&dmux->mem_), TAG_SIZE)) {746status = parser->parse(dmux);747if (status == PARSE_OK) dmux->state_ = WEBP_DEMUX_DONE;748if (status == PARSE_NEED_MORE_DATA && !partial) status = PARSE_ERROR;749if (status != PARSE_ERROR && !parser->valid(dmux)) status = PARSE_ERROR;750if (status == PARSE_ERROR) dmux->state_ = WEBP_DEMUX_PARSE_ERROR;751break;752}753}754if (state != NULL) *state = dmux->state_;755756if (status == PARSE_ERROR) {757WebPDemuxDelete(dmux);758return NULL;759}760return dmux;761}762763void WebPDemuxDelete(WebPDemuxer* dmux) {764Chunk* c;765Frame* f;766if (dmux == NULL) return;767768for (f = dmux->frames_; f != NULL;) {769Frame* const cur_frame = f;770f = f->next_;771WebPSafeFree(cur_frame);772}773for (c = dmux->chunks_; c != NULL;) {774Chunk* const cur_chunk = c;775c = c->next_;776WebPSafeFree(cur_chunk);777}778WebPSafeFree(dmux);779}780781// -----------------------------------------------------------------------------782783uint32_t WebPDemuxGetI(const WebPDemuxer* dmux, WebPFormatFeature feature) {784if (dmux == NULL) return 0;785786switch (feature) {787case WEBP_FF_FORMAT_FLAGS: return dmux->feature_flags_;788case WEBP_FF_CANVAS_WIDTH: return (uint32_t)dmux->canvas_width_;789case WEBP_FF_CANVAS_HEIGHT: return (uint32_t)dmux->canvas_height_;790case WEBP_FF_LOOP_COUNT: return (uint32_t)dmux->loop_count_;791case WEBP_FF_BACKGROUND_COLOR: return dmux->bgcolor_;792case WEBP_FF_FRAME_COUNT: return (uint32_t)dmux->num_frames_;793}794return 0;795}796797// -----------------------------------------------------------------------------798// Frame iteration799800static const Frame* GetFrame(const WebPDemuxer* const dmux, int frame_num) {801const Frame* f;802for (f = dmux->frames_; f != NULL; f = f->next_) {803if (frame_num == f->frame_num_) break;804}805return f;806}807808static const uint8_t* GetFramePayload(const uint8_t* const mem_buf,809const Frame* const frame,810size_t* const data_size) {811*data_size = 0;812if (frame != NULL) {813const ChunkData* const image = frame->img_components_;814const ChunkData* const alpha = frame->img_components_ + 1;815size_t start_offset = image->offset_;816*data_size = image->size_;817818// if alpha exists it precedes image, update the size allowing for819// intervening chunks.820if (alpha->size_ > 0) {821const size_t inter_size = (image->offset_ > 0)822? image->offset_ - (alpha->offset_ + alpha->size_)823: 0;824start_offset = alpha->offset_;825*data_size += alpha->size_ + inter_size;826}827return mem_buf + start_offset;828}829return NULL;830}831832// Create a whole 'frame' from VP8 (+ alpha) or lossless.833static int SynthesizeFrame(const WebPDemuxer* const dmux,834const Frame* const frame,835WebPIterator* const iter) {836const uint8_t* const mem_buf = dmux->mem_.buf_;837size_t payload_size = 0;838const uint8_t* const payload = GetFramePayload(mem_buf, frame, &payload_size);839if (payload == NULL) return 0;840assert(frame != NULL);841842iter->frame_num = frame->frame_num_;843iter->num_frames = dmux->num_frames_;844iter->x_offset = frame->x_offset_;845iter->y_offset = frame->y_offset_;846iter->width = frame->width_;847iter->height = frame->height_;848iter->has_alpha = frame->has_alpha_;849iter->duration = frame->duration_;850iter->dispose_method = frame->dispose_method_;851iter->blend_method = frame->blend_method_;852iter->complete = frame->complete_;853iter->fragment.bytes = payload;854iter->fragment.size = payload_size;855return 1;856}857858static int SetFrame(int frame_num, WebPIterator* const iter) {859const Frame* frame;860const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;861if (dmux == NULL || frame_num < 0) return 0;862if (frame_num > dmux->num_frames_) return 0;863if (frame_num == 0) frame_num = dmux->num_frames_;864865frame = GetFrame(dmux, frame_num);866if (frame == NULL) return 0;867868return SynthesizeFrame(dmux, frame, iter);869}870871int WebPDemuxGetFrame(const WebPDemuxer* dmux, int frame, WebPIterator* iter) {872if (iter == NULL) return 0;873874memset(iter, 0, sizeof(*iter));875iter->private_ = (void*)dmux;876return SetFrame(frame, iter);877}878879int WebPDemuxNextFrame(WebPIterator* iter) {880if (iter == NULL) return 0;881return SetFrame(iter->frame_num + 1, iter);882}883884int WebPDemuxPrevFrame(WebPIterator* iter) {885if (iter == NULL) return 0;886if (iter->frame_num <= 1) return 0;887return SetFrame(iter->frame_num - 1, iter);888}889890void WebPDemuxReleaseIterator(WebPIterator* iter) {891(void)iter;892}893894// -----------------------------------------------------------------------------895// Chunk iteration896897static int ChunkCount(const WebPDemuxer* const dmux, const char fourcc[4]) {898const uint8_t* const mem_buf = dmux->mem_.buf_;899const Chunk* c;900int count = 0;901for (c = dmux->chunks_; c != NULL; c = c->next_) {902const uint8_t* const header = mem_buf + c->data_.offset_;903if (!memcmp(header, fourcc, TAG_SIZE)) ++count;904}905return count;906}907908static const Chunk* GetChunk(const WebPDemuxer* const dmux,909const char fourcc[4], int chunk_num) {910const uint8_t* const mem_buf = dmux->mem_.buf_;911const Chunk* c;912int count = 0;913for (c = dmux->chunks_; c != NULL; c = c->next_) {914const uint8_t* const header = mem_buf + c->data_.offset_;915if (!memcmp(header, fourcc, TAG_SIZE)) ++count;916if (count == chunk_num) break;917}918return c;919}920921static int SetChunk(const char fourcc[4], int chunk_num,922WebPChunkIterator* const iter) {923const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;924int count;925926if (dmux == NULL || fourcc == NULL || chunk_num < 0) return 0;927count = ChunkCount(dmux, fourcc);928if (count == 0) return 0;929if (chunk_num == 0) chunk_num = count;930931if (chunk_num <= count) {932const uint8_t* const mem_buf = dmux->mem_.buf_;933const Chunk* const chunk = GetChunk(dmux, fourcc, chunk_num);934iter->chunk.bytes = mem_buf + chunk->data_.offset_ + CHUNK_HEADER_SIZE;935iter->chunk.size = chunk->data_.size_ - CHUNK_HEADER_SIZE;936iter->num_chunks = count;937iter->chunk_num = chunk_num;938return 1;939}940return 0;941}942943int WebPDemuxGetChunk(const WebPDemuxer* dmux,944const char fourcc[4], int chunk_num,945WebPChunkIterator* iter) {946if (iter == NULL) return 0;947948memset(iter, 0, sizeof(*iter));949iter->private_ = (void*)dmux;950return SetChunk(fourcc, chunk_num, iter);951}952953int WebPDemuxNextChunk(WebPChunkIterator* iter) {954if (iter != NULL) {955const char* const fourcc =956(const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;957return SetChunk(fourcc, iter->chunk_num + 1, iter);958}959return 0;960}961962int WebPDemuxPrevChunk(WebPChunkIterator* iter) {963if (iter != NULL && iter->chunk_num > 1) {964const char* const fourcc =965(const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;966return SetChunk(fourcc, iter->chunk_num - 1, iter);967}968return 0;969}970971void WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter) {972(void)iter;973}974975976977