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: internal header.
11//
12// Author: Skal (pascal.massimino@gmail.com)
13
14#ifndef WEBP_ENC_VP8ENCI_H_
15#define WEBP_ENC_VP8ENCI_H_
16
17#include <string.h>     // for memcpy()
18#include "../webp/encode.h"
19#include "../dsp/dsp.h"
20#include "../utils/bit_writer.h"
21#include "../utils/thread.h"
22
23#ifdef __cplusplus
24extern "C" {
25#endif
26
27//------------------------------------------------------------------------------
28// Various defines and enums
29
30// version numbers
31#define ENC_MAJ_VERSION 0
32#define ENC_MIN_VERSION 4
33#define ENC_REV_VERSION 1
34
35// intra prediction modes
36enum { B_DC_PRED = 0,   // 4x4 modes
37       B_TM_PRED = 1,
38       B_VE_PRED = 2,
39       B_HE_PRED = 3,
40       B_RD_PRED = 4,
41       B_VR_PRED = 5,
42       B_LD_PRED = 6,
43       B_VL_PRED = 7,
44       B_HD_PRED = 8,
45       B_HU_PRED = 9,
46       NUM_BMODES = B_HU_PRED + 1 - B_DC_PRED,  // = 10
47
48       // Luma16 or UV modes
49       DC_PRED = B_DC_PRED, V_PRED = B_VE_PRED,
50       H_PRED = B_HE_PRED, TM_PRED = B_TM_PRED,
51       NUM_PRED_MODES = 4
52     };
53
54enum { NUM_MB_SEGMENTS = 4,
55       MAX_NUM_PARTITIONS = 8,
56       NUM_TYPES = 4,   // 0: i16-AC,  1: i16-DC,  2:chroma-AC,  3:i4-AC
57       NUM_BANDS = 8,
58       NUM_CTX = 3,
59       NUM_PROBAS = 11,
60       MAX_LF_LEVELS = 64,       // Maximum loop filter level
61       MAX_VARIABLE_LEVEL = 67,  // last (inclusive) level with variable cost
62       MAX_LEVEL = 2047          // max level (note: max codable is 2047 + 67)
63     };
64
65typedef enum {   // Rate-distortion optimization levels
66  RD_OPT_NONE        = 0,  // no rd-opt
67  RD_OPT_BASIC       = 1,  // basic scoring (no trellis)
68  RD_OPT_TRELLIS     = 2,  // perform trellis-quant on the final decision only
69  RD_OPT_TRELLIS_ALL = 3   // trellis-quant for every scoring (much slower)
70} VP8RDLevel;
71
72// YUV-cache parameters. Cache is 16-pixels wide.
73// The original or reconstructed samples can be accessed using VP8Scan[]
74// The predicted blocks can be accessed using offsets to yuv_p_ and
75// the arrays VP8*ModeOffsets[];
76//         +----+      YUV Samples area. See VP8Scan[] for accessing the blocks.
77//  Y_OFF  |YYYY| <- original samples  ('yuv_in_')
78//         |YYYY|
79//         |YYYY|
80//         |YYYY|
81//  U_OFF  |UUVV| V_OFF  (=U_OFF + 8)
82//         |UUVV|
83//         +----+
84//  Y_OFF  |YYYY| <- compressed/decoded samples  ('yuv_out_')
85//         |YYYY|    There are two buffers like this ('yuv_out_'/'yuv_out2_')
86//         |YYYY|
87//         |YYYY|
88//  U_OFF  |UUVV| V_OFF
89//         |UUVV|
90//          x2 (for yuv_out2_)
91//         +----+     Prediction area ('yuv_p_', size = PRED_SIZE)
92// I16DC16 |YYYY|  Intra16 predictions (16x16 block each)
93//         |YYYY|
94//         |YYYY|
95//         |YYYY|
96// I16TM16 |YYYY|
97//         |YYYY|
98//         |YYYY|
99//         |YYYY|
100// I16VE16 |YYYY|
101//         |YYYY|
102//         |YYYY|
103//         |YYYY|
104// I16HE16 |YYYY|
105//         |YYYY|
106//         |YYYY|
107//         |YYYY|
108//         +----+  Chroma U/V predictions (16x8 block each)
109// C8DC8   |UUVV|
110//         |UUVV|
111// C8TM8   |UUVV|
112//         |UUVV|
113// C8VE8   |UUVV|
114//         |UUVV|
115// C8HE8   |UUVV|
116//         |UUVV|
117//         +----+  Intra 4x4 predictions (4x4 block each)
118//         |YYYY| I4DC4 I4TM4 I4VE4 I4HE4
119//         |YYYY| I4RD4 I4VR4 I4LD4 I4VL4
120//         |YY..| I4HD4 I4HU4 I4TMP
121//         +----+
122#define BPS       16   // this is the common stride
123#define Y_SIZE   (BPS * 16)
124#define UV_SIZE  (BPS * 8)
125#define YUV_SIZE (Y_SIZE + UV_SIZE)
126#define PRED_SIZE (6 * 16 * BPS + 12 * BPS)
127#define Y_OFF    (0)
128#define U_OFF    (Y_SIZE)
129#define V_OFF    (U_OFF + 8)
130#define ALIGN_CST 15
131#define DO_ALIGN(PTR) ((uintptr_t)((PTR) + ALIGN_CST) & ~ALIGN_CST)
132
133extern const int VP8Scan[16];           // in quant.c
134extern const int VP8UVModeOffsets[4];   // in analyze.c
135extern const int VP8I16ModeOffsets[4];
136extern const int VP8I4ModeOffsets[NUM_BMODES];
137
138// Layout of prediction blocks
139// intra 16x16
140#define I16DC16 (0 * 16 * BPS)
141#define I16TM16 (1 * 16 * BPS)
142#define I16VE16 (2 * 16 * BPS)
143#define I16HE16 (3 * 16 * BPS)
144// chroma 8x8, two U/V blocks side by side (hence: 16x8 each)
145#define C8DC8 (4 * 16 * BPS)
146#define C8TM8 (4 * 16 * BPS + 8 * BPS)
147#define C8VE8 (5 * 16 * BPS)
148#define C8HE8 (5 * 16 * BPS + 8 * BPS)
149// intra 4x4
150#define I4DC4 (6 * 16 * BPS +  0)
151#define I4TM4 (6 * 16 * BPS +  4)
152#define I4VE4 (6 * 16 * BPS +  8)
153#define I4HE4 (6 * 16 * BPS + 12)
154#define I4RD4 (6 * 16 * BPS + 4 * BPS +  0)
155#define I4VR4 (6 * 16 * BPS + 4 * BPS +  4)
156#define I4LD4 (6 * 16 * BPS + 4 * BPS +  8)
157#define I4VL4 (6 * 16 * BPS + 4 * BPS + 12)
158#define I4HD4 (6 * 16 * BPS + 8 * BPS +  0)
159#define I4HU4 (6 * 16 * BPS + 8 * BPS +  4)
160#define I4TMP (6 * 16 * BPS + 8 * BPS +  8)
161
162typedef int64_t score_t;     // type used for scores, rate, distortion
163// Note that MAX_COST is not the maximum allowed by sizeof(score_t),
164// in order to allow overflowing computations.
165#define MAX_COST ((score_t)0x7fffffffffffffLL)
166
167#define QFIX 17
168#define BIAS(b)  ((b) << (QFIX - 8))
169// Fun fact: this is the _only_ line where we're actually being lossy and
170// discarding bits.
171static WEBP_INLINE int QUANTDIV(uint32_t n, uint32_t iQ, uint32_t B) {
172  return (int)((n * iQ + B) >> QFIX);
173}
174
175// size of histogram used by CollectHistogram.
176#define MAX_COEFF_THRESH   31
177typedef struct VP8Histogram VP8Histogram;
178struct VP8Histogram {
179  // TODO(skal): we only need to store the max_value and last_non_zero actually.
180  int distribution[MAX_COEFF_THRESH + 1];
181};
182
183// Uncomment the following to remove token-buffer code:
184// #define DISABLE_TOKEN_BUFFER
185
186//------------------------------------------------------------------------------
187// Headers
188
189typedef uint32_t proba_t;   // 16b + 16b
190typedef uint8_t ProbaArray[NUM_CTX][NUM_PROBAS];
191typedef proba_t StatsArray[NUM_CTX][NUM_PROBAS];
192typedef uint16_t CostArray[NUM_CTX][MAX_VARIABLE_LEVEL + 1];
193typedef double LFStats[NUM_MB_SEGMENTS][MAX_LF_LEVELS];  // filter stats
194
195typedef struct VP8Encoder VP8Encoder;
196
197// segment features
198typedef struct {
199  int num_segments_;      // Actual number of segments. 1 segment only = unused.
200  int update_map_;        // whether to update the segment map or not.
201                          // must be 0 if there's only 1 segment.
202  int size_;              // bit-cost for transmitting the segment map
203} VP8SegmentHeader;
204
205// Struct collecting all frame-persistent probabilities.
206typedef struct {
207  uint8_t segments_[3];     // probabilities for segment tree
208  uint8_t skip_proba_;      // final probability of being skipped.
209  ProbaArray coeffs_[NUM_TYPES][NUM_BANDS];      // 1056 bytes
210  StatsArray stats_[NUM_TYPES][NUM_BANDS];       // 4224 bytes
211  CostArray level_cost_[NUM_TYPES][NUM_BANDS];   // 13056 bytes
212  int dirty_;               // if true, need to call VP8CalculateLevelCosts()
213  int use_skip_proba_;      // Note: we always use skip_proba for now.
214  int nb_skip_;             // number of skipped blocks
215} VP8Proba;
216
217// Filter parameters. Not actually used in the code (we don't perform
218// the in-loop filtering), but filled from user's config
219typedef struct {
220  int simple_;             // filtering type: 0=complex, 1=simple
221  int level_;              // base filter level [0..63]
222  int sharpness_;          // [0..7]
223  int i4x4_lf_delta_;      // delta filter level for i4x4 relative to i16x16
224} VP8FilterHeader;
225
226//------------------------------------------------------------------------------
227// Informations about the macroblocks.
228
229typedef struct {
230  // block type
231  unsigned int type_:2;     // 0=i4x4, 1=i16x16
232  unsigned int uv_mode_:2;
233  unsigned int skip_:1;
234  unsigned int segment_:2;
235  uint8_t alpha_;      // quantization-susceptibility
236} VP8MBInfo;
237
238typedef struct VP8Matrix {
239  uint16_t q_[16];        // quantizer steps
240  uint16_t iq_[16];       // reciprocals, fixed point.
241  uint32_t bias_[16];     // rounding bias
242  uint32_t zthresh_[16];  // value below which a coefficient is zeroed
243  uint16_t sharpen_[16];  // frequency boosters for slight sharpening
244} VP8Matrix;
245
246typedef struct {
247  VP8Matrix y1_, y2_, uv_;  // quantization matrices
248  int alpha_;      // quant-susceptibility, range [-127,127]. Zero is neutral.
249                   // Lower values indicate a lower risk of blurriness.
250  int beta_;       // filter-susceptibility, range [0,255].
251  int quant_;      // final segment quantizer.
252  int fstrength_;  // final in-loop filtering strength
253  int max_edge_;   // max edge delta (for filtering strength)
254  int min_disto_;  // minimum distortion required to trigger filtering record
255  // reactivities
256  int lambda_i16_, lambda_i4_, lambda_uv_;
257  int lambda_mode_, lambda_trellis_, tlambda_;
258  int lambda_trellis_i16_, lambda_trellis_i4_, lambda_trellis_uv_;
259} VP8SegmentInfo;
260
261// Handy transient struct to accumulate score and info during RD-optimization
262// and mode evaluation.
263typedef struct {
264  score_t D, SD;              // Distortion, spectral distortion
265  score_t H, R, score;        // header bits, rate, score.
266  int16_t y_dc_levels[16];    // Quantized levels for luma-DC, luma-AC, chroma.
267  int16_t y_ac_levels[16][16];
268  int16_t uv_levels[4 + 4][16];
269  int mode_i16;               // mode number for intra16 prediction
270  uint8_t modes_i4[16];       // mode numbers for intra4 predictions
271  int mode_uv;                // mode number of chroma prediction
272  uint32_t nz;                // non-zero blocks
273} VP8ModeScore;
274
275// Iterator structure to iterate through macroblocks, pointing to the
276// right neighbouring data (samples, predictions, contexts, ...)
277typedef struct {
278  int x_, y_;                      // current macroblock
279  int y_stride_, uv_stride_;       // respective strides
280  uint8_t*      yuv_in_;           // input samples
281  uint8_t*      yuv_out_;          // output samples
282  uint8_t*      yuv_out2_;         // secondary buffer swapped with yuv_out_.
283  uint8_t*      yuv_p_;            // scratch buffer for prediction
284  VP8Encoder*   enc_;              // back-pointer
285  VP8MBInfo*    mb_;               // current macroblock
286  VP8BitWriter* bw_;               // current bit-writer
287  uint8_t*      preds_;            // intra mode predictors (4x4 blocks)
288  uint32_t*     nz_;               // non-zero pattern
289  uint8_t       i4_boundary_[37];  // 32+5 boundary samples needed by intra4x4
290  uint8_t*      i4_top_;           // pointer to the current top boundary sample
291  int           i4_;               // current intra4x4 mode being tested
292  int           top_nz_[9];        // top-non-zero context.
293  int           left_nz_[9];       // left-non-zero. left_nz[8] is independent.
294  uint64_t      bit_count_[4][3];  // bit counters for coded levels.
295  uint64_t      luma_bits_;        // macroblock bit-cost for luma
296  uint64_t      uv_bits_;          // macroblock bit-cost for chroma
297  LFStats*      lf_stats_;         // filter stats (borrowed from enc_)
298  int           do_trellis_;       // if true, perform extra level optimisation
299  int           count_down_;       // number of mb still to be processed
300  int           count_down0_;      // starting counter value (for progress)
301  int           percent0_;         // saved initial progress percent
302
303  uint8_t* y_left_;    // left luma samples (addressable from index -1 to 15).
304  uint8_t* u_left_;    // left u samples (addressable from index -1 to 7)
305  uint8_t* v_left_;    // left v samples (addressable from index -1 to 7)
306
307  uint8_t* y_top_;     // top luma samples at position 'x_'
308  uint8_t* uv_top_;    // top u/v samples at position 'x_', packed as 16 bytes
309
310  // memory for storing y/u/v_left_ and yuv_in_/out_*
311  uint8_t yuv_left_mem_[17 + 16 + 16 + 8 + ALIGN_CST];     // memory for *_left_
312  uint8_t yuv_mem_[3 * YUV_SIZE + PRED_SIZE + ALIGN_CST];  // memory for yuv_*
313} VP8EncIterator;
314
315  // in iterator.c
316// must be called first
317void VP8IteratorInit(VP8Encoder* const enc, VP8EncIterator* const it);
318// restart a scan
319void VP8IteratorReset(VP8EncIterator* const it);
320// reset iterator position to row 'y'
321void VP8IteratorSetRow(VP8EncIterator* const it, int y);
322// set count down (=number of iterations to go)
323void VP8IteratorSetCountDown(VP8EncIterator* const it, int count_down);
324// return true if iteration is finished
325int VP8IteratorIsDone(const VP8EncIterator* const it);
326// Import uncompressed samples from source.
327// If tmp_32 is not NULL, import boundary samples too.
328// tmp_32 is a 32-bytes scratch buffer that must be aligned in memory.
329void VP8IteratorImport(VP8EncIterator* const it, uint8_t* tmp_32);
330// export decimated samples
331void VP8IteratorExport(const VP8EncIterator* const it);
332// go to next macroblock. Returns false if not finished.
333int VP8IteratorNext(VP8EncIterator* const it);
334// save the yuv_out_ boundary values to top_/left_ arrays for next iterations.
335void VP8IteratorSaveBoundary(VP8EncIterator* const it);
336// Report progression based on macroblock rows. Return 0 for user-abort request.
337int VP8IteratorProgress(const VP8EncIterator* const it,
338                        int final_delta_percent);
339// Intra4x4 iterations
340void VP8IteratorStartI4(VP8EncIterator* const it);
341// returns true if not done.
342int VP8IteratorRotateI4(VP8EncIterator* const it,
343                        const uint8_t* const yuv_out);
344
345// Non-zero context setup/teardown
346void VP8IteratorNzToBytes(VP8EncIterator* const it);
347void VP8IteratorBytesToNz(VP8EncIterator* const it);
348
349// Helper functions to set mode properties
350void VP8SetIntra16Mode(const VP8EncIterator* const it, int mode);
351void VP8SetIntra4Mode(const VP8EncIterator* const it, const uint8_t* modes);
352void VP8SetIntraUVMode(const VP8EncIterator* const it, int mode);
353void VP8SetSkip(const VP8EncIterator* const it, int skip);
354void VP8SetSegment(const VP8EncIterator* const it, int segment);
355
356//------------------------------------------------------------------------------
357// Paginated token buffer
358
359typedef struct VP8Tokens VP8Tokens;  // struct details in token.c
360
361typedef struct {
362#if !defined(DISABLE_TOKEN_BUFFER)
363  VP8Tokens* pages_;        // first page
364  VP8Tokens** last_page_;   // last page
365  uint16_t* tokens_;        // set to (*last_page_)->tokens_
366  int left_;                // how many free tokens left before the page is full
367  int page_size_;           // number of tokens per page
368#endif
369  int error_;         // true in case of malloc error
370} VP8TBuffer;
371
372// initialize an empty buffer
373void VP8TBufferInit(VP8TBuffer* const b, int page_size);
374void VP8TBufferClear(VP8TBuffer* const b);   // de-allocate pages memory
375
376#if !defined(DISABLE_TOKEN_BUFFER)
377
378// Finalizes bitstream when probabilities are known.
379// Deletes the allocated token memory if final_pass is true.
380int VP8EmitTokens(VP8TBuffer* const b, VP8BitWriter* const bw,
381                  const uint8_t* const probas, int final_pass);
382
383// record the coding of coefficients without knowing the probabilities yet
384int VP8RecordCoeffTokens(int ctx, int coeff_type, int first, int last,
385                         const int16_t* const coeffs,
386                         VP8TBuffer* const tokens);
387
388// Estimate the final coded size given a set of 'probas'.
389size_t VP8EstimateTokenSize(VP8TBuffer* const b, const uint8_t* const probas);
390
391// unused for now
392void VP8TokenToStats(const VP8TBuffer* const b, proba_t* const stats);
393
394#endif  // !DISABLE_TOKEN_BUFFER
395
396//------------------------------------------------------------------------------
397// VP8Encoder
398
399struct VP8Encoder {
400  const WebPConfig* config_;    // user configuration and parameters
401  WebPPicture* pic_;            // input / output picture
402
403  // headers
404  VP8FilterHeader   filter_hdr_;     // filtering information
405  VP8SegmentHeader  segment_hdr_;    // segment information
406
407  int profile_;                      // VP8's profile, deduced from Config.
408
409  // dimension, in macroblock units.
410  int mb_w_, mb_h_;
411  int preds_w_;   // stride of the *preds_ prediction plane (=4*mb_w + 1)
412
413  // number of partitions (1, 2, 4 or 8 = MAX_NUM_PARTITIONS)
414  int num_parts_;
415
416  // per-partition boolean decoders.
417  VP8BitWriter bw_;                         // part0
418  VP8BitWriter parts_[MAX_NUM_PARTITIONS];  // token partitions
419  VP8TBuffer tokens_;                       // token buffer
420
421  int percent_;                             // for progress
422
423  // transparency blob
424  int has_alpha_;
425  uint8_t* alpha_data_;       // non-NULL if transparency is present
426  uint32_t alpha_data_size_;
427  WebPWorker alpha_worker_;
428
429  // quantization info (one set of DC/AC dequant factor per segment)
430  VP8SegmentInfo dqm_[NUM_MB_SEGMENTS];
431  int base_quant_;                 // nominal quantizer value. Only used
432                                   // for relative coding of segments' quant.
433  int alpha_;                      // global susceptibility (<=> complexity)
434  int uv_alpha_;                   // U/V quantization susceptibility
435  // global offset of quantizers, shared by all segments
436  int dq_y1_dc_;
437  int dq_y2_dc_, dq_y2_ac_;
438  int dq_uv_dc_, dq_uv_ac_;
439
440  // probabilities and statistics
441  VP8Proba proba_;
442  uint64_t sse_[4];        // sum of Y/U/V/A squared errors for all macroblocks
443  uint64_t sse_count_;     // pixel count for the sse_[] stats
444  int      coded_size_;
445  int      residual_bytes_[3][4];
446  int      block_count_[3];
447
448  // quality/speed settings
449  int method_;               // 0=fastest, 6=best/slowest.
450  VP8RDLevel rd_opt_level_;  // Deduced from method_.
451  int max_i4_header_bits_;   // partition #0 safeness factor
452  int thread_level_;         // derived from config->thread_level
453  int do_search_;            // derived from config->target_XXX
454  int use_tokens_;           // if true, use token buffer
455
456  // Memory
457  VP8MBInfo* mb_info_;   // contextual macroblock infos (mb_w_ + 1)
458  uint8_t*   preds_;     // predictions modes: (4*mb_w+1) * (4*mb_h+1)
459  uint32_t*  nz_;        // non-zero bit context: mb_w+1
460  uint8_t   *y_top_;     // top luma samples.
461  uint8_t   *uv_top_;    // top u/v samples.
462                         // U and V are packed into 16 bytes (8 U + 8 V)
463  LFStats   *lf_stats_;  // autofilter stats (if NULL, autofilter is off)
464};
465
466//------------------------------------------------------------------------------
467// internal functions. Not public.
468
469  // in tree.c
470extern const uint8_t VP8CoeffsProba0[NUM_TYPES][NUM_BANDS][NUM_CTX][NUM_PROBAS];
471extern const uint8_t
472    VP8CoeffsUpdateProba[NUM_TYPES][NUM_BANDS][NUM_CTX][NUM_PROBAS];
473// Reset the token probabilities to their initial (default) values
474void VP8DefaultProbas(VP8Encoder* const enc);
475// Write the token probabilities
476void VP8WriteProbas(VP8BitWriter* const bw, const VP8Proba* const probas);
477// Writes the partition #0 modes (that is: all intra modes)
478void VP8CodeIntraModes(VP8Encoder* const enc);
479
480  // in syntax.c
481// Generates the final bitstream by coding the partition0 and headers,
482// and appending an assembly of all the pre-coded token partitions.
483// Return true if everything is ok.
484int VP8EncWrite(VP8Encoder* const enc);
485// Release memory allocated for bit-writing in VP8EncLoop & seq.
486void VP8EncFreeBitWriters(VP8Encoder* const enc);
487
488  // in frame.c
489extern const uint8_t VP8EncBands[16 + 1];
490extern const uint8_t VP8Cat3[];
491extern const uint8_t VP8Cat4[];
492extern const uint8_t VP8Cat5[];
493extern const uint8_t VP8Cat6[];
494
495// Form all the four Intra16x16 predictions in the yuv_p_ cache
496void VP8MakeLuma16Preds(const VP8EncIterator* const it);
497// Form all the four Chroma8x8 predictions in the yuv_p_ cache
498void VP8MakeChroma8Preds(const VP8EncIterator* const it);
499// Form all the ten Intra4x4 predictions in the yuv_p_ cache
500// for the 4x4 block it->i4_
501void VP8MakeIntra4Preds(const VP8EncIterator* const it);
502// Rate calculation
503int VP8GetCostLuma16(VP8EncIterator* const it, const VP8ModeScore* const rd);
504int VP8GetCostLuma4(VP8EncIterator* const it, const int16_t levels[16]);
505int VP8GetCostUV(VP8EncIterator* const it, const VP8ModeScore* const rd);
506// Main coding calls
507int VP8EncLoop(VP8Encoder* const enc);
508int VP8EncTokenLoop(VP8Encoder* const enc);
509
510  // in webpenc.c
511// Assign an error code to a picture. Return false for convenience.
512int WebPEncodingSetError(const WebPPicture* const pic, WebPEncodingError error);
513int WebPReportProgress(const WebPPicture* const pic,
514                       int percent, int* const percent_store);
515
516  // in analysis.c
517// Main analysis loop. Decides the segmentations and complexity.
518// Assigns a first guess for Intra16 and uvmode_ prediction modes.
519int VP8EncAnalyze(VP8Encoder* const enc);
520
521  // in quant.c
522// Sets up segment's quantization values, base_quant_ and filter strengths.
523void VP8SetSegmentParams(VP8Encoder* const enc, float quality);
524// Pick best modes and fills the levels. Returns true if skipped.
525int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd,
526                VP8RDLevel rd_opt);
527
528  // in alpha.c
529void VP8EncInitAlpha(VP8Encoder* const enc);    // initialize alpha compression
530int VP8EncStartAlpha(VP8Encoder* const enc);    // start alpha coding process
531int VP8EncFinishAlpha(VP8Encoder* const enc);   // finalize compressed data
532int VP8EncDeleteAlpha(VP8Encoder* const enc);   // delete compressed data
533
534  // in filter.c
535
536// SSIM utils
537typedef struct {
538  double w, xm, ym, xxm, xym, yym;
539} DistoStats;
540void VP8SSIMAddStats(const DistoStats* const src, DistoStats* const dst);
541void VP8SSIMAccumulatePlane(const uint8_t* src1, int stride1,
542                            const uint8_t* src2, int stride2,
543                            int W, int H, DistoStats* const stats);
544double VP8SSIMGet(const DistoStats* const stats);
545double VP8SSIMGetSquaredError(const DistoStats* const stats);
546
547// autofilter
548void VP8InitFilter(VP8EncIterator* const it);
549void VP8StoreFilterStats(VP8EncIterator* const it);
550void VP8AdjustFilterStrength(VP8EncIterator* const it);
551
552// returns the approximate filtering strength needed to smooth a edge
553// step of 'delta', given a sharpness parameter 'sharpness'.
554int VP8FilterStrengthFromDelta(int sharpness, int delta);
555
556  // misc utils for picture_*.c:
557
558// Remove reference to the ARGB/YUVA buffer (doesn't free anything).
559void WebPPictureResetBuffers(WebPPicture* const picture);
560
561// Allocates ARGB buffer of given dimension (previous one is always free'd).
562// Preserves the YUV(A) buffer. Returns false in case of error (invalid param,
563// out-of-memory).
564int WebPPictureAllocARGB(WebPPicture* const picture, int width, int height);
565
566// Allocates YUVA buffer of given dimension (previous one is always free'd).
567// Uses picture->csp to determine whether an alpha buffer is needed.
568// Preserves the ARGB buffer.
569// Returns false in case of error (invalid param, out-of-memory).
570int WebPPictureAllocYUVA(WebPPicture* const picture, int width, int height);
571
572//------------------------------------------------------------------------------
573
574#if WEBP_ENCODER_ABI_VERSION <= 0x0202
575void WebPMemoryWriterClear(WebPMemoryWriter* writer);
576#endif
577
578#ifdef __cplusplus
579}    // extern "C"
580#endif
581
582#endif  /* WEBP_ENC_VP8ENCI_H_ */
583