Path: blob/master/3rdparty/libwebp/src/enc/vp8i_enc.h
16344 views
// Copyright 2011 Google Inc. All Rights Reserved.1//2// Use of this source code is governed by a BSD-style license3// that can be found in the COPYING file in the root of the source4// tree. An additional intellectual property rights grant can be found5// in the file PATENTS. All contributing project authors may6// be found in the AUTHORS file in the root of the source tree.7// -----------------------------------------------------------------------------8//9// WebP encoder: internal header.10//11// Author: Skal ([email protected])1213#ifndef WEBP_ENC_VP8I_ENC_H_14#define WEBP_ENC_VP8I_ENC_H_1516#include <string.h> // for memcpy()17#include "src/dec/common_dec.h"18#include "src/dsp/dsp.h"19#include "src/utils/bit_writer_utils.h"20#include "src/utils/thread_utils.h"21#include "src/utils/utils.h"22#include "src/webp/encode.h"2324#ifdef __cplusplus25extern "C" {26#endif2728//------------------------------------------------------------------------------29// Various defines and enums3031// version numbers32#define ENC_MAJ_VERSION 133#define ENC_MIN_VERSION 034#define ENC_REV_VERSION 03536enum { MAX_LF_LEVELS = 64, // Maximum loop filter level37MAX_VARIABLE_LEVEL = 67, // last (inclusive) level with variable cost38MAX_LEVEL = 2047 // max level (note: max codable is 2047 + 67)39};4041typedef enum { // Rate-distortion optimization levels42RD_OPT_NONE = 0, // no rd-opt43RD_OPT_BASIC = 1, // basic scoring (no trellis)44RD_OPT_TRELLIS = 2, // perform trellis-quant on the final decision only45RD_OPT_TRELLIS_ALL = 3 // trellis-quant for every scoring (much slower)46} VP8RDLevel;4748// YUV-cache parameters. Cache is 32-bytes wide (= one cacheline).49// The original or reconstructed samples can be accessed using VP8Scan[].50// The predicted blocks can be accessed using offsets to yuv_p_ and51// the arrays VP8*ModeOffsets[].52// * YUV Samples area (yuv_in_/yuv_out_/yuv_out2_)53// (see VP8Scan[] for accessing the blocks, along with54// Y_OFF_ENC/U_OFF_ENC/V_OFF_ENC):55// +----+----+56// Y_OFF_ENC |YYYY|UUVV|57// U_OFF_ENC |YYYY|UUVV|58// V_OFF_ENC |YYYY|....| <- 25% wasted U/V area59// |YYYY|....|60// +----+----+61// * Prediction area ('yuv_p_', size = PRED_SIZE_ENC)62// Intra16 predictions (16x16 block each, two per row):63// |I16DC16|I16TM16|64// |I16VE16|I16HE16|65// Chroma U/V predictions (16x8 block each, two per row):66// |C8DC8|C8TM8|67// |C8VE8|C8HE8|68// Intra 4x4 predictions (4x4 block each)69// |I4DC4 I4TM4 I4VE4 I4HE4|I4RD4 I4VR4 I4LD4 I4VL4|70// |I4HD4 I4HU4 I4TMP .....|.......................| <- ~31% wasted71#define YUV_SIZE_ENC (BPS * 16)72#define PRED_SIZE_ENC (32 * BPS + 16 * BPS + 8 * BPS) // I16+Chroma+I4 preds73#define Y_OFF_ENC (0)74#define U_OFF_ENC (16)75#define V_OFF_ENC (16 + 8)7677extern const uint16_t VP8Scan[16];78extern const uint16_t VP8UVModeOffsets[4];79extern const uint16_t VP8I16ModeOffsets[4];80extern const uint16_t VP8I4ModeOffsets[NUM_BMODES];8182// Layout of prediction blocks83// intra 16x1684#define I16DC16 (0 * 16 * BPS)85#define I16TM16 (I16DC16 + 16)86#define I16VE16 (1 * 16 * BPS)87#define I16HE16 (I16VE16 + 16)88// chroma 8x8, two U/V blocks side by side (hence: 16x8 each)89#define C8DC8 (2 * 16 * BPS)90#define C8TM8 (C8DC8 + 1 * 16)91#define C8VE8 (2 * 16 * BPS + 8 * BPS)92#define C8HE8 (C8VE8 + 1 * 16)93// intra 4x494#define I4DC4 (3 * 16 * BPS + 0)95#define I4TM4 (I4DC4 + 4)96#define I4VE4 (I4DC4 + 8)97#define I4HE4 (I4DC4 + 12)98#define I4RD4 (I4DC4 + 16)99#define I4VR4 (I4DC4 + 20)100#define I4LD4 (I4DC4 + 24)101#define I4VL4 (I4DC4 + 28)102#define I4HD4 (3 * 16 * BPS + 4 * BPS)103#define I4HU4 (I4HD4 + 4)104#define I4TMP (I4HD4 + 8)105106typedef int64_t score_t; // type used for scores, rate, distortion107// Note that MAX_COST is not the maximum allowed by sizeof(score_t),108// in order to allow overflowing computations.109#define MAX_COST ((score_t)0x7fffffffffffffLL)110111#define QFIX 17112#define BIAS(b) ((b) << (QFIX - 8))113// Fun fact: this is the _only_ line where we're actually being lossy and114// discarding bits.115static WEBP_INLINE int QUANTDIV(uint32_t n, uint32_t iQ, uint32_t B) {116return (int)((n * iQ + B) >> QFIX);117}118119// Uncomment the following to remove token-buffer code:120// #define DISABLE_TOKEN_BUFFER121122// quality below which error-diffusion is enabled123#define ERROR_DIFFUSION_QUALITY 98124125//------------------------------------------------------------------------------126// Headers127128typedef uint32_t proba_t; // 16b + 16b129typedef uint8_t ProbaArray[NUM_CTX][NUM_PROBAS];130typedef proba_t StatsArray[NUM_CTX][NUM_PROBAS];131typedef uint16_t CostArray[NUM_CTX][MAX_VARIABLE_LEVEL + 1];132typedef const uint16_t* (*CostArrayPtr)[NUM_CTX]; // for easy casting133typedef const uint16_t* CostArrayMap[16][NUM_CTX];134typedef double LFStats[NUM_MB_SEGMENTS][MAX_LF_LEVELS]; // filter stats135136typedef struct VP8Encoder VP8Encoder;137138// segment features139typedef struct {140int num_segments_; // Actual number of segments. 1 segment only = unused.141int update_map_; // whether to update the segment map or not.142// must be 0 if there's only 1 segment.143int size_; // bit-cost for transmitting the segment map144} VP8EncSegmentHeader;145146// Struct collecting all frame-persistent probabilities.147typedef struct {148uint8_t segments_[3]; // probabilities for segment tree149uint8_t skip_proba_; // final probability of being skipped.150ProbaArray coeffs_[NUM_TYPES][NUM_BANDS]; // 1056 bytes151StatsArray stats_[NUM_TYPES][NUM_BANDS]; // 4224 bytes152CostArray level_cost_[NUM_TYPES][NUM_BANDS]; // 13056 bytes153CostArrayMap remapped_costs_[NUM_TYPES]; // 1536 bytes154int dirty_; // if true, need to call VP8CalculateLevelCosts()155int use_skip_proba_; // Note: we always use skip_proba for now.156int nb_skip_; // number of skipped blocks157} VP8EncProba;158159// Filter parameters. Not actually used in the code (we don't perform160// the in-loop filtering), but filled from user's config161typedef struct {162int simple_; // filtering type: 0=complex, 1=simple163int level_; // base filter level [0..63]164int sharpness_; // [0..7]165int i4x4_lf_delta_; // delta filter level for i4x4 relative to i16x16166} VP8EncFilterHeader;167168//------------------------------------------------------------------------------169// Informations about the macroblocks.170171typedef struct {172// block type173unsigned int type_:2; // 0=i4x4, 1=i16x16174unsigned int uv_mode_:2;175unsigned int skip_:1;176unsigned int segment_:2;177uint8_t alpha_; // quantization-susceptibility178} VP8MBInfo;179180typedef struct VP8Matrix {181uint16_t q_[16]; // quantizer steps182uint16_t iq_[16]; // reciprocals, fixed point.183uint32_t bias_[16]; // rounding bias184uint32_t zthresh_[16]; // value below which a coefficient is zeroed185uint16_t sharpen_[16]; // frequency boosters for slight sharpening186} VP8Matrix;187188typedef struct {189VP8Matrix y1_, y2_, uv_; // quantization matrices190int alpha_; // quant-susceptibility, range [-127,127]. Zero is neutral.191// Lower values indicate a lower risk of blurriness.192int beta_; // filter-susceptibility, range [0,255].193int quant_; // final segment quantizer.194int fstrength_; // final in-loop filtering strength195int max_edge_; // max edge delta (for filtering strength)196int min_disto_; // minimum distortion required to trigger filtering record197// reactivities198int lambda_i16_, lambda_i4_, lambda_uv_;199int lambda_mode_, lambda_trellis_, tlambda_;200int lambda_trellis_i16_, lambda_trellis_i4_, lambda_trellis_uv_;201202// lambda values for distortion-based evaluation203score_t i4_penalty_; // penalty for using Intra4204} VP8SegmentInfo;205206typedef int8_t DError[2 /* u/v */][2 /* top or left */];207208// Handy transient struct to accumulate score and info during RD-optimization209// and mode evaluation.210typedef struct {211score_t D, SD; // Distortion, spectral distortion212score_t H, R, score; // header bits, rate, score.213int16_t y_dc_levels[16]; // Quantized levels for luma-DC, luma-AC, chroma.214int16_t y_ac_levels[16][16];215int16_t uv_levels[4 + 4][16];216int mode_i16; // mode number for intra16 prediction217uint8_t modes_i4[16]; // mode numbers for intra4 predictions218int mode_uv; // mode number of chroma prediction219uint32_t nz; // non-zero blocks220int8_t derr[2][3]; // DC diffusion errors for U/V for blocks #1/2/3221} VP8ModeScore;222223// Iterator structure to iterate through macroblocks, pointing to the224// right neighbouring data (samples, predictions, contexts, ...)225typedef struct {226int x_, y_; // current macroblock227uint8_t* yuv_in_; // input samples228uint8_t* yuv_out_; // output samples229uint8_t* yuv_out2_; // secondary buffer swapped with yuv_out_.230uint8_t* yuv_p_; // scratch buffer for prediction231VP8Encoder* enc_; // back-pointer232VP8MBInfo* mb_; // current macroblock233VP8BitWriter* bw_; // current bit-writer234uint8_t* preds_; // intra mode predictors (4x4 blocks)235uint32_t* nz_; // non-zero pattern236uint8_t i4_boundary_[37]; // 32+5 boundary samples needed by intra4x4237uint8_t* i4_top_; // pointer to the current top boundary sample238int i4_; // current intra4x4 mode being tested239int top_nz_[9]; // top-non-zero context.240int left_nz_[9]; // left-non-zero. left_nz[8] is independent.241uint64_t bit_count_[4][3]; // bit counters for coded levels.242uint64_t luma_bits_; // macroblock bit-cost for luma243uint64_t uv_bits_; // macroblock bit-cost for chroma244LFStats* lf_stats_; // filter stats (borrowed from enc_)245int do_trellis_; // if true, perform extra level optimisation246int count_down_; // number of mb still to be processed247int count_down0_; // starting counter value (for progress)248int percent0_; // saved initial progress percent249250DError left_derr_; // left error diffusion (u/v)251DError *top_derr_; // top diffusion error - NULL if disabled252253uint8_t* y_left_; // left luma samples (addressable from index -1 to 15).254uint8_t* u_left_; // left u samples (addressable from index -1 to 7)255uint8_t* v_left_; // left v samples (addressable from index -1 to 7)256257uint8_t* y_top_; // top luma samples at position 'x_'258uint8_t* uv_top_; // top u/v samples at position 'x_', packed as 16 bytes259260// memory for storing y/u/v_left_261uint8_t yuv_left_mem_[17 + 16 + 16 + 8 + WEBP_ALIGN_CST];262// memory for yuv_*263uint8_t yuv_mem_[3 * YUV_SIZE_ENC + PRED_SIZE_ENC + WEBP_ALIGN_CST];264} VP8EncIterator;265266// in iterator.c267// must be called first268void VP8IteratorInit(VP8Encoder* const enc, VP8EncIterator* const it);269// restart a scan270void VP8IteratorReset(VP8EncIterator* const it);271// reset iterator position to row 'y'272void VP8IteratorSetRow(VP8EncIterator* const it, int y);273// set count down (=number of iterations to go)274void VP8IteratorSetCountDown(VP8EncIterator* const it, int count_down);275// return true if iteration is finished276int VP8IteratorIsDone(const VP8EncIterator* const it);277// Import uncompressed samples from source.278// If tmp_32 is not NULL, import boundary samples too.279// tmp_32 is a 32-bytes scratch buffer that must be aligned in memory.280void VP8IteratorImport(VP8EncIterator* const it, uint8_t* tmp_32);281// export decimated samples282void VP8IteratorExport(const VP8EncIterator* const it);283// go to next macroblock. Returns false if not finished.284int VP8IteratorNext(VP8EncIterator* const it);285// save the yuv_out_ boundary values to top_/left_ arrays for next iterations.286void VP8IteratorSaveBoundary(VP8EncIterator* const it);287// Report progression based on macroblock rows. Return 0 for user-abort request.288int VP8IteratorProgress(const VP8EncIterator* const it,289int final_delta_percent);290// Intra4x4 iterations291void VP8IteratorStartI4(VP8EncIterator* const it);292// returns true if not done.293int VP8IteratorRotateI4(VP8EncIterator* const it,294const uint8_t* const yuv_out);295296// Non-zero context setup/teardown297void VP8IteratorNzToBytes(VP8EncIterator* const it);298void VP8IteratorBytesToNz(VP8EncIterator* const it);299300// Helper functions to set mode properties301void VP8SetIntra16Mode(const VP8EncIterator* const it, int mode);302void VP8SetIntra4Mode(const VP8EncIterator* const it, const uint8_t* modes);303void VP8SetIntraUVMode(const VP8EncIterator* const it, int mode);304void VP8SetSkip(const VP8EncIterator* const it, int skip);305void VP8SetSegment(const VP8EncIterator* const it, int segment);306307//------------------------------------------------------------------------------308// Paginated token buffer309310typedef struct VP8Tokens VP8Tokens; // struct details in token.c311312typedef struct {313#if !defined(DISABLE_TOKEN_BUFFER)314VP8Tokens* pages_; // first page315VP8Tokens** last_page_; // last page316uint16_t* tokens_; // set to (*last_page_)->tokens_317int left_; // how many free tokens left before the page is full318int page_size_; // number of tokens per page319#endif320int error_; // true in case of malloc error321} VP8TBuffer;322323// initialize an empty buffer324void VP8TBufferInit(VP8TBuffer* const b, int page_size);325void VP8TBufferClear(VP8TBuffer* const b); // de-allocate pages memory326327#if !defined(DISABLE_TOKEN_BUFFER)328329// Finalizes bitstream when probabilities are known.330// Deletes the allocated token memory if final_pass is true.331int VP8EmitTokens(VP8TBuffer* const b, VP8BitWriter* const bw,332const uint8_t* const probas, int final_pass);333334// record the coding of coefficients without knowing the probabilities yet335int VP8RecordCoeffTokens(int ctx, const struct VP8Residual* const res,336VP8TBuffer* const tokens);337338// Estimate the final coded size given a set of 'probas'.339size_t VP8EstimateTokenSize(VP8TBuffer* const b, const uint8_t* const probas);340341#endif // !DISABLE_TOKEN_BUFFER342343//------------------------------------------------------------------------------344// VP8Encoder345346struct VP8Encoder {347const WebPConfig* config_; // user configuration and parameters348WebPPicture* pic_; // input / output picture349350// headers351VP8EncFilterHeader filter_hdr_; // filtering information352VP8EncSegmentHeader segment_hdr_; // segment information353354int profile_; // VP8's profile, deduced from Config.355356// dimension, in macroblock units.357int mb_w_, mb_h_;358int preds_w_; // stride of the *preds_ prediction plane (=4*mb_w + 1)359360// number of partitions (1, 2, 4 or 8 = MAX_NUM_PARTITIONS)361int num_parts_;362363// per-partition boolean decoders.364VP8BitWriter bw_; // part0365VP8BitWriter parts_[MAX_NUM_PARTITIONS]; // token partitions366VP8TBuffer tokens_; // token buffer367368int percent_; // for progress369370// transparency blob371int has_alpha_;372uint8_t* alpha_data_; // non-NULL if transparency is present373uint32_t alpha_data_size_;374WebPWorker alpha_worker_;375376// quantization info (one set of DC/AC dequant factor per segment)377VP8SegmentInfo dqm_[NUM_MB_SEGMENTS];378int base_quant_; // nominal quantizer value. Only used379// for relative coding of segments' quant.380int alpha_; // global susceptibility (<=> complexity)381int uv_alpha_; // U/V quantization susceptibility382// global offset of quantizers, shared by all segments383int dq_y1_dc_;384int dq_y2_dc_, dq_y2_ac_;385int dq_uv_dc_, dq_uv_ac_;386387// probabilities and statistics388VP8EncProba proba_;389uint64_t sse_[4]; // sum of Y/U/V/A squared errors for all macroblocks390uint64_t sse_count_; // pixel count for the sse_[] stats391int coded_size_;392int residual_bytes_[3][4];393int block_count_[3];394395// quality/speed settings396int method_; // 0=fastest, 6=best/slowest.397VP8RDLevel rd_opt_level_; // Deduced from method_.398int max_i4_header_bits_; // partition #0 safeness factor399int mb_header_limit_; // rough limit for header bits per MB400int thread_level_; // derived from config->thread_level401int do_search_; // derived from config->target_XXX402int use_tokens_; // if true, use token buffer403404// Memory405VP8MBInfo* mb_info_; // contextual macroblock infos (mb_w_ + 1)406uint8_t* preds_; // predictions modes: (4*mb_w+1) * (4*mb_h+1)407uint32_t* nz_; // non-zero bit context: mb_w+1408uint8_t* y_top_; // top luma samples.409uint8_t* uv_top_; // top u/v samples.410// U and V are packed into 16 bytes (8 U + 8 V)411LFStats* lf_stats_; // autofilter stats (if NULL, autofilter is off)412DError* top_derr_; // diffusion error (NULL if disabled)413};414415//------------------------------------------------------------------------------416// internal functions. Not public.417418// in tree.c419extern const uint8_t VP8CoeffsProba0[NUM_TYPES][NUM_BANDS][NUM_CTX][NUM_PROBAS];420extern const uint8_t421VP8CoeffsUpdateProba[NUM_TYPES][NUM_BANDS][NUM_CTX][NUM_PROBAS];422// Reset the token probabilities to their initial (default) values423void VP8DefaultProbas(VP8Encoder* const enc);424// Write the token probabilities425void VP8WriteProbas(VP8BitWriter* const bw, const VP8EncProba* const probas);426// Writes the partition #0 modes (that is: all intra modes)427void VP8CodeIntraModes(VP8Encoder* const enc);428429// in syntax.c430// Generates the final bitstream by coding the partition0 and headers,431// and appending an assembly of all the pre-coded token partitions.432// Return true if everything is ok.433int VP8EncWrite(VP8Encoder* const enc);434// Release memory allocated for bit-writing in VP8EncLoop & seq.435void VP8EncFreeBitWriters(VP8Encoder* const enc);436437// in frame.c438extern const uint8_t VP8Cat3[];439extern const uint8_t VP8Cat4[];440extern const uint8_t VP8Cat5[];441extern const uint8_t VP8Cat6[];442443// Form all the four Intra16x16 predictions in the yuv_p_ cache444void VP8MakeLuma16Preds(const VP8EncIterator* const it);445// Form all the four Chroma8x8 predictions in the yuv_p_ cache446void VP8MakeChroma8Preds(const VP8EncIterator* const it);447// Form all the ten Intra4x4 predictions in the yuv_p_ cache448// for the 4x4 block it->i4_449void VP8MakeIntra4Preds(const VP8EncIterator* const it);450// Rate calculation451int VP8GetCostLuma16(VP8EncIterator* const it, const VP8ModeScore* const rd);452int VP8GetCostLuma4(VP8EncIterator* const it, const int16_t levels[16]);453int VP8GetCostUV(VP8EncIterator* const it, const VP8ModeScore* const rd);454// Main coding calls455int VP8EncLoop(VP8Encoder* const enc);456int VP8EncTokenLoop(VP8Encoder* const enc);457458// in webpenc.c459// Assign an error code to a picture. Return false for convenience.460int WebPEncodingSetError(const WebPPicture* const pic, WebPEncodingError error);461int WebPReportProgress(const WebPPicture* const pic,462int percent, int* const percent_store);463464// in analysis.c465// Main analysis loop. Decides the segmentations and complexity.466// Assigns a first guess for Intra16 and uvmode_ prediction modes.467int VP8EncAnalyze(VP8Encoder* const enc);468469// in quant.c470// Sets up segment's quantization values, base_quant_ and filter strengths.471void VP8SetSegmentParams(VP8Encoder* const enc, float quality);472// Pick best modes and fills the levels. Returns true if skipped.473int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd,474VP8RDLevel rd_opt);475476// in alpha.c477void VP8EncInitAlpha(VP8Encoder* const enc); // initialize alpha compression478int VP8EncStartAlpha(VP8Encoder* const enc); // start alpha coding process479int VP8EncFinishAlpha(VP8Encoder* const enc); // finalize compressed data480int VP8EncDeleteAlpha(VP8Encoder* const enc); // delete compressed data481482// autofilter483void VP8InitFilter(VP8EncIterator* const it);484void VP8StoreFilterStats(VP8EncIterator* const it);485void VP8AdjustFilterStrength(VP8EncIterator* const it);486487// returns the approximate filtering strength needed to smooth a edge488// step of 'delta', given a sharpness parameter 'sharpness'.489int VP8FilterStrengthFromDelta(int sharpness, int delta);490491// misc utils for picture_*.c:492493// Remove reference to the ARGB/YUVA buffer (doesn't free anything).494void WebPPictureResetBuffers(WebPPicture* const picture);495496// Allocates ARGB buffer of given dimension (previous one is always free'd).497// Preserves the YUV(A) buffer. Returns false in case of error (invalid param,498// out-of-memory).499int WebPPictureAllocARGB(WebPPicture* const picture, int width, int height);500501// Allocates YUVA buffer of given dimension (previous one is always free'd).502// Uses picture->csp to determine whether an alpha buffer is needed.503// Preserves the ARGB buffer.504// Returns false in case of error (invalid param, out-of-memory).505int WebPPictureAllocYUVA(WebPPicture* const picture, int width, int height);506507// Clean-up the RGB samples under fully transparent area, to help lossless508// compressibility (no guarantee, though). Assumes that pic->use_argb is true.509void WebPCleanupTransparentAreaLossless(WebPPicture* const pic);510511//------------------------------------------------------------------------------512513#ifdef __cplusplus514} // extern "C"515#endif516517#endif /* WEBP_ENC_VP8I_ENC_H_ */518519520