Home | History | Annotate | Download | only in webp
      1 // Copyright 2011 Google Inc.
      2 //
      3 // This code is licensed under the same terms as WebM:
      4 //  Software License Agreement:  http://www.webmproject.org/license/software/
      5 //  Additional IP Rights Grant:  http://www.webmproject.org/license/additional/
      6 // -----------------------------------------------------------------------------
      7 //
      8 //   WebP encoder: main interface
      9 //
     10 // Author: Skal (pascal.massimino (at) gmail.com)
     11 
     12 #ifndef WEBP_WEBP_ENCODE_H_
     13 #define WEBP_WEBP_ENCODE_H_
     14 
     15 #include <stdlib.h>
     16 
     17 #include "./types.h"
     18 
     19 #if defined(__cplusplus) || defined(c_plusplus)
     20 extern "C" {
     21 #endif
     22 
     23 #define WEBP_ENCODER_ABI_VERSION 0x0002
     24 
     25 // Return the encoder's version number, packed in hexadecimal using 8bits for
     26 // each of major/minor/revision. E.g: v2.5.7 is 0x020507.
     27 WEBP_EXTERN(int) WebPGetEncoderVersion(void);
     28 
     29 //-----------------------------------------------------------------------------
     30 // One-stop-shop call! No questions asked:
     31 
     32 // Returns the size of the compressed data (pointed to by *output), or 0 if
     33 // an error occurred. The compressed data must be released by the caller
     34 // using the call 'free(*output)'.
     35 WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb,
     36                                   int width, int height, int stride,
     37                                   float quality_factor, uint8_t** output);
     38 WEBP_EXTERN(size_t) WebPEncodeBGR(const uint8_t* bgr,
     39                                   int width, int height, int stride,
     40                                   float quality_factor, uint8_t** output);
     41 WEBP_EXTERN(size_t) WebPEncodeRGBA(const uint8_t* rgba,
     42                                    int width, int height, int stride,
     43                                    float quality_factor, uint8_t** output);
     44 WEBP_EXTERN(size_t) WebPEncodeBGRA(const uint8_t* bgra,
     45                                    int width, int height, int stride,
     46                                    float quality_factor, uint8_t** output);
     47 
     48 //-----------------------------------------------------------------------------
     49 // Coding parameters
     50 
     51 typedef struct {
     52   float quality;         // between 0 (smallest file) and 100 (biggest)
     53   int target_size;       // if non-zero, set the desired target size in bytes.
     54                          // Takes precedence over the 'compression' parameter.
     55   float target_PSNR;     // if non-zero, specifies the minimal distortion to
     56                          // try to achieve. Takes precedence over target_size.
     57   int method;            // quality/speed trade-off (0=fast, 6=slower-better)
     58   int segments;          // maximum number of segments to use, in [1..4]
     59   int sns_strength;      // Spatial Noise Shaping. 0=off, 100=maximum.
     60   int filter_strength;   // range: [0 = off .. 100 = strongest]
     61   int filter_sharpness;  // range: [0 = off .. 7 = least sharp]
     62   int filter_type;       // filtering type: 0 = simple, 1 = strong
     63                          // (only used if filter_strength > 0 or autofilter > 0)
     64   int autofilter;        // Auto adjust filter's strength [0 = off, 1 = on]
     65   int pass;              // number of entropy-analysis passes (in [1..10]).
     66 
     67   int show_compressed;   // if true, export the compressed picture back.
     68                          // In-loop filtering is not applied.
     69   int preprocessing;     // preprocessing filter (0=none, 1=segment-smooth)
     70   int partitions;        // log2(number of token partitions) in [0..3]
     71                          // Default is set to 0 for easier progressive decoding.
     72   int alpha_compression;  // Algorithm for optimizing the alpha plane (0 = none)
     73 } WebPConfig;
     74 
     75 // Enumerate some predefined settings for WebPConfig, depending on the type
     76 // of source picture. These presets are used when calling WebPConfigPreset().
     77 typedef enum {
     78   WEBP_PRESET_DEFAULT = 0,  // default preset.
     79   WEBP_PRESET_PICTURE,      // digital picture, like portrait, inner shot
     80   WEBP_PRESET_PHOTO,        // outdoor photograph, with natural lighting
     81   WEBP_PRESET_DRAWING,      // hand or line drawing, with high-contrast details
     82   WEBP_PRESET_ICON,         // small-sized colorful images
     83   WEBP_PRESET_TEXT          // text-like
     84 } WebPPreset;
     85 
     86 // Internal, version-checked, entry point
     87 WEBP_EXTERN(int) WebPConfigInitInternal(
     88     WebPConfig* const, WebPPreset, float, int);
     89 
     90 // Should always be called, to initialize a fresh WebPConfig structure before
     91 // modification. Returns 0 in case of version mismatch. WebPConfigInit() must
     92 // have succeeded before using the 'config' object.
     93 static inline int WebPConfigInit(WebPConfig* const config) {
     94   return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f,
     95                                 WEBP_ENCODER_ABI_VERSION);
     96 }
     97 
     98 // This function will initialize the configuration according to a predefined
     99 // set of parameters (referred to by 'preset') and a given quality factor.
    100 // This function can be called as a replacement to WebPConfigInit(). Will
    101 // return 0 in case of error.
    102 static inline int WebPConfigPreset(WebPConfig* const config,
    103                                    WebPPreset preset, float quality) {
    104   return WebPConfigInitInternal(config, preset, quality,
    105                                 WEBP_ENCODER_ABI_VERSION);
    106 }
    107 
    108 // Returns 1 if all parameters are in valid range and the configuration is OK.
    109 WEBP_EXTERN(int) WebPValidateConfig(const WebPConfig* const config);
    110 
    111 //-----------------------------------------------------------------------------
    112 // Input / Output
    113 
    114 typedef struct WebPPicture WebPPicture;   // main structure for I/O
    115 
    116 // non-essential structure for storing auxiliary statistics
    117 typedef struct {
    118   float PSNR[4];          // peak-signal-to-noise ratio for Y/U/V/All
    119   int coded_size;         // final size
    120   int block_count[3];     // number of intra4/intra16/skipped macroblocks
    121   int header_bytes[2];    // approximate number of bytes spent for header
    122                           // and mode-partition #0
    123   int residual_bytes[3][4];  // approximate number of bytes spent for
    124                              // DC/AC/uv coefficients for each (0..3) segments.
    125   int segment_size[4];    // number of macroblocks in each segments
    126   int segment_quant[4];   // quantizer values for each segments
    127   int segment_level[4];   // filtering strength for each segments [0..63]
    128 
    129   int alpha_data_size;    // size of the transparency data
    130   int layer_data_size;    // size of the enhancement layer data
    131 } WebPAuxStats;
    132 
    133 // Signature for output function. Should return 1 if writing was successful.
    134 // data/data_size is the segment of data to write, and 'picture' is for
    135 // reference (and so one can make use of picture->custom_ptr).
    136 typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size,
    137                                   const WebPPicture* const picture);
    138 
    139 typedef enum {
    140   // chroma sampling
    141   WEBP_YUV420 = 0,   // 4:2:0
    142   WEBP_YUV422 = 1,   // 4:2:2
    143   WEBP_YUV444 = 2,   // 4:4:4
    144   WEBP_YUV400 = 3,   // grayscale
    145   WEBP_CSP_UV_MASK = 3,   // bit-mask to get the UV sampling factors
    146   // alpha channel variants
    147   WEBP_YUV420A = 4,
    148   WEBP_YUV422A = 5,
    149   WEBP_YUV444A = 6,
    150   WEBP_YUV400A = 7,   // grayscale + alpha
    151   WEBP_CSP_ALPHA_BIT = 4   // bit that is set if alpha is present
    152 } WebPEncCSP;
    153 
    154 // Encoding error conditions.
    155 typedef enum {
    156   VP8_ENC_OK = 0,
    157   VP8_ENC_ERROR_OUT_OF_MEMORY,            // memory error allocating objects
    158   VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY,  // memory error while flushing bits
    159   VP8_ENC_ERROR_NULL_PARAMETER,           // a pointer parameter is NULL
    160   VP8_ENC_ERROR_INVALID_CONFIGURATION,    // configuration is invalid
    161   VP8_ENC_ERROR_BAD_DIMENSION,            // picture has invalid width/height
    162   VP8_ENC_ERROR_PARTITION0_OVERFLOW,      // partition is too bigger than 16M
    163   VP8_ENC_ERROR_PARTITION_OVERFLOW,       // partition is too bigger than 512k
    164   VP8_ENC_ERROR_BAD_WRITE,                // error while flushing bytes
    165 } WebPEncodingError;
    166 
    167 struct WebPPicture {
    168   // input
    169   WebPEncCSP colorspace;     // colorspace: should be YUV420 for now (=Y'CbCr).
    170   int width, height;         // dimensions.
    171   uint8_t *y, *u, *v;        // pointers to luma/chroma planes.
    172   int y_stride, uv_stride;   // luma/chroma strides.
    173   uint8_t *a;                // pointer to the alpha plane
    174   int a_stride;              // stride of the alpha plane
    175 
    176   // output
    177   WebPWriterFunction writer;  // can be NULL
    178   void* custom_ptr;           // can be used by the writer.
    179 
    180   // map for extra information
    181   int extra_info_type;    // 1: intra type, 2: segment, 3: quant
    182                           // 4: intra-16 prediction mode,
    183                           // 5: chroma prediction mode,
    184                           // 6: bit cost, 7: distortion
    185   uint8_t* extra_info;    // if not NULL, points to an array of size
    186                           // ((width + 15) / 16) * ((height + 15) / 16) that
    187                           // will be filled with a macroblock map, depending
    188                           // on extra_info_type.
    189 
    190   // where to store statistics, if not NULL:
    191   WebPAuxStats* stats;
    192 
    193   // original samples (for non-YUV420 modes)
    194   uint8_t *u0, *v0;
    195   int uv0_stride;
    196 
    197   WebPEncodingError error_code;   // error code in case of problem.
    198 };
    199 
    200 // Internal, version-checked, entry point
    201 WEBP_EXTERN(int) WebPPictureInitInternal(WebPPicture* const, int);
    202 
    203 // Should always be called, to initialize the structure. Returns 0 in case of
    204 // version mismatch. WebPPictureInit() must have succeeded before using the
    205 // 'picture' object.
    206 static inline int WebPPictureInit(WebPPicture* const picture) {
    207   return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION);
    208 }
    209 
    210 //-----------------------------------------------------------------------------
    211 // WebPPicture utils
    212 
    213 // Convenience allocation / deallocation based on picture->width/height:
    214 // Allocate y/u/v buffers as per colorspace/width/height specification.
    215 // Note! This function will free the previous buffer if needed.
    216 // Returns 0 in case of memory error.
    217 WEBP_EXTERN(int) WebPPictureAlloc(WebPPicture* const picture);
    218 
    219 // Release memory allocated by WebPPictureAlloc() or WebPPictureImport*()
    220 // Note that this function does _not_ free the memory pointed to by 'picture'.
    221 WEBP_EXTERN(void) WebPPictureFree(WebPPicture* const picture);
    222 
    223 // Copy the pixels of *src into *dst, using WebPPictureAlloc.
    224 // Returns 0 in case of memory allocation error.
    225 WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* const src,
    226                                  WebPPicture* const dst);
    227 
    228 // self-crops a picture to the rectangle defined by top/left/width/height.
    229 // Returns 0 in case of memory allocation error, or if the rectangle is
    230 // outside of the source picture.
    231 WEBP_EXTERN(int) WebPPictureCrop(WebPPicture* const picture,
    232                                  int left, int top, int width, int height);
    233 
    234 // Rescale a picture to new dimension width x height.
    235 // Now gamma correction is applied.
    236 // Returns false in case of error (invalid parameter or insufficient memory).
    237 WEBP_EXTERN(int) WebPPictureRescale(WebPPicture* const pic,
    238                                     int width, int height);
    239 
    240 // Colorspace conversion function to import RGB samples.
    241 // Previous buffer will be free'd, if any.
    242 // *rgb buffer should have a size of at least height * rgb_stride.
    243 // Returns 0 in case of memory error.
    244 WEBP_EXTERN(int) WebPPictureImportRGB(
    245     WebPPicture* const picture, const uint8_t* const rgb, int rgb_stride);
    246 // Same, but for RGBA buffer
    247 WEBP_EXTERN(int) WebPPictureImportRGBA(
    248     WebPPicture* const picture, const uint8_t* const rgba, int rgba_stride);
    249 
    250 // Variant of the above, but taking BGR(A) input:
    251 WEBP_EXTERN(int) WebPPictureImportBGR(
    252     WebPPicture* const picture, const uint8_t* const bgr, int bgr_stride);
    253 WEBP_EXTERN(int) WebPPictureImportBGRA(
    254     WebPPicture* const picture, const uint8_t* const bgra, int bgra_stride);
    255 
    256 //-----------------------------------------------------------------------------
    257 // Main call
    258 
    259 // Main encoding call, after config and picture have been initialized.
    260 // 'picture' must be less than 16384x16384 in dimension, and the 'config' object
    261 // must be a valid one.
    262 // Returns false in case of error, true otherwise.
    263 // In case of error, picture->error_code is updated accordingly.
    264 WEBP_EXTERN(int) WebPEncode(
    265     const WebPConfig* const config, WebPPicture* const picture);
    266 
    267 //-----------------------------------------------------------------------------
    268 
    269 #if defined(__cplusplus) || defined(c_plusplus)
    270 }    // extern "C"
    271 #endif
    272 
    273 #endif  /* WEBP_WEBP_ENCODE_H_ */
    274