Coverage Report

Created: 2026-10-28 07:26

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