Coverage Report

Created: 2025-06-13 06:49

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