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