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