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