Coverage Report

Created: 2025-12-31 07:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/src/dec/webp_dec.c
Line
Count
Source
1
// Copyright 2010 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
// Main decoding functions for WEBP images.
11
//
12
// Author: Skal (pascal.massimino@gmail.com)
13
14
#include <assert.h>
15
#include <stdlib.h>
16
#include <string.h>
17
18
#include "src/dec/common_dec.h"
19
#include "src/dec/vp8_dec.h"
20
#include "src/dec/vp8i_dec.h"
21
#include "src/dec/vp8li_dec.h"
22
#include "src/dec/webpi_dec.h"
23
#include "src/utils/rescaler_utils.h"
24
#include "src/utils/utils.h"
25
#include "src/webp/decode.h"
26
#include "src/webp/format_constants.h"
27
#include "src/webp/mux_types.h"  // ALPHA_FLAG
28
#include "src/webp/types.h"
29
30
WEBP_ASSUME_UNSAFE_INDEXABLE_ABI
31
32
//------------------------------------------------------------------------------
33
// RIFF layout is:
34
//   Offset  tag
35
//   0...3   "RIFF" 4-byte tag
36
//   4...7   size of image data (including metadata) starting at offset 8
37
//   8...11  "WEBP"   our form-type signature
38
// The RIFF container (12 bytes) is followed by appropriate chunks:
39
//   12..15  "VP8 ": 4-bytes tags, signaling the use of VP8 video format
40
//   16..19  size of the raw VP8 image data, starting at offset 20
41
//   20....  the VP8 bytes
42
// Or,
43
//   12..15  "VP8L": 4-bytes tags, signaling the use of VP8L lossless format
44
//   16..19  size of the raw VP8L image data, starting at offset 20
45
//   20....  the VP8L bytes
46
// Or,
47
//   12..15  "VP8X": 4-bytes tags, describing the extended-VP8 chunk.
48
//   16..19  size of the VP8X chunk starting at offset 20.
49
//   20..23  VP8X flags bit-map corresponding to the chunk-types present.
50
//   24..26  Width of the Canvas Image.
51
//   27..29  Height of the Canvas Image.
52
// There can be extra chunks after the "VP8X" chunk (ICCP, ANMF, VP8, VP8L,
53
// XMP, EXIF  ...)
54
// All sizes are in little-endian order.
55
// Note: chunk data size must be padded to multiple of 2 when written.
56
57
// Validates the RIFF container (if detected) and skips over it.
58
// If a RIFF container is detected, returns:
59
//     VP8_STATUS_BITSTREAM_ERROR for invalid header,
60
//     VP8_STATUS_NOT_ENOUGH_DATA for truncated data if have_all_data is true,
61
// and VP8_STATUS_OK otherwise.
62
// In case there are not enough bytes (partial RIFF container), return 0 for
63
// *riff_size. Else return the RIFF size extracted from the header.
64
static VP8StatusCode ParseRIFF(const uint8_t* WEBP_COUNTED_BY(*data_size) *
65
                                   WEBP_SINGLE const data,
66
                               size_t* WEBP_SINGLE const data_size,
67
                               int have_all_data,
68
964k
                               size_t* WEBP_SINGLE const riff_size) {
69
964k
  assert(data != NULL);
70
964k
  assert(data_size != NULL);
71
964k
  assert(riff_size != NULL);
72
73
964k
  *riff_size = 0;  // Default: no RIFF present.
74
964k
  if (*data_size >= RIFF_HEADER_SIZE && !memcmp(*data, "RIFF", TAG_SIZE)) {
75
599k
    if (memcmp(*data + 8, "WEBP", TAG_SIZE)) {
76
4
      return VP8_STATUS_BITSTREAM_ERROR;  // Wrong image file signature.
77
599k
    } else {
78
599k
      const uint32_t size = GetLE32(*data + TAG_SIZE);
79
      // Check that we have at least one chunk (i.e "WEBP" + "VP8?nnnn").
80
599k
      if (size < TAG_SIZE + CHUNK_HEADER_SIZE) {
81
1.10k
        return VP8_STATUS_BITSTREAM_ERROR;
82
1.10k
      }
83
598k
      if (size > MAX_CHUNK_PAYLOAD) {
84
866
        return VP8_STATUS_BITSTREAM_ERROR;
85
866
      }
86
597k
      if (have_all_data && (size > *data_size - CHUNK_HEADER_SIZE)) {
87
2.21k
        return VP8_STATUS_NOT_ENOUGH_DATA;  // Truncated bitstream.
88
2.21k
      }
89
      // We have a RIFF container. Skip it.
90
594k
      *riff_size = size;
91
594k
      *data_size -= RIFF_HEADER_SIZE;
92
594k
      *data += RIFF_HEADER_SIZE;
93
594k
    }
94
599k
  }
95
959k
  return VP8_STATUS_OK;
96
964k
}
97
98
// Validates the VP8X header and skips over it.
99
// Returns VP8_STATUS_BITSTREAM_ERROR for invalid VP8X header,
100
//         VP8_STATUS_NOT_ENOUGH_DATA in case of insufficient data, and
101
//         VP8_STATUS_OK otherwise.
102
// If a VP8X chunk is found, found_vp8x is set to true and *width_ptr,
103
// *height_ptr and *flags_ptr are set to the corresponding values extracted
104
// from the VP8X chunk.
105
static VP8StatusCode ParseVP8X(const uint8_t* WEBP_COUNTED_BY(*data_size) *
106
                                   WEBP_SINGLE const data,
107
                               size_t* WEBP_SINGLE const data_size,
108
                               int* WEBP_SINGLE const found_vp8x,
109
                               int* WEBP_SINGLE const width_ptr,
110
                               int* WEBP_SINGLE const height_ptr,
111
959k
                               uint32_t* WEBP_SINGLE const flags_ptr) {
112
959k
  const uint32_t vp8x_size = CHUNK_HEADER_SIZE + VP8X_CHUNK_SIZE;
113
959k
  assert(data != NULL);
114
959k
  assert(data_size != NULL);
115
959k
  assert(found_vp8x != NULL);
116
117
959k
  *found_vp8x = 0;
118
119
959k
  if (*data_size < CHUNK_HEADER_SIZE) {
120
3.66k
    return VP8_STATUS_NOT_ENOUGH_DATA;  // Insufficient data.
121
3.66k
  }
122
123
956k
  if (!memcmp(*data, "VP8X", TAG_SIZE)) {
124
14.9k
    int width, height;
125
14.9k
    uint32_t flags;
126
14.9k
    const uint32_t chunk_size = GetLE32(*data + TAG_SIZE);
127
14.9k
    if (chunk_size != VP8X_CHUNK_SIZE) {
128
2.33k
      return VP8_STATUS_BITSTREAM_ERROR;  // Wrong chunk size.
129
2.33k
    }
130
131
    // Verify if enough data is available to validate the VP8X chunk.
132
12.6k
    if (*data_size < vp8x_size) {
133
469
      return VP8_STATUS_NOT_ENOUGH_DATA;  // Insufficient data.
134
469
    }
135
12.1k
    flags = GetLE32(*data + 8);
136
12.1k
    width = 1 + GetLE24(*data + 12);
137
12.1k
    height = 1 + GetLE24(*data + 15);
138
12.1k
    if (width * (uint64_t)height >= MAX_IMAGE_AREA) {
139
228
      return VP8_STATUS_BITSTREAM_ERROR;  // image is too large
140
228
    }
141
142
11.9k
    if (flags_ptr != NULL) *flags_ptr = flags;
143
11.9k
    if (width_ptr != NULL) *width_ptr = width;
144
11.9k
    if (height_ptr != NULL) *height_ptr = height;
145
    // Skip over VP8X header bytes.
146
11.9k
    *data_size -= vp8x_size;
147
11.9k
    *data += vp8x_size;
148
11.9k
    *found_vp8x = 1;
149
11.9k
  }
150
953k
  return VP8_STATUS_OK;
151
956k
}
152
153
// Skips to the next VP8/VP8L chunk header in the data given the size of the
154
// RIFF chunk 'riff_size'.
155
// Returns VP8_STATUS_BITSTREAM_ERROR if any invalid chunk size is encountered,
156
//         VP8_STATUS_NOT_ENOUGH_DATA in case of insufficient data, and
157
//         VP8_STATUS_OK otherwise.
158
// If an alpha chunk is found, *alpha_data and *alpha_size are set
159
// appropriately.
160
static VP8StatusCode ParseOptionalChunks(
161
    const uint8_t* WEBP_COUNTED_BY(*data_size) * WEBP_SINGLE const data,
162
    size_t* WEBP_SINGLE const data_size, size_t const riff_size,
163
    const uint8_t* WEBP_COUNTED_BY(*alpha_size) * WEBP_SINGLE const alpha_data,
164
20.2k
    size_t* WEBP_SINGLE const alpha_size) {
165
20.2k
  size_t buf_size;
166
20.2k
  const uint8_t* WEBP_COUNTED_BY(buf_size) buf;
167
20.2k
  uint32_t total_size = TAG_SIZE +           // "WEBP".
168
20.2k
                        CHUNK_HEADER_SIZE +  // "VP8Xnnnn".
169
20.2k
                        VP8X_CHUNK_SIZE;     // data.
170
20.2k
  assert(data != NULL);
171
20.2k
  assert(data_size != NULL);
172
20.2k
  buf = *data;
173
20.2k
  buf_size = *data_size;
174
175
20.2k
  assert(alpha_data != NULL);
176
20.2k
  assert(alpha_size != NULL);
177
20.2k
  *alpha_data = NULL;
178
20.2k
  *alpha_size = 0;
179
180
46.1k
  while (1) {
181
46.1k
    uint32_t chunk_size;
182
46.1k
    uint32_t disk_chunk_size;  // chunk_size with padding
183
184
46.1k
    *data_size = buf_size;
185
46.1k
    *data = buf;
186
187
46.1k
    if (buf_size < CHUNK_HEADER_SIZE) {  // Insufficient data.
188
3.07k
      return VP8_STATUS_NOT_ENOUGH_DATA;
189
3.07k
    }
190
191
43.0k
    chunk_size = GetLE32(buf + TAG_SIZE);
192
43.0k
    if (chunk_size > MAX_CHUNK_PAYLOAD) {
193
29
      return VP8_STATUS_BITSTREAM_ERROR;  // Not a valid chunk size.
194
29
    }
195
    // For odd-sized chunk-payload, there's one byte padding at the end.
196
43.0k
    disk_chunk_size = (CHUNK_HEADER_SIZE + chunk_size + 1) & ~1u;
197
43.0k
    total_size += disk_chunk_size;
198
199
    // Check that total bytes skipped so far does not exceed riff_size.
200
43.0k
    if (riff_size > 0 && (total_size > riff_size)) {
201
3.11k
      return VP8_STATUS_BITSTREAM_ERROR;  // Not a valid chunk size.
202
3.11k
    }
203
204
    // Start of a (possibly incomplete) VP8/VP8L chunk implies that we have
205
    // parsed all the optional chunks.
206
    // Note: This check must occur before the check 'buf_size < disk_chunk_size'
207
    // below to allow incomplete VP8/VP8L chunks.
208
39.9k
    if (!memcmp(buf, "VP8 ", TAG_SIZE) || !memcmp(buf, "VP8L", TAG_SIZE)) {
209
8.52k
      return VP8_STATUS_OK;
210
8.52k
    }
211
212
31.4k
    if (buf_size < disk_chunk_size) {  // Insufficient data.
213
5.53k
      return VP8_STATUS_NOT_ENOUGH_DATA;
214
5.53k
    }
215
216
25.8k
    if (!memcmp(buf, "ALPH", TAG_SIZE)) {  // A valid ALPH header.
217
7.40k
      *alpha_data = buf + CHUNK_HEADER_SIZE;
218
7.40k
      *alpha_size = chunk_size;
219
7.40k
    }
220
221
    // We have a full and valid chunk; skip it.
222
25.8k
    buf += disk_chunk_size;
223
25.8k
    buf_size -= disk_chunk_size;
224
25.8k
  }
225
20.2k
}
226
227
// Validates the VP8/VP8L Header ("VP8 nnnn" or "VP8L nnnn") and skips over it.
228
// Returns VP8_STATUS_BITSTREAM_ERROR for invalid (chunk larger than
229
//         riff_size) VP8/VP8L header,
230
//         VP8_STATUS_NOT_ENOUGH_DATA in case of insufficient data, and
231
//         VP8_STATUS_OK otherwise.
232
// If a VP8/VP8L chunk is found, *chunk_size is set to the total number of bytes
233
// extracted from the VP8/VP8L chunk header.
234
// The flag '*is_lossless' is set to 1 in case of VP8L chunk / raw VP8L data.
235
static VP8StatusCode ParseVP8Header(const uint8_t* WEBP_COUNTED_BY(*data_size) *
236
                                        WEBP_SINGLE const data_ptr,
237
                                    size_t* WEBP_SINGLE const data_size,
238
                                    int have_all_data, size_t riff_size,
239
                                    size_t* WEBP_SINGLE const chunk_size,
240
940k
                                    int* WEBP_SINGLE const is_lossless) {
241
940k
  const size_t local_data_size = *data_size;
242
940k
  const uint8_t* WEBP_COUNTED_BY(local_data_size) const data = *data_ptr;
243
940k
  const int is_vp8 = !memcmp(data, "VP8 ", TAG_SIZE);
244
940k
  const int is_vp8l = !memcmp(data, "VP8L", TAG_SIZE);
245
940k
  const uint32_t minimal_size =
246
940k
      TAG_SIZE + CHUNK_HEADER_SIZE;  // "WEBP" + "VP8 nnnn" OR
247
                                     // "WEBP" + "VP8Lnnnn"
248
940k
  (void)local_data_size;
249
940k
  assert(data != NULL);
250
940k
  assert(data_size != NULL);
251
940k
  assert(chunk_size != NULL);
252
940k
  assert(is_lossless != NULL);
253
254
940k
  if (*data_size < CHUNK_HEADER_SIZE) {
255
0
    return VP8_STATUS_NOT_ENOUGH_DATA;  // Insufficient data.
256
0
  }
257
258
940k
  if (is_vp8 || is_vp8l) {
259
    // Bitstream contains VP8/VP8L header.
260
22.8k
    const uint32_t size = GetLE32(data + TAG_SIZE);
261
22.8k
    if ((riff_size >= minimal_size) && (size > riff_size - minimal_size)) {
262
1.60k
      return VP8_STATUS_BITSTREAM_ERROR;  // Inconsistent size information.
263
1.60k
    }
264
21.2k
    if (have_all_data && (size > *data_size - CHUNK_HEADER_SIZE)) {
265
37
      return VP8_STATUS_NOT_ENOUGH_DATA;  // Truncated bitstream.
266
37
    }
267
    // Skip over CHUNK_HEADER_SIZE bytes from VP8/VP8L Header.
268
21.2k
    *chunk_size = size;
269
21.2k
    *data_size -= CHUNK_HEADER_SIZE;
270
21.2k
    *data_ptr += CHUNK_HEADER_SIZE;
271
21.2k
    *is_lossless = is_vp8l;
272
917k
  } else {
273
    // Raw VP8/VP8L bitstream (no header).
274
917k
    *is_lossless = VP8LCheckSignature(data, *data_size);
275
917k
    *chunk_size = *data_size;
276
917k
  }
277
278
938k
  return VP8_STATUS_OK;
279
940k
}
280
281
//------------------------------------------------------------------------------
282
283
// Fetch '*width', '*height', '*has_alpha' and fill out 'headers' based on
284
// 'data'. All the output parameters may be NULL. If 'headers' is NULL only the
285
// minimal amount will be read to fetch the remaining parameters.
286
// If 'headers' is non-NULL this function will attempt to locate both alpha
287
// data (with or without a VP8X chunk) and the bitstream chunk (VP8/VP8L).
288
// Note: The following chunk sequences (before the raw VP8/VP8L data) are
289
// considered valid by this function:
290
// RIFF + VP8(L)
291
// RIFF + VP8X + (optional chunks) + VP8(L)
292
// ALPH + VP8 <-- Not a valid WebP format: only allowed for internal purpose.
293
// VP8(L)     <-- Not a valid WebP format: only allowed for internal purpose.
294
static VP8StatusCode ParseHeadersInternal(
295
    const uint8_t* WEBP_COUNTED_BY(data_size_param) data_param,
296
    size_t data_size_param, int* const width, int* const height,
297
    int* const has_alpha, int* const has_animation, int* const format,
298
964k
    WebPHeaderStructure* const headers) {
299
964k
  size_t data_size = data_size_param;
300
964k
  const uint8_t* WEBP_COUNTED_BY(data_size) data = data_param;
301
964k
  int canvas_width = 0;
302
964k
  int canvas_height = 0;
303
964k
  int image_width = 0;
304
964k
  int image_height = 0;
305
964k
  int found_riff = 0;
306
964k
  int found_vp8x = 0;
307
964k
  int animation_present = 0;
308
964k
  const int have_all_data = (headers != NULL) ? headers->have_all_data : 0;
309
310
964k
  VP8StatusCode status;
311
964k
  WebPHeaderStructure hdrs;
312
313
964k
  if (data == NULL || data_size < RIFF_HEADER_SIZE) {
314
14
    return VP8_STATUS_NOT_ENOUGH_DATA;
315
14
  }
316
964k
  WEBP_UNSAFE_MEMSET(&hdrs, 0, sizeof(hdrs));
317
964k
  hdrs.data = data;
318
964k
  hdrs.data_size = data_size;
319
320
  // Skip over RIFF header.
321
964k
  status = ParseRIFF(&data, &data_size, have_all_data, &hdrs.riff_size);
322
964k
  if (status != VP8_STATUS_OK) {
323
4.19k
    return status;  // Wrong RIFF header / insufficient data.
324
4.19k
  }
325
959k
  found_riff = (hdrs.riff_size > 0);
326
327
  // Skip over VP8X.
328
959k
  {
329
959k
    uint32_t flags = 0;
330
959k
    status = ParseVP8X(&data, &data_size, &found_vp8x, &canvas_width,
331
959k
                       &canvas_height, &flags);
332
959k
    if (status != VP8_STATUS_OK) {
333
6.70k
      return status;  // Wrong VP8X / insufficient data.
334
6.70k
    }
335
953k
    animation_present = !!(flags & ANIMATION_FLAG);
336
953k
    if (!found_riff && found_vp8x) {
337
      // Note: This restriction may be removed in the future, if it becomes
338
      // necessary to send VP8X chunk to the decoder.
339
2
      return VP8_STATUS_BITSTREAM_ERROR;
340
2
    }
341
953k
    if (has_alpha != NULL) *has_alpha = !!(flags & ALPHA_FLAG);
342
953k
    if (has_animation != NULL) *has_animation = animation_present;
343
953k
    if (format != NULL) *format = 0;  // default = undefined
344
345
953k
    image_width = canvas_width;
346
953k
    image_height = canvas_height;
347
953k
    if (found_vp8x && animation_present && headers == NULL) {
348
1.03k
      status = VP8_STATUS_OK;
349
1.03k
      goto ReturnWidthHeight;  // Just return features from VP8X header.
350
1.03k
    }
351
953k
  }
352
353
952k
  if (data_size < TAG_SIZE) {
354
19
    status = VP8_STATUS_NOT_ENOUGH_DATA;
355
19
    goto ReturnWidthHeight;
356
19
  }
357
358
  // Skip over optional chunks if data started with "RIFF + VP8X" or "ALPH".
359
952k
  if ((found_riff && found_vp8x) ||
360
941k
      (!found_riff && !found_vp8x && !memcmp(data, "ALPH", TAG_SIZE))) {
361
20.2k
    size_t local_alpha_data_size = 0;
362
20.2k
    const uint8_t* WEBP_COUNTED_BY(local_alpha_data_size) local_alpha_data =
363
20.2k
        NULL;
364
20.2k
    status = ParseOptionalChunks(&data, &data_size, hdrs.riff_size,
365
20.2k
                                 &local_alpha_data, &local_alpha_data_size);
366
20.2k
    if (status != VP8_STATUS_OK) {
367
11.7k
      goto ReturnWidthHeight;  // Invalid chunk size / insufficient data.
368
11.7k
    }
369
8.52k
    hdrs.alpha_data = local_alpha_data;
370
8.52k
    hdrs.alpha_data_size = local_alpha_data_size;
371
8.52k
  }
372
373
  // Skip over VP8/VP8L header.
374
940k
  status = ParseVP8Header(&data, &data_size, have_all_data, hdrs.riff_size,
375
940k
                          &hdrs.compressed_size, &hdrs.is_lossless);
376
940k
  if (status != VP8_STATUS_OK) {
377
1.63k
    goto ReturnWidthHeight;  // Wrong VP8/VP8L chunk-header / insufficient data.
378
1.63k
  }
379
938k
  if (hdrs.compressed_size > MAX_CHUNK_PAYLOAD) {
380
39
    return VP8_STATUS_BITSTREAM_ERROR;
381
39
  }
382
383
938k
  if (format != NULL && !animation_present) {
384
664k
    *format = hdrs.is_lossless ? 2 : 1;
385
664k
  }
386
387
938k
  if (!hdrs.is_lossless) {
388
584k
    if (data_size < VP8_FRAME_HEADER_SIZE) {
389
3.29k
      status = VP8_STATUS_NOT_ENOUGH_DATA;
390
3.29k
      goto ReturnWidthHeight;
391
3.29k
    }
392
    // Validates raw VP8 data.
393
581k
    if (!VP8GetInfo(data, data_size, (uint32_t)hdrs.compressed_size,
394
581k
                    &image_width, &image_height)) {
395
21.8k
      return VP8_STATUS_BITSTREAM_ERROR;
396
21.8k
    }
397
581k
  } else {
398
353k
    if (data_size < VP8L_FRAME_HEADER_SIZE) {
399
2.92k
      status = VP8_STATUS_NOT_ENOUGH_DATA;
400
2.92k
      goto ReturnWidthHeight;
401
2.92k
    }
402
    // Validates raw VP8L data.
403
350k
    if (!VP8LGetInfo(data, data_size, &image_width, &image_height, has_alpha)) {
404
4.69k
      return VP8_STATUS_BITSTREAM_ERROR;
405
4.69k
    }
406
350k
  }
407
  // Validates image size coherency.
408
905k
  if (found_vp8x) {
409
412
    if (canvas_width != image_width || canvas_height != image_height) {
410
38
      return VP8_STATUS_BITSTREAM_ERROR;
411
38
    }
412
412
  }
413
905k
  if (headers != NULL) {
414
274k
    *headers = hdrs;
415
274k
    headers->offset = data - headers->data;
416
274k
    assert((uint64_t)(data - headers->data) < MAX_CHUNK_PAYLOAD);
417
274k
    assert(headers->offset == headers->data_size - data_size);
418
274k
  }
419
926k
ReturnWidthHeight:
420
926k
  if (status == VP8_STATUS_OK ||
421
909k
      (status == VP8_STATUS_NOT_ENOUGH_DATA && found_vp8x && headers == NULL)) {
422
909k
    if (has_alpha != NULL) {
423
      // If the data did not contain a VP8X/VP8L chunk the only definitive way
424
      // to set this is by looking for alpha data (from an ALPH chunk).
425
635k
      *has_alpha |= (hdrs.alpha_data != NULL);
426
635k
    }
427
909k
    if (width != NULL) *width = image_width;
428
909k
    if (height != NULL) *height = image_height;
429
909k
    return VP8_STATUS_OK;
430
909k
  } else {
431
16.5k
    return status;
432
16.5k
  }
433
926k
}
434
435
276k
VP8StatusCode WebPParseHeaders(WebPHeaderStructure* const headers) {
436
  // status is marked volatile as a workaround for a clang-3.8 (aarch64) bug
437
276k
  volatile VP8StatusCode status;
438
276k
  int has_animation = 0;
439
276k
  assert(headers != NULL);
440
  // fill out headers, ignore width/height/has_alpha.
441
276k
  {
442
276k
    const uint8_t* WEBP_BIDI_INDEXABLE const bounded_data =
443
276k
        WEBP_UNSAFE_FORGE_BIDI_INDEXABLE(const uint8_t*, headers->data,
444
276k
                                         headers->data_size);
445
276k
    status = ParseHeadersInternal(bounded_data, headers->data_size, NULL, NULL,
446
276k
                                  NULL, &has_animation, NULL, headers);
447
276k
  }
448
276k
  if (status == VP8_STATUS_OK || status == VP8_STATUS_NOT_ENOUGH_DATA) {
449
    // The WebPDemux API + libwebp can be used to decode individual
450
    // uncomposited frames or the WebPAnimDecoder can be used to fully
451
    // reconstruct them (see webp/demux.h).
452
276k
    if (has_animation) {
453
124
      status = VP8_STATUS_UNSUPPORTED_FEATURE;
454
124
    }
455
276k
  }
456
276k
  return status;
457
276k
}
458
459
//------------------------------------------------------------------------------
460
// WebPDecParams
461
462
276k
void WebPResetDecParams(WebPDecParams* const params) {
463
276k
  if (params != NULL) {
464
276k
    WEBP_UNSAFE_MEMSET(params, 0, sizeof(*params));
465
276k
  }
466
276k
}
467
468
//------------------------------------------------------------------------------
469
// "Into" decoding variants
470
471
// Main flow
472
WEBP_NODISCARD static VP8StatusCode DecodeInto(
473
    const uint8_t* WEBP_COUNTED_BY(data_size) const data, size_t data_size,
474
273k
    WebPDecParams* const params) {
475
273k
  VP8StatusCode status;
476
273k
  VP8Io io;
477
273k
  WebPHeaderStructure headers;
478
479
273k
  headers.data = data;
480
273k
  headers.data_size = data_size;
481
273k
  headers.have_all_data = 1;
482
273k
  status = WebPParseHeaders(&headers);  // Process Pre-VP8 chunks.
483
273k
  if (status != VP8_STATUS_OK) {
484
2.53k
    return status;
485
2.53k
  }
486
487
273k
  assert(params != NULL);
488
271k
  if (!VP8InitIo(&io)) {
489
0
    return VP8_STATUS_INVALID_PARAM;
490
0
  }
491
271k
  io.data = headers.data + headers.offset;
492
271k
  io.data_size = headers.data_size - headers.offset;
493
271k
  WebPInitCustomIo(params, &io);  // Plug the I/O functions.
494
495
271k
  if (!headers.is_lossless) {
496
165k
    VP8Decoder* const dec = VP8New();
497
165k
    if (dec == NULL) {
498
0
      return VP8_STATUS_OUT_OF_MEMORY;
499
0
    }
500
165k
    dec->alpha_data = headers.alpha_data;
501
165k
    dec->alpha_data_size = headers.alpha_data_size;
502
503
    // Decode bitstream header, update io->width/io->height.
504
165k
    if (!VP8GetHeaders(dec, &io)) {
505
20.9k
      status = dec->status;  // An error occurred. Grab error status.
506
144k
    } else {
507
      // Allocate/check output buffers.
508
144k
      status = WebPAllocateDecBuffer(io.width, io.height, params->options,
509
144k
                                     params->output);
510
144k
      if (status == VP8_STATUS_OK) {  // Decode
511
        // This change must be done before calling VP8Decode()
512
144k
        dec->mt_method =
513
144k
            VP8GetThreadMethod(params->options, &headers, io.width, io.height);
514
144k
        VP8InitDithering(params->options, dec);
515
144k
        if (!VP8Decode(dec, &io)) {
516
29.4k
          status = dec->status;
517
29.4k
        }
518
144k
      }
519
144k
    }
520
165k
    VP8Delete(dec);
521
165k
  } else {
522
106k
    VP8LDecoder* const dec = VP8LNew();
523
106k
    if (dec == NULL) {
524
0
      return VP8_STATUS_OUT_OF_MEMORY;
525
0
    }
526
106k
    if (!VP8LDecodeHeader(dec, &io)) {
527
70.2k
      status = dec->status;  // An error occurred. Grab error status.
528
70.2k
    } else {
529
      // Allocate/check output buffers.
530
35.9k
      status = WebPAllocateDecBuffer(io.width, io.height, params->options,
531
35.9k
                                     params->output);
532
35.9k
      if (status == VP8_STATUS_OK) {  // Decode
533
35.9k
        if (!VP8LDecodeImage(dec)) {
534
404
          status = dec->status;
535
404
        }
536
35.9k
      }
537
35.9k
    }
538
106k
    VP8LDelete(dec);
539
106k
  }
540
541
271k
  if (status != VP8_STATUS_OK) {
542
121k
    WebPFreeDecBuffer(params->output);
543
150k
  } else {
544
150k
    if (params->options != NULL && params->options->flip) {
545
      // This restores the original stride values if options->flip was used
546
      // during the call to WebPAllocateDecBuffer above.
547
0
      status = WebPFlipBuffer(params->output);
548
0
    }
549
150k
  }
550
271k
  return status;
551
271k
}
552
553
// Helpers
554
WEBP_NODISCARD static uint8_t* DecodeIntoRGBABuffer(
555
    WEBP_CSP_MODE colorspace,
556
    const uint8_t* WEBP_COUNTED_BY(data_size) const data, size_t data_size,
557
0
    uint8_t* WEBP_COUNTED_BY(size) const rgba, int stride, size_t size) {
558
0
  WebPDecParams params;
559
0
  WebPDecBuffer buf;
560
0
  if (rgba == NULL || !WebPInitDecBuffer(&buf)) {
561
0
    return NULL;
562
0
  }
563
0
  WebPResetDecParams(&params);
564
0
  params.output = &buf;
565
0
  buf.colorspace = colorspace;
566
0
  buf.u.RGBA.rgba = rgba;
567
0
  buf.u.RGBA.stride = stride;
568
0
  buf.u.RGBA.size = size;
569
0
  buf.is_external_memory = 1;
570
0
  if (DecodeInto(data, data_size, &params) != VP8_STATUS_OK) {
571
0
    return NULL;
572
0
  }
573
0
  return rgba;
574
0
}
575
576
uint8_t* WebPDecodeRGBInto(const uint8_t* WEBP_COUNTED_BY(data_size) data,
577
                           size_t data_size,
578
                           uint8_t* WEBP_COUNTED_BY(size) output, size_t size,
579
0
                           int stride) {
580
0
  return DecodeIntoRGBABuffer(MODE_RGB, data, data_size, output, stride, size);
581
0
}
582
583
uint8_t* WebPDecodeRGBAInto(const uint8_t* WEBP_COUNTED_BY(data_size) data,
584
                            size_t data_size,
585
                            uint8_t* WEBP_COUNTED_BY(size) output, size_t size,
586
0
                            int stride) {
587
0
  return DecodeIntoRGBABuffer(MODE_RGBA, data, data_size, output, stride, size);
588
0
}
589
590
uint8_t* WebPDecodeARGBInto(const uint8_t* WEBP_COUNTED_BY(data_size) data,
591
                            size_t data_size,
592
                            uint8_t* WEBP_COUNTED_BY(size) output, size_t size,
593
0
                            int stride) {
594
0
  return DecodeIntoRGBABuffer(MODE_ARGB, data, data_size, output, stride, size);
595
0
}
596
597
uint8_t* WebPDecodeBGRInto(const uint8_t* WEBP_COUNTED_BY(data_size) data,
598
                           size_t data_size,
599
                           uint8_t* WEBP_COUNTED_BY(size) output, size_t size,
600
0
                           int stride) {
601
0
  return DecodeIntoRGBABuffer(MODE_BGR, data, data_size, output, stride, size);
602
0
}
603
604
uint8_t* WebPDecodeBGRAInto(const uint8_t* WEBP_COUNTED_BY(data_size) data,
605
                            size_t data_size,
606
                            uint8_t* WEBP_COUNTED_BY(size) output, size_t size,
607
0
                            int stride) {
608
0
  return DecodeIntoRGBABuffer(MODE_BGRA, data, data_size, output, stride, size);
609
0
}
610
611
uint8_t* WebPDecodeYUVInto(const uint8_t* WEBP_COUNTED_BY(data_size) data,
612
                           size_t data_size,
613
                           uint8_t* WEBP_COUNTED_BY(luma_size) luma,
614
                           size_t luma_size, int luma_stride,
615
                           uint8_t* WEBP_COUNTED_BY(u_size) u, size_t u_size,
616
                           int u_stride, uint8_t* WEBP_COUNTED_BY(v_size) v,
617
0
                           size_t v_size, int v_stride) {
618
0
  WebPDecParams params;
619
0
  WebPDecBuffer output;
620
0
  if (luma == NULL || !WebPInitDecBuffer(&output)) return NULL;
621
0
  WebPResetDecParams(&params);
622
0
  params.output = &output;
623
0
  output.colorspace = MODE_YUV;
624
0
  output.u.YUVA.y = luma;
625
0
  output.u.YUVA.y_stride = luma_stride;
626
0
  output.u.YUVA.y_size = luma_size;
627
0
  output.u.YUVA.u = u;
628
0
  output.u.YUVA.u_stride = u_stride;
629
0
  output.u.YUVA.u_size = u_size;
630
0
  output.u.YUVA.v = v;
631
0
  output.u.YUVA.v_stride = v_stride;
632
0
  output.u.YUVA.v_size = v_size;
633
0
  output.is_external_memory = 1;
634
0
  if (DecodeInto(data, data_size, &params) != VP8_STATUS_OK) {
635
0
    return NULL;
636
0
  }
637
0
  return luma;
638
0
}
639
640
//------------------------------------------------------------------------------
641
642
WEBP_NODISCARD static uint8_t* Decode(WEBP_CSP_MODE mode,
643
                                      const uint8_t* WEBP_COUNTED_BY(data_size)
644
                                          const data,
645
                                      size_t data_size, int* const width,
646
                                      int* const height,
647
273k
                                      WebPDecBuffer* const keep_info) {
648
273k
  WebPDecParams params;
649
273k
  WebPDecBuffer output;
650
651
273k
  if (!WebPInitDecBuffer(&output)) {
652
0
    return NULL;
653
0
  }
654
273k
  WebPResetDecParams(&params);
655
273k
  params.output = &output;
656
273k
  output.colorspace = mode;
657
658
  // Retrieve (and report back) the required dimensions from bitstream.
659
273k
  if (!WebPGetInfo(data, data_size, &output.width, &output.height)) {
660
0
    return NULL;
661
0
  }
662
273k
  if (width != NULL) *width = output.width;
663
273k
  if (height != NULL) *height = output.height;
664
665
  // Decode
666
273k
  if (DecodeInto(data, data_size, &params) != VP8_STATUS_OK) {
667
123k
    return NULL;
668
123k
  }
669
150k
  if (keep_info != NULL) {  // keep track of the side-info
670
0
    WebPCopyDecBuffer(&output, keep_info);
671
0
  }
672
  // return decoded samples (don't clear 'output'!)
673
150k
  return WebPIsRGBMode(mode) ? output.u.RGBA.rgba : output.u.YUVA.y;
674
273k
}
675
676
uint8_t* WebPDecodeRGB(const uint8_t* WEBP_COUNTED_BY(data_size) data,
677
269k
                       size_t data_size, int* width, int* height) {
678
269k
  return Decode(MODE_RGB, data, data_size, width, height, NULL);
679
269k
}
680
681
uint8_t* WebPDecodeRGBA(const uint8_t* WEBP_COUNTED_BY(data_size) data,
682
3.97k
                        size_t data_size, int* width, int* height) {
683
3.97k
  return Decode(MODE_RGBA, data, data_size, width, height, NULL);
684
3.97k
}
685
686
uint8_t* WebPDecodeARGB(const uint8_t* WEBP_COUNTED_BY(data_size) data,
687
0
                        size_t data_size, int* width, int* height) {
688
0
  return Decode(MODE_ARGB, data, data_size, width, height, NULL);
689
0
}
690
691
uint8_t* WebPDecodeBGR(const uint8_t* WEBP_COUNTED_BY(data_size) data,
692
0
                       size_t data_size, int* width, int* height) {
693
0
  return Decode(MODE_BGR, data, data_size, width, height, NULL);
694
0
}
695
696
uint8_t* WebPDecodeBGRA(const uint8_t* WEBP_COUNTED_BY(data_size) data,
697
0
                        size_t data_size, int* width, int* height) {
698
0
  return Decode(MODE_BGRA, data, data_size, width, height, NULL);
699
0
}
700
701
uint8_t* WebPDecodeYUV(const uint8_t* WEBP_COUNTED_BY(data_size) data,
702
                       size_t data_size, int* width, int* height, uint8_t** u,
703
0
                       uint8_t** v, int* stride, int* uv_stride) {
704
  // data, width and height are checked by Decode().
705
0
  if (u == NULL || v == NULL || stride == NULL || uv_stride == NULL) {
706
0
    return NULL;
707
0
  }
708
709
0
  {
710
0
    WebPDecBuffer output;  // only to preserve the side-infos
711
0
    uint8_t* const out =
712
0
        Decode(MODE_YUV, data, data_size, width, height, &output);
713
714
0
    if (out != NULL) {
715
0
      const WebPYUVABuffer* const buf = &output.u.YUVA;
716
0
      *u = buf->u;
717
0
      *v = buf->v;
718
0
      *stride = buf->y_stride;
719
0
      *uv_stride = buf->u_stride;
720
0
      assert(buf->u_stride == buf->v_stride);
721
0
    }
722
0
    return out;
723
0
  }
724
0
}
725
726
690k
static void DefaultFeatures(WebPBitstreamFeatures* const features) {
727
690k
  assert(features != NULL);
728
690k
  WEBP_UNSAFE_MEMSET(features, 0, sizeof(*features));
729
690k
}
730
731
static VP8StatusCode GetFeatures(const uint8_t* WEBP_COUNTED_BY(data_size)
732
                                     const data,
733
                                 size_t data_size,
734
687k
                                 WebPBitstreamFeatures* const features) {
735
687k
  if (features == NULL || data == NULL) {
736
0
    return VP8_STATUS_INVALID_PARAM;
737
0
  }
738
687k
  DefaultFeatures(features);
739
740
  // Only parse enough of the data to retrieve the features.
741
687k
  return ParseHeadersInternal(
742
687k
      data, data_size, &features->width, &features->height,
743
687k
      &features->has_alpha, &features->has_animation, &features->format, NULL);
744
687k
}
745
746
//------------------------------------------------------------------------------
747
// WebPGetInfo()
748
749
int WebPGetInfo(const uint8_t* WEBP_COUNTED_BY(data_size) data,
750
276k
                size_t data_size, int* width, int* height) {
751
276k
  WebPBitstreamFeatures features;
752
753
276k
  if (GetFeatures(data, data_size, &features) != VP8_STATUS_OK) {
754
108
    return 0;
755
108
  }
756
757
276k
  if (width != NULL) {
758
276k
    *width = features.width;
759
276k
  }
760
276k
  if (height != NULL) {
761
276k
    *height = features.height;
762
276k
  }
763
764
276k
  return 1;
765
276k
}
766
767
//------------------------------------------------------------------------------
768
// Advance decoding API
769
770
2.84k
int WebPInitDecoderConfigInternal(WebPDecoderConfig* config, int version) {
771
2.84k
  if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_DECODER_ABI_VERSION)) {
772
0
    return 0;  // version mismatch
773
0
  }
774
2.84k
  if (config == NULL) {
775
0
    return 0;
776
0
  }
777
2.84k
  WEBP_UNSAFE_MEMSET(config, 0, sizeof(*config));
778
2.84k
  DefaultFeatures(&config->input);
779
2.84k
  if (!WebPInitDecBuffer(&config->output)) {
780
0
    return 0;
781
0
  }
782
2.84k
  return 1;
783
2.84k
}
784
785
0
static int WebPCheckCropDimensionsBasic(int x, int y, int w, int h) {
786
0
  return !(x < 0 || y < 0 || w <= 0 || h <= 0);
787
0
}
788
789
0
int WebPValidateDecoderConfig(const WebPDecoderConfig* config) {
790
0
  const WebPDecoderOptions* options;
791
0
  if (config == NULL) return 0;
792
0
  if (!IsValidColorspace(config->output.colorspace)) {
793
0
    return 0;
794
0
  }
795
796
0
  options = &config->options;
797
  // bypass_filtering, no_fancy_upsampling, use_cropping, use_scaling,
798
  // use_threads, flip can be any integer and are interpreted as boolean.
799
800
  // Check for cropping.
801
0
  if (options->use_cropping && !WebPCheckCropDimensionsBasic(
802
0
                                   options->crop_left, options->crop_top,
803
0
                                   options->crop_width, options->crop_height)) {
804
0
    return 0;
805
0
  }
806
  // Check for scaling.
807
0
  if (options->use_scaling &&
808
0
      (options->scaled_width < 0 || options->scaled_height < 0 ||
809
0
       (options->scaled_width == 0 && options->scaled_height == 0))) {
810
0
    return 0;
811
0
  }
812
813
  // In case the WebPBitstreamFeatures has been filled in, check further.
814
0
  if (config->input.width > 0 || config->input.height > 0) {
815
0
    int scaled_width = options->scaled_width;
816
0
    int scaled_height = options->scaled_height;
817
0
    if (options->use_cropping &&
818
0
        !WebPCheckCropDimensions(config->input.width, config->input.height,
819
0
                                 options->crop_left, options->crop_top,
820
0
                                 options->crop_width, options->crop_height)) {
821
0
      return 0;
822
0
    }
823
0
    if (options->use_scaling && !WebPRescalerGetScaledDimensions(
824
0
                                    config->input.width, config->input.height,
825
0
                                    &scaled_width, &scaled_height)) {
826
0
      return 0;
827
0
    }
828
0
  }
829
830
  // Check for dithering.
831
0
  if (options->dithering_strength < 0 || options->dithering_strength > 100 ||
832
0
      options->alpha_dithering_strength < 0 ||
833
0
      options->alpha_dithering_strength > 100) {
834
0
    return 0;
835
0
  }
836
837
0
  return 1;
838
0
}
839
840
VP8StatusCode WebPGetFeaturesInternal(const uint8_t* WEBP_COUNTED_BY(data_size)
841
                                          data,
842
                                      size_t data_size,
843
                                      WebPBitstreamFeatures* features,
844
410k
                                      int version) {
845
410k
  if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_DECODER_ABI_VERSION)) {
846
0
    return VP8_STATUS_INVALID_PARAM;  // version mismatch
847
0
  }
848
410k
  if (features == NULL) {
849
0
    return VP8_STATUS_INVALID_PARAM;
850
0
  }
851
410k
  return GetFeatures(data, data_size, features);
852
410k
}
853
854
VP8StatusCode WebPDecode(const uint8_t* WEBP_COUNTED_BY(data_size) data,
855
0
                         size_t data_size, WebPDecoderConfig* config) {
856
0
  WebPDecParams params;
857
0
  VP8StatusCode status;
858
859
0
  if (config == NULL) {
860
0
    return VP8_STATUS_INVALID_PARAM;
861
0
  }
862
863
0
  status = GetFeatures(data, data_size, &config->input);
864
0
  if (status != VP8_STATUS_OK) {
865
0
    if (status == VP8_STATUS_NOT_ENOUGH_DATA) {
866
0
      return VP8_STATUS_BITSTREAM_ERROR;  // Not-enough-data treated as error.
867
0
    }
868
0
    return status;
869
0
  }
870
871
0
  WebPResetDecParams(&params);
872
0
  params.options = &config->options;
873
0
  params.output = &config->output;
874
0
  if (WebPAvoidSlowMemory(params.output, &config->input)) {
875
    // decoding to slow memory: use a temporary in-mem buffer to decode into.
876
0
    WebPDecBuffer in_mem_buffer;
877
0
    if (!WebPInitDecBuffer(&in_mem_buffer)) {
878
0
      return VP8_STATUS_INVALID_PARAM;
879
0
    }
880
0
    in_mem_buffer.colorspace = config->output.colorspace;
881
0
    in_mem_buffer.width = config->input.width;
882
0
    in_mem_buffer.height = config->input.height;
883
0
    params.output = &in_mem_buffer;
884
0
    status = DecodeInto(data, data_size, &params);
885
0
    if (status == VP8_STATUS_OK) {  // do the slow-copy
886
0
      status = WebPCopyDecBufferPixels(&in_mem_buffer, &config->output);
887
0
    }
888
0
    WebPFreeDecBuffer(&in_mem_buffer);
889
0
  } else {
890
0
    status = DecodeInto(data, data_size, &params);
891
0
  }
892
893
0
  return status;
894
0
}
895
896
//------------------------------------------------------------------------------
897
// Cropping and rescaling.
898
899
int WebPCheckCropDimensions(int image_width, int image_height, int x, int y,
900
0
                            int w, int h) {
901
0
  return WebPCheckCropDimensionsBasic(x, y, w, h) &&
902
0
         !(x >= image_width || w > image_width || w > image_width - x ||
903
0
           y >= image_height || h > image_height || h > image_height - y);
904
0
}
905
906
int WebPIoInitFromOptions(const WebPDecoderOptions* const options,
907
182k
                          VP8Io* const io, WEBP_CSP_MODE src_colorspace) {
908
182k
  const int W = io->width;
909
182k
  const int H = io->height;
910
182k
  int x = 0, y = 0, w = W, h = H;
911
912
  // Cropping
913
182k
  io->use_cropping = (options != NULL) && options->use_cropping;
914
182k
  if (io->use_cropping) {
915
0
    w = options->crop_width;
916
0
    h = options->crop_height;
917
0
    x = options->crop_left;
918
0
    y = options->crop_top;
919
0
    if (!WebPIsRGBMode(src_colorspace)) {  // only snap for YUV420
920
0
      x &= ~1;
921
0
      y &= ~1;
922
0
    }
923
0
    if (!WebPCheckCropDimensions(W, H, x, y, w, h)) {
924
0
      return 0;  // out of frame boundary error
925
0
    }
926
0
  }
927
182k
  io->crop_left = x;
928
182k
  io->crop_top = y;
929
182k
  io->crop_right = x + w;
930
182k
  io->crop_bottom = y + h;
931
182k
  io->mb_w = w;
932
182k
  io->mb_h = h;
933
934
  // Scaling
935
182k
  io->use_scaling = (options != NULL) && options->use_scaling;
936
182k
  if (io->use_scaling) {
937
0
    int scaled_width = options->scaled_width;
938
0
    int scaled_height = options->scaled_height;
939
0
    if (!WebPRescalerGetScaledDimensions(w, h, &scaled_width, &scaled_height)) {
940
0
      return 0;
941
0
    }
942
0
    io->scaled_width = scaled_width;
943
0
    io->scaled_height = scaled_height;
944
0
  }
945
946
  // Filter
947
182k
  io->bypass_filtering = (options != NULL) && options->bypass_filtering;
948
949
  // Fancy upsampler
950
182k
#ifdef FANCY_UPSAMPLING
951
182k
  io->fancy_upsampling = (options == NULL) || (!options->no_fancy_upsampling);
952
182k
#endif
953
954
182k
  if (io->use_scaling) {
955
    // disable filter (only for large downscaling ratio).
956
0
    io->bypass_filtering |=
957
0
        (io->scaled_width < W * 3 / 4) && (io->scaled_height < H * 3 / 4);
958
0
    io->fancy_upsampling = 0;
959
0
  }
960
182k
  return 1;
961
182k
}
962
963
//------------------------------------------------------------------------------