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