Path: blob/master/3rdparty/libwebp/src/enc/quant_enc.c
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// Quantization10//11// Author: Skal ([email protected])1213#include <assert.h>14#include <math.h>15#include <stdlib.h> // for abs()1617#include "src/enc/vp8i_enc.h"18#include "src/enc/cost_enc.h"1920#define DO_TRELLIS_I4 121#define DO_TRELLIS_I16 1 // not a huge gain, but ok at low bitrate.22#define DO_TRELLIS_UV 0 // disable trellis for UV. Risky. Not worth.23#define USE_TDISTO 12425#define MID_ALPHA 64 // neutral value for susceptibility26#define MIN_ALPHA 30 // lowest usable value for susceptibility27#define MAX_ALPHA 100 // higher meaningful value for susceptibility2829#define SNS_TO_DQ 0.9 // Scaling constant between the sns value and the QP30// power-law modulation. Must be strictly less than 1.3132// number of non-zero coeffs below which we consider the block very flat33// (and apply a penalty to complex predictions)34#define FLATNESS_LIMIT_I16 10 // I16 mode35#define FLATNESS_LIMIT_I4 3 // I4 mode36#define FLATNESS_LIMIT_UV 2 // UV mode37#define FLATNESS_PENALTY 140 // roughly ~1bit per block3839#define MULT_8B(a, b) (((a) * (b) + 128) >> 8)4041#define RD_DISTO_MULT 256 // distortion multiplier (equivalent of lambda)4243// #define DEBUG_BLOCK4445//------------------------------------------------------------------------------4647#if defined(DEBUG_BLOCK)4849#include <stdio.h>50#include <stdlib.h>5152static void PrintBlockInfo(const VP8EncIterator* const it,53const VP8ModeScore* const rd) {54int i, j;55const int is_i16 = (it->mb_->type_ == 1);56const uint8_t* const y_in = it->yuv_in_ + Y_OFF_ENC;57const uint8_t* const y_out = it->yuv_out_ + Y_OFF_ENC;58const uint8_t* const uv_in = it->yuv_in_ + U_OFF_ENC;59const uint8_t* const uv_out = it->yuv_out_ + U_OFF_ENC;60printf("SOURCE / OUTPUT / ABS DELTA\n");61for (j = 0; j < 16; ++j) {62for (i = 0; i < 16; ++i) printf("%3d ", y_in[i + j * BPS]);63printf(" ");64for (i = 0; i < 16; ++i) printf("%3d ", y_out[i + j * BPS]);65printf(" ");66for (i = 0; i < 16; ++i) {67printf("%1d ", abs(y_in[i + j * BPS] - y_out[i + j * BPS]));68}69printf("\n");70}71printf("\n"); // newline before the U/V block72for (j = 0; j < 8; ++j) {73for (i = 0; i < 8; ++i) printf("%3d ", uv_in[i + j * BPS]);74printf(" ");75for (i = 8; i < 16; ++i) printf("%3d ", uv_in[i + j * BPS]);76printf(" ");77for (i = 0; i < 8; ++i) printf("%3d ", uv_out[i + j * BPS]);78printf(" ");79for (i = 8; i < 16; ++i) printf("%3d ", uv_out[i + j * BPS]);80printf(" ");81for (i = 0; i < 8; ++i) {82printf("%1d ", abs(uv_out[i + j * BPS] - uv_in[i + j * BPS]));83}84printf(" ");85for (i = 8; i < 16; ++i) {86printf("%1d ", abs(uv_out[i + j * BPS] - uv_in[i + j * BPS]));87}88printf("\n");89}90printf("\nD:%d SD:%d R:%d H:%d nz:0x%x score:%d\n",91(int)rd->D, (int)rd->SD, (int)rd->R, (int)rd->H, (int)rd->nz,92(int)rd->score);93if (is_i16) {94printf("Mode: %d\n", rd->mode_i16);95printf("y_dc_levels:");96for (i = 0; i < 16; ++i) printf("%3d ", rd->y_dc_levels[i]);97printf("\n");98} else {99printf("Modes[16]: ");100for (i = 0; i < 16; ++i) printf("%d ", rd->modes_i4[i]);101printf("\n");102}103printf("y_ac_levels:\n");104for (j = 0; j < 16; ++j) {105for (i = is_i16 ? 1 : 0; i < 16; ++i) {106printf("%4d ", rd->y_ac_levels[j][i]);107}108printf("\n");109}110printf("\n");111printf("uv_levels (mode=%d):\n", rd->mode_uv);112for (j = 0; j < 8; ++j) {113for (i = 0; i < 16; ++i) {114printf("%4d ", rd->uv_levels[j][i]);115}116printf("\n");117}118}119120#endif // DEBUG_BLOCK121122//------------------------------------------------------------------------------123124static WEBP_INLINE int clip(int v, int m, int M) {125return v < m ? m : v > M ? M : v;126}127128static const uint8_t kZigzag[16] = {1290, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15130};131132static const uint8_t kDcTable[128] = {1334, 5, 6, 7, 8, 9, 10, 10,13411, 12, 13, 14, 15, 16, 17, 17,13518, 19, 20, 20, 21, 21, 22, 22,13623, 23, 24, 25, 25, 26, 27, 28,13729, 30, 31, 32, 33, 34, 35, 36,13837, 37, 38, 39, 40, 41, 42, 43,13944, 45, 46, 46, 47, 48, 49, 50,14051, 52, 53, 54, 55, 56, 57, 58,14159, 60, 61, 62, 63, 64, 65, 66,14267, 68, 69, 70, 71, 72, 73, 74,14375, 76, 76, 77, 78, 79, 80, 81,14482, 83, 84, 85, 86, 87, 88, 89,14591, 93, 95, 96, 98, 100, 101, 102,146104, 106, 108, 110, 112, 114, 116, 118,147122, 124, 126, 128, 130, 132, 134, 136,148138, 140, 143, 145, 148, 151, 154, 157149};150151static const uint16_t kAcTable[128] = {1524, 5, 6, 7, 8, 9, 10, 11,15312, 13, 14, 15, 16, 17, 18, 19,15420, 21, 22, 23, 24, 25, 26, 27,15528, 29, 30, 31, 32, 33, 34, 35,15636, 37, 38, 39, 40, 41, 42, 43,15744, 45, 46, 47, 48, 49, 50, 51,15852, 53, 54, 55, 56, 57, 58, 60,15962, 64, 66, 68, 70, 72, 74, 76,16078, 80, 82, 84, 86, 88, 90, 92,16194, 96, 98, 100, 102, 104, 106, 108,162110, 112, 114, 116, 119, 122, 125, 128,163131, 134, 137, 140, 143, 146, 149, 152,164155, 158, 161, 164, 167, 170, 173, 177,165181, 185, 189, 193, 197, 201, 205, 209,166213, 217, 221, 225, 229, 234, 239, 245,167249, 254, 259, 264, 269, 274, 279, 284168};169170static const uint16_t kAcTable2[128] = {1718, 8, 9, 10, 12, 13, 15, 17,17218, 20, 21, 23, 24, 26, 27, 29,17331, 32, 34, 35, 37, 38, 40, 41,17443, 44, 46, 48, 49, 51, 52, 54,17555, 57, 58, 60, 62, 63, 65, 66,17668, 69, 71, 72, 74, 75, 77, 79,17780, 82, 83, 85, 86, 88, 89, 93,17896, 99, 102, 105, 108, 111, 114, 117,179120, 124, 127, 130, 133, 136, 139, 142,180145, 148, 151, 155, 158, 161, 164, 167,181170, 173, 176, 179, 184, 189, 193, 198,182203, 207, 212, 217, 221, 226, 230, 235,183240, 244, 249, 254, 258, 263, 268, 274,184280, 286, 292, 299, 305, 311, 317, 323,185330, 336, 342, 348, 354, 362, 370, 379,186385, 393, 401, 409, 416, 424, 432, 440187};188189static const uint8_t kBiasMatrices[3][2] = { // [luma-ac,luma-dc,chroma][dc,ac]190{ 96, 110 }, { 96, 108 }, { 110, 115 }191};192193// Sharpening by (slightly) raising the hi-frequency coeffs.194// Hack-ish but helpful for mid-bitrate range. Use with care.195#define SHARPEN_BITS 11 // number of descaling bits for sharpening bias196static const uint8_t kFreqSharpening[16] = {1970, 30, 60, 90,19830, 60, 90, 90,19960, 90, 90, 90,20090, 90, 90, 90201};202203//------------------------------------------------------------------------------204// Initialize quantization parameters in VP8Matrix205206// Returns the average quantizer207static int ExpandMatrix(VP8Matrix* const m, int type) {208int i, sum;209for (i = 0; i < 2; ++i) {210const int is_ac_coeff = (i > 0);211const int bias = kBiasMatrices[type][is_ac_coeff];212m->iq_[i] = (1 << QFIX) / m->q_[i];213m->bias_[i] = BIAS(bias);214// zthresh_ is the exact value such that QUANTDIV(coeff, iQ, B) is:215// * zero if coeff <= zthresh216// * non-zero if coeff > zthresh217m->zthresh_[i] = ((1 << QFIX) - 1 - m->bias_[i]) / m->iq_[i];218}219for (i = 2; i < 16; ++i) {220m->q_[i] = m->q_[1];221m->iq_[i] = m->iq_[1];222m->bias_[i] = m->bias_[1];223m->zthresh_[i] = m->zthresh_[1];224}225for (sum = 0, i = 0; i < 16; ++i) {226if (type == 0) { // we only use sharpening for AC luma coeffs227m->sharpen_[i] = (kFreqSharpening[i] * m->q_[i]) >> SHARPEN_BITS;228} else {229m->sharpen_[i] = 0;230}231sum += m->q_[i];232}233return (sum + 8) >> 4;234}235236static void CheckLambdaValue(int* const v) { if (*v < 1) *v = 1; }237238static void SetupMatrices(VP8Encoder* enc) {239int i;240const int tlambda_scale =241(enc->method_ >= 4) ? enc->config_->sns_strength242: 0;243const int num_segments = enc->segment_hdr_.num_segments_;244for (i = 0; i < num_segments; ++i) {245VP8SegmentInfo* const m = &enc->dqm_[i];246const int q = m->quant_;247int q_i4, q_i16, q_uv;248m->y1_.q_[0] = kDcTable[clip(q + enc->dq_y1_dc_, 0, 127)];249m->y1_.q_[1] = kAcTable[clip(q, 0, 127)];250251m->y2_.q_[0] = kDcTable[ clip(q + enc->dq_y2_dc_, 0, 127)] * 2;252m->y2_.q_[1] = kAcTable2[clip(q + enc->dq_y2_ac_, 0, 127)];253254m->uv_.q_[0] = kDcTable[clip(q + enc->dq_uv_dc_, 0, 117)];255m->uv_.q_[1] = kAcTable[clip(q + enc->dq_uv_ac_, 0, 127)];256257q_i4 = ExpandMatrix(&m->y1_, 0);258q_i16 = ExpandMatrix(&m->y2_, 1);259q_uv = ExpandMatrix(&m->uv_, 2);260261m->lambda_i4_ = (3 * q_i4 * q_i4) >> 7;262m->lambda_i16_ = (3 * q_i16 * q_i16);263m->lambda_uv_ = (3 * q_uv * q_uv) >> 6;264m->lambda_mode_ = (1 * q_i4 * q_i4) >> 7;265m->lambda_trellis_i4_ = (7 * q_i4 * q_i4) >> 3;266m->lambda_trellis_i16_ = (q_i16 * q_i16) >> 2;267m->lambda_trellis_uv_ = (q_uv * q_uv) << 1;268m->tlambda_ = (tlambda_scale * q_i4) >> 5;269270// none of these constants should be < 1271CheckLambdaValue(&m->lambda_i4_);272CheckLambdaValue(&m->lambda_i16_);273CheckLambdaValue(&m->lambda_uv_);274CheckLambdaValue(&m->lambda_mode_);275CheckLambdaValue(&m->lambda_trellis_i4_);276CheckLambdaValue(&m->lambda_trellis_i16_);277CheckLambdaValue(&m->lambda_trellis_uv_);278CheckLambdaValue(&m->tlambda_);279280m->min_disto_ = 20 * m->y1_.q_[0]; // quantization-aware min disto281m->max_edge_ = 0;282283m->i4_penalty_ = 1000 * q_i4 * q_i4;284}285}286287//------------------------------------------------------------------------------288// Initialize filtering parameters289290// Very small filter-strength values have close to no visual effect. So we can291// save a little decoding-CPU by turning filtering off for these.292#define FSTRENGTH_CUTOFF 2293294static void SetupFilterStrength(VP8Encoder* const enc) {295int i;296// level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering.297const int level0 = 5 * enc->config_->filter_strength;298for (i = 0; i < NUM_MB_SEGMENTS; ++i) {299VP8SegmentInfo* const m = &enc->dqm_[i];300// We focus on the quantization of AC coeffs.301const int qstep = kAcTable[clip(m->quant_, 0, 127)] >> 2;302const int base_strength =303VP8FilterStrengthFromDelta(enc->filter_hdr_.sharpness_, qstep);304// Segments with lower complexity ('beta') will be less filtered.305const int f = base_strength * level0 / (256 + m->beta_);306m->fstrength_ = (f < FSTRENGTH_CUTOFF) ? 0 : (f > 63) ? 63 : f;307}308// We record the initial strength (mainly for the case of 1-segment only).309enc->filter_hdr_.level_ = enc->dqm_[0].fstrength_;310enc->filter_hdr_.simple_ = (enc->config_->filter_type == 0);311enc->filter_hdr_.sharpness_ = enc->config_->filter_sharpness;312}313314//------------------------------------------------------------------------------315316// Note: if you change the values below, remember that the max range317// allowed by the syntax for DQ_UV is [-16,16].318#define MAX_DQ_UV (6)319#define MIN_DQ_UV (-4)320321// We want to emulate jpeg-like behaviour where the expected "good" quality322// is around q=75. Internally, our "good" middle is around c=50. So we323// map accordingly using linear piece-wise function324static double QualityToCompression(double c) {325const double linear_c = (c < 0.75) ? c * (2. / 3.) : 2. * c - 1.;326// The file size roughly scales as pow(quantizer, 3.). Actually, the327// exponent is somewhere between 2.8 and 3.2, but we're mostly interested328// in the mid-quant range. So we scale the compressibility inversely to329// this power-law: quant ~= compression ^ 1/3. This law holds well for330// low quant. Finer modeling for high-quant would make use of kAcTable[]331// more explicitly.332const double v = pow(linear_c, 1 / 3.);333return v;334}335336static double QualityToJPEGCompression(double c, double alpha) {337// We map the complexity 'alpha' and quality setting 'c' to a compression338// exponent empirically matched to the compression curve of libjpeg6b.339// On average, the WebP output size will be roughly similar to that of a340// JPEG file compressed with same quality factor.341const double amin = 0.30;342const double amax = 0.85;343const double exp_min = 0.4;344const double exp_max = 0.9;345const double slope = (exp_min - exp_max) / (amax - amin);346// Linearly interpolate 'expn' from exp_min to exp_max347// in the [amin, amax] range.348const double expn = (alpha > amax) ? exp_min349: (alpha < amin) ? exp_max350: exp_max + slope * (alpha - amin);351const double v = pow(c, expn);352return v;353}354355static int SegmentsAreEquivalent(const VP8SegmentInfo* const S1,356const VP8SegmentInfo* const S2) {357return (S1->quant_ == S2->quant_) && (S1->fstrength_ == S2->fstrength_);358}359360static void SimplifySegments(VP8Encoder* const enc) {361int map[NUM_MB_SEGMENTS] = { 0, 1, 2, 3 };362// 'num_segments_' is previously validated and <= NUM_MB_SEGMENTS, but an363// explicit check is needed to avoid a spurious warning about 'i' exceeding364// array bounds of 'dqm_' with some compilers (noticed with gcc-4.9).365const int num_segments = (enc->segment_hdr_.num_segments_ < NUM_MB_SEGMENTS)366? enc->segment_hdr_.num_segments_367: NUM_MB_SEGMENTS;368int num_final_segments = 1;369int s1, s2;370for (s1 = 1; s1 < num_segments; ++s1) { // find similar segments371const VP8SegmentInfo* const S1 = &enc->dqm_[s1];372int found = 0;373// check if we already have similar segment374for (s2 = 0; s2 < num_final_segments; ++s2) {375const VP8SegmentInfo* const S2 = &enc->dqm_[s2];376if (SegmentsAreEquivalent(S1, S2)) {377found = 1;378break;379}380}381map[s1] = s2;382if (!found) {383if (num_final_segments != s1) {384enc->dqm_[num_final_segments] = enc->dqm_[s1];385}386++num_final_segments;387}388}389if (num_final_segments < num_segments) { // Remap390int i = enc->mb_w_ * enc->mb_h_;391while (i-- > 0) enc->mb_info_[i].segment_ = map[enc->mb_info_[i].segment_];392enc->segment_hdr_.num_segments_ = num_final_segments;393// Replicate the trailing segment infos (it's mostly cosmetics)394for (i = num_final_segments; i < num_segments; ++i) {395enc->dqm_[i] = enc->dqm_[num_final_segments - 1];396}397}398}399400void VP8SetSegmentParams(VP8Encoder* const enc, float quality) {401int i;402int dq_uv_ac, dq_uv_dc;403const int num_segments = enc->segment_hdr_.num_segments_;404const double amp = SNS_TO_DQ * enc->config_->sns_strength / 100. / 128.;405const double Q = quality / 100.;406const double c_base = enc->config_->emulate_jpeg_size ?407QualityToJPEGCompression(Q, enc->alpha_ / 255.) :408QualityToCompression(Q);409for (i = 0; i < num_segments; ++i) {410// We modulate the base coefficient to accommodate for the quantization411// susceptibility and allow denser segments to be quantized more.412const double expn = 1. - amp * enc->dqm_[i].alpha_;413const double c = pow(c_base, expn);414const int q = (int)(127. * (1. - c));415assert(expn > 0.);416enc->dqm_[i].quant_ = clip(q, 0, 127);417}418419// purely indicative in the bitstream (except for the 1-segment case)420enc->base_quant_ = enc->dqm_[0].quant_;421422// fill-in values for the unused segments (required by the syntax)423for (i = num_segments; i < NUM_MB_SEGMENTS; ++i) {424enc->dqm_[i].quant_ = enc->base_quant_;425}426427// uv_alpha_ is normally spread around ~60. The useful range is428// typically ~30 (quite bad) to ~100 (ok to decimate UV more).429// We map it to the safe maximal range of MAX/MIN_DQ_UV for dq_uv.430dq_uv_ac = (enc->uv_alpha_ - MID_ALPHA) * (MAX_DQ_UV - MIN_DQ_UV)431/ (MAX_ALPHA - MIN_ALPHA);432// we rescale by the user-defined strength of adaptation433dq_uv_ac = dq_uv_ac * enc->config_->sns_strength / 100;434// and make it safe.435dq_uv_ac = clip(dq_uv_ac, MIN_DQ_UV, MAX_DQ_UV);436// We also boost the dc-uv-quant a little, based on sns-strength, since437// U/V channels are quite more reactive to high quants (flat DC-blocks438// tend to appear, and are unpleasant).439dq_uv_dc = -4 * enc->config_->sns_strength / 100;440dq_uv_dc = clip(dq_uv_dc, -15, 15); // 4bit-signed max allowed441442enc->dq_y1_dc_ = 0; // TODO(skal): dq-lum443enc->dq_y2_dc_ = 0;444enc->dq_y2_ac_ = 0;445enc->dq_uv_dc_ = dq_uv_dc;446enc->dq_uv_ac_ = dq_uv_ac;447448SetupFilterStrength(enc); // initialize segments' filtering, eventually449450if (num_segments > 1) SimplifySegments(enc);451452SetupMatrices(enc); // finalize quantization matrices453}454455//------------------------------------------------------------------------------456// Form the predictions in cache457458// Must be ordered using {DC_PRED, TM_PRED, V_PRED, H_PRED} as index459const uint16_t VP8I16ModeOffsets[4] = { I16DC16, I16TM16, I16VE16, I16HE16 };460const uint16_t VP8UVModeOffsets[4] = { C8DC8, C8TM8, C8VE8, C8HE8 };461462// Must be indexed using {B_DC_PRED -> B_HU_PRED} as index463const uint16_t VP8I4ModeOffsets[NUM_BMODES] = {464I4DC4, I4TM4, I4VE4, I4HE4, I4RD4, I4VR4, I4LD4, I4VL4, I4HD4, I4HU4465};466467void VP8MakeLuma16Preds(const VP8EncIterator* const it) {468const uint8_t* const left = it->x_ ? it->y_left_ : NULL;469const uint8_t* const top = it->y_ ? it->y_top_ : NULL;470VP8EncPredLuma16(it->yuv_p_, left, top);471}472473void VP8MakeChroma8Preds(const VP8EncIterator* const it) {474const uint8_t* const left = it->x_ ? it->u_left_ : NULL;475const uint8_t* const top = it->y_ ? it->uv_top_ : NULL;476VP8EncPredChroma8(it->yuv_p_, left, top);477}478479void VP8MakeIntra4Preds(const VP8EncIterator* const it) {480VP8EncPredLuma4(it->yuv_p_, it->i4_top_);481}482483//------------------------------------------------------------------------------484// Quantize485486// Layout:487// +----+----+488// |YYYY|UUVV| 0489// |YYYY|UUVV| 4490// |YYYY|....| 8491// |YYYY|....| 12492// +----+----+493494const uint16_t VP8Scan[16] = { // Luma4950 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS,4960 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS,4970 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS,4980 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS,499};500501static const uint16_t VP8ScanUV[4 + 4] = {5020 + 0 * BPS, 4 + 0 * BPS, 0 + 4 * BPS, 4 + 4 * BPS, // U5038 + 0 * BPS, 12 + 0 * BPS, 8 + 4 * BPS, 12 + 4 * BPS // V504};505506//------------------------------------------------------------------------------507// Distortion measurement508509static const uint16_t kWeightY[16] = {51038, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2511};512513static const uint16_t kWeightTrellis[16] = {514#if USE_TDISTO == 051516, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16516#else51730, 27, 19, 11,51827, 24, 17, 10,51919, 17, 12, 8,52011, 10, 8, 6521#endif522};523524// Init/Copy the common fields in score.525static void InitScore(VP8ModeScore* const rd) {526rd->D = 0;527rd->SD = 0;528rd->R = 0;529rd->H = 0;530rd->nz = 0;531rd->score = MAX_COST;532}533534static void CopyScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {535dst->D = src->D;536dst->SD = src->SD;537dst->R = src->R;538dst->H = src->H;539dst->nz = src->nz; // note that nz is not accumulated, but just copied.540dst->score = src->score;541}542543static void AddScore(VP8ModeScore* const dst, const VP8ModeScore* const src) {544dst->D += src->D;545dst->SD += src->SD;546dst->R += src->R;547dst->H += src->H;548dst->nz |= src->nz; // here, new nz bits are accumulated.549dst->score += src->score;550}551552//------------------------------------------------------------------------------553// Performs trellis-optimized quantization.554555// Trellis node556typedef struct {557int8_t prev; // best previous node558int8_t sign; // sign of coeff_i559int16_t level; // level560} Node;561562// Score state563typedef struct {564score_t score; // partial RD score565const uint16_t* costs; // shortcut to cost tables566} ScoreState;567568// If a coefficient was quantized to a value Q (using a neutral bias),569// we test all alternate possibilities between [Q-MIN_DELTA, Q+MAX_DELTA]570// We don't test negative values though.571#define MIN_DELTA 0 // how much lower level to try572#define MAX_DELTA 1 // how much higher573#define NUM_NODES (MIN_DELTA + 1 + MAX_DELTA)574#define NODE(n, l) (nodes[(n)][(l) + MIN_DELTA])575#define SCORE_STATE(n, l) (score_states[n][(l) + MIN_DELTA])576577static WEBP_INLINE void SetRDScore(int lambda, VP8ModeScore* const rd) {578rd->score = (rd->R + rd->H) * lambda + RD_DISTO_MULT * (rd->D + rd->SD);579}580581static WEBP_INLINE score_t RDScoreTrellis(int lambda, score_t rate,582score_t distortion) {583return rate * lambda + RD_DISTO_MULT * distortion;584}585586static int TrellisQuantizeBlock(const VP8Encoder* const enc,587int16_t in[16], int16_t out[16],588int ctx0, int coeff_type,589const VP8Matrix* const mtx,590int lambda) {591const ProbaArray* const probas = enc->proba_.coeffs_[coeff_type];592CostArrayPtr const costs =593(CostArrayPtr)enc->proba_.remapped_costs_[coeff_type];594const int first = (coeff_type == 0) ? 1 : 0;595Node nodes[16][NUM_NODES];596ScoreState score_states[2][NUM_NODES];597ScoreState* ss_cur = &SCORE_STATE(0, MIN_DELTA);598ScoreState* ss_prev = &SCORE_STATE(1, MIN_DELTA);599int best_path[3] = {-1, -1, -1}; // store best-last/best-level/best-previous600score_t best_score;601int n, m, p, last;602603{604score_t cost;605const int thresh = mtx->q_[1] * mtx->q_[1] / 4;606const int last_proba = probas[VP8EncBands[first]][ctx0][0];607608// compute the position of the last interesting coefficient609last = first - 1;610for (n = 15; n >= first; --n) {611const int j = kZigzag[n];612const int err = in[j] * in[j];613if (err > thresh) {614last = n;615break;616}617}618// we don't need to go inspect up to n = 16 coeffs. We can just go up619// to last + 1 (inclusive) without losing much.620if (last < 15) ++last;621622// compute 'skip' score. This is the max score one can do.623cost = VP8BitCost(0, last_proba);624best_score = RDScoreTrellis(lambda, cost, 0);625626// initialize source node.627for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {628const score_t rate = (ctx0 == 0) ? VP8BitCost(1, last_proba) : 0;629ss_cur[m].score = RDScoreTrellis(lambda, rate, 0);630ss_cur[m].costs = costs[first][ctx0];631}632}633634// traverse trellis.635for (n = first; n <= last; ++n) {636const int j = kZigzag[n];637const uint32_t Q = mtx->q_[j];638const uint32_t iQ = mtx->iq_[j];639const uint32_t B = BIAS(0x00); // neutral bias640// note: it's important to take sign of the _original_ coeff,641// so we don't have to consider level < 0 afterward.642const int sign = (in[j] < 0);643const uint32_t coeff0 = (sign ? -in[j] : in[j]) + mtx->sharpen_[j];644int level0 = QUANTDIV(coeff0, iQ, B);645int thresh_level = QUANTDIV(coeff0, iQ, BIAS(0x80));646if (thresh_level > MAX_LEVEL) thresh_level = MAX_LEVEL;647if (level0 > MAX_LEVEL) level0 = MAX_LEVEL;648649{ // Swap current and previous score states650ScoreState* const tmp = ss_cur;651ss_cur = ss_prev;652ss_prev = tmp;653}654655// test all alternate level values around level0.656for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {657Node* const cur = &NODE(n, m);658int level = level0 + m;659const int ctx = (level > 2) ? 2 : level;660const int band = VP8EncBands[n + 1];661score_t base_score;662score_t best_cur_score = MAX_COST;663int best_prev = 0; // default, in case664665ss_cur[m].score = MAX_COST;666ss_cur[m].costs = costs[n + 1][ctx];667if (level < 0 || level > thresh_level) {668// Node is dead.669continue;670}671672{673// Compute delta_error = how much coding this level will674// subtract to max_error as distortion.675// Here, distortion = sum of (|coeff_i| - level_i * Q_i)^2676const int new_error = coeff0 - level * Q;677const int delta_error =678kWeightTrellis[j] * (new_error * new_error - coeff0 * coeff0);679base_score = RDScoreTrellis(lambda, 0, delta_error);680}681682// Inspect all possible non-dead predecessors. Retain only the best one.683for (p = -MIN_DELTA; p <= MAX_DELTA; ++p) {684// Dead nodes (with ss_prev[p].score >= MAX_COST) are automatically685// eliminated since their score can't be better than the current best.686const score_t cost = VP8LevelCost(ss_prev[p].costs, level);687// Examine node assuming it's a non-terminal one.688const score_t score =689base_score + ss_prev[p].score + RDScoreTrellis(lambda, cost, 0);690if (score < best_cur_score) {691best_cur_score = score;692best_prev = p;693}694}695// Store best finding in current node.696cur->sign = sign;697cur->level = level;698cur->prev = best_prev;699ss_cur[m].score = best_cur_score;700701// Now, record best terminal node (and thus best entry in the graph).702if (level != 0) {703const score_t last_pos_cost =704(n < 15) ? VP8BitCost(0, probas[band][ctx][0]) : 0;705const score_t last_pos_score = RDScoreTrellis(lambda, last_pos_cost, 0);706const score_t score = best_cur_score + last_pos_score;707if (score < best_score) {708best_score = score;709best_path[0] = n; // best eob position710best_path[1] = m; // best node index711best_path[2] = best_prev; // best predecessor712}713}714}715}716717// Fresh start718memset(in + first, 0, (16 - first) * sizeof(*in));719memset(out + first, 0, (16 - first) * sizeof(*out));720if (best_path[0] == -1) {721return 0; // skip!722}723724{725// Unwind the best path.726// Note: best-prev on terminal node is not necessarily equal to the727// best_prev for non-terminal. So we patch best_path[2] in.728int nz = 0;729int best_node = best_path[1];730n = best_path[0];731NODE(n, best_node).prev = best_path[2]; // force best-prev for terminal732733for (; n >= first; --n) {734const Node* const node = &NODE(n, best_node);735const int j = kZigzag[n];736out[n] = node->sign ? -node->level : node->level;737nz |= node->level;738in[j] = out[n] * mtx->q_[j];739best_node = node->prev;740}741return (nz != 0);742}743}744745#undef NODE746747//------------------------------------------------------------------------------748// Performs: difference, transform, quantize, back-transform, add749// all at once. Output is the reconstructed block in *yuv_out, and the750// quantized levels in *levels.751752static int ReconstructIntra16(VP8EncIterator* const it,753VP8ModeScore* const rd,754uint8_t* const yuv_out,755int mode) {756const VP8Encoder* const enc = it->enc_;757const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];758const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC;759const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];760int nz = 0;761int n;762int16_t tmp[16][16], dc_tmp[16];763764for (n = 0; n < 16; n += 2) {765VP8FTransform2(src + VP8Scan[n], ref + VP8Scan[n], tmp[n]);766}767VP8FTransformWHT(tmp[0], dc_tmp);768nz |= VP8EncQuantizeBlockWHT(dc_tmp, rd->y_dc_levels, &dqm->y2_) << 24;769770if (DO_TRELLIS_I16 && it->do_trellis_) {771int x, y;772VP8IteratorNzToBytes(it);773for (y = 0, n = 0; y < 4; ++y) {774for (x = 0; x < 4; ++x, ++n) {775const int ctx = it->top_nz_[x] + it->left_nz_[y];776const int non_zero =777TrellisQuantizeBlock(enc, tmp[n], rd->y_ac_levels[n], ctx, 0,778&dqm->y1_, dqm->lambda_trellis_i16_);779it->top_nz_[x] = it->left_nz_[y] = non_zero;780rd->y_ac_levels[n][0] = 0;781nz |= non_zero << n;782}783}784} else {785for (n = 0; n < 16; n += 2) {786// Zero-out the first coeff, so that: a) nz is correct below, and787// b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified.788tmp[n][0] = tmp[n + 1][0] = 0;789nz |= VP8EncQuantize2Blocks(tmp[n], rd->y_ac_levels[n], &dqm->y1_) << n;790assert(rd->y_ac_levels[n + 0][0] == 0);791assert(rd->y_ac_levels[n + 1][0] == 0);792}793}794795// Transform back796VP8TransformWHT(dc_tmp, tmp[0]);797for (n = 0; n < 16; n += 2) {798VP8ITransform(ref + VP8Scan[n], tmp[n], yuv_out + VP8Scan[n], 1);799}800801return nz;802}803804static int ReconstructIntra4(VP8EncIterator* const it,805int16_t levels[16],806const uint8_t* const src,807uint8_t* const yuv_out,808int mode) {809const VP8Encoder* const enc = it->enc_;810const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];811const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];812int nz = 0;813int16_t tmp[16];814815VP8FTransform(src, ref, tmp);816if (DO_TRELLIS_I4 && it->do_trellis_) {817const int x = it->i4_ & 3, y = it->i4_ >> 2;818const int ctx = it->top_nz_[x] + it->left_nz_[y];819nz = TrellisQuantizeBlock(enc, tmp, levels, ctx, 3, &dqm->y1_,820dqm->lambda_trellis_i4_);821} else {822nz = VP8EncQuantizeBlock(tmp, levels, &dqm->y1_);823}824VP8ITransform(ref, tmp, yuv_out, 0);825return nz;826}827828//------------------------------------------------------------------------------829// DC-error diffusion830831// Diffusion weights. We under-correct a bit (15/16th of the error is actually832// diffused) to avoid 'rainbow' chessboard pattern of blocks at q~=0.833#define C1 7 // fraction of error sent to the 4x4 block below834#define C2 8 // fraction of error sent to the 4x4 block on the right835#define DSHIFT 4836#define DSCALE 1 // storage descaling, needed to make the error fit int8_t837838// Quantize as usual, but also compute and return the quantization error.839// Error is already divided by DSHIFT.840static int QuantizeSingle(int16_t* const v, const VP8Matrix* const mtx) {841int V = *v;842const int sign = (V < 0);843if (sign) V = -V;844if (V > (int)mtx->zthresh_[0]) {845const int qV = QUANTDIV(V, mtx->iq_[0], mtx->bias_[0]) * mtx->q_[0];846const int err = (V - qV);847*v = sign ? -qV : qV;848return (sign ? -err : err) >> DSCALE;849}850*v = 0;851return (sign ? -V : V) >> DSCALE;852}853854static void CorrectDCValues(const VP8EncIterator* const it,855const VP8Matrix* const mtx,856int16_t tmp[][16], VP8ModeScore* const rd) {857// | top[0] | top[1]858// --------+--------+---------859// left[0] | tmp[0] tmp[1] <-> err0 err1860// left[1] | tmp[2] tmp[3] err2 err3861//862// Final errors {err1,err2,err3} are preserved and later restored863// as top[]/left[] on the next block.864int ch;865for (ch = 0; ch <= 1; ++ch) {866const int8_t* const top = it->top_derr_[it->x_][ch];867const int8_t* const left = it->left_derr_[ch];868int16_t (* const c)[16] = &tmp[ch * 4];869int err0, err1, err2, err3;870c[0][0] += (C1 * top[0] + C2 * left[0]) >> (DSHIFT - DSCALE);871err0 = QuantizeSingle(&c[0][0], mtx);872c[1][0] += (C1 * top[1] + C2 * err0) >> (DSHIFT - DSCALE);873err1 = QuantizeSingle(&c[1][0], mtx);874c[2][0] += (C1 * err0 + C2 * left[1]) >> (DSHIFT - DSCALE);875err2 = QuantizeSingle(&c[2][0], mtx);876c[3][0] += (C1 * err1 + C2 * err2) >> (DSHIFT - DSCALE);877err3 = QuantizeSingle(&c[3][0], mtx);878// error 'err' is bounded by mtx->q_[0] which is 132 at max. Hence879// err >> DSCALE will fit in an int8_t type if DSCALE>=1.880assert(abs(err1) <= 127 && abs(err2) <= 127 && abs(err3) <= 127);881rd->derr[ch][0] = (int8_t)err1;882rd->derr[ch][1] = (int8_t)err2;883rd->derr[ch][2] = (int8_t)err3;884}885}886887static void StoreDiffusionErrors(VP8EncIterator* const it,888const VP8ModeScore* const rd) {889int ch;890for (ch = 0; ch <= 1; ++ch) {891int8_t* const top = it->top_derr_[it->x_][ch];892int8_t* const left = it->left_derr_[ch];893left[0] = rd->derr[ch][0]; // restore err1894left[1] = 3 * rd->derr[ch][2] >> 2; // ... 3/4th of err3895top[0] = rd->derr[ch][1]; // ... err2896top[1] = rd->derr[ch][2] - left[1]; // ... 1/4th of err3.897}898}899900#undef C1901#undef C2902#undef DSHIFT903#undef DSCALE904905//------------------------------------------------------------------------------906907static int ReconstructUV(VP8EncIterator* const it, VP8ModeScore* const rd,908uint8_t* const yuv_out, int mode) {909const VP8Encoder* const enc = it->enc_;910const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode];911const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;912const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];913int nz = 0;914int n;915int16_t tmp[8][16];916917for (n = 0; n < 8; n += 2) {918VP8FTransform2(src + VP8ScanUV[n], ref + VP8ScanUV[n], tmp[n]);919}920if (it->top_derr_ != NULL) CorrectDCValues(it, &dqm->uv_, tmp, rd);921922if (DO_TRELLIS_UV && it->do_trellis_) {923int ch, x, y;924for (ch = 0, n = 0; ch <= 2; ch += 2) {925for (y = 0; y < 2; ++y) {926for (x = 0; x < 2; ++x, ++n) {927const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];928const int non_zero =929TrellisQuantizeBlock(enc, tmp[n], rd->uv_levels[n], ctx, 2,930&dqm->uv_, dqm->lambda_trellis_uv_);931it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = non_zero;932nz |= non_zero << n;933}934}935}936} else {937for (n = 0; n < 8; n += 2) {938nz |= VP8EncQuantize2Blocks(tmp[n], rd->uv_levels[n], &dqm->uv_) << n;939}940}941942for (n = 0; n < 8; n += 2) {943VP8ITransform(ref + VP8ScanUV[n], tmp[n], yuv_out + VP8ScanUV[n], 1);944}945return (nz << 16);946}947948//------------------------------------------------------------------------------949// RD-opt decision. Reconstruct each modes, evalue distortion and bit-cost.950// Pick the mode is lower RD-cost = Rate + lambda * Distortion.951952static void StoreMaxDelta(VP8SegmentInfo* const dqm, const int16_t DCs[16]) {953// We look at the first three AC coefficients to determine what is the average954// delta between each sub-4x4 block.955const int v0 = abs(DCs[1]);956const int v1 = abs(DCs[2]);957const int v2 = abs(DCs[4]);958int max_v = (v1 > v0) ? v1 : v0;959max_v = (v2 > max_v) ? v2 : max_v;960if (max_v > dqm->max_edge_) dqm->max_edge_ = max_v;961}962963static void SwapModeScore(VP8ModeScore** a, VP8ModeScore** b) {964VP8ModeScore* const tmp = *a;965*a = *b;966*b = tmp;967}968969static void SwapPtr(uint8_t** a, uint8_t** b) {970uint8_t* const tmp = *a;971*a = *b;972*b = tmp;973}974975static void SwapOut(VP8EncIterator* const it) {976SwapPtr(&it->yuv_out_, &it->yuv_out2_);977}978979static score_t IsFlat(const int16_t* levels, int num_blocks, score_t thresh) {980score_t score = 0;981while (num_blocks-- > 0) { // TODO(skal): refine positional scoring?982int i;983for (i = 1; i < 16; ++i) { // omit DC, we're only interested in AC984score += (levels[i] != 0);985if (score > thresh) return 0;986}987levels += 16;988}989return 1;990}991992static void PickBestIntra16(VP8EncIterator* const it, VP8ModeScore* rd) {993const int kNumBlocks = 16;994VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];995const int lambda = dqm->lambda_i16_;996const int tlambda = dqm->tlambda_;997const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC;998VP8ModeScore rd_tmp;999VP8ModeScore* rd_cur = &rd_tmp;1000VP8ModeScore* rd_best = rd;1001int mode;10021003rd->mode_i16 = -1;1004for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1005uint8_t* const tmp_dst = it->yuv_out2_ + Y_OFF_ENC; // scratch buffer1006rd_cur->mode_i16 = mode;10071008// Reconstruct1009rd_cur->nz = ReconstructIntra16(it, rd_cur, tmp_dst, mode);10101011// Measure RD-score1012rd_cur->D = VP8SSE16x16(src, tmp_dst);1013rd_cur->SD =1014tlambda ? MULT_8B(tlambda, VP8TDisto16x16(src, tmp_dst, kWeightY)) : 0;1015rd_cur->H = VP8FixedCostsI16[mode];1016rd_cur->R = VP8GetCostLuma16(it, rd_cur);1017if (mode > 0 &&1018IsFlat(rd_cur->y_ac_levels[0], kNumBlocks, FLATNESS_LIMIT_I16)) {1019// penalty to avoid flat area to be mispredicted by complex mode1020rd_cur->R += FLATNESS_PENALTY * kNumBlocks;1021}10221023// Since we always examine Intra16 first, we can overwrite *rd directly.1024SetRDScore(lambda, rd_cur);1025if (mode == 0 || rd_cur->score < rd_best->score) {1026SwapModeScore(&rd_cur, &rd_best);1027SwapOut(it);1028}1029}1030if (rd_best != rd) {1031memcpy(rd, rd_best, sizeof(*rd));1032}1033SetRDScore(dqm->lambda_mode_, rd); // finalize score for mode decision.1034VP8SetIntra16Mode(it, rd->mode_i16);10351036// we have a blocky macroblock (only DCs are non-zero) with fairly high1037// distortion, record max delta so we can later adjust the minimal filtering1038// strength needed to smooth these blocks out.1039if ((rd->nz & 0x100ffff) == 0x1000000 && rd->D > dqm->min_disto_) {1040StoreMaxDelta(dqm, rd->y_dc_levels);1041}1042}10431044//------------------------------------------------------------------------------10451046// return the cost array corresponding to the surrounding prediction modes.1047static const uint16_t* GetCostModeI4(VP8EncIterator* const it,1048const uint8_t modes[16]) {1049const int preds_w = it->enc_->preds_w_;1050const int x = (it->i4_ & 3), y = it->i4_ >> 2;1051const int left = (x == 0) ? it->preds_[y * preds_w - 1] : modes[it->i4_ - 1];1052const int top = (y == 0) ? it->preds_[-preds_w + x] : modes[it->i4_ - 4];1053return VP8FixedCostsI4[top][left];1054}10551056static int PickBestIntra4(VP8EncIterator* const it, VP8ModeScore* const rd) {1057const VP8Encoder* const enc = it->enc_;1058const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];1059const int lambda = dqm->lambda_i4_;1060const int tlambda = dqm->tlambda_;1061const uint8_t* const src0 = it->yuv_in_ + Y_OFF_ENC;1062uint8_t* const best_blocks = it->yuv_out2_ + Y_OFF_ENC;1063int total_header_bits = 0;1064VP8ModeScore rd_best;10651066if (enc->max_i4_header_bits_ == 0) {1067return 0;1068}10691070InitScore(&rd_best);1071rd_best.H = 211; // '211' is the value of VP8BitCost(0, 145)1072SetRDScore(dqm->lambda_mode_, &rd_best);1073VP8IteratorStartI4(it);1074do {1075const int kNumBlocks = 1;1076VP8ModeScore rd_i4;1077int mode;1078int best_mode = -1;1079const uint8_t* const src = src0 + VP8Scan[it->i4_];1080const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);1081uint8_t* best_block = best_blocks + VP8Scan[it->i4_];1082uint8_t* tmp_dst = it->yuv_p_ + I4TMP; // scratch buffer.10831084InitScore(&rd_i4);1085VP8MakeIntra4Preds(it);1086for (mode = 0; mode < NUM_BMODES; ++mode) {1087VP8ModeScore rd_tmp;1088int16_t tmp_levels[16];10891090// Reconstruct1091rd_tmp.nz =1092ReconstructIntra4(it, tmp_levels, src, tmp_dst, mode) << it->i4_;10931094// Compute RD-score1095rd_tmp.D = VP8SSE4x4(src, tmp_dst);1096rd_tmp.SD =1097tlambda ? MULT_8B(tlambda, VP8TDisto4x4(src, tmp_dst, kWeightY))1098: 0;1099rd_tmp.H = mode_costs[mode];11001101// Add flatness penalty1102if (mode > 0 && IsFlat(tmp_levels, kNumBlocks, FLATNESS_LIMIT_I4)) {1103rd_tmp.R = FLATNESS_PENALTY * kNumBlocks;1104} else {1105rd_tmp.R = 0;1106}11071108// early-out check1109SetRDScore(lambda, &rd_tmp);1110if (best_mode >= 0 && rd_tmp.score >= rd_i4.score) continue;11111112// finish computing score1113rd_tmp.R += VP8GetCostLuma4(it, tmp_levels);1114SetRDScore(lambda, &rd_tmp);11151116if (best_mode < 0 || rd_tmp.score < rd_i4.score) {1117CopyScore(&rd_i4, &rd_tmp);1118best_mode = mode;1119SwapPtr(&tmp_dst, &best_block);1120memcpy(rd_best.y_ac_levels[it->i4_], tmp_levels,1121sizeof(rd_best.y_ac_levels[it->i4_]));1122}1123}1124SetRDScore(dqm->lambda_mode_, &rd_i4);1125AddScore(&rd_best, &rd_i4);1126if (rd_best.score >= rd->score) {1127return 0;1128}1129total_header_bits += (int)rd_i4.H; // <- equal to mode_costs[best_mode];1130if (total_header_bits > enc->max_i4_header_bits_) {1131return 0;1132}1133// Copy selected samples if not in the right place already.1134if (best_block != best_blocks + VP8Scan[it->i4_]) {1135VP8Copy4x4(best_block, best_blocks + VP8Scan[it->i4_]);1136}1137rd->modes_i4[it->i4_] = best_mode;1138it->top_nz_[it->i4_ & 3] = it->left_nz_[it->i4_ >> 2] = (rd_i4.nz ? 1 : 0);1139} while (VP8IteratorRotateI4(it, best_blocks));11401141// finalize state1142CopyScore(rd, &rd_best);1143VP8SetIntra4Mode(it, rd->modes_i4);1144SwapOut(it);1145memcpy(rd->y_ac_levels, rd_best.y_ac_levels, sizeof(rd->y_ac_levels));1146return 1; // select intra4x4 over intra16x161147}11481149//------------------------------------------------------------------------------11501151static void PickBestUV(VP8EncIterator* const it, VP8ModeScore* const rd) {1152const int kNumBlocks = 8;1153const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];1154const int lambda = dqm->lambda_uv_;1155const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;1156uint8_t* tmp_dst = it->yuv_out2_ + U_OFF_ENC; // scratch buffer1157uint8_t* dst0 = it->yuv_out_ + U_OFF_ENC;1158uint8_t* dst = dst0;1159VP8ModeScore rd_best;1160int mode;11611162rd->mode_uv = -1;1163InitScore(&rd_best);1164for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1165VP8ModeScore rd_uv;11661167// Reconstruct1168rd_uv.nz = ReconstructUV(it, &rd_uv, tmp_dst, mode);11691170// Compute RD-score1171rd_uv.D = VP8SSE16x8(src, tmp_dst);1172rd_uv.SD = 0; // not calling TDisto here: it tends to flatten areas.1173rd_uv.H = VP8FixedCostsUV[mode];1174rd_uv.R = VP8GetCostUV(it, &rd_uv);1175if (mode > 0 && IsFlat(rd_uv.uv_levels[0], kNumBlocks, FLATNESS_LIMIT_UV)) {1176rd_uv.R += FLATNESS_PENALTY * kNumBlocks;1177}11781179SetRDScore(lambda, &rd_uv);1180if (mode == 0 || rd_uv.score < rd_best.score) {1181CopyScore(&rd_best, &rd_uv);1182rd->mode_uv = mode;1183memcpy(rd->uv_levels, rd_uv.uv_levels, sizeof(rd->uv_levels));1184if (it->top_derr_ != NULL) {1185memcpy(rd->derr, rd_uv.derr, sizeof(rd_uv.derr));1186}1187SwapPtr(&dst, &tmp_dst);1188}1189}1190VP8SetIntraUVMode(it, rd->mode_uv);1191AddScore(rd, &rd_best);1192if (dst != dst0) { // copy 16x8 block if needed1193VP8Copy16x8(dst, dst0);1194}1195if (it->top_derr_ != NULL) { // store diffusion errors for next block1196StoreDiffusionErrors(it, rd);1197}1198}11991200//------------------------------------------------------------------------------1201// Final reconstruction and quantization.12021203static void SimpleQuantize(VP8EncIterator* const it, VP8ModeScore* const rd) {1204const VP8Encoder* const enc = it->enc_;1205const int is_i16 = (it->mb_->type_ == 1);1206int nz = 0;12071208if (is_i16) {1209nz = ReconstructIntra16(it, rd, it->yuv_out_ + Y_OFF_ENC, it->preds_[0]);1210} else {1211VP8IteratorStartI4(it);1212do {1213const int mode =1214it->preds_[(it->i4_ & 3) + (it->i4_ >> 2) * enc->preds_w_];1215const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_];1216uint8_t* const dst = it->yuv_out_ + Y_OFF_ENC + VP8Scan[it->i4_];1217VP8MakeIntra4Preds(it);1218nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4_],1219src, dst, mode) << it->i4_;1220} while (VP8IteratorRotateI4(it, it->yuv_out_ + Y_OFF_ENC));1221}12221223nz |= ReconstructUV(it, rd, it->yuv_out_ + U_OFF_ENC, it->mb_->uv_mode_);1224rd->nz = nz;1225}12261227// Refine intra16/intra4 sub-modes based on distortion only (not rate).1228static void RefineUsingDistortion(VP8EncIterator* const it,1229int try_both_modes, int refine_uv_mode,1230VP8ModeScore* const rd) {1231score_t best_score = MAX_COST;1232int nz = 0;1233int mode;1234int is_i16 = try_both_modes || (it->mb_->type_ == 1);12351236const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];1237// Some empiric constants, of approximate order of magnitude.1238const int lambda_d_i16 = 106;1239const int lambda_d_i4 = 11;1240const int lambda_d_uv = 120;1241score_t score_i4 = dqm->i4_penalty_;1242score_t i4_bit_sum = 0;1243const score_t bit_limit = try_both_modes ? it->enc_->mb_header_limit_1244: MAX_COST; // no early-out allowed12451246if (is_i16) { // First, evaluate Intra16 distortion1247int best_mode = -1;1248const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC;1249for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1250const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];1251const score_t score = (score_t)VP8SSE16x16(src, ref) * RD_DISTO_MULT1252+ VP8FixedCostsI16[mode] * lambda_d_i16;1253if (mode > 0 && VP8FixedCostsI16[mode] > bit_limit) {1254continue;1255}1256if (score < best_score) {1257best_mode = mode;1258best_score = score;1259}1260}1261VP8SetIntra16Mode(it, best_mode);1262// we'll reconstruct later, if i16 mode actually gets selected1263}12641265// Next, evaluate Intra41266if (try_both_modes || !is_i16) {1267// We don't evaluate the rate here, but just account for it through a1268// constant penalty (i4 mode usually needs more bits compared to i16).1269is_i16 = 0;1270VP8IteratorStartI4(it);1271do {1272int best_i4_mode = -1;1273score_t best_i4_score = MAX_COST;1274const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_];1275const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);12761277VP8MakeIntra4Preds(it);1278for (mode = 0; mode < NUM_BMODES; ++mode) {1279const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];1280const score_t score = VP8SSE4x4(src, ref) * RD_DISTO_MULT1281+ mode_costs[mode] * lambda_d_i4;1282if (score < best_i4_score) {1283best_i4_mode = mode;1284best_i4_score = score;1285}1286}1287i4_bit_sum += mode_costs[best_i4_mode];1288rd->modes_i4[it->i4_] = best_i4_mode;1289score_i4 += best_i4_score;1290if (score_i4 >= best_score || i4_bit_sum > bit_limit) {1291// Intra4 won't be better than Intra16. Bail out and pick Intra16.1292is_i16 = 1;1293break;1294} else { // reconstruct partial block inside yuv_out2_ buffer1295uint8_t* const tmp_dst = it->yuv_out2_ + Y_OFF_ENC + VP8Scan[it->i4_];1296nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4_],1297src, tmp_dst, best_i4_mode) << it->i4_;1298}1299} while (VP8IteratorRotateI4(it, it->yuv_out2_ + Y_OFF_ENC));1300}13011302// Final reconstruction, depending on which mode is selected.1303if (!is_i16) {1304VP8SetIntra4Mode(it, rd->modes_i4);1305SwapOut(it);1306best_score = score_i4;1307} else {1308nz = ReconstructIntra16(it, rd, it->yuv_out_ + Y_OFF_ENC, it->preds_[0]);1309}13101311// ... and UV!1312if (refine_uv_mode) {1313int best_mode = -1;1314score_t best_uv_score = MAX_COST;1315const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;1316for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1317const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode];1318const score_t score = VP8SSE16x8(src, ref) * RD_DISTO_MULT1319+ VP8FixedCostsUV[mode] * lambda_d_uv;1320if (score < best_uv_score) {1321best_mode = mode;1322best_uv_score = score;1323}1324}1325VP8SetIntraUVMode(it, best_mode);1326}1327nz |= ReconstructUV(it, rd, it->yuv_out_ + U_OFF_ENC, it->mb_->uv_mode_);13281329rd->nz = nz;1330rd->score = best_score;1331}13321333//------------------------------------------------------------------------------1334// Entry point13351336int VP8Decimate(VP8EncIterator* const it, VP8ModeScore* const rd,1337VP8RDLevel rd_opt) {1338int is_skipped;1339const int method = it->enc_->method_;13401341InitScore(rd);13421343// We can perform predictions for Luma16x16 and Chroma8x8 already.1344// Luma4x4 predictions needs to be done as-we-go.1345VP8MakeLuma16Preds(it);1346VP8MakeChroma8Preds(it);13471348if (rd_opt > RD_OPT_NONE) {1349it->do_trellis_ = (rd_opt >= RD_OPT_TRELLIS_ALL);1350PickBestIntra16(it, rd);1351if (method >= 2) {1352PickBestIntra4(it, rd);1353}1354PickBestUV(it, rd);1355if (rd_opt == RD_OPT_TRELLIS) { // finish off with trellis-optim now1356it->do_trellis_ = 1;1357SimpleQuantize(it, rd);1358}1359} else {1360// At this point we have heuristically decided intra16 / intra4.1361// For method >= 2, pick the best intra4/intra16 based on SSE (~tad slower).1362// For method <= 1, we don't re-examine the decision but just go ahead with1363// quantization/reconstruction.1364RefineUsingDistortion(it, (method >= 2), (method >= 1), rd);1365}1366is_skipped = (rd->nz == 0);1367VP8SetSkip(it, is_skipped);1368return is_skipped;1369}137013711372