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