Path: blob/master/3rdparty/libwebp/src/demux/demux.c
16349 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 027#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);223const uint32_t payload_size_padded = payload_size + (payload_size & 1);224const size_t payload_available = (payload_size_padded > MemDataSize(mem))225? MemDataSize(mem) : payload_size_padded;226const size_t chunk_size = CHUNK_HEADER_SIZE + payload_available;227228if (payload_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;229if (SizeIsInvalid(mem, payload_size_padded)) return PARSE_ERROR;230if (payload_size_padded > MemDataSize(mem)) status = PARSE_NEED_MORE_DATA;231232switch (fourcc) {233case MKFOURCC('A', 'L', 'P', 'H'):234if (alpha_chunks == 0) {235++alpha_chunks;236frame->img_components_[1].offset_ = chunk_start_offset;237frame->img_components_[1].size_ = chunk_size;238frame->has_alpha_ = 1;239frame->frame_num_ = frame_num;240Skip(mem, payload_available);241} else {242goto Done;243}244break;245case MKFOURCC('V', 'P', '8', 'L'):246if (alpha_chunks > 0) return PARSE_ERROR; // VP8L has its own alpha247// fall through248case MKFOURCC('V', 'P', '8', ' '):249if (image_chunks == 0) {250// Extract the bitstream features, tolerating failures when the data251// is incomplete.252WebPBitstreamFeatures features;253const VP8StatusCode vp8_status =254WebPGetFeatures(mem->buf_ + chunk_start_offset, chunk_size,255&features);256if (status == PARSE_NEED_MORE_DATA &&257vp8_status == VP8_STATUS_NOT_ENOUGH_DATA) {258return PARSE_NEED_MORE_DATA;259} else if (vp8_status != VP8_STATUS_OK) {260// We have enough data, and yet WebPGetFeatures() failed.261return PARSE_ERROR;262}263++image_chunks;264SetFrameInfo(chunk_start_offset, chunk_size, frame_num,265status == PARSE_OK, &features, frame);266Skip(mem, payload_available);267} else {268goto Done;269}270break;271Done:272default:273// Restore fourcc/size when moving up one level in parsing.274Rewind(mem, CHUNK_HEADER_SIZE);275done = 1;276break;277}278279if (mem->start_ == mem->riff_end_) {280done = 1;281} else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {282status = PARSE_NEED_MORE_DATA;283}284} while (!done && status == PARSE_OK);285286return status;287}288289// Creates a new Frame if 'actual_size' is within bounds and 'mem' contains290// enough data ('min_size') to parse the payload.291// Returns PARSE_OK on success with *frame pointing to the new Frame.292// Returns PARSE_NEED_MORE_DATA with insufficient data, PARSE_ERROR otherwise.293static ParseStatus NewFrame(const MemBuffer* const mem,294uint32_t min_size, uint32_t actual_size,295Frame** frame) {296if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;297if (actual_size < min_size) return PARSE_ERROR;298if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;299300*frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(**frame));301return (*frame == NULL) ? PARSE_ERROR : PARSE_OK;302}303304// Parse a 'ANMF' chunk and any image bearing chunks that immediately follow.305// 'frame_chunk_size' is the previously validated, padded chunk size.306static ParseStatus ParseAnimationFrame(307WebPDemuxer* const dmux, uint32_t frame_chunk_size) {308const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);309const uint32_t anmf_payload_size = frame_chunk_size - ANMF_CHUNK_SIZE;310int added_frame = 0;311int bits;312MemBuffer* const mem = &dmux->mem_;313Frame* frame;314ParseStatus status =315NewFrame(mem, ANMF_CHUNK_SIZE, frame_chunk_size, &frame);316if (status != PARSE_OK) return status;317318frame->x_offset_ = 2 * ReadLE24s(mem);319frame->y_offset_ = 2 * ReadLE24s(mem);320frame->width_ = 1 + ReadLE24s(mem);321frame->height_ = 1 + ReadLE24s(mem);322frame->duration_ = ReadLE24s(mem);323bits = ReadByte(mem);324frame->dispose_method_ =325(bits & 1) ? WEBP_MUX_DISPOSE_BACKGROUND : WEBP_MUX_DISPOSE_NONE;326frame->blend_method_ = (bits & 2) ? WEBP_MUX_NO_BLEND : WEBP_MUX_BLEND;327if (frame->width_ * (uint64_t)frame->height_ >= MAX_IMAGE_AREA) {328WebPSafeFree(frame);329return PARSE_ERROR;330}331332// Store a frame only if the animation flag is set there is some data for333// this frame is available.334status = StoreFrame(dmux->num_frames_ + 1, anmf_payload_size, mem, frame);335if (status != PARSE_ERROR && is_animation && frame->frame_num_ > 0) {336added_frame = AddFrame(dmux, frame);337if (added_frame) {338++dmux->num_frames_;339} else {340status = PARSE_ERROR;341}342}343344if (!added_frame) WebPSafeFree(frame);345return status;346}347348// General chunk storage, starting with the header at 'start_offset', allowing349// the user to request the payload via a fourcc string. 'size' includes the350// header and the unpadded payload size.351// Returns true on success, false otherwise.352static int StoreChunk(WebPDemuxer* const dmux,353size_t start_offset, uint32_t size) {354Chunk* const chunk = (Chunk*)WebPSafeCalloc(1ULL, sizeof(*chunk));355if (chunk == NULL) return 0;356357chunk->data_.offset_ = start_offset;358chunk->data_.size_ = size;359AddChunk(dmux, chunk);360return 1;361}362363// -----------------------------------------------------------------------------364// Primary chunk parsing365366static ParseStatus ReadHeader(MemBuffer* const mem) {367const size_t min_size = RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE;368uint32_t riff_size;369370// Basic file level validation.371if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;372if (memcmp(GetBuffer(mem), "RIFF", CHUNK_SIZE_BYTES) ||373memcmp(GetBuffer(mem) + CHUNK_HEADER_SIZE, "WEBP", CHUNK_SIZE_BYTES)) {374return PARSE_ERROR;375}376377riff_size = GetLE32(GetBuffer(mem) + TAG_SIZE);378if (riff_size < CHUNK_HEADER_SIZE) return PARSE_ERROR;379if (riff_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;380381// There's no point in reading past the end of the RIFF chunk382mem->riff_end_ = riff_size + CHUNK_HEADER_SIZE;383if (mem->buf_size_ > mem->riff_end_) {384mem->buf_size_ = mem->end_ = mem->riff_end_;385}386387Skip(mem, RIFF_HEADER_SIZE);388return PARSE_OK;389}390391static ParseStatus ParseSingleImage(WebPDemuxer* const dmux) {392const size_t min_size = CHUNK_HEADER_SIZE;393MemBuffer* const mem = &dmux->mem_;394Frame* frame;395ParseStatus status;396int image_added = 0;397398if (dmux->frames_ != NULL) return PARSE_ERROR;399if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;400if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;401402frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));403if (frame == NULL) return PARSE_ERROR;404405// For the single image case we allow parsing of a partial frame, so no406// minimum size is imposed here.407status = StoreFrame(1, 0, &dmux->mem_, frame);408if (status != PARSE_ERROR) {409const int has_alpha = !!(dmux->feature_flags_ & ALPHA_FLAG);410// Clear any alpha when the alpha flag is missing.411if (!has_alpha && frame->img_components_[1].size_ > 0) {412frame->img_components_[1].offset_ = 0;413frame->img_components_[1].size_ = 0;414frame->has_alpha_ = 0;415}416417// Use the frame width/height as the canvas values for non-vp8x files.418// Also, set ALPHA_FLAG if this is a lossless image with alpha.419if (!dmux->is_ext_format_ && frame->width_ > 0 && frame->height_ > 0) {420dmux->state_ = WEBP_DEMUX_PARSED_HEADER;421dmux->canvas_width_ = frame->width_;422dmux->canvas_height_ = frame->height_;423dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;424}425if (!AddFrame(dmux, frame)) {426status = PARSE_ERROR; // last frame was left incomplete427} else {428image_added = 1;429dmux->num_frames_ = 1;430}431}432433if (!image_added) WebPSafeFree(frame);434return status;435}436437static ParseStatus ParseVP8XChunks(WebPDemuxer* const dmux) {438const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);439MemBuffer* const mem = &dmux->mem_;440int anim_chunks = 0;441ParseStatus status = PARSE_OK;442443do {444int store_chunk = 1;445const size_t chunk_start_offset = mem->start_;446const uint32_t fourcc = ReadLE32(mem);447const uint32_t chunk_size = ReadLE32(mem);448const uint32_t chunk_size_padded = chunk_size + (chunk_size & 1);449450if (chunk_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;451if (SizeIsInvalid(mem, chunk_size_padded)) return PARSE_ERROR;452453switch (fourcc) {454case MKFOURCC('V', 'P', '8', 'X'): {455return PARSE_ERROR;456}457case MKFOURCC('A', 'L', 'P', 'H'):458case MKFOURCC('V', 'P', '8', ' '):459case MKFOURCC('V', 'P', '8', 'L'): {460// check that this isn't an animation (all frames should be in an ANMF).461if (anim_chunks > 0 || is_animation) return PARSE_ERROR;462463Rewind(mem, CHUNK_HEADER_SIZE);464status = ParseSingleImage(dmux);465break;466}467case MKFOURCC('A', 'N', 'I', 'M'): {468if (chunk_size_padded < ANIM_CHUNK_SIZE) return PARSE_ERROR;469470if (MemDataSize(mem) < chunk_size_padded) {471status = PARSE_NEED_MORE_DATA;472} else if (anim_chunks == 0) {473++anim_chunks;474dmux->bgcolor_ = ReadLE32(mem);475dmux->loop_count_ = ReadLE16s(mem);476Skip(mem, chunk_size_padded - ANIM_CHUNK_SIZE);477} else {478store_chunk = 0;479goto Skip;480}481break;482}483case MKFOURCC('A', 'N', 'M', 'F'): {484if (anim_chunks == 0) return PARSE_ERROR; // 'ANIM' precedes frames.485status = ParseAnimationFrame(dmux, chunk_size_padded);486break;487}488case MKFOURCC('I', 'C', 'C', 'P'): {489store_chunk = !!(dmux->feature_flags_ & ICCP_FLAG);490goto Skip;491}492case MKFOURCC('E', 'X', 'I', 'F'): {493store_chunk = !!(dmux->feature_flags_ & EXIF_FLAG);494goto Skip;495}496case MKFOURCC('X', 'M', 'P', ' '): {497store_chunk = !!(dmux->feature_flags_ & XMP_FLAG);498goto Skip;499}500Skip:501default: {502if (chunk_size_padded <= MemDataSize(mem)) {503if (store_chunk) {504// Store only the chunk header and unpadded size as only the payload505// will be returned to the user.506if (!StoreChunk(dmux, chunk_start_offset,507CHUNK_HEADER_SIZE + chunk_size)) {508return PARSE_ERROR;509}510}511Skip(mem, chunk_size_padded);512} else {513status = PARSE_NEED_MORE_DATA;514}515}516}517518if (mem->start_ == mem->riff_end_) {519break;520} else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {521status = PARSE_NEED_MORE_DATA;522}523} while (status == PARSE_OK);524525return status;526}527528static ParseStatus ParseVP8X(WebPDemuxer* const dmux) {529MemBuffer* const mem = &dmux->mem_;530uint32_t vp8x_size;531532if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;533534dmux->is_ext_format_ = 1;535Skip(mem, TAG_SIZE); // VP8X536vp8x_size = ReadLE32(mem);537if (vp8x_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;538if (vp8x_size < VP8X_CHUNK_SIZE) return PARSE_ERROR;539vp8x_size += vp8x_size & 1;540if (SizeIsInvalid(mem, vp8x_size)) return PARSE_ERROR;541if (MemDataSize(mem) < vp8x_size) return PARSE_NEED_MORE_DATA;542543dmux->feature_flags_ = ReadByte(mem);544Skip(mem, 3); // Reserved.545dmux->canvas_width_ = 1 + ReadLE24s(mem);546dmux->canvas_height_ = 1 + ReadLE24s(mem);547if (dmux->canvas_width_ * (uint64_t)dmux->canvas_height_ >= MAX_IMAGE_AREA) {548return PARSE_ERROR; // image final dimension is too large549}550Skip(mem, vp8x_size - VP8X_CHUNK_SIZE); // skip any trailing data.551dmux->state_ = WEBP_DEMUX_PARSED_HEADER;552553if (SizeIsInvalid(mem, CHUNK_HEADER_SIZE)) return PARSE_ERROR;554if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;555556return ParseVP8XChunks(dmux);557}558559// -----------------------------------------------------------------------------560// Format validation561562static int IsValidSimpleFormat(const WebPDemuxer* const dmux) {563const Frame* const frame = dmux->frames_;564if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;565566if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;567if (dmux->state_ == WEBP_DEMUX_DONE && frame == NULL) return 0;568569if (frame->width_ <= 0 || frame->height_ <= 0) return 0;570return 1;571}572573// If 'exact' is true, check that the image resolution matches the canvas.574// If 'exact' is false, check that the x/y offsets do not exceed the canvas.575static int CheckFrameBounds(const Frame* const frame, int exact,576int canvas_width, int canvas_height) {577if (exact) {578if (frame->x_offset_ != 0 || frame->y_offset_ != 0) {579return 0;580}581if (frame->width_ != canvas_width || frame->height_ != canvas_height) {582return 0;583}584} else {585if (frame->x_offset_ < 0 || frame->y_offset_ < 0) return 0;586if (frame->width_ + frame->x_offset_ > canvas_width) return 0;587if (frame->height_ + frame->y_offset_ > canvas_height) return 0;588}589return 1;590}591592static int IsValidExtendedFormat(const WebPDemuxer* const dmux) {593const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);594const Frame* f = dmux->frames_;595596if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;597598if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;599if (dmux->loop_count_ < 0) return 0;600if (dmux->state_ == WEBP_DEMUX_DONE && dmux->frames_ == NULL) return 0;601if (dmux->feature_flags_ & ~ALL_VALID_FLAGS) return 0; // invalid bitstream602603while (f != NULL) {604const int cur_frame_set = f->frame_num_;605int frame_count = 0;606607// Check frame properties.608for (; f != NULL && f->frame_num_ == cur_frame_set; f = f->next_) {609const ChunkData* const image = f->img_components_;610const ChunkData* const alpha = f->img_components_ + 1;611612if (!is_animation && f->frame_num_ > 1) return 0;613614if (f->complete_) {615if (alpha->size_ == 0 && image->size_ == 0) return 0;616// Ensure alpha precedes image bitstream.617if (alpha->size_ > 0 && alpha->offset_ > image->offset_) {618return 0;619}620621if (f->width_ <= 0 || f->height_ <= 0) return 0;622} else {623// There shouldn't be a partial frame in a complete file.624if (dmux->state_ == WEBP_DEMUX_DONE) return 0;625626// Ensure alpha precedes image bitstream.627if (alpha->size_ > 0 && image->size_ > 0 &&628alpha->offset_ > image->offset_) {629return 0;630}631// There shouldn't be any frames after an incomplete one.632if (f->next_ != NULL) return 0;633}634635if (f->width_ > 0 && f->height_ > 0 &&636!CheckFrameBounds(f, !is_animation,637dmux->canvas_width_, dmux->canvas_height_)) {638return 0;639}640641++frame_count;642}643}644return 1;645}646647// -----------------------------------------------------------------------------648// WebPDemuxer object649650static void InitDemux(WebPDemuxer* const dmux, const MemBuffer* const mem) {651dmux->state_ = WEBP_DEMUX_PARSING_HEADER;652dmux->loop_count_ = 1;653dmux->bgcolor_ = 0xFFFFFFFF; // White background by default.654dmux->canvas_width_ = -1;655dmux->canvas_height_ = -1;656dmux->frames_tail_ = &dmux->frames_;657dmux->chunks_tail_ = &dmux->chunks_;658dmux->mem_ = *mem;659}660661static ParseStatus CreateRawImageDemuxer(MemBuffer* const mem,662WebPDemuxer** demuxer) {663WebPBitstreamFeatures features;664const VP8StatusCode status =665WebPGetFeatures(mem->buf_, mem->buf_size_, &features);666*demuxer = NULL;667if (status != VP8_STATUS_OK) {668return (status == VP8_STATUS_NOT_ENOUGH_DATA) ? PARSE_NEED_MORE_DATA669: PARSE_ERROR;670}671672{673WebPDemuxer* const dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));674Frame* const frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));675if (dmux == NULL || frame == NULL) goto Error;676InitDemux(dmux, mem);677SetFrameInfo(0, mem->buf_size_, 1 /*frame_num*/, 1 /*complete*/, &features,678frame);679if (!AddFrame(dmux, frame)) goto Error;680dmux->state_ = WEBP_DEMUX_DONE;681dmux->canvas_width_ = frame->width_;682dmux->canvas_height_ = frame->height_;683dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;684dmux->num_frames_ = 1;685assert(IsValidSimpleFormat(dmux));686*demuxer = dmux;687return PARSE_OK;688689Error:690WebPSafeFree(dmux);691WebPSafeFree(frame);692return PARSE_ERROR;693}694}695696WebPDemuxer* WebPDemuxInternal(const WebPData* data, int allow_partial,697WebPDemuxState* state, int version) {698const ChunkParser* parser;699int partial;700ParseStatus status = PARSE_ERROR;701MemBuffer mem;702WebPDemuxer* dmux;703704if (state != NULL) *state = WEBP_DEMUX_PARSE_ERROR;705706if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_DEMUX_ABI_VERSION)) return NULL;707if (data == NULL || data->bytes == NULL || data->size == 0) return NULL;708709if (!InitMemBuffer(&mem, data->bytes, data->size)) return NULL;710status = ReadHeader(&mem);711if (status != PARSE_OK) {712// If parsing of the webp file header fails attempt to handle a raw713// VP8/VP8L frame. Note 'allow_partial' is ignored in this case.714if (status == PARSE_ERROR) {715status = CreateRawImageDemuxer(&mem, &dmux);716if (status == PARSE_OK) {717if (state != NULL) *state = WEBP_DEMUX_DONE;718return dmux;719}720}721if (state != NULL) {722*state = (status == PARSE_NEED_MORE_DATA) ? WEBP_DEMUX_PARSING_HEADER723: WEBP_DEMUX_PARSE_ERROR;724}725return NULL;726}727728partial = (mem.buf_size_ < mem.riff_end_);729if (!allow_partial && partial) return NULL;730731dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));732if (dmux == NULL) return NULL;733InitDemux(dmux, &mem);734735status = PARSE_ERROR;736for (parser = kMasterChunks; parser->parse != NULL; ++parser) {737if (!memcmp(parser->id, GetBuffer(&dmux->mem_), TAG_SIZE)) {738status = parser->parse(dmux);739if (status == PARSE_OK) dmux->state_ = WEBP_DEMUX_DONE;740if (status == PARSE_NEED_MORE_DATA && !partial) status = PARSE_ERROR;741if (status != PARSE_ERROR && !parser->valid(dmux)) status = PARSE_ERROR;742if (status == PARSE_ERROR) dmux->state_ = WEBP_DEMUX_PARSE_ERROR;743break;744}745}746if (state != NULL) *state = dmux->state_;747748if (status == PARSE_ERROR) {749WebPDemuxDelete(dmux);750return NULL;751}752return dmux;753}754755void WebPDemuxDelete(WebPDemuxer* dmux) {756Chunk* c;757Frame* f;758if (dmux == NULL) return;759760for (f = dmux->frames_; f != NULL;) {761Frame* const cur_frame = f;762f = f->next_;763WebPSafeFree(cur_frame);764}765for (c = dmux->chunks_; c != NULL;) {766Chunk* const cur_chunk = c;767c = c->next_;768WebPSafeFree(cur_chunk);769}770WebPSafeFree(dmux);771}772773// -----------------------------------------------------------------------------774775uint32_t WebPDemuxGetI(const WebPDemuxer* dmux, WebPFormatFeature feature) {776if (dmux == NULL) return 0;777778switch (feature) {779case WEBP_FF_FORMAT_FLAGS: return dmux->feature_flags_;780case WEBP_FF_CANVAS_WIDTH: return (uint32_t)dmux->canvas_width_;781case WEBP_FF_CANVAS_HEIGHT: return (uint32_t)dmux->canvas_height_;782case WEBP_FF_LOOP_COUNT: return (uint32_t)dmux->loop_count_;783case WEBP_FF_BACKGROUND_COLOR: return dmux->bgcolor_;784case WEBP_FF_FRAME_COUNT: return (uint32_t)dmux->num_frames_;785}786return 0;787}788789// -----------------------------------------------------------------------------790// Frame iteration791792static const Frame* GetFrame(const WebPDemuxer* const dmux, int frame_num) {793const Frame* f;794for (f = dmux->frames_; f != NULL; f = f->next_) {795if (frame_num == f->frame_num_) break;796}797return f;798}799800static const uint8_t* GetFramePayload(const uint8_t* const mem_buf,801const Frame* const frame,802size_t* const data_size) {803*data_size = 0;804if (frame != NULL) {805const ChunkData* const image = frame->img_components_;806const ChunkData* const alpha = frame->img_components_ + 1;807size_t start_offset = image->offset_;808*data_size = image->size_;809810// if alpha exists it precedes image, update the size allowing for811// intervening chunks.812if (alpha->size_ > 0) {813const size_t inter_size = (image->offset_ > 0)814? image->offset_ - (alpha->offset_ + alpha->size_)815: 0;816start_offset = alpha->offset_;817*data_size += alpha->size_ + inter_size;818}819return mem_buf + start_offset;820}821return NULL;822}823824// Create a whole 'frame' from VP8 (+ alpha) or lossless.825static int SynthesizeFrame(const WebPDemuxer* const dmux,826const Frame* const frame,827WebPIterator* const iter) {828const uint8_t* const mem_buf = dmux->mem_.buf_;829size_t payload_size = 0;830const uint8_t* const payload = GetFramePayload(mem_buf, frame, &payload_size);831if (payload == NULL) return 0;832assert(frame != NULL);833834iter->frame_num = frame->frame_num_;835iter->num_frames = dmux->num_frames_;836iter->x_offset = frame->x_offset_;837iter->y_offset = frame->y_offset_;838iter->width = frame->width_;839iter->height = frame->height_;840iter->has_alpha = frame->has_alpha_;841iter->duration = frame->duration_;842iter->dispose_method = frame->dispose_method_;843iter->blend_method = frame->blend_method_;844iter->complete = frame->complete_;845iter->fragment.bytes = payload;846iter->fragment.size = payload_size;847return 1;848}849850static int SetFrame(int frame_num, WebPIterator* const iter) {851const Frame* frame;852const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;853if (dmux == NULL || frame_num < 0) return 0;854if (frame_num > dmux->num_frames_) return 0;855if (frame_num == 0) frame_num = dmux->num_frames_;856857frame = GetFrame(dmux, frame_num);858if (frame == NULL) return 0;859860return SynthesizeFrame(dmux, frame, iter);861}862863int WebPDemuxGetFrame(const WebPDemuxer* dmux, int frame, WebPIterator* iter) {864if (iter == NULL) return 0;865866memset(iter, 0, sizeof(*iter));867iter->private_ = (void*)dmux;868return SetFrame(frame, iter);869}870871int WebPDemuxNextFrame(WebPIterator* iter) {872if (iter == NULL) return 0;873return SetFrame(iter->frame_num + 1, iter);874}875876int WebPDemuxPrevFrame(WebPIterator* iter) {877if (iter == NULL) return 0;878if (iter->frame_num <= 1) return 0;879return SetFrame(iter->frame_num - 1, iter);880}881882void WebPDemuxReleaseIterator(WebPIterator* iter) {883(void)iter;884}885886// -----------------------------------------------------------------------------887// Chunk iteration888889static int ChunkCount(const WebPDemuxer* const dmux, const char fourcc[4]) {890const uint8_t* const mem_buf = dmux->mem_.buf_;891const Chunk* c;892int count = 0;893for (c = dmux->chunks_; c != NULL; c = c->next_) {894const uint8_t* const header = mem_buf + c->data_.offset_;895if (!memcmp(header, fourcc, TAG_SIZE)) ++count;896}897return count;898}899900static const Chunk* GetChunk(const WebPDemuxer* const dmux,901const char fourcc[4], int chunk_num) {902const uint8_t* const mem_buf = dmux->mem_.buf_;903const Chunk* c;904int count = 0;905for (c = dmux->chunks_; c != NULL; c = c->next_) {906const uint8_t* const header = mem_buf + c->data_.offset_;907if (!memcmp(header, fourcc, TAG_SIZE)) ++count;908if (count == chunk_num) break;909}910return c;911}912913static int SetChunk(const char fourcc[4], int chunk_num,914WebPChunkIterator* const iter) {915const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;916int count;917918if (dmux == NULL || fourcc == NULL || chunk_num < 0) return 0;919count = ChunkCount(dmux, fourcc);920if (count == 0) return 0;921if (chunk_num == 0) chunk_num = count;922923if (chunk_num <= count) {924const uint8_t* const mem_buf = dmux->mem_.buf_;925const Chunk* const chunk = GetChunk(dmux, fourcc, chunk_num);926iter->chunk.bytes = mem_buf + chunk->data_.offset_ + CHUNK_HEADER_SIZE;927iter->chunk.size = chunk->data_.size_ - CHUNK_HEADER_SIZE;928iter->num_chunks = count;929iter->chunk_num = chunk_num;930return 1;931}932return 0;933}934935int WebPDemuxGetChunk(const WebPDemuxer* dmux,936const char fourcc[4], int chunk_num,937WebPChunkIterator* iter) {938if (iter == NULL) return 0;939940memset(iter, 0, sizeof(*iter));941iter->private_ = (void*)dmux;942return SetChunk(fourcc, chunk_num, iter);943}944945int WebPDemuxNextChunk(WebPChunkIterator* iter) {946if (iter != NULL) {947const char* const fourcc =948(const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;949return SetChunk(fourcc, iter->chunk_num + 1, iter);950}951return 0;952}953954int WebPDemuxPrevChunk(WebPChunkIterator* iter) {955if (iter != NULL && iter->chunk_num > 1) {956const char* const fourcc =957(const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;958return SetChunk(fourcc, iter->chunk_num - 1, iter);959}960return 0;961}962963void WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter) {964(void)iter;965}966967968969