• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 //  WebP container demux.
11 //
12 
13 #ifdef HAVE_CONFIG_H
14 #include "src/webp/config.h"
15 #endif
16 
17 #include <assert.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 #include "src/utils/utils.h"
22 #include "src/webp/decode.h"     // WebPGetFeatures
23 #include "src/webp/demux.h"
24 #include "src/webp/format_constants.h"
25 
26 #define DMUX_MAJ_VERSION 1
27 #define DMUX_MIN_VERSION 2
28 #define DMUX_REV_VERSION 0
29 
30 typedef struct {
31   size_t start_;        // start location of the data
32   size_t end_;          // end location
33   size_t riff_end_;     // riff chunk end location, can be > end_.
34   size_t buf_size_;     // size of the buffer
35   const uint8_t* buf_;
36 } MemBuffer;
37 
38 typedef struct {
39   size_t offset_;
40   size_t size_;
41 } ChunkData;
42 
43 typedef struct Frame {
44   int x_offset_, y_offset_;
45   int width_, height_;
46   int has_alpha_;
47   int duration_;
48   WebPMuxAnimDispose dispose_method_;
49   WebPMuxAnimBlend blend_method_;
50   int frame_num_;
51   int complete_;   // img_components_ contains a full image.
52   ChunkData img_components_[2];  // 0=VP8{,L} 1=ALPH
53   struct Frame* next_;
54 } Frame;
55 
56 typedef struct Chunk {
57   ChunkData data_;
58   struct Chunk* next_;
59 } Chunk;
60 
61 struct WebPDemuxer {
62   MemBuffer mem_;
63   WebPDemuxState state_;
64   int is_ext_format_;
65   uint32_t feature_flags_;
66   int canvas_width_, canvas_height_;
67   int loop_count_;
68   uint32_t bgcolor_;
69   int num_frames_;
70   Frame* frames_;
71   Frame** frames_tail_;
72   Chunk* chunks_;  // non-image chunks
73   Chunk** chunks_tail_;
74 };
75 
76 typedef enum {
77   PARSE_OK,
78   PARSE_NEED_MORE_DATA,
79   PARSE_ERROR
80 } ParseStatus;
81 
82 typedef struct ChunkParser {
83   uint8_t id[4];
84   ParseStatus (*parse)(WebPDemuxer* const dmux);
85   int (*valid)(const WebPDemuxer* const dmux);
86 } ChunkParser;
87 
88 static ParseStatus ParseSingleImage(WebPDemuxer* const dmux);
89 static ParseStatus ParseVP8X(WebPDemuxer* const dmux);
90 static int IsValidSimpleFormat(const WebPDemuxer* const dmux);
91 static int IsValidExtendedFormat(const WebPDemuxer* const dmux);
92 
93 static const ChunkParser kMasterChunks[] = {
94   { { 'V', 'P', '8', ' ' }, ParseSingleImage, IsValidSimpleFormat },
95   { { 'V', 'P', '8', 'L' }, ParseSingleImage, IsValidSimpleFormat },
96   { { 'V', 'P', '8', 'X' }, ParseVP8X,        IsValidExtendedFormat },
97   { { '0', '0', '0', '0' }, NULL,             NULL },
98 };
99 
100 //------------------------------------------------------------------------------
101 
WebPGetDemuxVersion(void)102 int WebPGetDemuxVersion(void) {
103   return (DMUX_MAJ_VERSION << 16) | (DMUX_MIN_VERSION << 8) | DMUX_REV_VERSION;
104 }
105 
106 // -----------------------------------------------------------------------------
107 // MemBuffer
108 
RemapMemBuffer(MemBuffer * const mem,const uint8_t * data,size_t size)109 static int RemapMemBuffer(MemBuffer* const mem,
110                           const uint8_t* data, size_t size) {
111   if (size < mem->buf_size_) return 0;  // can't remap to a shorter buffer!
112 
113   mem->buf_ = data;
114   mem->end_ = mem->buf_size_ = size;
115   return 1;
116 }
117 
InitMemBuffer(MemBuffer * const mem,const uint8_t * data,size_t size)118 static int InitMemBuffer(MemBuffer* const mem,
119                          const uint8_t* data, size_t size) {
120   memset(mem, 0, sizeof(*mem));
121   return RemapMemBuffer(mem, data, size);
122 }
123 
124 // Return the remaining data size available in 'mem'.
MemDataSize(const MemBuffer * const mem)125 static WEBP_INLINE size_t MemDataSize(const MemBuffer* const mem) {
126   return (mem->end_ - mem->start_);
127 }
128 
129 // Return true if 'size' exceeds the end of the RIFF chunk.
SizeIsInvalid(const MemBuffer * const mem,size_t size)130 static WEBP_INLINE int SizeIsInvalid(const MemBuffer* const mem, size_t size) {
131   return (size > mem->riff_end_ - mem->start_);
132 }
133 
Skip(MemBuffer * const mem,size_t size)134 static WEBP_INLINE void Skip(MemBuffer* const mem, size_t size) {
135   mem->start_ += size;
136 }
137 
Rewind(MemBuffer * const mem,size_t size)138 static WEBP_INLINE void Rewind(MemBuffer* const mem, size_t size) {
139   mem->start_ -= size;
140 }
141 
GetBuffer(MemBuffer * const mem)142 static WEBP_INLINE const uint8_t* GetBuffer(MemBuffer* const mem) {
143   return mem->buf_ + mem->start_;
144 }
145 
146 // Read from 'mem' and skip the read bytes.
ReadByte(MemBuffer * const mem)147 static WEBP_INLINE uint8_t ReadByte(MemBuffer* const mem) {
148   const uint8_t byte = mem->buf_[mem->start_];
149   Skip(mem, 1);
150   return byte;
151 }
152 
ReadLE16s(MemBuffer * const mem)153 static WEBP_INLINE int ReadLE16s(MemBuffer* const mem) {
154   const uint8_t* const data = mem->buf_ + mem->start_;
155   const int val = GetLE16(data);
156   Skip(mem, 2);
157   return val;
158 }
159 
ReadLE24s(MemBuffer * const mem)160 static WEBP_INLINE int ReadLE24s(MemBuffer* const mem) {
161   const uint8_t* const data = mem->buf_ + mem->start_;
162   const int val = GetLE24(data);
163   Skip(mem, 3);
164   return val;
165 }
166 
ReadLE32(MemBuffer * const mem)167 static WEBP_INLINE uint32_t ReadLE32(MemBuffer* const mem) {
168   const uint8_t* const data = mem->buf_ + mem->start_;
169   const uint32_t val = GetLE32(data);
170   Skip(mem, 4);
171   return val;
172 }
173 
174 // -----------------------------------------------------------------------------
175 // Secondary chunk parsing
176 
AddChunk(WebPDemuxer * const dmux,Chunk * const chunk)177 static void AddChunk(WebPDemuxer* const dmux, Chunk* const chunk) {
178   *dmux->chunks_tail_ = chunk;
179   chunk->next_ = NULL;
180   dmux->chunks_tail_ = &chunk->next_;
181 }
182 
183 // Add a frame to the end of the list, ensuring the last frame is complete.
184 // Returns true on success, false otherwise.
AddFrame(WebPDemuxer * const dmux,Frame * const frame)185 static int AddFrame(WebPDemuxer* const dmux, Frame* const frame) {
186   const Frame* const last_frame = *dmux->frames_tail_;
187   if (last_frame != NULL && !last_frame->complete_) return 0;
188 
189   *dmux->frames_tail_ = frame;
190   frame->next_ = NULL;
191   dmux->frames_tail_ = &frame->next_;
192   return 1;
193 }
194 
SetFrameInfo(size_t start_offset,size_t size,int frame_num,int complete,const WebPBitstreamFeatures * const features,Frame * const frame)195 static void SetFrameInfo(size_t start_offset, size_t size,
196                          int frame_num, int complete,
197                          const WebPBitstreamFeatures* const features,
198                          Frame* const frame) {
199   frame->img_components_[0].offset_ = start_offset;
200   frame->img_components_[0].size_ = size;
201   frame->width_ = features->width;
202   frame->height_ = features->height;
203   frame->has_alpha_ |= features->has_alpha;
204   frame->frame_num_ = frame_num;
205   frame->complete_ = complete;
206 }
207 
208 // Store image bearing chunks to 'frame'. 'min_size' is an optional size
209 // requirement, it may be zero.
StoreFrame(int frame_num,uint32_t min_size,MemBuffer * const mem,Frame * const frame)210 static ParseStatus StoreFrame(int frame_num, uint32_t min_size,
211                               MemBuffer* const mem, Frame* const frame) {
212   int alpha_chunks = 0;
213   int image_chunks = 0;
214   int done = (MemDataSize(mem) < CHUNK_HEADER_SIZE ||
215               MemDataSize(mem) < min_size);
216   ParseStatus status = PARSE_OK;
217 
218   if (done) return PARSE_NEED_MORE_DATA;
219 
220   do {
221     const size_t chunk_start_offset = mem->start_;
222     const uint32_t fourcc = ReadLE32(mem);
223     const uint32_t payload_size = ReadLE32(mem);
224     const uint32_t payload_size_padded = payload_size + (payload_size & 1);
225     const size_t payload_available = (payload_size_padded > MemDataSize(mem))
226                                    ? MemDataSize(mem) : payload_size_padded;
227     const size_t chunk_size = CHUNK_HEADER_SIZE + payload_available;
228 
229     if (payload_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
230     if (SizeIsInvalid(mem, payload_size_padded)) return PARSE_ERROR;
231     if (payload_size_padded > MemDataSize(mem)) status = PARSE_NEED_MORE_DATA;
232 
233     switch (fourcc) {
234       case MKFOURCC('A', 'L', 'P', 'H'):
235         if (alpha_chunks == 0) {
236           ++alpha_chunks;
237           frame->img_components_[1].offset_ = chunk_start_offset;
238           frame->img_components_[1].size_ = chunk_size;
239           frame->has_alpha_ = 1;
240           frame->frame_num_ = frame_num;
241           Skip(mem, payload_available);
242         } else {
243           goto Done;
244         }
245         break;
246       case MKFOURCC('V', 'P', '8', 'L'):
247         if (alpha_chunks > 0) return PARSE_ERROR;  // VP8L has its own alpha
248         // fall through
249       case MKFOURCC('V', 'P', '8', ' '):
250         if (image_chunks == 0) {
251           // Extract the bitstream features, tolerating failures when the data
252           // is incomplete.
253           WebPBitstreamFeatures features;
254           const VP8StatusCode vp8_status =
255               WebPGetFeatures(mem->buf_ + chunk_start_offset, chunk_size,
256                               &features);
257           if (status == PARSE_NEED_MORE_DATA &&
258               vp8_status == VP8_STATUS_NOT_ENOUGH_DATA) {
259             return PARSE_NEED_MORE_DATA;
260           } else if (vp8_status != VP8_STATUS_OK) {
261             // We have enough data, and yet WebPGetFeatures() failed.
262             return PARSE_ERROR;
263           }
264           ++image_chunks;
265           SetFrameInfo(chunk_start_offset, chunk_size, frame_num,
266                        status == PARSE_OK, &features, frame);
267           Skip(mem, payload_available);
268         } else {
269           goto Done;
270         }
271         break;
272  Done:
273       default:
274         // Restore fourcc/size when moving up one level in parsing.
275         Rewind(mem, CHUNK_HEADER_SIZE);
276         done = 1;
277         break;
278     }
279 
280     if (mem->start_ == mem->riff_end_) {
281       done = 1;
282     } else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {
283       status = PARSE_NEED_MORE_DATA;
284     }
285   } while (!done && status == PARSE_OK);
286 
287   return status;
288 }
289 
290 // Creates a new Frame if 'actual_size' is within bounds and 'mem' contains
291 // enough data ('min_size') to parse the payload.
292 // Returns PARSE_OK on success with *frame pointing to the new Frame.
293 // Returns PARSE_NEED_MORE_DATA with insufficient data, PARSE_ERROR otherwise.
NewFrame(const MemBuffer * const mem,uint32_t min_size,uint32_t actual_size,Frame ** frame)294 static ParseStatus NewFrame(const MemBuffer* const mem,
295                             uint32_t min_size, uint32_t actual_size,
296                             Frame** frame) {
297   if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;
298   if (actual_size < min_size) return PARSE_ERROR;
299   if (MemDataSize(mem) < min_size)  return PARSE_NEED_MORE_DATA;
300 
301   *frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(**frame));
302   return (*frame == NULL) ? PARSE_ERROR : PARSE_OK;
303 }
304 
305 // Parse a 'ANMF' chunk and any image bearing chunks that immediately follow.
306 // 'frame_chunk_size' is the previously validated, padded chunk size.
ParseAnimationFrame(WebPDemuxer * const dmux,uint32_t frame_chunk_size)307 static ParseStatus ParseAnimationFrame(
308     WebPDemuxer* const dmux, uint32_t frame_chunk_size) {
309   const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);
310   const uint32_t anmf_payload_size = frame_chunk_size - ANMF_CHUNK_SIZE;
311   int added_frame = 0;
312   int bits;
313   MemBuffer* const mem = &dmux->mem_;
314   Frame* frame;
315   size_t start_offset;
316   ParseStatus status =
317       NewFrame(mem, ANMF_CHUNK_SIZE, frame_chunk_size, &frame);
318   if (status != PARSE_OK) return status;
319 
320   frame->x_offset_       = 2 * ReadLE24s(mem);
321   frame->y_offset_       = 2 * ReadLE24s(mem);
322   frame->width_          = 1 + ReadLE24s(mem);
323   frame->height_         = 1 + ReadLE24s(mem);
324   frame->duration_       = ReadLE24s(mem);
325   bits = ReadByte(mem);
326   frame->dispose_method_ =
327       (bits & 1) ? WEBP_MUX_DISPOSE_BACKGROUND : WEBP_MUX_DISPOSE_NONE;
328   frame->blend_method_ = (bits & 2) ? WEBP_MUX_NO_BLEND : WEBP_MUX_BLEND;
329   if (frame->width_ * (uint64_t)frame->height_ >= MAX_IMAGE_AREA) {
330     WebPSafeFree(frame);
331     return PARSE_ERROR;
332   }
333 
334   // Store a frame only if the animation flag is set there is some data for
335   // this frame is available.
336   start_offset = mem->start_;
337   status = StoreFrame(dmux->num_frames_ + 1, anmf_payload_size, mem, frame);
338   if (status != PARSE_ERROR && mem->start_ - start_offset > anmf_payload_size) {
339     status = PARSE_ERROR;
340   }
341   if (status != PARSE_ERROR && is_animation && frame->frame_num_ > 0) {
342     added_frame = AddFrame(dmux, frame);
343     if (added_frame) {
344       ++dmux->num_frames_;
345     } else {
346       status = PARSE_ERROR;
347     }
348   }
349 
350   if (!added_frame) WebPSafeFree(frame);
351   return status;
352 }
353 
354 // General chunk storage, starting with the header at 'start_offset', allowing
355 // the user to request the payload via a fourcc string. 'size' includes the
356 // header and the unpadded payload size.
357 // Returns true on success, false otherwise.
StoreChunk(WebPDemuxer * const dmux,size_t start_offset,uint32_t size)358 static int StoreChunk(WebPDemuxer* const dmux,
359                       size_t start_offset, uint32_t size) {
360   Chunk* const chunk = (Chunk*)WebPSafeCalloc(1ULL, sizeof(*chunk));
361   if (chunk == NULL) return 0;
362 
363   chunk->data_.offset_ = start_offset;
364   chunk->data_.size_ = size;
365   AddChunk(dmux, chunk);
366   return 1;
367 }
368 
369 // -----------------------------------------------------------------------------
370 // Primary chunk parsing
371 
ReadHeader(MemBuffer * const mem)372 static ParseStatus ReadHeader(MemBuffer* const mem) {
373   const size_t min_size = RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE;
374   uint32_t riff_size;
375 
376   // Basic file level validation.
377   if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;
378   if (memcmp(GetBuffer(mem), "RIFF", CHUNK_SIZE_BYTES) ||
379       memcmp(GetBuffer(mem) + CHUNK_HEADER_SIZE, "WEBP", CHUNK_SIZE_BYTES)) {
380     return PARSE_ERROR;
381   }
382 
383   riff_size = GetLE32(GetBuffer(mem) + TAG_SIZE);
384   if (riff_size < CHUNK_HEADER_SIZE) return PARSE_ERROR;
385   if (riff_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
386 
387   // There's no point in reading past the end of the RIFF chunk
388   mem->riff_end_ = riff_size + CHUNK_HEADER_SIZE;
389   if (mem->buf_size_ > mem->riff_end_) {
390     mem->buf_size_ = mem->end_ = mem->riff_end_;
391   }
392 
393   Skip(mem, RIFF_HEADER_SIZE);
394   return PARSE_OK;
395 }
396 
ParseSingleImage(WebPDemuxer * const dmux)397 static ParseStatus ParseSingleImage(WebPDemuxer* const dmux) {
398   const size_t min_size = CHUNK_HEADER_SIZE;
399   MemBuffer* const mem = &dmux->mem_;
400   Frame* frame;
401   ParseStatus status;
402   int image_added = 0;
403 
404   if (dmux->frames_ != NULL) return PARSE_ERROR;
405   if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;
406   if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;
407 
408   frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));
409   if (frame == NULL) return PARSE_ERROR;
410 
411   // For the single image case we allow parsing of a partial frame, so no
412   // minimum size is imposed here.
413   status = StoreFrame(1, 0, &dmux->mem_, frame);
414   if (status != PARSE_ERROR) {
415     const int has_alpha = !!(dmux->feature_flags_ & ALPHA_FLAG);
416     // Clear any alpha when the alpha flag is missing.
417     if (!has_alpha && frame->img_components_[1].size_ > 0) {
418       frame->img_components_[1].offset_ = 0;
419       frame->img_components_[1].size_ = 0;
420       frame->has_alpha_ = 0;
421     }
422 
423     // Use the frame width/height as the canvas values for non-vp8x files.
424     // Also, set ALPHA_FLAG if this is a lossless image with alpha.
425     if (!dmux->is_ext_format_ && frame->width_ > 0 && frame->height_ > 0) {
426       dmux->state_ = WEBP_DEMUX_PARSED_HEADER;
427       dmux->canvas_width_ = frame->width_;
428       dmux->canvas_height_ = frame->height_;
429       dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;
430     }
431     if (!AddFrame(dmux, frame)) {
432       status = PARSE_ERROR;  // last frame was left incomplete
433     } else {
434       image_added = 1;
435       dmux->num_frames_ = 1;
436     }
437   }
438 
439   if (!image_added) WebPSafeFree(frame);
440   return status;
441 }
442 
ParseVP8XChunks(WebPDemuxer * const dmux)443 static ParseStatus ParseVP8XChunks(WebPDemuxer* const dmux) {
444   const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);
445   MemBuffer* const mem = &dmux->mem_;
446   int anim_chunks = 0;
447   ParseStatus status = PARSE_OK;
448 
449   do {
450     int store_chunk = 1;
451     const size_t chunk_start_offset = mem->start_;
452     const uint32_t fourcc = ReadLE32(mem);
453     const uint32_t chunk_size = ReadLE32(mem);
454     const uint32_t chunk_size_padded = chunk_size + (chunk_size & 1);
455 
456     if (chunk_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
457     if (SizeIsInvalid(mem, chunk_size_padded)) return PARSE_ERROR;
458 
459     switch (fourcc) {
460       case MKFOURCC('V', 'P', '8', 'X'): {
461         return PARSE_ERROR;
462       }
463       case MKFOURCC('A', 'L', 'P', 'H'):
464       case MKFOURCC('V', 'P', '8', ' '):
465       case MKFOURCC('V', 'P', '8', 'L'): {
466         // check that this isn't an animation (all frames should be in an ANMF).
467         if (anim_chunks > 0 || is_animation) return PARSE_ERROR;
468 
469         Rewind(mem, CHUNK_HEADER_SIZE);
470         status = ParseSingleImage(dmux);
471         break;
472       }
473       case MKFOURCC('A', 'N', 'I', 'M'): {
474         if (chunk_size_padded < ANIM_CHUNK_SIZE) return PARSE_ERROR;
475 
476         if (MemDataSize(mem) < chunk_size_padded) {
477           status = PARSE_NEED_MORE_DATA;
478         } else if (anim_chunks == 0) {
479           ++anim_chunks;
480           dmux->bgcolor_ = ReadLE32(mem);
481           dmux->loop_count_ = ReadLE16s(mem);
482           Skip(mem, chunk_size_padded - ANIM_CHUNK_SIZE);
483         } else {
484           store_chunk = 0;
485           goto Skip;
486         }
487         break;
488       }
489       case MKFOURCC('A', 'N', 'M', 'F'): {
490         if (anim_chunks == 0) return PARSE_ERROR;  // 'ANIM' precedes frames.
491         status = ParseAnimationFrame(dmux, chunk_size_padded);
492         break;
493       }
494       case MKFOURCC('I', 'C', 'C', 'P'): {
495         store_chunk = !!(dmux->feature_flags_ & ICCP_FLAG);
496         goto Skip;
497       }
498       case MKFOURCC('E', 'X', 'I', 'F'): {
499         store_chunk = !!(dmux->feature_flags_ & EXIF_FLAG);
500         goto Skip;
501       }
502       case MKFOURCC('X', 'M', 'P', ' '): {
503         store_chunk = !!(dmux->feature_flags_ & XMP_FLAG);
504         goto Skip;
505       }
506  Skip:
507       default: {
508         if (chunk_size_padded <= MemDataSize(mem)) {
509           if (store_chunk) {
510             // Store only the chunk header and unpadded size as only the payload
511             // will be returned to the user.
512             if (!StoreChunk(dmux, chunk_start_offset,
513                             CHUNK_HEADER_SIZE + chunk_size)) {
514               return PARSE_ERROR;
515             }
516           }
517           Skip(mem, chunk_size_padded);
518         } else {
519           status = PARSE_NEED_MORE_DATA;
520         }
521       }
522     }
523 
524     if (mem->start_ == mem->riff_end_) {
525       break;
526     } else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {
527       status = PARSE_NEED_MORE_DATA;
528     }
529   } while (status == PARSE_OK);
530 
531   return status;
532 }
533 
ParseVP8X(WebPDemuxer * const dmux)534 static ParseStatus ParseVP8X(WebPDemuxer* const dmux) {
535   MemBuffer* const mem = &dmux->mem_;
536   uint32_t vp8x_size;
537 
538   if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;
539 
540   dmux->is_ext_format_ = 1;
541   Skip(mem, TAG_SIZE);  // VP8X
542   vp8x_size = ReadLE32(mem);
543   if (vp8x_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
544   if (vp8x_size < VP8X_CHUNK_SIZE) return PARSE_ERROR;
545   vp8x_size += vp8x_size & 1;
546   if (SizeIsInvalid(mem, vp8x_size)) return PARSE_ERROR;
547   if (MemDataSize(mem) < vp8x_size) return PARSE_NEED_MORE_DATA;
548 
549   dmux->feature_flags_ = ReadByte(mem);
550   Skip(mem, 3);  // Reserved.
551   dmux->canvas_width_  = 1 + ReadLE24s(mem);
552   dmux->canvas_height_ = 1 + ReadLE24s(mem);
553   if (dmux->canvas_width_ * (uint64_t)dmux->canvas_height_ >= MAX_IMAGE_AREA) {
554     return PARSE_ERROR;  // image final dimension is too large
555   }
556   Skip(mem, vp8x_size - VP8X_CHUNK_SIZE);  // skip any trailing data.
557   dmux->state_ = WEBP_DEMUX_PARSED_HEADER;
558 
559   if (SizeIsInvalid(mem, CHUNK_HEADER_SIZE)) return PARSE_ERROR;
560   if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;
561 
562   return ParseVP8XChunks(dmux);
563 }
564 
565 // -----------------------------------------------------------------------------
566 // Format validation
567 
IsValidSimpleFormat(const WebPDemuxer * const dmux)568 static int IsValidSimpleFormat(const WebPDemuxer* const dmux) {
569   const Frame* const frame = dmux->frames_;
570   if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;
571 
572   if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;
573   if (dmux->state_ == WEBP_DEMUX_DONE && frame == NULL) return 0;
574 
575   if (frame->width_ <= 0 || frame->height_ <= 0) return 0;
576   return 1;
577 }
578 
579 // If 'exact' is true, check that the image resolution matches the canvas.
580 // If 'exact' is false, check that the x/y offsets do not exceed the canvas.
CheckFrameBounds(const Frame * const frame,int exact,int canvas_width,int canvas_height)581 static int CheckFrameBounds(const Frame* const frame, int exact,
582                             int canvas_width, int canvas_height) {
583   if (exact) {
584     if (frame->x_offset_ != 0 || frame->y_offset_ != 0) {
585       return 0;
586     }
587     if (frame->width_ != canvas_width || frame->height_ != canvas_height) {
588       return 0;
589     }
590   } else {
591     if (frame->x_offset_ < 0 || frame->y_offset_ < 0) return 0;
592     if (frame->width_ + frame->x_offset_ > canvas_width) return 0;
593     if (frame->height_ + frame->y_offset_ > canvas_height) return 0;
594   }
595   return 1;
596 }
597 
IsValidExtendedFormat(const WebPDemuxer * const dmux)598 static int IsValidExtendedFormat(const WebPDemuxer* const dmux) {
599   const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);
600   const Frame* f = dmux->frames_;
601 
602   if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;
603 
604   if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;
605   if (dmux->loop_count_ < 0) return 0;
606   if (dmux->state_ == WEBP_DEMUX_DONE && dmux->frames_ == NULL) return 0;
607   if (dmux->feature_flags_ & ~ALL_VALID_FLAGS) return 0;  // invalid bitstream
608 
609   while (f != NULL) {
610     const int cur_frame_set = f->frame_num_;
611     int frame_count = 0;
612 
613     // Check frame properties.
614     for (; f != NULL && f->frame_num_ == cur_frame_set; f = f->next_) {
615       const ChunkData* const image = f->img_components_;
616       const ChunkData* const alpha = f->img_components_ + 1;
617 
618       if (!is_animation && f->frame_num_ > 1) return 0;
619 
620       if (f->complete_) {
621         if (alpha->size_ == 0 && image->size_ == 0) return 0;
622         // Ensure alpha precedes image bitstream.
623         if (alpha->size_ > 0 && alpha->offset_ > image->offset_) {
624           return 0;
625         }
626 
627         if (f->width_ <= 0 || f->height_ <= 0) return 0;
628       } else {
629         // There shouldn't be a partial frame in a complete file.
630         if (dmux->state_ == WEBP_DEMUX_DONE) return 0;
631 
632         // Ensure alpha precedes image bitstream.
633         if (alpha->size_ > 0 && image->size_ > 0 &&
634             alpha->offset_ > image->offset_) {
635           return 0;
636         }
637         // There shouldn't be any frames after an incomplete one.
638         if (f->next_ != NULL) return 0;
639       }
640 
641       if (f->width_ > 0 && f->height_ > 0 &&
642           !CheckFrameBounds(f, !is_animation,
643                             dmux->canvas_width_, dmux->canvas_height_)) {
644         return 0;
645       }
646 
647       ++frame_count;
648     }
649   }
650   return 1;
651 }
652 
653 // -----------------------------------------------------------------------------
654 // WebPDemuxer object
655 
InitDemux(WebPDemuxer * const dmux,const MemBuffer * const mem)656 static void InitDemux(WebPDemuxer* const dmux, const MemBuffer* const mem) {
657   dmux->state_ = WEBP_DEMUX_PARSING_HEADER;
658   dmux->loop_count_ = 1;
659   dmux->bgcolor_ = 0xFFFFFFFF;  // White background by default.
660   dmux->canvas_width_ = -1;
661   dmux->canvas_height_ = -1;
662   dmux->frames_tail_ = &dmux->frames_;
663   dmux->chunks_tail_ = &dmux->chunks_;
664   dmux->mem_ = *mem;
665 }
666 
CreateRawImageDemuxer(MemBuffer * const mem,WebPDemuxer ** demuxer)667 static ParseStatus CreateRawImageDemuxer(MemBuffer* const mem,
668                                          WebPDemuxer** demuxer) {
669   WebPBitstreamFeatures features;
670   const VP8StatusCode status =
671       WebPGetFeatures(mem->buf_, mem->buf_size_, &features);
672   *demuxer = NULL;
673   if (status != VP8_STATUS_OK) {
674     return (status == VP8_STATUS_NOT_ENOUGH_DATA) ? PARSE_NEED_MORE_DATA
675                                                   : PARSE_ERROR;
676   }
677 
678   {
679     WebPDemuxer* const dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));
680     Frame* const frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));
681     if (dmux == NULL || frame == NULL) goto Error;
682     InitDemux(dmux, mem);
683     SetFrameInfo(0, mem->buf_size_, 1 /*frame_num*/, 1 /*complete*/, &features,
684                  frame);
685     if (!AddFrame(dmux, frame)) goto Error;
686     dmux->state_ = WEBP_DEMUX_DONE;
687     dmux->canvas_width_ = frame->width_;
688     dmux->canvas_height_ = frame->height_;
689     dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;
690     dmux->num_frames_ = 1;
691     assert(IsValidSimpleFormat(dmux));
692     *demuxer = dmux;
693     return PARSE_OK;
694 
695  Error:
696     WebPSafeFree(dmux);
697     WebPSafeFree(frame);
698     return PARSE_ERROR;
699   }
700 }
701 
WebPDemuxInternal(const WebPData * data,int allow_partial,WebPDemuxState * state,int version)702 WebPDemuxer* WebPDemuxInternal(const WebPData* data, int allow_partial,
703                                WebPDemuxState* state, int version) {
704   const ChunkParser* parser;
705   int partial;
706   ParseStatus status = PARSE_ERROR;
707   MemBuffer mem;
708   WebPDemuxer* dmux;
709 
710   if (state != NULL) *state = WEBP_DEMUX_PARSE_ERROR;
711 
712   if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_DEMUX_ABI_VERSION)) return NULL;
713   if (data == NULL || data->bytes == NULL || data->size == 0) return NULL;
714 
715   if (!InitMemBuffer(&mem, data->bytes, data->size)) return NULL;
716   status = ReadHeader(&mem);
717   if (status != PARSE_OK) {
718     // If parsing of the webp file header fails attempt to handle a raw
719     // VP8/VP8L frame. Note 'allow_partial' is ignored in this case.
720     if (status == PARSE_ERROR) {
721       status = CreateRawImageDemuxer(&mem, &dmux);
722       if (status == PARSE_OK) {
723         if (state != NULL) *state = WEBP_DEMUX_DONE;
724         return dmux;
725       }
726     }
727     if (state != NULL) {
728       *state = (status == PARSE_NEED_MORE_DATA) ? WEBP_DEMUX_PARSING_HEADER
729                                                 : WEBP_DEMUX_PARSE_ERROR;
730     }
731     return NULL;
732   }
733 
734   partial = (mem.buf_size_ < mem.riff_end_);
735   if (!allow_partial && partial) return NULL;
736 
737   dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));
738   if (dmux == NULL) return NULL;
739   InitDemux(dmux, &mem);
740 
741   status = PARSE_ERROR;
742   for (parser = kMasterChunks; parser->parse != NULL; ++parser) {
743     if (!memcmp(parser->id, GetBuffer(&dmux->mem_), TAG_SIZE)) {
744       status = parser->parse(dmux);
745       if (status == PARSE_OK) dmux->state_ = WEBP_DEMUX_DONE;
746       if (status == PARSE_NEED_MORE_DATA && !partial) status = PARSE_ERROR;
747       if (status != PARSE_ERROR && !parser->valid(dmux)) status = PARSE_ERROR;
748       if (status == PARSE_ERROR) dmux->state_ = WEBP_DEMUX_PARSE_ERROR;
749       break;
750     }
751   }
752   if (state != NULL) *state = dmux->state_;
753 
754   if (status == PARSE_ERROR) {
755     WebPDemuxDelete(dmux);
756     return NULL;
757   }
758   return dmux;
759 }
760 
WebPDemuxDelete(WebPDemuxer * dmux)761 void WebPDemuxDelete(WebPDemuxer* dmux) {
762   Chunk* c;
763   Frame* f;
764   if (dmux == NULL) return;
765 
766   for (f = dmux->frames_; f != NULL;) {
767     Frame* const cur_frame = f;
768     f = f->next_;
769     WebPSafeFree(cur_frame);
770   }
771   for (c = dmux->chunks_; c != NULL;) {
772     Chunk* const cur_chunk = c;
773     c = c->next_;
774     WebPSafeFree(cur_chunk);
775   }
776   WebPSafeFree(dmux);
777 }
778 
779 // -----------------------------------------------------------------------------
780 
WebPDemuxGetI(const WebPDemuxer * dmux,WebPFormatFeature feature)781 uint32_t WebPDemuxGetI(const WebPDemuxer* dmux, WebPFormatFeature feature) {
782   if (dmux == NULL) return 0;
783 
784   switch (feature) {
785     case WEBP_FF_FORMAT_FLAGS:     return dmux->feature_flags_;
786     case WEBP_FF_CANVAS_WIDTH:     return (uint32_t)dmux->canvas_width_;
787     case WEBP_FF_CANVAS_HEIGHT:    return (uint32_t)dmux->canvas_height_;
788     case WEBP_FF_LOOP_COUNT:       return (uint32_t)dmux->loop_count_;
789     case WEBP_FF_BACKGROUND_COLOR: return dmux->bgcolor_;
790     case WEBP_FF_FRAME_COUNT:      return (uint32_t)dmux->num_frames_;
791   }
792   return 0;
793 }
794 
795 // -----------------------------------------------------------------------------
796 // Frame iteration
797 
GetFrame(const WebPDemuxer * const dmux,int frame_num)798 static const Frame* GetFrame(const WebPDemuxer* const dmux, int frame_num) {
799   const Frame* f;
800   for (f = dmux->frames_; f != NULL; f = f->next_) {
801     if (frame_num == f->frame_num_) break;
802   }
803   return f;
804 }
805 
GetFramePayload(const uint8_t * const mem_buf,const Frame * const frame,size_t * const data_size)806 static const uint8_t* GetFramePayload(const uint8_t* const mem_buf,
807                                       const Frame* const frame,
808                                       size_t* const data_size) {
809   *data_size = 0;
810   if (frame != NULL) {
811     const ChunkData* const image = frame->img_components_;
812     const ChunkData* const alpha = frame->img_components_ + 1;
813     size_t start_offset = image->offset_;
814     *data_size = image->size_;
815 
816     // if alpha exists it precedes image, update the size allowing for
817     // intervening chunks.
818     if (alpha->size_ > 0) {
819       const size_t inter_size = (image->offset_ > 0)
820                               ? image->offset_ - (alpha->offset_ + alpha->size_)
821                               : 0;
822       start_offset = alpha->offset_;
823       *data_size  += alpha->size_ + inter_size;
824     }
825     return mem_buf + start_offset;
826   }
827   return NULL;
828 }
829 
830 // Create a whole 'frame' from VP8 (+ alpha) or lossless.
SynthesizeFrame(const WebPDemuxer * const dmux,const Frame * const frame,WebPIterator * const iter)831 static int SynthesizeFrame(const WebPDemuxer* const dmux,
832                            const Frame* const frame,
833                            WebPIterator* const iter) {
834   const uint8_t* const mem_buf = dmux->mem_.buf_;
835   size_t payload_size = 0;
836   const uint8_t* const payload = GetFramePayload(mem_buf, frame, &payload_size);
837   if (payload == NULL) return 0;
838   assert(frame != NULL);
839 
840   iter->frame_num      = frame->frame_num_;
841   iter->num_frames     = dmux->num_frames_;
842   iter->x_offset       = frame->x_offset_;
843   iter->y_offset       = frame->y_offset_;
844   iter->width          = frame->width_;
845   iter->height         = frame->height_;
846   iter->has_alpha      = frame->has_alpha_;
847   iter->duration       = frame->duration_;
848   iter->dispose_method = frame->dispose_method_;
849   iter->blend_method   = frame->blend_method_;
850   iter->complete       = frame->complete_;
851   iter->fragment.bytes = payload;
852   iter->fragment.size  = payload_size;
853   return 1;
854 }
855 
SetFrame(int frame_num,WebPIterator * const iter)856 static int SetFrame(int frame_num, WebPIterator* const iter) {
857   const Frame* frame;
858   const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;
859   if (dmux == NULL || frame_num < 0) return 0;
860   if (frame_num > dmux->num_frames_) return 0;
861   if (frame_num == 0) frame_num = dmux->num_frames_;
862 
863   frame = GetFrame(dmux, frame_num);
864   if (frame == NULL) return 0;
865 
866   return SynthesizeFrame(dmux, frame, iter);
867 }
868 
WebPDemuxGetFrame(const WebPDemuxer * dmux,int frame,WebPIterator * iter)869 int WebPDemuxGetFrame(const WebPDemuxer* dmux, int frame, WebPIterator* iter) {
870   if (iter == NULL) return 0;
871 
872   memset(iter, 0, sizeof(*iter));
873   iter->private_ = (void*)dmux;
874   return SetFrame(frame, iter);
875 }
876 
WebPDemuxNextFrame(WebPIterator * iter)877 int WebPDemuxNextFrame(WebPIterator* iter) {
878   if (iter == NULL) return 0;
879   return SetFrame(iter->frame_num + 1, iter);
880 }
881 
WebPDemuxPrevFrame(WebPIterator * iter)882 int WebPDemuxPrevFrame(WebPIterator* iter) {
883   if (iter == NULL) return 0;
884   if (iter->frame_num <= 1) return 0;
885   return SetFrame(iter->frame_num - 1, iter);
886 }
887 
WebPDemuxReleaseIterator(WebPIterator * iter)888 void WebPDemuxReleaseIterator(WebPIterator* iter) {
889   (void)iter;
890 }
891 
892 // -----------------------------------------------------------------------------
893 // Chunk iteration
894 
ChunkCount(const WebPDemuxer * const dmux,const char fourcc[4])895 static int ChunkCount(const WebPDemuxer* const dmux, const char fourcc[4]) {
896   const uint8_t* const mem_buf = dmux->mem_.buf_;
897   const Chunk* c;
898   int count = 0;
899   for (c = dmux->chunks_; c != NULL; c = c->next_) {
900     const uint8_t* const header = mem_buf + c->data_.offset_;
901     if (!memcmp(header, fourcc, TAG_SIZE)) ++count;
902   }
903   return count;
904 }
905 
GetChunk(const WebPDemuxer * const dmux,const char fourcc[4],int chunk_num)906 static const Chunk* GetChunk(const WebPDemuxer* const dmux,
907                              const char fourcc[4], int chunk_num) {
908   const uint8_t* const mem_buf = dmux->mem_.buf_;
909   const Chunk* c;
910   int count = 0;
911   for (c = dmux->chunks_; c != NULL; c = c->next_) {
912     const uint8_t* const header = mem_buf + c->data_.offset_;
913     if (!memcmp(header, fourcc, TAG_SIZE)) ++count;
914     if (count == chunk_num) break;
915   }
916   return c;
917 }
918 
SetChunk(const char fourcc[4],int chunk_num,WebPChunkIterator * const iter)919 static int SetChunk(const char fourcc[4], int chunk_num,
920                     WebPChunkIterator* const iter) {
921   const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;
922   int count;
923 
924   if (dmux == NULL || fourcc == NULL || chunk_num < 0) return 0;
925   count = ChunkCount(dmux, fourcc);
926   if (count == 0) return 0;
927   if (chunk_num == 0) chunk_num = count;
928 
929   if (chunk_num <= count) {
930     const uint8_t* const mem_buf = dmux->mem_.buf_;
931     const Chunk* const chunk = GetChunk(dmux, fourcc, chunk_num);
932     iter->chunk.bytes = mem_buf + chunk->data_.offset_ + CHUNK_HEADER_SIZE;
933     iter->chunk.size  = chunk->data_.size_ - CHUNK_HEADER_SIZE;
934     iter->num_chunks  = count;
935     iter->chunk_num   = chunk_num;
936     return 1;
937   }
938   return 0;
939 }
940 
WebPDemuxGetChunk(const WebPDemuxer * dmux,const char fourcc[4],int chunk_num,WebPChunkIterator * iter)941 int WebPDemuxGetChunk(const WebPDemuxer* dmux,
942                       const char fourcc[4], int chunk_num,
943                       WebPChunkIterator* iter) {
944   if (iter == NULL) return 0;
945 
946   memset(iter, 0, sizeof(*iter));
947   iter->private_ = (void*)dmux;
948   return SetChunk(fourcc, chunk_num, iter);
949 }
950 
WebPDemuxNextChunk(WebPChunkIterator * iter)951 int WebPDemuxNextChunk(WebPChunkIterator* iter) {
952   if (iter != NULL) {
953     const char* const fourcc =
954         (const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;
955     return SetChunk(fourcc, iter->chunk_num + 1, iter);
956   }
957   return 0;
958 }
959 
WebPDemuxPrevChunk(WebPChunkIterator * iter)960 int WebPDemuxPrevChunk(WebPChunkIterator* iter) {
961   if (iter != NULL && iter->chunk_num > 1) {
962     const char* const fourcc =
963         (const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;
964     return SetChunk(fourcc, iter->chunk_num - 1, iter);
965   }
966   return 0;
967 }
968 
WebPDemuxReleaseChunkIterator(WebPChunkIterator * iter)969 void WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter) {
970   (void)iter;
971 }
972 
973