• 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 1
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     uint32_t payload_size_padded;
225     size_t payload_available;
226     size_t chunk_size;
227 
228     if (payload_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
229 
230     payload_size_padded = payload_size + (payload_size & 1);
231     payload_available = (payload_size_padded > MemDataSize(mem))
232                       ? MemDataSize(mem) : payload_size_padded;
233     chunk_size = CHUNK_HEADER_SIZE + payload_available;
234     if (SizeIsInvalid(mem, payload_size_padded)) return PARSE_ERROR;
235     if (payload_size_padded > MemDataSize(mem)) status = PARSE_NEED_MORE_DATA;
236 
237     switch (fourcc) {
238       case MKFOURCC('A', 'L', 'P', 'H'):
239         if (alpha_chunks == 0) {
240           ++alpha_chunks;
241           frame->img_components_[1].offset_ = chunk_start_offset;
242           frame->img_components_[1].size_ = chunk_size;
243           frame->has_alpha_ = 1;
244           frame->frame_num_ = frame_num;
245           Skip(mem, payload_available);
246         } else {
247           goto Done;
248         }
249         break;
250       case MKFOURCC('V', 'P', '8', 'L'):
251         if (alpha_chunks > 0) return PARSE_ERROR;  // VP8L has its own alpha
252         // fall through
253       case MKFOURCC('V', 'P', '8', ' '):
254         if (image_chunks == 0) {
255           // Extract the bitstream features, tolerating failures when the data
256           // is incomplete.
257           WebPBitstreamFeatures features;
258           const VP8StatusCode vp8_status =
259               WebPGetFeatures(mem->buf_ + chunk_start_offset, chunk_size,
260                               &features);
261           if (status == PARSE_NEED_MORE_DATA &&
262               vp8_status == VP8_STATUS_NOT_ENOUGH_DATA) {
263             return PARSE_NEED_MORE_DATA;
264           } else if (vp8_status != VP8_STATUS_OK) {
265             // We have enough data, and yet WebPGetFeatures() failed.
266             return PARSE_ERROR;
267           }
268           ++image_chunks;
269           SetFrameInfo(chunk_start_offset, chunk_size, frame_num,
270                        status == PARSE_OK, &features, frame);
271           Skip(mem, payload_available);
272         } else {
273           goto Done;
274         }
275         break;
276  Done:
277       default:
278         // Restore fourcc/size when moving up one level in parsing.
279         Rewind(mem, CHUNK_HEADER_SIZE);
280         done = 1;
281         break;
282     }
283 
284     if (mem->start_ == mem->riff_end_) {
285       done = 1;
286     } else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {
287       status = PARSE_NEED_MORE_DATA;
288     }
289   } while (!done && status == PARSE_OK);
290 
291   return status;
292 }
293 
294 // Creates a new Frame if 'actual_size' is within bounds and 'mem' contains
295 // enough data ('min_size') to parse the payload.
296 // Returns PARSE_OK on success with *frame pointing to the new Frame.
297 // 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)298 static ParseStatus NewFrame(const MemBuffer* const mem,
299                             uint32_t min_size, uint32_t actual_size,
300                             Frame** frame) {
301   if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;
302   if (actual_size < min_size) return PARSE_ERROR;
303   if (MemDataSize(mem) < min_size)  return PARSE_NEED_MORE_DATA;
304 
305   *frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(**frame));
306   return (*frame == NULL) ? PARSE_ERROR : PARSE_OK;
307 }
308 
309 // Parse a 'ANMF' chunk and any image bearing chunks that immediately follow.
310 // 'frame_chunk_size' is the previously validated, padded chunk size.
ParseAnimationFrame(WebPDemuxer * const dmux,uint32_t frame_chunk_size)311 static ParseStatus ParseAnimationFrame(
312     WebPDemuxer* const dmux, uint32_t frame_chunk_size) {
313   const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);
314   const uint32_t anmf_payload_size = frame_chunk_size - ANMF_CHUNK_SIZE;
315   int added_frame = 0;
316   int bits;
317   MemBuffer* const mem = &dmux->mem_;
318   Frame* frame;
319   size_t start_offset;
320   ParseStatus status =
321       NewFrame(mem, ANMF_CHUNK_SIZE, frame_chunk_size, &frame);
322   if (status != PARSE_OK) return status;
323 
324   frame->x_offset_       = 2 * ReadLE24s(mem);
325   frame->y_offset_       = 2 * ReadLE24s(mem);
326   frame->width_          = 1 + ReadLE24s(mem);
327   frame->height_         = 1 + ReadLE24s(mem);
328   frame->duration_       = ReadLE24s(mem);
329   bits = ReadByte(mem);
330   frame->dispose_method_ =
331       (bits & 1) ? WEBP_MUX_DISPOSE_BACKGROUND : WEBP_MUX_DISPOSE_NONE;
332   frame->blend_method_ = (bits & 2) ? WEBP_MUX_NO_BLEND : WEBP_MUX_BLEND;
333   if (frame->width_ * (uint64_t)frame->height_ >= MAX_IMAGE_AREA) {
334     WebPSafeFree(frame);
335     return PARSE_ERROR;
336   }
337 
338   // Store a frame only if the animation flag is set there is some data for
339   // this frame is available.
340   start_offset = mem->start_;
341   status = StoreFrame(dmux->num_frames_ + 1, anmf_payload_size, mem, frame);
342   if (status != PARSE_ERROR && mem->start_ - start_offset > anmf_payload_size) {
343     status = PARSE_ERROR;
344   }
345   if (status != PARSE_ERROR && is_animation && frame->frame_num_ > 0) {
346     added_frame = AddFrame(dmux, frame);
347     if (added_frame) {
348       ++dmux->num_frames_;
349     } else {
350       status = PARSE_ERROR;
351     }
352   }
353 
354   if (!added_frame) WebPSafeFree(frame);
355   return status;
356 }
357 
358 // General chunk storage, starting with the header at 'start_offset', allowing
359 // the user to request the payload via a fourcc string. 'size' includes the
360 // header and the unpadded payload size.
361 // Returns true on success, false otherwise.
StoreChunk(WebPDemuxer * const dmux,size_t start_offset,uint32_t size)362 static int StoreChunk(WebPDemuxer* const dmux,
363                       size_t start_offset, uint32_t size) {
364   Chunk* const chunk = (Chunk*)WebPSafeCalloc(1ULL, sizeof(*chunk));
365   if (chunk == NULL) return 0;
366 
367   chunk->data_.offset_ = start_offset;
368   chunk->data_.size_ = size;
369   AddChunk(dmux, chunk);
370   return 1;
371 }
372 
373 // -----------------------------------------------------------------------------
374 // Primary chunk parsing
375 
ReadHeader(MemBuffer * const mem)376 static ParseStatus ReadHeader(MemBuffer* const mem) {
377   const size_t min_size = RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE;
378   uint32_t riff_size;
379 
380   // Basic file level validation.
381   if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;
382   if (memcmp(GetBuffer(mem), "RIFF", CHUNK_SIZE_BYTES) ||
383       memcmp(GetBuffer(mem) + CHUNK_HEADER_SIZE, "WEBP", CHUNK_SIZE_BYTES)) {
384     return PARSE_ERROR;
385   }
386 
387   riff_size = GetLE32(GetBuffer(mem) + TAG_SIZE);
388   if (riff_size < CHUNK_HEADER_SIZE) return PARSE_ERROR;
389   if (riff_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
390 
391   // There's no point in reading past the end of the RIFF chunk
392   mem->riff_end_ = riff_size + CHUNK_HEADER_SIZE;
393   if (mem->buf_size_ > mem->riff_end_) {
394     mem->buf_size_ = mem->end_ = mem->riff_end_;
395   }
396 
397   Skip(mem, RIFF_HEADER_SIZE);
398   return PARSE_OK;
399 }
400 
ParseSingleImage(WebPDemuxer * const dmux)401 static ParseStatus ParseSingleImage(WebPDemuxer* const dmux) {
402   const size_t min_size = CHUNK_HEADER_SIZE;
403   MemBuffer* const mem = &dmux->mem_;
404   Frame* frame;
405   ParseStatus status;
406   int image_added = 0;
407 
408   if (dmux->frames_ != NULL) return PARSE_ERROR;
409   if (SizeIsInvalid(mem, min_size)) return PARSE_ERROR;
410   if (MemDataSize(mem) < min_size) return PARSE_NEED_MORE_DATA;
411 
412   frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));
413   if (frame == NULL) return PARSE_ERROR;
414 
415   // For the single image case we allow parsing of a partial frame, so no
416   // minimum size is imposed here.
417   status = StoreFrame(1, 0, &dmux->mem_, frame);
418   if (status != PARSE_ERROR) {
419     const int has_alpha = !!(dmux->feature_flags_ & ALPHA_FLAG);
420     // Clear any alpha when the alpha flag is missing.
421     if (!has_alpha && frame->img_components_[1].size_ > 0) {
422       frame->img_components_[1].offset_ = 0;
423       frame->img_components_[1].size_ = 0;
424       frame->has_alpha_ = 0;
425     }
426 
427     // Use the frame width/height as the canvas values for non-vp8x files.
428     // Also, set ALPHA_FLAG if this is a lossless image with alpha.
429     if (!dmux->is_ext_format_ && frame->width_ > 0 && frame->height_ > 0) {
430       dmux->state_ = WEBP_DEMUX_PARSED_HEADER;
431       dmux->canvas_width_ = frame->width_;
432       dmux->canvas_height_ = frame->height_;
433       dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;
434     }
435     if (!AddFrame(dmux, frame)) {
436       status = PARSE_ERROR;  // last frame was left incomplete
437     } else {
438       image_added = 1;
439       dmux->num_frames_ = 1;
440     }
441   }
442 
443   if (!image_added) WebPSafeFree(frame);
444   return status;
445 }
446 
ParseVP8XChunks(WebPDemuxer * const dmux)447 static ParseStatus ParseVP8XChunks(WebPDemuxer* const dmux) {
448   const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);
449   MemBuffer* const mem = &dmux->mem_;
450   int anim_chunks = 0;
451   ParseStatus status = PARSE_OK;
452 
453   do {
454     int store_chunk = 1;
455     const size_t chunk_start_offset = mem->start_;
456     const uint32_t fourcc = ReadLE32(mem);
457     const uint32_t chunk_size = ReadLE32(mem);
458     uint32_t chunk_size_padded;
459 
460     if (chunk_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
461 
462     chunk_size_padded = chunk_size + (chunk_size & 1);
463     if (SizeIsInvalid(mem, chunk_size_padded)) return PARSE_ERROR;
464 
465     switch (fourcc) {
466       case MKFOURCC('V', 'P', '8', 'X'): {
467         return PARSE_ERROR;
468       }
469       case MKFOURCC('A', 'L', 'P', 'H'):
470       case MKFOURCC('V', 'P', '8', ' '):
471       case MKFOURCC('V', 'P', '8', 'L'): {
472         // check that this isn't an animation (all frames should be in an ANMF).
473         if (anim_chunks > 0 || is_animation) return PARSE_ERROR;
474 
475         Rewind(mem, CHUNK_HEADER_SIZE);
476         status = ParseSingleImage(dmux);
477         break;
478       }
479       case MKFOURCC('A', 'N', 'I', 'M'): {
480         if (chunk_size_padded < ANIM_CHUNK_SIZE) return PARSE_ERROR;
481 
482         if (MemDataSize(mem) < chunk_size_padded) {
483           status = PARSE_NEED_MORE_DATA;
484         } else if (anim_chunks == 0) {
485           ++anim_chunks;
486           dmux->bgcolor_ = ReadLE32(mem);
487           dmux->loop_count_ = ReadLE16s(mem);
488           Skip(mem, chunk_size_padded - ANIM_CHUNK_SIZE);
489         } else {
490           store_chunk = 0;
491           goto Skip;
492         }
493         break;
494       }
495       case MKFOURCC('A', 'N', 'M', 'F'): {
496         if (anim_chunks == 0) return PARSE_ERROR;  // 'ANIM' precedes frames.
497         status = ParseAnimationFrame(dmux, chunk_size_padded);
498         break;
499       }
500       case MKFOURCC('I', 'C', 'C', 'P'): {
501         store_chunk = !!(dmux->feature_flags_ & ICCP_FLAG);
502         goto Skip;
503       }
504       case MKFOURCC('E', 'X', 'I', 'F'): {
505         store_chunk = !!(dmux->feature_flags_ & EXIF_FLAG);
506         goto Skip;
507       }
508       case MKFOURCC('X', 'M', 'P', ' '): {
509         store_chunk = !!(dmux->feature_flags_ & XMP_FLAG);
510         goto Skip;
511       }
512  Skip:
513       default: {
514         if (chunk_size_padded <= MemDataSize(mem)) {
515           if (store_chunk) {
516             // Store only the chunk header and unpadded size as only the payload
517             // will be returned to the user.
518             if (!StoreChunk(dmux, chunk_start_offset,
519                             CHUNK_HEADER_SIZE + chunk_size)) {
520               return PARSE_ERROR;
521             }
522           }
523           Skip(mem, chunk_size_padded);
524         } else {
525           status = PARSE_NEED_MORE_DATA;
526         }
527       }
528     }
529 
530     if (mem->start_ == mem->riff_end_) {
531       break;
532     } else if (MemDataSize(mem) < CHUNK_HEADER_SIZE) {
533       status = PARSE_NEED_MORE_DATA;
534     }
535   } while (status == PARSE_OK);
536 
537   return status;
538 }
539 
ParseVP8X(WebPDemuxer * const dmux)540 static ParseStatus ParseVP8X(WebPDemuxer* const dmux) {
541   MemBuffer* const mem = &dmux->mem_;
542   uint32_t vp8x_size;
543 
544   if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;
545 
546   dmux->is_ext_format_ = 1;
547   Skip(mem, TAG_SIZE);  // VP8X
548   vp8x_size = ReadLE32(mem);
549   if (vp8x_size > MAX_CHUNK_PAYLOAD) return PARSE_ERROR;
550   if (vp8x_size < VP8X_CHUNK_SIZE) return PARSE_ERROR;
551   vp8x_size += vp8x_size & 1;
552   if (SizeIsInvalid(mem, vp8x_size)) return PARSE_ERROR;
553   if (MemDataSize(mem) < vp8x_size) return PARSE_NEED_MORE_DATA;
554 
555   dmux->feature_flags_ = ReadByte(mem);
556   Skip(mem, 3);  // Reserved.
557   dmux->canvas_width_  = 1 + ReadLE24s(mem);
558   dmux->canvas_height_ = 1 + ReadLE24s(mem);
559   if (dmux->canvas_width_ * (uint64_t)dmux->canvas_height_ >= MAX_IMAGE_AREA) {
560     return PARSE_ERROR;  // image final dimension is too large
561   }
562   Skip(mem, vp8x_size - VP8X_CHUNK_SIZE);  // skip any trailing data.
563   dmux->state_ = WEBP_DEMUX_PARSED_HEADER;
564 
565   if (SizeIsInvalid(mem, CHUNK_HEADER_SIZE)) return PARSE_ERROR;
566   if (MemDataSize(mem) < CHUNK_HEADER_SIZE) return PARSE_NEED_MORE_DATA;
567 
568   return ParseVP8XChunks(dmux);
569 }
570 
571 // -----------------------------------------------------------------------------
572 // Format validation
573 
IsValidSimpleFormat(const WebPDemuxer * const dmux)574 static int IsValidSimpleFormat(const WebPDemuxer* const dmux) {
575   const Frame* const frame = dmux->frames_;
576   if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;
577 
578   if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;
579   if (dmux->state_ == WEBP_DEMUX_DONE && frame == NULL) return 0;
580 
581   if (frame->width_ <= 0 || frame->height_ <= 0) return 0;
582   return 1;
583 }
584 
585 // If 'exact' is true, check that the image resolution matches the canvas.
586 // 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)587 static int CheckFrameBounds(const Frame* const frame, int exact,
588                             int canvas_width, int canvas_height) {
589   if (exact) {
590     if (frame->x_offset_ != 0 || frame->y_offset_ != 0) {
591       return 0;
592     }
593     if (frame->width_ != canvas_width || frame->height_ != canvas_height) {
594       return 0;
595     }
596   } else {
597     if (frame->x_offset_ < 0 || frame->y_offset_ < 0) return 0;
598     if (frame->width_ + frame->x_offset_ > canvas_width) return 0;
599     if (frame->height_ + frame->y_offset_ > canvas_height) return 0;
600   }
601   return 1;
602 }
603 
IsValidExtendedFormat(const WebPDemuxer * const dmux)604 static int IsValidExtendedFormat(const WebPDemuxer* const dmux) {
605   const int is_animation = !!(dmux->feature_flags_ & ANIMATION_FLAG);
606   const Frame* f = dmux->frames_;
607 
608   if (dmux->state_ == WEBP_DEMUX_PARSING_HEADER) return 1;
609 
610   if (dmux->canvas_width_ <= 0 || dmux->canvas_height_ <= 0) return 0;
611   if (dmux->loop_count_ < 0) return 0;
612   if (dmux->state_ == WEBP_DEMUX_DONE && dmux->frames_ == NULL) return 0;
613   if (dmux->feature_flags_ & ~ALL_VALID_FLAGS) return 0;  // invalid bitstream
614 
615   while (f != NULL) {
616     const int cur_frame_set = f->frame_num_;
617     int frame_count = 0;
618 
619     // Check frame properties.
620     for (; f != NULL && f->frame_num_ == cur_frame_set; f = f->next_) {
621       const ChunkData* const image = f->img_components_;
622       const ChunkData* const alpha = f->img_components_ + 1;
623 
624       if (!is_animation && f->frame_num_ > 1) return 0;
625 
626       if (f->complete_) {
627         if (alpha->size_ == 0 && image->size_ == 0) return 0;
628         // Ensure alpha precedes image bitstream.
629         if (alpha->size_ > 0 && alpha->offset_ > image->offset_) {
630           return 0;
631         }
632 
633         if (f->width_ <= 0 || f->height_ <= 0) return 0;
634       } else {
635         // There shouldn't be a partial frame in a complete file.
636         if (dmux->state_ == WEBP_DEMUX_DONE) return 0;
637 
638         // Ensure alpha precedes image bitstream.
639         if (alpha->size_ > 0 && image->size_ > 0 &&
640             alpha->offset_ > image->offset_) {
641           return 0;
642         }
643         // There shouldn't be any frames after an incomplete one.
644         if (f->next_ != NULL) return 0;
645       }
646 
647       if (f->width_ > 0 && f->height_ > 0 &&
648           !CheckFrameBounds(f, !is_animation,
649                             dmux->canvas_width_, dmux->canvas_height_)) {
650         return 0;
651       }
652 
653       ++frame_count;
654     }
655   }
656   return 1;
657 }
658 
659 // -----------------------------------------------------------------------------
660 // WebPDemuxer object
661 
InitDemux(WebPDemuxer * const dmux,const MemBuffer * const mem)662 static void InitDemux(WebPDemuxer* const dmux, const MemBuffer* const mem) {
663   dmux->state_ = WEBP_DEMUX_PARSING_HEADER;
664   dmux->loop_count_ = 1;
665   dmux->bgcolor_ = 0xFFFFFFFF;  // White background by default.
666   dmux->canvas_width_ = -1;
667   dmux->canvas_height_ = -1;
668   dmux->frames_tail_ = &dmux->frames_;
669   dmux->chunks_tail_ = &dmux->chunks_;
670   dmux->mem_ = *mem;
671 }
672 
CreateRawImageDemuxer(MemBuffer * const mem,WebPDemuxer ** demuxer)673 static ParseStatus CreateRawImageDemuxer(MemBuffer* const mem,
674                                          WebPDemuxer** demuxer) {
675   WebPBitstreamFeatures features;
676   const VP8StatusCode status =
677       WebPGetFeatures(mem->buf_, mem->buf_size_, &features);
678   *demuxer = NULL;
679   if (status != VP8_STATUS_OK) {
680     return (status == VP8_STATUS_NOT_ENOUGH_DATA) ? PARSE_NEED_MORE_DATA
681                                                   : PARSE_ERROR;
682   }
683 
684   {
685     WebPDemuxer* const dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));
686     Frame* const frame = (Frame*)WebPSafeCalloc(1ULL, sizeof(*frame));
687     if (dmux == NULL || frame == NULL) goto Error;
688     InitDemux(dmux, mem);
689     SetFrameInfo(0, mem->buf_size_, 1 /*frame_num*/, 1 /*complete*/, &features,
690                  frame);
691     if (!AddFrame(dmux, frame)) goto Error;
692     dmux->state_ = WEBP_DEMUX_DONE;
693     dmux->canvas_width_ = frame->width_;
694     dmux->canvas_height_ = frame->height_;
695     dmux->feature_flags_ |= frame->has_alpha_ ? ALPHA_FLAG : 0;
696     dmux->num_frames_ = 1;
697     assert(IsValidSimpleFormat(dmux));
698     *demuxer = dmux;
699     return PARSE_OK;
700 
701  Error:
702     WebPSafeFree(dmux);
703     WebPSafeFree(frame);
704     return PARSE_ERROR;
705   }
706 }
707 
WebPDemuxInternal(const WebPData * data,int allow_partial,WebPDemuxState * state,int version)708 WebPDemuxer* WebPDemuxInternal(const WebPData* data, int allow_partial,
709                                WebPDemuxState* state, int version) {
710   const ChunkParser* parser;
711   int partial;
712   ParseStatus status = PARSE_ERROR;
713   MemBuffer mem;
714   WebPDemuxer* dmux;
715 
716   if (state != NULL) *state = WEBP_DEMUX_PARSE_ERROR;
717 
718   if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_DEMUX_ABI_VERSION)) return NULL;
719   if (data == NULL || data->bytes == NULL || data->size == 0) return NULL;
720 
721   if (!InitMemBuffer(&mem, data->bytes, data->size)) return NULL;
722   status = ReadHeader(&mem);
723   if (status != PARSE_OK) {
724     // If parsing of the webp file header fails attempt to handle a raw
725     // VP8/VP8L frame. Note 'allow_partial' is ignored in this case.
726     if (status == PARSE_ERROR) {
727       status = CreateRawImageDemuxer(&mem, &dmux);
728       if (status == PARSE_OK) {
729         if (state != NULL) *state = WEBP_DEMUX_DONE;
730         return dmux;
731       }
732     }
733     if (state != NULL) {
734       *state = (status == PARSE_NEED_MORE_DATA) ? WEBP_DEMUX_PARSING_HEADER
735                                                 : WEBP_DEMUX_PARSE_ERROR;
736     }
737     return NULL;
738   }
739 
740   partial = (mem.buf_size_ < mem.riff_end_);
741   if (!allow_partial && partial) return NULL;
742 
743   dmux = (WebPDemuxer*)WebPSafeCalloc(1ULL, sizeof(*dmux));
744   if (dmux == NULL) return NULL;
745   InitDemux(dmux, &mem);
746 
747   status = PARSE_ERROR;
748   for (parser = kMasterChunks; parser->parse != NULL; ++parser) {
749     if (!memcmp(parser->id, GetBuffer(&dmux->mem_), TAG_SIZE)) {
750       status = parser->parse(dmux);
751       if (status == PARSE_OK) dmux->state_ = WEBP_DEMUX_DONE;
752       if (status == PARSE_NEED_MORE_DATA && !partial) status = PARSE_ERROR;
753       if (status != PARSE_ERROR && !parser->valid(dmux)) status = PARSE_ERROR;
754       if (status == PARSE_ERROR) dmux->state_ = WEBP_DEMUX_PARSE_ERROR;
755       break;
756     }
757   }
758   if (state != NULL) *state = dmux->state_;
759 
760   if (status == PARSE_ERROR) {
761     WebPDemuxDelete(dmux);
762     return NULL;
763   }
764   return dmux;
765 }
766 
WebPDemuxDelete(WebPDemuxer * dmux)767 void WebPDemuxDelete(WebPDemuxer* dmux) {
768   Chunk* c;
769   Frame* f;
770   if (dmux == NULL) return;
771 
772   for (f = dmux->frames_; f != NULL;) {
773     Frame* const cur_frame = f;
774     f = f->next_;
775     WebPSafeFree(cur_frame);
776   }
777   for (c = dmux->chunks_; c != NULL;) {
778     Chunk* const cur_chunk = c;
779     c = c->next_;
780     WebPSafeFree(cur_chunk);
781   }
782   WebPSafeFree(dmux);
783 }
784 
785 // -----------------------------------------------------------------------------
786 
WebPDemuxGetI(const WebPDemuxer * dmux,WebPFormatFeature feature)787 uint32_t WebPDemuxGetI(const WebPDemuxer* dmux, WebPFormatFeature feature) {
788   if (dmux == NULL) return 0;
789 
790   switch (feature) {
791     case WEBP_FF_FORMAT_FLAGS:     return dmux->feature_flags_;
792     case WEBP_FF_CANVAS_WIDTH:     return (uint32_t)dmux->canvas_width_;
793     case WEBP_FF_CANVAS_HEIGHT:    return (uint32_t)dmux->canvas_height_;
794     case WEBP_FF_LOOP_COUNT:       return (uint32_t)dmux->loop_count_;
795     case WEBP_FF_BACKGROUND_COLOR: return dmux->bgcolor_;
796     case WEBP_FF_FRAME_COUNT:      return (uint32_t)dmux->num_frames_;
797   }
798   return 0;
799 }
800 
801 // -----------------------------------------------------------------------------
802 // Frame iteration
803 
GetFrame(const WebPDemuxer * const dmux,int frame_num)804 static const Frame* GetFrame(const WebPDemuxer* const dmux, int frame_num) {
805   const Frame* f;
806   for (f = dmux->frames_; f != NULL; f = f->next_) {
807     if (frame_num == f->frame_num_) break;
808   }
809   return f;
810 }
811 
GetFramePayload(const uint8_t * const mem_buf,const Frame * const frame,size_t * const data_size)812 static const uint8_t* GetFramePayload(const uint8_t* const mem_buf,
813                                       const Frame* const frame,
814                                       size_t* const data_size) {
815   *data_size = 0;
816   if (frame != NULL) {
817     const ChunkData* const image = frame->img_components_;
818     const ChunkData* const alpha = frame->img_components_ + 1;
819     size_t start_offset = image->offset_;
820     *data_size = image->size_;
821 
822     // if alpha exists it precedes image, update the size allowing for
823     // intervening chunks.
824     if (alpha->size_ > 0) {
825       const size_t inter_size = (image->offset_ > 0)
826                               ? image->offset_ - (alpha->offset_ + alpha->size_)
827                               : 0;
828       start_offset = alpha->offset_;
829       *data_size  += alpha->size_ + inter_size;
830     }
831     return mem_buf + start_offset;
832   }
833   return NULL;
834 }
835 
836 // Create a whole 'frame' from VP8 (+ alpha) or lossless.
SynthesizeFrame(const WebPDemuxer * const dmux,const Frame * const frame,WebPIterator * const iter)837 static int SynthesizeFrame(const WebPDemuxer* const dmux,
838                            const Frame* const frame,
839                            WebPIterator* const iter) {
840   const uint8_t* const mem_buf = dmux->mem_.buf_;
841   size_t payload_size = 0;
842   const uint8_t* const payload = GetFramePayload(mem_buf, frame, &payload_size);
843   if (payload == NULL) return 0;
844   assert(frame != NULL);
845 
846   iter->frame_num      = frame->frame_num_;
847   iter->num_frames     = dmux->num_frames_;
848   iter->x_offset       = frame->x_offset_;
849   iter->y_offset       = frame->y_offset_;
850   iter->width          = frame->width_;
851   iter->height         = frame->height_;
852   iter->has_alpha      = frame->has_alpha_;
853   iter->duration       = frame->duration_;
854   iter->dispose_method = frame->dispose_method_;
855   iter->blend_method   = frame->blend_method_;
856   iter->complete       = frame->complete_;
857   iter->fragment.bytes = payload;
858   iter->fragment.size  = payload_size;
859   return 1;
860 }
861 
SetFrame(int frame_num,WebPIterator * const iter)862 static int SetFrame(int frame_num, WebPIterator* const iter) {
863   const Frame* frame;
864   const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;
865   if (dmux == NULL || frame_num < 0) return 0;
866   if (frame_num > dmux->num_frames_) return 0;
867   if (frame_num == 0) frame_num = dmux->num_frames_;
868 
869   frame = GetFrame(dmux, frame_num);
870   if (frame == NULL) return 0;
871 
872   return SynthesizeFrame(dmux, frame, iter);
873 }
874 
WebPDemuxGetFrame(const WebPDemuxer * dmux,int frame,WebPIterator * iter)875 int WebPDemuxGetFrame(const WebPDemuxer* dmux, int frame, WebPIterator* iter) {
876   if (iter == NULL) return 0;
877 
878   memset(iter, 0, sizeof(*iter));
879   iter->private_ = (void*)dmux;
880   return SetFrame(frame, iter);
881 }
882 
WebPDemuxNextFrame(WebPIterator * iter)883 int WebPDemuxNextFrame(WebPIterator* iter) {
884   if (iter == NULL) return 0;
885   return SetFrame(iter->frame_num + 1, iter);
886 }
887 
WebPDemuxPrevFrame(WebPIterator * iter)888 int WebPDemuxPrevFrame(WebPIterator* iter) {
889   if (iter == NULL) return 0;
890   if (iter->frame_num <= 1) return 0;
891   return SetFrame(iter->frame_num - 1, iter);
892 }
893 
WebPDemuxReleaseIterator(WebPIterator * iter)894 void WebPDemuxReleaseIterator(WebPIterator* iter) {
895   (void)iter;
896 }
897 
898 // -----------------------------------------------------------------------------
899 // Chunk iteration
900 
ChunkCount(const WebPDemuxer * const dmux,const char fourcc[4])901 static int ChunkCount(const WebPDemuxer* const dmux, const char fourcc[4]) {
902   const uint8_t* const mem_buf = dmux->mem_.buf_;
903   const Chunk* c;
904   int count = 0;
905   for (c = dmux->chunks_; c != NULL; c = c->next_) {
906     const uint8_t* const header = mem_buf + c->data_.offset_;
907     if (!memcmp(header, fourcc, TAG_SIZE)) ++count;
908   }
909   return count;
910 }
911 
GetChunk(const WebPDemuxer * const dmux,const char fourcc[4],int chunk_num)912 static const Chunk* GetChunk(const WebPDemuxer* const dmux,
913                              const char fourcc[4], int chunk_num) {
914   const uint8_t* const mem_buf = dmux->mem_.buf_;
915   const Chunk* c;
916   int count = 0;
917   for (c = dmux->chunks_; c != NULL; c = c->next_) {
918     const uint8_t* const header = mem_buf + c->data_.offset_;
919     if (!memcmp(header, fourcc, TAG_SIZE)) ++count;
920     if (count == chunk_num) break;
921   }
922   return c;
923 }
924 
SetChunk(const char fourcc[4],int chunk_num,WebPChunkIterator * const iter)925 static int SetChunk(const char fourcc[4], int chunk_num,
926                     WebPChunkIterator* const iter) {
927   const WebPDemuxer* const dmux = (WebPDemuxer*)iter->private_;
928   int count;
929 
930   if (dmux == NULL || fourcc == NULL || chunk_num < 0) return 0;
931   count = ChunkCount(dmux, fourcc);
932   if (count == 0) return 0;
933   if (chunk_num == 0) chunk_num = count;
934 
935   if (chunk_num <= count) {
936     const uint8_t* const mem_buf = dmux->mem_.buf_;
937     const Chunk* const chunk = GetChunk(dmux, fourcc, chunk_num);
938     iter->chunk.bytes = mem_buf + chunk->data_.offset_ + CHUNK_HEADER_SIZE;
939     iter->chunk.size  = chunk->data_.size_ - CHUNK_HEADER_SIZE;
940     iter->num_chunks  = count;
941     iter->chunk_num   = chunk_num;
942     return 1;
943   }
944   return 0;
945 }
946 
WebPDemuxGetChunk(const WebPDemuxer * dmux,const char fourcc[4],int chunk_num,WebPChunkIterator * iter)947 int WebPDemuxGetChunk(const WebPDemuxer* dmux,
948                       const char fourcc[4], int chunk_num,
949                       WebPChunkIterator* iter) {
950   if (iter == NULL) return 0;
951 
952   memset(iter, 0, sizeof(*iter));
953   iter->private_ = (void*)dmux;
954   return SetChunk(fourcc, chunk_num, iter);
955 }
956 
WebPDemuxNextChunk(WebPChunkIterator * iter)957 int WebPDemuxNextChunk(WebPChunkIterator* iter) {
958   if (iter != NULL) {
959     const char* const fourcc =
960         (const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;
961     return SetChunk(fourcc, iter->chunk_num + 1, iter);
962   }
963   return 0;
964 }
965 
WebPDemuxPrevChunk(WebPChunkIterator * iter)966 int WebPDemuxPrevChunk(WebPChunkIterator* iter) {
967   if (iter != NULL && iter->chunk_num > 1) {
968     const char* const fourcc =
969         (const char*)iter->chunk.bytes - CHUNK_HEADER_SIZE;
970     return SetChunk(fourcc, iter->chunk_num - 1, iter);
971   }
972   return 0;
973 }
974 
WebPDemuxReleaseChunkIterator(WebPChunkIterator * iter)975 void WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter) {
976   (void)iter;
977 }
978 
979