github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/image/webp/libwebp/src/dec/webp.c (about)

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