Path: blob/master/3rdparty/libwebp/src/enc/frame_enc.c
16349 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// frame coding and analysis10//11// Author: Skal ([email protected])1213#include <string.h>14#include <math.h>1516#include "src/enc/cost_enc.h"17#include "src/enc/vp8i_enc.h"18#include "src/dsp/dsp.h"19#include "src/webp/format_constants.h" // RIFF constants2021#define SEGMENT_VISU 022#define DEBUG_SEARCH 0 // useful to track search convergence2324//------------------------------------------------------------------------------25// multi-pass convergence2627#define HEADER_SIZE_ESTIMATE (RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + \28VP8_FRAME_HEADER_SIZE)29#define DQ_LIMIT 0.4 // convergence is considered reached if dq < DQ_LIMIT30// we allow 2k of extra head-room in PARTITION0 limit.31#define PARTITION0_SIZE_LIMIT ((VP8_MAX_PARTITION0_SIZE - 2048ULL) << 11)3233typedef struct { // struct for organizing convergence in either size or PSNR34int is_first;35float dq;36float q, last_q;37double value, last_value; // PSNR or size38double target;39int do_size_search;40} PassStats;4142static int InitPassStats(const VP8Encoder* const enc, PassStats* const s) {43const uint64_t target_size = (uint64_t)enc->config_->target_size;44const int do_size_search = (target_size != 0);45const float target_PSNR = enc->config_->target_PSNR;4647s->is_first = 1;48s->dq = 10.f;49s->q = s->last_q = enc->config_->quality;50s->target = do_size_search ? (double)target_size51: (target_PSNR > 0.) ? target_PSNR52: 40.; // default, just in case53s->value = s->last_value = 0.;54s->do_size_search = do_size_search;55return do_size_search;56}5758static float Clamp(float v, float min, float max) {59return (v < min) ? min : (v > max) ? max : v;60}6162static float ComputeNextQ(PassStats* const s) {63float dq;64if (s->is_first) {65dq = (s->value > s->target) ? -s->dq : s->dq;66s->is_first = 0;67} else if (s->value != s->last_value) {68const double slope = (s->target - s->value) / (s->last_value - s->value);69dq = (float)(slope * (s->last_q - s->q));70} else {71dq = 0.; // we're done?!72}73// Limit variable to avoid large swings.74s->dq = Clamp(dq, -30.f, 30.f);75s->last_q = s->q;76s->last_value = s->value;77s->q = Clamp(s->q + s->dq, 0.f, 100.f);78return s->q;79}8081//------------------------------------------------------------------------------82// Tables for level coding8384const uint8_t VP8Cat3[] = { 173, 148, 140 };85const uint8_t VP8Cat4[] = { 176, 155, 140, 135 };86const uint8_t VP8Cat5[] = { 180, 157, 141, 134, 130 };87const uint8_t VP8Cat6[] =88{ 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 };8990//------------------------------------------------------------------------------91// Reset the statistics about: number of skips, token proba, level cost,...9293static void ResetStats(VP8Encoder* const enc) {94VP8EncProba* const proba = &enc->proba_;95VP8CalculateLevelCosts(proba);96proba->nb_skip_ = 0;97}9899//------------------------------------------------------------------------------100// Skip decision probability101102#define SKIP_PROBA_THRESHOLD 250 // value below which using skip_proba is OK.103104static int CalcSkipProba(uint64_t nb, uint64_t total) {105return (int)(total ? (total - nb) * 255 / total : 255);106}107108// Returns the bit-cost for coding the skip probability.109static int FinalizeSkipProba(VP8Encoder* const enc) {110VP8EncProba* const proba = &enc->proba_;111const int nb_mbs = enc->mb_w_ * enc->mb_h_;112const int nb_events = proba->nb_skip_;113int size;114proba->skip_proba_ = CalcSkipProba(nb_events, nb_mbs);115proba->use_skip_proba_ = (proba->skip_proba_ < SKIP_PROBA_THRESHOLD);116size = 256; // 'use_skip_proba' bit117if (proba->use_skip_proba_) {118size += nb_events * VP8BitCost(1, proba->skip_proba_)119+ (nb_mbs - nb_events) * VP8BitCost(0, proba->skip_proba_);120size += 8 * 256; // cost of signaling the skip_proba_ itself.121}122return size;123}124125// Collect statistics and deduce probabilities for next coding pass.126// Return the total bit-cost for coding the probability updates.127static int CalcTokenProba(int nb, int total) {128assert(nb <= total);129return nb ? (255 - nb * 255 / total) : 255;130}131132// Cost of coding 'nb' 1's and 'total-nb' 0's using 'proba' probability.133static int BranchCost(int nb, int total, int proba) {134return nb * VP8BitCost(1, proba) + (total - nb) * VP8BitCost(0, proba);135}136137static void ResetTokenStats(VP8Encoder* const enc) {138VP8EncProba* const proba = &enc->proba_;139memset(proba->stats_, 0, sizeof(proba->stats_));140}141142static int FinalizeTokenProbas(VP8EncProba* const proba) {143int has_changed = 0;144int size = 0;145int t, b, c, p;146for (t = 0; t < NUM_TYPES; ++t) {147for (b = 0; b < NUM_BANDS; ++b) {148for (c = 0; c < NUM_CTX; ++c) {149for (p = 0; p < NUM_PROBAS; ++p) {150const proba_t stats = proba->stats_[t][b][c][p];151const int nb = (stats >> 0) & 0xffff;152const int total = (stats >> 16) & 0xffff;153const int update_proba = VP8CoeffsUpdateProba[t][b][c][p];154const int old_p = VP8CoeffsProba0[t][b][c][p];155const int new_p = CalcTokenProba(nb, total);156const int old_cost = BranchCost(nb, total, old_p)157+ VP8BitCost(0, update_proba);158const int new_cost = BranchCost(nb, total, new_p)159+ VP8BitCost(1, update_proba)160+ 8 * 256;161const int use_new_p = (old_cost > new_cost);162size += VP8BitCost(use_new_p, update_proba);163if (use_new_p) { // only use proba that seem meaningful enough.164proba->coeffs_[t][b][c][p] = new_p;165has_changed |= (new_p != old_p);166size += 8 * 256;167} else {168proba->coeffs_[t][b][c][p] = old_p;169}170}171}172}173}174proba->dirty_ = has_changed;175return size;176}177178//------------------------------------------------------------------------------179// Finalize Segment probability based on the coding tree180181static int GetProba(int a, int b) {182const int total = a + b;183return (total == 0) ? 255 // that's the default probability.184: (255 * a + total / 2) / total; // rounded proba185}186187static void ResetSegments(VP8Encoder* const enc) {188int n;189for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {190enc->mb_info_[n].segment_ = 0;191}192}193194static void SetSegmentProbas(VP8Encoder* const enc) {195int p[NUM_MB_SEGMENTS] = { 0 };196int n;197198for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {199const VP8MBInfo* const mb = &enc->mb_info_[n];200++p[mb->segment_];201}202#if !defined(WEBP_DISABLE_STATS)203if (enc->pic_->stats != NULL) {204for (n = 0; n < NUM_MB_SEGMENTS; ++n) {205enc->pic_->stats->segment_size[n] = p[n];206}207}208#endif209if (enc->segment_hdr_.num_segments_ > 1) {210uint8_t* const probas = enc->proba_.segments_;211probas[0] = GetProba(p[0] + p[1], p[2] + p[3]);212probas[1] = GetProba(p[0], p[1]);213probas[2] = GetProba(p[2], p[3]);214215enc->segment_hdr_.update_map_ =216(probas[0] != 255) || (probas[1] != 255) || (probas[2] != 255);217if (!enc->segment_hdr_.update_map_) ResetSegments(enc);218enc->segment_hdr_.size_ =219p[0] * (VP8BitCost(0, probas[0]) + VP8BitCost(0, probas[1])) +220p[1] * (VP8BitCost(0, probas[0]) + VP8BitCost(1, probas[1])) +221p[2] * (VP8BitCost(1, probas[0]) + VP8BitCost(0, probas[2])) +222p[3] * (VP8BitCost(1, probas[0]) + VP8BitCost(1, probas[2]));223} else {224enc->segment_hdr_.update_map_ = 0;225enc->segment_hdr_.size_ = 0;226}227}228229//------------------------------------------------------------------------------230// Coefficient coding231232static int PutCoeffs(VP8BitWriter* const bw, int ctx, const VP8Residual* res) {233int n = res->first;234// should be prob[VP8EncBands[n]], but it's equivalent for n=0 or 1235const uint8_t* p = res->prob[n][ctx];236if (!VP8PutBit(bw, res->last >= 0, p[0])) {237return 0;238}239240while (n < 16) {241const int c = res->coeffs[n++];242const int sign = c < 0;243int v = sign ? -c : c;244if (!VP8PutBit(bw, v != 0, p[1])) {245p = res->prob[VP8EncBands[n]][0];246continue;247}248if (!VP8PutBit(bw, v > 1, p[2])) {249p = res->prob[VP8EncBands[n]][1];250} else {251if (!VP8PutBit(bw, v > 4, p[3])) {252if (VP8PutBit(bw, v != 2, p[4])) {253VP8PutBit(bw, v == 4, p[5]);254}255} else if (!VP8PutBit(bw, v > 10, p[6])) {256if (!VP8PutBit(bw, v > 6, p[7])) {257VP8PutBit(bw, v == 6, 159);258} else {259VP8PutBit(bw, v >= 9, 165);260VP8PutBit(bw, !(v & 1), 145);261}262} else {263int mask;264const uint8_t* tab;265if (v < 3 + (8 << 1)) { // VP8Cat3 (3b)266VP8PutBit(bw, 0, p[8]);267VP8PutBit(bw, 0, p[9]);268v -= 3 + (8 << 0);269mask = 1 << 2;270tab = VP8Cat3;271} else if (v < 3 + (8 << 2)) { // VP8Cat4 (4b)272VP8PutBit(bw, 0, p[8]);273VP8PutBit(bw, 1, p[9]);274v -= 3 + (8 << 1);275mask = 1 << 3;276tab = VP8Cat4;277} else if (v < 3 + (8 << 3)) { // VP8Cat5 (5b)278VP8PutBit(bw, 1, p[8]);279VP8PutBit(bw, 0, p[10]);280v -= 3 + (8 << 2);281mask = 1 << 4;282tab = VP8Cat5;283} else { // VP8Cat6 (11b)284VP8PutBit(bw, 1, p[8]);285VP8PutBit(bw, 1, p[10]);286v -= 3 + (8 << 3);287mask = 1 << 10;288tab = VP8Cat6;289}290while (mask) {291VP8PutBit(bw, !!(v & mask), *tab++);292mask >>= 1;293}294}295p = res->prob[VP8EncBands[n]][2];296}297VP8PutBitUniform(bw, sign);298if (n == 16 || !VP8PutBit(bw, n <= res->last, p[0])) {299return 1; // EOB300}301}302return 1;303}304305static void CodeResiduals(VP8BitWriter* const bw, VP8EncIterator* const it,306const VP8ModeScore* const rd) {307int x, y, ch;308VP8Residual res;309uint64_t pos1, pos2, pos3;310const int i16 = (it->mb_->type_ == 1);311const int segment = it->mb_->segment_;312VP8Encoder* const enc = it->enc_;313314VP8IteratorNzToBytes(it);315316pos1 = VP8BitWriterPos(bw);317if (i16) {318VP8InitResidual(0, 1, enc, &res);319VP8SetResidualCoeffs(rd->y_dc_levels, &res);320it->top_nz_[8] = it->left_nz_[8] =321PutCoeffs(bw, it->top_nz_[8] + it->left_nz_[8], &res);322VP8InitResidual(1, 0, enc, &res);323} else {324VP8InitResidual(0, 3, enc, &res);325}326327// luma-AC328for (y = 0; y < 4; ++y) {329for (x = 0; x < 4; ++x) {330const int ctx = it->top_nz_[x] + it->left_nz_[y];331VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);332it->top_nz_[x] = it->left_nz_[y] = PutCoeffs(bw, ctx, &res);333}334}335pos2 = VP8BitWriterPos(bw);336337// U/V338VP8InitResidual(0, 2, enc, &res);339for (ch = 0; ch <= 2; ch += 2) {340for (y = 0; y < 2; ++y) {341for (x = 0; x < 2; ++x) {342const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];343VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);344it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] =345PutCoeffs(bw, ctx, &res);346}347}348}349pos3 = VP8BitWriterPos(bw);350it->luma_bits_ = pos2 - pos1;351it->uv_bits_ = pos3 - pos2;352it->bit_count_[segment][i16] += it->luma_bits_;353it->bit_count_[segment][2] += it->uv_bits_;354VP8IteratorBytesToNz(it);355}356357// Same as CodeResiduals, but doesn't actually write anything.358// Instead, it just records the event distribution.359static void RecordResiduals(VP8EncIterator* const it,360const VP8ModeScore* const rd) {361int x, y, ch;362VP8Residual res;363VP8Encoder* const enc = it->enc_;364365VP8IteratorNzToBytes(it);366367if (it->mb_->type_ == 1) { // i16x16368VP8InitResidual(0, 1, enc, &res);369VP8SetResidualCoeffs(rd->y_dc_levels, &res);370it->top_nz_[8] = it->left_nz_[8] =371VP8RecordCoeffs(it->top_nz_[8] + it->left_nz_[8], &res);372VP8InitResidual(1, 0, enc, &res);373} else {374VP8InitResidual(0, 3, enc, &res);375}376377// luma-AC378for (y = 0; y < 4; ++y) {379for (x = 0; x < 4; ++x) {380const int ctx = it->top_nz_[x] + it->left_nz_[y];381VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);382it->top_nz_[x] = it->left_nz_[y] = VP8RecordCoeffs(ctx, &res);383}384}385386// U/V387VP8InitResidual(0, 2, enc, &res);388for (ch = 0; ch <= 2; ch += 2) {389for (y = 0; y < 2; ++y) {390for (x = 0; x < 2; ++x) {391const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];392VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);393it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] =394VP8RecordCoeffs(ctx, &res);395}396}397}398399VP8IteratorBytesToNz(it);400}401402//------------------------------------------------------------------------------403// Token buffer404405#if !defined(DISABLE_TOKEN_BUFFER)406407static int RecordTokens(VP8EncIterator* const it, const VP8ModeScore* const rd,408VP8TBuffer* const tokens) {409int x, y, ch;410VP8Residual res;411VP8Encoder* const enc = it->enc_;412413VP8IteratorNzToBytes(it);414if (it->mb_->type_ == 1) { // i16x16415const int ctx = it->top_nz_[8] + it->left_nz_[8];416VP8InitResidual(0, 1, enc, &res);417VP8SetResidualCoeffs(rd->y_dc_levels, &res);418it->top_nz_[8] = it->left_nz_[8] =419VP8RecordCoeffTokens(ctx, &res, tokens);420VP8InitResidual(1, 0, enc, &res);421} else {422VP8InitResidual(0, 3, enc, &res);423}424425// luma-AC426for (y = 0; y < 4; ++y) {427for (x = 0; x < 4; ++x) {428const int ctx = it->top_nz_[x] + it->left_nz_[y];429VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);430it->top_nz_[x] = it->left_nz_[y] =431VP8RecordCoeffTokens(ctx, &res, tokens);432}433}434435// U/V436VP8InitResidual(0, 2, enc, &res);437for (ch = 0; ch <= 2; ch += 2) {438for (y = 0; y < 2; ++y) {439for (x = 0; x < 2; ++x) {440const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];441VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);442it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] =443VP8RecordCoeffTokens(ctx, &res, tokens);444}445}446}447VP8IteratorBytesToNz(it);448return !tokens->error_;449}450451#endif // !DISABLE_TOKEN_BUFFER452453//------------------------------------------------------------------------------454// ExtraInfo map / Debug function455456#if !defined(WEBP_DISABLE_STATS)457458#if SEGMENT_VISU459static void SetBlock(uint8_t* p, int value, int size) {460int y;461for (y = 0; y < size; ++y) {462memset(p, value, size);463p += BPS;464}465}466#endif467468static void ResetSSE(VP8Encoder* const enc) {469enc->sse_[0] = 0;470enc->sse_[1] = 0;471enc->sse_[2] = 0;472// Note: enc->sse_[3] is managed by alpha.c473enc->sse_count_ = 0;474}475476static void StoreSSE(const VP8EncIterator* const it) {477VP8Encoder* const enc = it->enc_;478const uint8_t* const in = it->yuv_in_;479const uint8_t* const out = it->yuv_out_;480// Note: not totally accurate at boundary. And doesn't include in-loop filter.481enc->sse_[0] += VP8SSE16x16(in + Y_OFF_ENC, out + Y_OFF_ENC);482enc->sse_[1] += VP8SSE8x8(in + U_OFF_ENC, out + U_OFF_ENC);483enc->sse_[2] += VP8SSE8x8(in + V_OFF_ENC, out + V_OFF_ENC);484enc->sse_count_ += 16 * 16;485}486487static void StoreSideInfo(const VP8EncIterator* const it) {488VP8Encoder* const enc = it->enc_;489const VP8MBInfo* const mb = it->mb_;490WebPPicture* const pic = enc->pic_;491492if (pic->stats != NULL) {493StoreSSE(it);494enc->block_count_[0] += (mb->type_ == 0);495enc->block_count_[1] += (mb->type_ == 1);496enc->block_count_[2] += (mb->skip_ != 0);497}498499if (pic->extra_info != NULL) {500uint8_t* const info = &pic->extra_info[it->x_ + it->y_ * enc->mb_w_];501switch (pic->extra_info_type) {502case 1: *info = mb->type_; break;503case 2: *info = mb->segment_; break;504case 3: *info = enc->dqm_[mb->segment_].quant_; break;505case 4: *info = (mb->type_ == 1) ? it->preds_[0] : 0xff; break;506case 5: *info = mb->uv_mode_; break;507case 6: {508const int b = (int)((it->luma_bits_ + it->uv_bits_ + 7) >> 3);509*info = (b > 255) ? 255 : b; break;510}511case 7: *info = mb->alpha_; break;512default: *info = 0; break;513}514}515#if SEGMENT_VISU // visualize segments and prediction modes516SetBlock(it->yuv_out_ + Y_OFF_ENC, mb->segment_ * 64, 16);517SetBlock(it->yuv_out_ + U_OFF_ENC, it->preds_[0] * 64, 8);518SetBlock(it->yuv_out_ + V_OFF_ENC, mb->uv_mode_ * 64, 8);519#endif520}521522static void ResetSideInfo(const VP8EncIterator* const it) {523VP8Encoder* const enc = it->enc_;524WebPPicture* const pic = enc->pic_;525if (pic->stats != NULL) {526memset(enc->block_count_, 0, sizeof(enc->block_count_));527}528ResetSSE(enc);529}530#else // defined(WEBP_DISABLE_STATS)531static void ResetSSE(VP8Encoder* const enc) {532(void)enc;533}534static void StoreSideInfo(const VP8EncIterator* const it) {535VP8Encoder* const enc = it->enc_;536WebPPicture* const pic = enc->pic_;537if (pic->extra_info != NULL) {538if (it->x_ == 0 && it->y_ == 0) { // only do it once, at start539memset(pic->extra_info, 0,540enc->mb_w_ * enc->mb_h_ * sizeof(*pic->extra_info));541}542}543}544545static void ResetSideInfo(const VP8EncIterator* const it) {546(void)it;547}548#endif // !defined(WEBP_DISABLE_STATS)549550static double GetPSNR(uint64_t mse, uint64_t size) {551return (mse > 0 && size > 0) ? 10. * log10(255. * 255. * size / mse) : 99;552}553554//------------------------------------------------------------------------------555// StatLoop(): only collect statistics (number of skips, token usage, ...).556// This is used for deciding optimal probabilities. It also modifies the557// quantizer value if some target (size, PSNR) was specified.558559static void SetLoopParams(VP8Encoder* const enc, float q) {560// Make sure the quality parameter is inside valid bounds561q = Clamp(q, 0.f, 100.f);562563VP8SetSegmentParams(enc, q); // setup segment quantizations and filters564SetSegmentProbas(enc); // compute segment probabilities565566ResetStats(enc);567ResetSSE(enc);568}569570static uint64_t OneStatPass(VP8Encoder* const enc, VP8RDLevel rd_opt,571int nb_mbs, int percent_delta,572PassStats* const s) {573VP8EncIterator it;574uint64_t size = 0;575uint64_t size_p0 = 0;576uint64_t distortion = 0;577const uint64_t pixel_count = nb_mbs * 384;578579VP8IteratorInit(enc, &it);580SetLoopParams(enc, s->q);581do {582VP8ModeScore info;583VP8IteratorImport(&it, NULL);584if (VP8Decimate(&it, &info, rd_opt)) {585// Just record the number of skips and act like skip_proba is not used.586++enc->proba_.nb_skip_;587}588RecordResiduals(&it, &info);589size += info.R + info.H;590size_p0 += info.H;591distortion += info.D;592if (percent_delta && !VP8IteratorProgress(&it, percent_delta)) {593return 0;594}595VP8IteratorSaveBoundary(&it);596} while (VP8IteratorNext(&it) && --nb_mbs > 0);597598size_p0 += enc->segment_hdr_.size_;599if (s->do_size_search) {600size += FinalizeSkipProba(enc);601size += FinalizeTokenProbas(&enc->proba_);602size = ((size + size_p0 + 1024) >> 11) + HEADER_SIZE_ESTIMATE;603s->value = (double)size;604} else {605s->value = GetPSNR(distortion, pixel_count);606}607return size_p0;608}609610static int StatLoop(VP8Encoder* const enc) {611const int method = enc->method_;612const int do_search = enc->do_search_;613const int fast_probe = ((method == 0 || method == 3) && !do_search);614int num_pass_left = enc->config_->pass;615const int task_percent = 20;616const int percent_per_pass =617(task_percent + num_pass_left / 2) / num_pass_left;618const int final_percent = enc->percent_ + task_percent;619const VP8RDLevel rd_opt =620(method >= 3 || do_search) ? RD_OPT_BASIC : RD_OPT_NONE;621int nb_mbs = enc->mb_w_ * enc->mb_h_;622PassStats stats;623624InitPassStats(enc, &stats);625ResetTokenStats(enc);626627// Fast mode: quick analysis pass over few mbs. Better than nothing.628if (fast_probe) {629if (method == 3) { // we need more stats for method 3 to be reliable.630nb_mbs = (nb_mbs > 200) ? nb_mbs >> 1 : 100;631} else {632nb_mbs = (nb_mbs > 200) ? nb_mbs >> 2 : 50;633}634}635636while (num_pass_left-- > 0) {637const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) ||638(num_pass_left == 0) ||639(enc->max_i4_header_bits_ == 0);640const uint64_t size_p0 =641OneStatPass(enc, rd_opt, nb_mbs, percent_per_pass, &stats);642if (size_p0 == 0) return 0;643#if (DEBUG_SEARCH > 0)644printf("#%d value:%.1lf -> %.1lf q:%.2f -> %.2f\n",645num_pass_left, stats.last_value, stats.value, stats.last_q, stats.q);646#endif647if (enc->max_i4_header_bits_ > 0 && size_p0 > PARTITION0_SIZE_LIMIT) {648++num_pass_left;649enc->max_i4_header_bits_ >>= 1; // strengthen header bit limitation...650continue; // ...and start over651}652if (is_last_pass) {653break;654}655// If no target size: just do several pass without changing 'q'656if (do_search) {657ComputeNextQ(&stats);658if (fabs(stats.dq) <= DQ_LIMIT) break;659}660}661if (!do_search || !stats.do_size_search) {662// Need to finalize probas now, since it wasn't done during the search.663FinalizeSkipProba(enc);664FinalizeTokenProbas(&enc->proba_);665}666VP8CalculateLevelCosts(&enc->proba_); // finalize costs667return WebPReportProgress(enc->pic_, final_percent, &enc->percent_);668}669670//------------------------------------------------------------------------------671// Main loops672//673674static const uint8_t kAverageBytesPerMB[8] = { 50, 24, 16, 9, 7, 5, 3, 2 };675676static int PreLoopInitialize(VP8Encoder* const enc) {677int p;678int ok = 1;679const int average_bytes_per_MB = kAverageBytesPerMB[enc->base_quant_ >> 4];680const int bytes_per_parts =681enc->mb_w_ * enc->mb_h_ * average_bytes_per_MB / enc->num_parts_;682// Initialize the bit-writers683for (p = 0; ok && p < enc->num_parts_; ++p) {684ok = VP8BitWriterInit(enc->parts_ + p, bytes_per_parts);685}686if (!ok) {687VP8EncFreeBitWriters(enc); // malloc error occurred688WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY);689}690return ok;691}692693static int PostLoopFinalize(VP8EncIterator* const it, int ok) {694VP8Encoder* const enc = it->enc_;695if (ok) { // Finalize the partitions, check for extra errors.696int p;697for (p = 0; p < enc->num_parts_; ++p) {698VP8BitWriterFinish(enc->parts_ + p);699ok &= !enc->parts_[p].error_;700}701}702703if (ok) { // All good. Finish up.704#if !defined(WEBP_DISABLE_STATS)705if (enc->pic_->stats != NULL) { // finalize byte counters...706int i, s;707for (i = 0; i <= 2; ++i) {708for (s = 0; s < NUM_MB_SEGMENTS; ++s) {709enc->residual_bytes_[i][s] = (int)((it->bit_count_[s][i] + 7) >> 3);710}711}712}713#endif714VP8AdjustFilterStrength(it); // ...and store filter stats.715} else {716// Something bad happened -> need to do some memory cleanup.717VP8EncFreeBitWriters(enc);718}719return ok;720}721722//------------------------------------------------------------------------------723// VP8EncLoop(): does the final bitstream coding.724725static void ResetAfterSkip(VP8EncIterator* const it) {726if (it->mb_->type_ == 1) {727*it->nz_ = 0; // reset all predictors728it->left_nz_[8] = 0;729} else {730*it->nz_ &= (1 << 24); // preserve the dc_nz bit731}732}733734int VP8EncLoop(VP8Encoder* const enc) {735VP8EncIterator it;736int ok = PreLoopInitialize(enc);737if (!ok) return 0;738739StatLoop(enc); // stats-collection loop740741VP8IteratorInit(enc, &it);742VP8InitFilter(&it);743do {744VP8ModeScore info;745const int dont_use_skip = !enc->proba_.use_skip_proba_;746const VP8RDLevel rd_opt = enc->rd_opt_level_;747748VP8IteratorImport(&it, NULL);749// Warning! order is important: first call VP8Decimate() and750// *then* decide how to code the skip decision if there's one.751if (!VP8Decimate(&it, &info, rd_opt) || dont_use_skip) {752CodeResiduals(it.bw_, &it, &info);753} else { // reset predictors after a skip754ResetAfterSkip(&it);755}756StoreSideInfo(&it);757VP8StoreFilterStats(&it);758VP8IteratorExport(&it);759ok = VP8IteratorProgress(&it, 20);760VP8IteratorSaveBoundary(&it);761} while (ok && VP8IteratorNext(&it));762763return PostLoopFinalize(&it, ok);764}765766//------------------------------------------------------------------------------767// Single pass using Token Buffer.768769#if !defined(DISABLE_TOKEN_BUFFER)770771#define MIN_COUNT 96 // minimum number of macroblocks before updating stats772773int VP8EncTokenLoop(VP8Encoder* const enc) {774// Roughly refresh the proba eight times per pass775int max_count = (enc->mb_w_ * enc->mb_h_) >> 3;776int num_pass_left = enc->config_->pass;777const int do_search = enc->do_search_;778VP8EncIterator it;779VP8EncProba* const proba = &enc->proba_;780const VP8RDLevel rd_opt = enc->rd_opt_level_;781const uint64_t pixel_count = enc->mb_w_ * enc->mb_h_ * 384;782PassStats stats;783int ok;784785InitPassStats(enc, &stats);786ok = PreLoopInitialize(enc);787if (!ok) return 0;788789if (max_count < MIN_COUNT) max_count = MIN_COUNT;790791assert(enc->num_parts_ == 1);792assert(enc->use_tokens_);793assert(proba->use_skip_proba_ == 0);794assert(rd_opt >= RD_OPT_BASIC); // otherwise, token-buffer won't be useful795assert(num_pass_left > 0);796797while (ok && num_pass_left-- > 0) {798const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) ||799(num_pass_left == 0) ||800(enc->max_i4_header_bits_ == 0);801uint64_t size_p0 = 0;802uint64_t distortion = 0;803int cnt = max_count;804VP8IteratorInit(enc, &it);805SetLoopParams(enc, stats.q);806if (is_last_pass) {807ResetTokenStats(enc);808VP8InitFilter(&it); // don't collect stats until last pass (too costly)809}810VP8TBufferClear(&enc->tokens_);811do {812VP8ModeScore info;813VP8IteratorImport(&it, NULL);814if (--cnt < 0) {815FinalizeTokenProbas(proba);816VP8CalculateLevelCosts(proba); // refresh cost tables for rd-opt817cnt = max_count;818}819VP8Decimate(&it, &info, rd_opt);820ok = RecordTokens(&it, &info, &enc->tokens_);821if (!ok) {822WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY);823break;824}825size_p0 += info.H;826distortion += info.D;827if (is_last_pass) {828StoreSideInfo(&it);829VP8StoreFilterStats(&it);830VP8IteratorExport(&it);831ok = VP8IteratorProgress(&it, 20);832}833VP8IteratorSaveBoundary(&it);834} while (ok && VP8IteratorNext(&it));835if (!ok) break;836837size_p0 += enc->segment_hdr_.size_;838if (stats.do_size_search) {839uint64_t size = FinalizeTokenProbas(&enc->proba_);840size += VP8EstimateTokenSize(&enc->tokens_,841(const uint8_t*)proba->coeffs_);842size = (size + size_p0 + 1024) >> 11; // -> size in bytes843size += HEADER_SIZE_ESTIMATE;844stats.value = (double)size;845} else { // compute and store PSNR846stats.value = GetPSNR(distortion, pixel_count);847}848849#if (DEBUG_SEARCH > 0)850printf("#%2d metric:%.1lf -> %.1lf last_q=%.2lf q=%.2lf dq=%.2lf\n",851num_pass_left, stats.last_value, stats.value,852stats.last_q, stats.q, stats.dq);853#endif854if (enc->max_i4_header_bits_ > 0 && size_p0 > PARTITION0_SIZE_LIMIT) {855++num_pass_left;856enc->max_i4_header_bits_ >>= 1; // strengthen header bit limitation...857if (is_last_pass) {858ResetSideInfo(&it);859}860continue; // ...and start over861}862if (is_last_pass) {863break; // done864}865if (do_search) {866ComputeNextQ(&stats); // Adjust q867}868}869if (ok) {870if (!stats.do_size_search) {871FinalizeTokenProbas(&enc->proba_);872}873ok = VP8EmitTokens(&enc->tokens_, enc->parts_ + 0,874(const uint8_t*)proba->coeffs_, 1);875}876ok = ok && WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);877return PostLoopFinalize(&it, ok);878}879880#else881882int VP8EncTokenLoop(VP8Encoder* const enc) {883(void)enc;884return 0; // we shouldn't be here.885}886887#endif // DISABLE_TOKEN_BUFFER888889//------------------------------------------------------------------------------890891892