go-libwebp

Experimental translation from libwebp to Go source.
Log | Files | Refs | README | LICENSE

encode.h (28501B)


      1 // Copyright 2011 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 //   WebP encoder: main interface
     11 //
     12 // Author: Skal (pascal.massimino@gmail.com)
     13 
     14 #ifndef WEBP_WEBP_ENCODE_H_
     15 #define WEBP_WEBP_ENCODE_H_
     16 
     17 #include <stddef.h>
     18 
     19 #include "./types.h"
     20 
     21 #ifdef __cplusplus
     22 extern "C" {
     23 #endif
     24 
     25 #define WEBP_ENCODER_ABI_VERSION 0x0210  // MAJOR(8b) + MINOR(8b)
     26 
     27 // Note: forward declaring enumerations is not allowed in (strict) C and C++,
     28 // the types are left here for reference.
     29 // typedef enum WebPImageHint WebPImageHint;
     30 // typedef enum WebPEncCSP WebPEncCSP;
     31 // typedef enum WebPPreset WebPPreset;
     32 // typedef enum WebPEncodingError WebPEncodingError;
     33 typedef struct WebPConfig WebPConfig;
     34 typedef struct WebPPicture WebPPicture;   // main structure for I/O
     35 typedef struct WebPAuxStats WebPAuxStats;
     36 typedef struct WebPMemoryWriter WebPMemoryWriter;
     37 
     38 // Return the encoder's version number, packed in hexadecimal using 8bits for
     39 // each of major/minor/revision. E.g: v2.5.7 is 0x020507.
     40 WEBP_EXTERN int WebPGetEncoderVersion(void);
     41 
     42 //------------------------------------------------------------------------------
     43 // One-stop-shop call! No questions asked:
     44 
     45 // Returns the size of the compressed data (pointed to by *output), or 0 if
     46 // an error occurred. The compressed data must be released by the caller
     47 // using the call 'WebPFree(*output)'.
     48 // These functions compress using the lossy format, and the quality_factor
     49 // can go from 0 (smaller output, lower quality) to 100 (best quality,
     50 // larger output).
     51 WEBP_EXTERN size_t WebPEncodeRGB(const uint8_t* rgb,
     52                                  int width, int height, int stride,
     53                                  float quality_factor, uint8_t** output);
     54 WEBP_EXTERN size_t WebPEncodeBGR(const uint8_t* bgr,
     55                                  int width, int height, int stride,
     56                                  float quality_factor, uint8_t** output);
     57 WEBP_EXTERN size_t WebPEncodeRGBA(const uint8_t* rgba,
     58                                   int width, int height, int stride,
     59                                   float quality_factor, uint8_t** output);
     60 WEBP_EXTERN size_t WebPEncodeBGRA(const uint8_t* bgra,
     61                                   int width, int height, int stride,
     62                                   float quality_factor, uint8_t** output);
     63 
     64 // These functions are the equivalent of the above, but compressing in a
     65 // lossless manner. Files are usually larger than lossy format, but will
     66 // not suffer any compression loss.
     67 // Note these functions, like the lossy versions, use the library's default
     68 // settings. For lossless this means 'exact' is disabled. RGB values in
     69 // transparent areas will be modified to improve compression. To avoid this,
     70 // use WebPEncode() and set WebPConfig::exact to 1.
     71 WEBP_EXTERN size_t WebPEncodeLosslessRGB(const uint8_t* rgb,
     72                                          int width, int height, int stride,
     73                                          uint8_t** output);
     74 WEBP_EXTERN size_t WebPEncodeLosslessBGR(const uint8_t* bgr,
     75                                          int width, int height, int stride,
     76                                          uint8_t** output);
     77 WEBP_EXTERN size_t WebPEncodeLosslessRGBA(const uint8_t* rgba,
     78                                           int width, int height, int stride,
     79                                           uint8_t** output);
     80 WEBP_EXTERN size_t WebPEncodeLosslessBGRA(const uint8_t* bgra,
     81                                           int width, int height, int stride,
     82                                           uint8_t** output);
     83 
     84 //------------------------------------------------------------------------------
     85 // Coding parameters
     86 
     87 // Image characteristics hint for the underlying encoder.
     88 typedef enum WebPImageHint {
     89   WEBP_HINT_DEFAULT = 0,  // default preset.
     90   WEBP_HINT_PICTURE,      // digital picture, like portrait, inner shot
     91   WEBP_HINT_PHOTO,        // outdoor photograph, with natural lighting
     92   WEBP_HINT_GRAPH,        // Discrete tone image (graph, map-tile etc).
     93   WEBP_HINT_LAST
     94 } WebPImageHint;
     95 
     96 // Compression parameters.
     97 struct WebPConfig {
     98   int lossless;           // Lossless encoding (0=lossy(default), 1=lossless).
     99   float quality;          // between 0 and 100. For lossy, 0 gives the smallest
    100                           // size and 100 the largest. For lossless, this
    101                           // parameter is the amount of effort put into the
    102                           // compression: 0 is the fastest but gives larger
    103                           // files compared to the slowest, but best, 100.
    104   int method;             // quality/speed trade-off (0=fast, 6=slower-better)
    105 
    106   WebPImageHint image_hint;  // Hint for image type (lossless only for now).
    107 
    108   int target_size;        // if non-zero, set the desired target size in bytes.
    109                           // Takes precedence over the 'compression' parameter.
    110   float target_PSNR;      // if non-zero, specifies the minimal distortion to
    111                           // try to achieve. Takes precedence over target_size.
    112   int segments;           // maximum number of segments to use, in [1..4]
    113   int sns_strength;       // Spatial Noise Shaping. 0=off, 100=maximum.
    114   int filter_strength;    // range: [0 = off .. 100 = strongest]
    115   int filter_sharpness;   // range: [0 = off .. 7 = least sharp]
    116   int filter_type;        // filtering type: 0 = simple, 1 = strong (only used
    117                           // if filter_strength > 0 or autofilter > 0)
    118   int autofilter;         // Auto adjust filter's strength [0 = off, 1 = on]
    119   int alpha_compression;  // Algorithm for encoding the alpha plane (0 = none,
    120                           // 1 = compressed with WebP lossless). Default is 1.
    121   int alpha_filtering;    // Predictive filtering method for alpha plane.
    122                           //  0: none, 1: fast, 2: best. Default if 1.
    123   int alpha_quality;      // Between 0 (smallest size) and 100 (lossless).
    124                           // Default is 100.
    125   int pass;               // number of entropy-analysis passes (in [1..10]).
    126 
    127   int show_compressed;    // if true, export the compressed picture back.
    128                           // In-loop filtering is not applied.
    129   int preprocessing;      // preprocessing filter:
    130                           // 0=none, 1=segment-smooth, 2=pseudo-random dithering
    131   int partitions;         // log2(number of token partitions) in [0..3]. Default
    132                           // is set to 0 for easier progressive decoding.
    133   int partition_limit;    // quality degradation allowed to fit the 512k limit
    134                           // on prediction modes coding (0: no degradation,
    135                           // 100: maximum possible degradation).
    136   int emulate_jpeg_size;  // If true, compression parameters will be remapped
    137                           // to better match the expected output size from
    138                           // JPEG compression. Generally, the output size will
    139                           // be similar but the degradation will be lower.
    140   int thread_level;       // If non-zero, try and use multi-threaded encoding.
    141   int low_memory;         // If set, reduce memory usage (but increase CPU use).
    142 
    143   int near_lossless;      // Near lossless encoding [0 = max loss .. 100 = off
    144                           // (default)].
    145   int exact;              // if non-zero, preserve the exact RGB values under
    146                           // transparent area. Otherwise, discard this invisible
    147                           // RGB information for better compression. The default
    148                           // value is 0.
    149 
    150   int use_delta_palette;  // reserved
    151   int use_sharp_yuv;      // if needed, use sharp (and slow) RGB->YUV conversion
    152 
    153   int qmin;               // minimum permissible quality factor
    154   int qmax;               // maximum permissible quality factor
    155 };
    156 
    157 // Enumerate some predefined settings for WebPConfig, depending on the type
    158 // of source picture. These presets are used when calling WebPConfigPreset().
    159 typedef enum WebPPreset {
    160   WEBP_PRESET_DEFAULT = 0,  // default preset.
    161   WEBP_PRESET_PICTURE,      // digital picture, like portrait, inner shot
    162   WEBP_PRESET_PHOTO,        // outdoor photograph, with natural lighting
    163   WEBP_PRESET_DRAWING,      // hand or line drawing, with high-contrast details
    164   WEBP_PRESET_ICON,         // small-sized colorful images
    165   WEBP_PRESET_TEXT          // text-like
    166 } WebPPreset;
    167 
    168 // Internal, version-checked, entry point
    169 WEBP_NODISCARD WEBP_EXTERN int WebPConfigInitInternal(WebPConfig*, WebPPreset,
    170                                                       float, int);
    171 
    172 // Should always be called, to initialize a fresh WebPConfig structure before
    173 // modification. Returns false in case of version mismatch. WebPConfigInit()
    174 // must have succeeded before using the 'config' object.
    175 // Note that the default values are lossless=0 and quality=75.
    176 WEBP_NODISCARD static WEBP_INLINE int WebPConfigInit(WebPConfig* config) {
    177   return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f,
    178                                 WEBP_ENCODER_ABI_VERSION);
    179 }
    180 
    181 // This function will initialize the configuration according to a predefined
    182 // set of parameters (referred to by 'preset') and a given quality factor.
    183 // This function can be called as a replacement to WebPConfigInit(). Will
    184 // return false in case of error.
    185 WEBP_NODISCARD static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
    186                                                        WebPPreset preset,
    187                                                        float quality) {
    188   return WebPConfigInitInternal(config, preset, quality,
    189                                 WEBP_ENCODER_ABI_VERSION);
    190 }
    191 
    192 // Activate the lossless compression mode with the desired efficiency level
    193 // between 0 (fastest, lowest compression) and 9 (slower, best compression).
    194 // A good default level is '6', providing a fair tradeoff between compression
    195 // speed and final compressed size.
    196 // This function will overwrite several fields from config: 'method', 'quality'
    197 // and 'lossless'. Returns false in case of parameter error.
    198 WEBP_NODISCARD WEBP_EXTERN int WebPConfigLosslessPreset(WebPConfig* config,
    199                                                         int level);
    200 
    201 // Returns true if 'config' is non-NULL and all configuration parameters are
    202 // within their valid ranges.
    203 WEBP_NODISCARD WEBP_EXTERN int WebPValidateConfig(const WebPConfig* config);
    204 
    205 //------------------------------------------------------------------------------
    206 // Input / Output
    207 // Structure for storing auxiliary statistics.
    208 
    209 struct WebPAuxStats {
    210   int coded_size;         // final size
    211 
    212   float PSNR[5];          // peak-signal-to-noise ratio for Y/U/V/All/Alpha
    213   int block_count[3];     // number of intra4/intra16/skipped macroblocks
    214   int header_bytes[2];    // approximate number of bytes spent for header
    215                           // and mode-partition #0
    216   int residual_bytes[3][4];  // approximate number of bytes spent for
    217                              // DC/AC/uv coefficients for each (0..3) segments.
    218   int segment_size[4];    // number of macroblocks in each segments
    219   int segment_quant[4];   // quantizer values for each segments
    220   int segment_level[4];   // filtering strength for each segments [0..63]
    221 
    222   int alpha_data_size;    // size of the transparency data
    223   int layer_data_size;    // size of the enhancement layer data
    224 
    225   // lossless encoder statistics
    226   uint32_t lossless_features;  // bit0:predictor bit1:cross-color transform
    227                                // bit2:subtract-green bit3:color indexing
    228   int histogram_bits;          // number of precision bits of histogram
    229   int transform_bits;          // precision bits for predictor transform
    230   int cache_bits;              // number of bits for color cache lookup
    231   int palette_size;            // number of color in palette, if used
    232   int lossless_size;           // final lossless size
    233   int lossless_hdr_size;       // lossless header (transform, huffman etc) size
    234   int lossless_data_size;      // lossless image data size
    235   int cross_color_transform_bits;  // precision bits for cross-color transform
    236 
    237   uint32_t pad[1];  // padding for later use
    238 };
    239 
    240 // Signature for output function. Should return true if writing was successful.
    241 // data/data_size is the segment of data to write, and 'picture' is for
    242 // reference (and so one can make use of picture->custom_ptr).
    243 typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size,
    244                                   const WebPPicture* picture);
    245 
    246 // WebPMemoryWrite: a special WebPWriterFunction that writes to memory using
    247 // the following WebPMemoryWriter object (to be set as a custom_ptr).
    248 struct WebPMemoryWriter {
    249   uint8_t* mem;       // final buffer (of size 'max_size', larger than 'size').
    250   size_t   size;      // final size
    251   size_t   max_size;  // total capacity
    252   uint32_t pad[1];    // padding for later use
    253 };
    254 
    255 // The following must be called first before any use.
    256 WEBP_EXTERN void WebPMemoryWriterInit(WebPMemoryWriter* writer);
    257 
    258 // The following must be called to deallocate writer->mem memory. The 'writer'
    259 // object itself is not deallocated.
    260 WEBP_EXTERN void WebPMemoryWriterClear(WebPMemoryWriter* writer);
    261 // The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon
    262 // completion, writer.mem and writer.size will hold the coded data.
    263 // writer.mem must be freed by calling WebPMemoryWriterClear.
    264 WEBP_NODISCARD WEBP_EXTERN int WebPMemoryWrite(
    265     const uint8_t* data, size_t data_size, const WebPPicture* picture);
    266 
    267 // Progress hook, called from time to time to report progress. It can return
    268 // false to request an abort of the encoding process, or true otherwise if
    269 // everything is OK.
    270 typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture);
    271 
    272 // Color spaces.
    273 typedef enum WebPEncCSP {
    274   // chroma sampling
    275   WEBP_YUV420  = 0,        // 4:2:0
    276   WEBP_YUV420A = 4,        // alpha channel variant
    277   WEBP_CSP_UV_MASK = 3,    // bit-mask to get the UV sampling factors
    278   WEBP_CSP_ALPHA_BIT = 4   // bit that is set if alpha is present
    279 } WebPEncCSP;
    280 
    281 // Encoding error conditions.
    282 typedef enum WebPEncodingError {
    283   VP8_ENC_OK = 0,
    284   VP8_ENC_ERROR_OUT_OF_MEMORY,            // memory error allocating objects
    285   VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY,  // memory error while flushing bits
    286   VP8_ENC_ERROR_NULL_PARAMETER,           // a pointer parameter is NULL
    287   VP8_ENC_ERROR_INVALID_CONFIGURATION,    // configuration is invalid
    288   VP8_ENC_ERROR_BAD_DIMENSION,            // picture has invalid width/height
    289   VP8_ENC_ERROR_PARTITION0_OVERFLOW,      // partition is bigger than 512k
    290   VP8_ENC_ERROR_PARTITION_OVERFLOW,       // partition is bigger than 16M
    291   VP8_ENC_ERROR_BAD_WRITE,                // error while flushing bytes
    292   VP8_ENC_ERROR_FILE_TOO_BIG,             // file is bigger than 4G
    293   VP8_ENC_ERROR_USER_ABORT,               // abort request by user
    294   VP8_ENC_ERROR_LAST                      // list terminator. always last.
    295 } WebPEncodingError;
    296 
    297 // maximum width/height allowed (inclusive), in pixels
    298 #define WEBP_MAX_DIMENSION 16383
    299 
    300 // Main exchange structure (input samples, output bytes, statistics)
    301 //
    302 // Once WebPPictureInit() has been called, it's ok to make all the INPUT fields
    303 // (use_argb, y/u/v, argb, ...) point to user-owned data, even if
    304 // WebPPictureAlloc() has been called. Depending on the value use_argb,
    305 // it's guaranteed that either *argb or *y/*u/*v content will be kept untouched.
    306 struct WebPPicture {
    307   //   INPUT
    308   //////////////
    309   // Main flag for encoder selecting between ARGB or YUV input.
    310   // It is recommended to use ARGB input (*argb, argb_stride) for lossless
    311   // compression, and YUV input (*y, *u, *v, etc.) for lossy compression
    312   // since these are the respective native colorspace for these formats.
    313   int use_argb;
    314 
    315   // YUV input (mostly used for input to lossy compression)
    316   WebPEncCSP colorspace;     // colorspace: should be YUV420 for now (=Y'CbCr).
    317   int width, height;         // dimensions (less or equal to WEBP_MAX_DIMENSION)
    318   uint8_t* y, *u, *v;        // pointers to luma/chroma planes.
    319   int y_stride, uv_stride;   // luma/chroma strides.
    320   uint8_t* a;                // pointer to the alpha plane
    321   int a_stride;              // stride of the alpha plane
    322   uint32_t pad1[2];          // padding for later use
    323 
    324   // ARGB input (mostly used for input to lossless compression)
    325   uint32_t* argb;            // Pointer to argb (32 bit) plane.
    326   int argb_stride;           // This is stride in pixels units, not bytes.
    327   uint32_t pad2[3];          // padding for later use
    328 
    329   //   OUTPUT
    330   ///////////////
    331   // Byte-emission hook, to store compressed bytes as they are ready.
    332   WebPWriterFunction writer;  // can be NULL
    333   void* custom_ptr;           // can be used by the writer.
    334 
    335   // map for extra information (only for lossy compression mode)
    336   int extra_info_type;    // 1: intra type, 2: segment, 3: quant
    337                           // 4: intra-16 prediction mode,
    338                           // 5: chroma prediction mode,
    339                           // 6: bit cost, 7: distortion
    340   uint8_t* extra_info;    // if not NULL, points to an array of size
    341                           // ((width + 15) / 16) * ((height + 15) / 16) that
    342                           // will be filled with a macroblock map, depending
    343                           // on extra_info_type.
    344 
    345   //   STATS AND REPORTS
    346   ///////////////////////////
    347   // Pointer to side statistics (updated only if not NULL)
    348   WebPAuxStats* stats;
    349 
    350   // Error code for the latest error encountered during encoding
    351   WebPEncodingError error_code;
    352 
    353   // If not NULL, report progress during encoding.
    354   WebPProgressHook progress_hook;
    355 
    356   void* user_data;        // this field is free to be set to any value and
    357                           // used during callbacks (like progress-report e.g.).
    358 
    359   uint32_t pad3[3];       // padding for later use
    360 
    361   // Unused for now
    362   uint8_t* pad4, *pad5;
    363   uint32_t pad6[8];       // padding for later use
    364 
    365   // PRIVATE FIELDS
    366   ////////////////////
    367   void* memory_;          // row chunk of memory for yuva planes
    368   void* memory_argb_;     // and for argb too.
    369   void* pad7[2];          // padding for later use
    370 };
    371 
    372 // Internal, version-checked, entry point
    373 WEBP_NODISCARD WEBP_EXTERN int WebPPictureInitInternal(WebPPicture*, int);
    374 
    375 // Should always be called, to initialize the structure. Returns false in case
    376 // of version mismatch. WebPPictureInit() must have succeeded before using the
    377 // 'picture' object.
    378 // Note that, by default, use_argb is false and colorspace is WEBP_YUV420.
    379 WEBP_NODISCARD static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) {
    380   return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION);
    381 }
    382 
    383 //------------------------------------------------------------------------------
    384 // WebPPicture utils
    385 
    386 // Convenience allocation / deallocation based on picture->width/height:
    387 // Allocate y/u/v buffers as per colorspace/width/height specification.
    388 // Note! This function will free the previous buffer if needed.
    389 // Returns false in case of memory error.
    390 WEBP_NODISCARD WEBP_EXTERN int WebPPictureAlloc(WebPPicture* picture);
    391 
    392 // Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*().
    393 // Note that this function does _not_ free the memory used by the 'picture'
    394 // object itself.
    395 // Besides memory (which is reclaimed) all other fields of 'picture' are
    396 // preserved.
    397 WEBP_EXTERN void WebPPictureFree(WebPPicture* picture);
    398 
    399 // Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return, *dst
    400 // will fully own the copied pixels (this is not a view). The 'dst' picture need
    401 // not be initialized as its content is overwritten.
    402 // Returns false in case of memory allocation error.
    403 WEBP_NODISCARD WEBP_EXTERN int WebPPictureCopy(const WebPPicture* src,
    404                                                WebPPicture* dst);
    405 
    406 // Compute the single distortion for packed planes of samples.
    407 // 'src' will be compared to 'ref', and the raw distortion stored into
    408 // '*distortion'. The refined metric (log(MSE), log(1 - ssim),...' will be
    409 // stored in '*result'.
    410 // 'x_step' is the horizontal stride (in bytes) between samples.
    411 // 'src/ref_stride' is the byte distance between rows.
    412 // Returns false in case of error (bad parameter, memory allocation error, ...).
    413 WEBP_NODISCARD WEBP_EXTERN int WebPPlaneDistortion(
    414     const uint8_t* src, size_t src_stride,
    415     const uint8_t* ref, size_t ref_stride, int width, int height, size_t x_step,
    416     int type,  // 0 = PSNR, 1 = SSIM, 2 = LSIM
    417     float* distortion, float* result);
    418 
    419 // Compute PSNR, SSIM or LSIM distortion metric between two pictures. Results
    420 // are in dB, stored in result[] in the B/G/R/A/All order. The distortion is
    421 // always performed using ARGB samples. Hence if the input is YUV(A), the
    422 // picture will be internally converted to ARGB (just for the measurement).
    423 // Warning: this function is rather CPU-intensive.
    424 WEBP_NODISCARD WEBP_EXTERN int WebPPictureDistortion(
    425     const WebPPicture* src, const WebPPicture* ref,
    426     int metric_type,           // 0 = PSNR, 1 = SSIM, 2 = LSIM
    427     float result[5]);
    428 
    429 // self-crops a picture to the rectangle defined by top/left/width/height.
    430 // Returns false in case of memory allocation error, or if the rectangle is
    431 // outside of the source picture.
    432 // The rectangle for the view is defined by the top-left corner pixel
    433 // coordinates (left, top) as well as its width and height. This rectangle
    434 // must be fully be comprised inside the 'src' source picture. If the source
    435 // picture uses the YUV420 colorspace, the top and left coordinates will be
    436 // snapped to even values.
    437 WEBP_NODISCARD WEBP_EXTERN int WebPPictureCrop(
    438     WebPPicture* picture, int left, int top, int width, int height);
    439 
    440 // Extracts a view from 'src' picture into 'dst'. The rectangle for the view
    441 // is defined by the top-left corner pixel coordinates (left, top) as well
    442 // as its width and height. This rectangle must be fully be comprised inside
    443 // the 'src' source picture. If the source picture uses the YUV420 colorspace,
    444 // the top and left coordinates will be snapped to even values.
    445 // Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed
    446 // ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so,
    447 // the original dimension will be lost). Picture 'dst' need not be initialized
    448 // with WebPPictureInit() if it is different from 'src', since its content will
    449 // be overwritten.
    450 // Returns false in case of invalid parameters.
    451 WEBP_NODISCARD WEBP_EXTERN int WebPPictureView(
    452     const WebPPicture* src, int left, int top, int width, int height,
    453     WebPPicture* dst);
    454 
    455 // Returns true if the 'picture' is actually a view and therefore does
    456 // not own the memory for pixels.
    457 WEBP_EXTERN int WebPPictureIsView(const WebPPicture* picture);
    458 
    459 // Rescale a picture to new dimension width x height.
    460 // If either 'width' or 'height' (but not both) is 0 the corresponding
    461 // dimension will be calculated preserving the aspect ratio.
    462 // No gamma correction is applied.
    463 // Returns false in case of error (invalid parameter or insufficient memory).
    464 WEBP_NODISCARD WEBP_EXTERN int WebPPictureRescale(WebPPicture* picture,
    465                                                   int width, int height);
    466 
    467 // Colorspace conversion function to import RGB samples.
    468 // Previous buffer will be free'd, if any.
    469 // *rgb buffer should have a size of at least height * rgb_stride.
    470 // Returns false in case of memory error.
    471 WEBP_NODISCARD WEBP_EXTERN int WebPPictureImportRGB(
    472     WebPPicture* picture, const uint8_t* rgb, int rgb_stride);
    473 // Same, but for RGBA buffer.
    474 WEBP_NODISCARD WEBP_EXTERN int WebPPictureImportRGBA(
    475     WebPPicture* picture, const uint8_t* rgba, int rgba_stride);
    476 // Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format
    477 // input buffer ignoring the alpha channel. Avoids needing to copy the data
    478 // to a temporary 24-bit RGB buffer to import the RGB only.
    479 WEBP_NODISCARD WEBP_EXTERN int WebPPictureImportRGBX(
    480     WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride);
    481 
    482 // Variants of the above, but taking BGR(A|X) input.
    483 WEBP_NODISCARD WEBP_EXTERN int WebPPictureImportBGR(
    484     WebPPicture* picture, const uint8_t* bgr, int bgr_stride);
    485 WEBP_NODISCARD WEBP_EXTERN int WebPPictureImportBGRA(
    486     WebPPicture* picture, const uint8_t* bgra, int bgra_stride);
    487 WEBP_NODISCARD WEBP_EXTERN int WebPPictureImportBGRX(
    488     WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride);
    489 
    490 // Converts picture->argb data to the YUV420A format. The 'colorspace'
    491 // parameter is deprecated and should be equal to WEBP_YUV420.
    492 // Upon return, picture->use_argb is set to false. The presence of real
    493 // non-opaque transparent values is detected, and 'colorspace' will be
    494 // adjusted accordingly. Note that this method is lossy.
    495 // Returns false in case of error.
    496 WEBP_NODISCARD WEBP_EXTERN int WebPPictureARGBToYUVA(
    497     WebPPicture* picture, WebPEncCSP /*colorspace = WEBP_YUV420*/);
    498 
    499 // Same as WebPPictureARGBToYUVA(), but the conversion is done using
    500 // pseudo-random dithering with a strength 'dithering' between
    501 // 0.0 (no dithering) and 1.0 (maximum dithering). This is useful
    502 // for photographic picture.
    503 WEBP_NODISCARD WEBP_EXTERN int WebPPictureARGBToYUVADithered(
    504     WebPPicture* picture, WebPEncCSP colorspace, float dithering);
    505 
    506 // Performs 'sharp' RGBA->YUVA420 downsampling and colorspace conversion
    507 // Downsampling is handled with extra care in case of color clipping. This
    508 // method is roughly 2x slower than WebPPictureARGBToYUVA() but produces better
    509 // and sharper YUV representation.
    510 // Returns false in case of error.
    511 WEBP_NODISCARD WEBP_EXTERN int WebPPictureSharpARGBToYUVA(WebPPicture* picture);
    512 // kept for backward compatibility:
    513 WEBP_NODISCARD WEBP_EXTERN int WebPPictureSmartARGBToYUVA(WebPPicture* picture);
    514 
    515 // Converts picture->yuv to picture->argb and sets picture->use_argb to true.
    516 // The input format must be YUV_420 or YUV_420A. The conversion from YUV420 to
    517 // ARGB incurs a small loss too.
    518 // Note that the use of this colorspace is discouraged if one has access to the
    519 // raw ARGB samples, since using YUV420 is comparatively lossy.
    520 // Returns false in case of error.
    521 WEBP_NODISCARD WEBP_EXTERN int WebPPictureYUVAToARGB(WebPPicture* picture);
    522 
    523 // Helper function: given a width x height plane of RGBA or YUV(A) samples
    524 // clean-up or smoothen the YUV or RGB samples under fully transparent area,
    525 // to help compressibility (no guarantee, though).
    526 WEBP_EXTERN void WebPCleanupTransparentArea(WebPPicture* picture);
    527 
    528 // Scan the picture 'picture' for the presence of non fully opaque alpha values.
    529 // Returns true in such case. Otherwise returns false (indicating that the
    530 // alpha plane can be ignored altogether e.g.).
    531 WEBP_EXTERN int WebPPictureHasTransparency(const WebPPicture* picture);
    532 
    533 // Remove the transparency information (if present) by blending the color with
    534 // the background color 'background_rgb' (specified as 24bit RGB triplet).
    535 // After this call, all alpha values are reset to 0xff.
    536 WEBP_EXTERN void WebPBlendAlpha(WebPPicture* picture, uint32_t background_rgb);
    537 
    538 //------------------------------------------------------------------------------
    539 // Main call
    540 
    541 // Main encoding call, after config and picture have been initialized.
    542 // 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION),
    543 // and the 'config' object must be a valid one.
    544 // Returns false in case of error, true otherwise.
    545 // In case of error, picture->error_code is updated accordingly.
    546 // 'picture' can hold the source samples in both YUV(A) or ARGB input, depending
    547 // on the value of 'picture->use_argb'. It is highly recommended to use
    548 // the former for lossy encoding, and the latter for lossless encoding
    549 // (when config.lossless is true). Automatic conversion from one format to
    550 // another is provided but they both incur some loss.
    551 WEBP_NODISCARD WEBP_EXTERN int WebPEncode(const WebPConfig* config,
    552                                           WebPPicture* picture);
    553 
    554 //------------------------------------------------------------------------------
    555 
    556 #ifdef __cplusplus
    557 }    // extern "C"
    558 #endif
    559 
    560 #endif  // WEBP_WEBP_ENCODE_H_