Coverage Report

Created: 2024-06-18 06:05

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