Coverage Report

Created: 2026-03-31 06:56

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