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