Path: blob/master/thirdparty/libwebp/src/enc/quant_enc.c
9913 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/dsp/quant.h"18#include "src/enc/vp8i_enc.h"19#include "src/enc/cost_enc.h"2021#define DO_TRELLIS_I4 122#define DO_TRELLIS_I16 1 // not a huge gain, but ok at low bitrate.23#define DO_TRELLIS_UV 0 // disable trellis for UV. Risky. Not worth.24#define USE_TDISTO 12526#define MID_ALPHA 64 // neutral value for susceptibility27#define MIN_ALPHA 30 // lowest usable value for susceptibility28#define MAX_ALPHA 100 // higher meaningful value for susceptibility2930#define SNS_TO_DQ 0.9 // Scaling constant between the sns value and the QP31// power-law modulation. Must be strictly less than 1.3233// number of non-zero coeffs below which we consider the block very flat34// (and apply a penalty to complex predictions)35#define FLATNESS_LIMIT_I16 0 // I16 mode (special case)36#define FLATNESS_LIMIT_I4 3 // I4 mode37#define FLATNESS_LIMIT_UV 2 // UV mode38#define FLATNESS_PENALTY 140 // roughly ~1bit per block3940#define MULT_8B(a, b) (((a) * (b) + 128) >> 8)4142#define RD_DISTO_MULT 256 // distortion multiplier (equivalent of lambda)4344// #define DEBUG_BLOCK4546//------------------------------------------------------------------------------4748#if defined(DEBUG_BLOCK)4950#include <stdio.h>51#include <stdlib.h>5253static void PrintBlockInfo(const VP8EncIterator* const it,54const VP8ModeScore* const rd) {55int i, j;56const int is_i16 = (it->mb_->type_ == 1);57const uint8_t* const y_in = it->yuv_in_ + Y_OFF_ENC;58const uint8_t* const y_out = it->yuv_out_ + Y_OFF_ENC;59const uint8_t* const uv_in = it->yuv_in_ + U_OFF_ENC;60const uint8_t* const uv_out = it->yuv_out_ + U_OFF_ENC;61printf("SOURCE / OUTPUT / ABS DELTA\n");62for (j = 0; j < 16; ++j) {63for (i = 0; i < 16; ++i) printf("%3d ", y_in[i + j * BPS]);64printf(" ");65for (i = 0; i < 16; ++i) printf("%3d ", y_out[i + j * BPS]);66printf(" ");67for (i = 0; i < 16; ++i) {68printf("%1d ", abs(y_in[i + j * BPS] - y_out[i + j * BPS]));69}70printf("\n");71}72printf("\n"); // newline before the U/V block73for (j = 0; j < 8; ++j) {74for (i = 0; i < 8; ++i) printf("%3d ", uv_in[i + j * BPS]);75printf(" ");76for (i = 8; i < 16; ++i) printf("%3d ", uv_in[i + j * BPS]);77printf(" ");78for (i = 0; i < 8; ++i) printf("%3d ", uv_out[i + j * BPS]);79printf(" ");80for (i = 8; i < 16; ++i) printf("%3d ", uv_out[i + j * BPS]);81printf(" ");82for (i = 0; i < 8; ++i) {83printf("%1d ", abs(uv_out[i + j * BPS] - uv_in[i + j * BPS]));84}85printf(" ");86for (i = 8; i < 16; ++i) {87printf("%1d ", abs(uv_out[i + j * BPS] - uv_in[i + j * BPS]));88}89printf("\n");90}91printf("\nD:%d SD:%d R:%d H:%d nz:0x%x score:%d\n",92(int)rd->D, (int)rd->SD, (int)rd->R, (int)rd->H, (int)rd->nz,93(int)rd->score);94if (is_i16) {95printf("Mode: %d\n", rd->mode_i16);96printf("y_dc_levels:");97for (i = 0; i < 16; ++i) printf("%3d ", rd->y_dc_levels[i]);98printf("\n");99} else {100printf("Modes[16]: ");101for (i = 0; i < 16; ++i) printf("%d ", rd->modes_i4[i]);102printf("\n");103}104printf("y_ac_levels:\n");105for (j = 0; j < 16; ++j) {106for (i = is_i16 ? 1 : 0; i < 16; ++i) {107printf("%4d ", rd->y_ac_levels[j][i]);108}109printf("\n");110}111printf("\n");112printf("uv_levels (mode=%d):\n", rd->mode_uv);113for (j = 0; j < 8; ++j) {114for (i = 0; i < 16; ++i) {115printf("%4d ", rd->uv_levels[j][i]);116}117printf("\n");118}119}120121#endif // DEBUG_BLOCK122123//------------------------------------------------------------------------------124125static WEBP_INLINE int clip(int v, int m, int M) {126return v < m ? m : v > M ? M : v;127}128129static const uint8_t kZigzag[16] = {1300, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15131};132133static const uint8_t kDcTable[128] = {1344, 5, 6, 7, 8, 9, 10, 10,13511, 12, 13, 14, 15, 16, 17, 17,13618, 19, 20, 20, 21, 21, 22, 22,13723, 23, 24, 25, 25, 26, 27, 28,13829, 30, 31, 32, 33, 34, 35, 36,13937, 37, 38, 39, 40, 41, 42, 43,14044, 45, 46, 46, 47, 48, 49, 50,14151, 52, 53, 54, 55, 56, 57, 58,14259, 60, 61, 62, 63, 64, 65, 66,14367, 68, 69, 70, 71, 72, 73, 74,14475, 76, 76, 77, 78, 79, 80, 81,14582, 83, 84, 85, 86, 87, 88, 89,14691, 93, 95, 96, 98, 100, 101, 102,147104, 106, 108, 110, 112, 114, 116, 118,148122, 124, 126, 128, 130, 132, 134, 136,149138, 140, 143, 145, 148, 151, 154, 157150};151152static const uint16_t kAcTable[128] = {1534, 5, 6, 7, 8, 9, 10, 11,15412, 13, 14, 15, 16, 17, 18, 19,15520, 21, 22, 23, 24, 25, 26, 27,15628, 29, 30, 31, 32, 33, 34, 35,15736, 37, 38, 39, 40, 41, 42, 43,15844, 45, 46, 47, 48, 49, 50, 51,15952, 53, 54, 55, 56, 57, 58, 60,16062, 64, 66, 68, 70, 72, 74, 76,16178, 80, 82, 84, 86, 88, 90, 92,16294, 96, 98, 100, 102, 104, 106, 108,163110, 112, 114, 116, 119, 122, 125, 128,164131, 134, 137, 140, 143, 146, 149, 152,165155, 158, 161, 164, 167, 170, 173, 177,166181, 185, 189, 193, 197, 201, 205, 209,167213, 217, 221, 225, 229, 234, 239, 245,168249, 254, 259, 264, 269, 274, 279, 284169};170171static const uint16_t kAcTable2[128] = {1728, 8, 9, 10, 12, 13, 15, 17,17318, 20, 21, 23, 24, 26, 27, 29,17431, 32, 34, 35, 37, 38, 40, 41,17543, 44, 46, 48, 49, 51, 52, 54,17655, 57, 58, 60, 62, 63, 65, 66,17768, 69, 71, 72, 74, 75, 77, 79,17880, 82, 83, 85, 86, 88, 89, 93,17996, 99, 102, 105, 108, 111, 114, 117,180120, 124, 127, 130, 133, 136, 139, 142,181145, 148, 151, 155, 158, 161, 164, 167,182170, 173, 176, 179, 184, 189, 193, 198,183203, 207, 212, 217, 221, 226, 230, 235,184240, 244, 249, 254, 258, 263, 268, 274,185280, 286, 292, 299, 305, 311, 317, 323,186330, 336, 342, 348, 354, 362, 370, 379,187385, 393, 401, 409, 416, 424, 432, 440188};189190static const uint8_t kBiasMatrices[3][2] = { // [luma-ac,luma-dc,chroma][dc,ac]191{ 96, 110 }, { 96, 108 }, { 110, 115 }192};193194// Sharpening by (slightly) raising the hi-frequency coeffs.195// Hack-ish but helpful for mid-bitrate range. Use with care.196#define SHARPEN_BITS 11 // number of descaling bits for sharpening bias197static const uint8_t kFreqSharpening[16] = {1980, 30, 60, 90,19930, 60, 90, 90,20060, 90, 90, 90,20190, 90, 90, 90202};203204//------------------------------------------------------------------------------205// Initialize quantization parameters in VP8Matrix206207// Returns the average quantizer208static int ExpandMatrix(VP8Matrix* const m, int type) {209int i, sum;210for (i = 0; i < 2; ++i) {211const int is_ac_coeff = (i > 0);212const int bias = kBiasMatrices[type][is_ac_coeff];213m->iq_[i] = (1 << QFIX) / m->q_[i];214m->bias_[i] = BIAS(bias);215// zthresh_ is the exact value such that QUANTDIV(coeff, iQ, B) is:216// * zero if coeff <= zthresh217// * non-zero if coeff > zthresh218m->zthresh_[i] = ((1 << QFIX) - 1 - m->bias_[i]) / m->iq_[i];219}220for (i = 2; i < 16; ++i) {221m->q_[i] = m->q_[1];222m->iq_[i] = m->iq_[1];223m->bias_[i] = m->bias_[1];224m->zthresh_[i] = m->zthresh_[1];225}226for (sum = 0, i = 0; i < 16; ++i) {227if (type == 0) { // we only use sharpening for AC luma coeffs228m->sharpen_[i] = (kFreqSharpening[i] * m->q_[i]) >> SHARPEN_BITS;229} else {230m->sharpen_[i] = 0;231}232sum += m->q_[i];233}234return (sum + 8) >> 4;235}236237static void CheckLambdaValue(int* const v) { if (*v < 1) *v = 1; }238239static void SetupMatrices(VP8Encoder* enc) {240int i;241const int tlambda_scale =242(enc->method_ >= 4) ? enc->config_->sns_strength243: 0;244const int num_segments = enc->segment_hdr_.num_segments_;245for (i = 0; i < num_segments; ++i) {246VP8SegmentInfo* const m = &enc->dqm_[i];247const int q = m->quant_;248int q_i4, q_i16, q_uv;249m->y1_.q_[0] = kDcTable[clip(q + enc->dq_y1_dc_, 0, 127)];250m->y1_.q_[1] = kAcTable[clip(q, 0, 127)];251252m->y2_.q_[0] = kDcTable[ clip(q + enc->dq_y2_dc_, 0, 127)] * 2;253m->y2_.q_[1] = kAcTable2[clip(q + enc->dq_y2_ac_, 0, 127)];254255m->uv_.q_[0] = kDcTable[clip(q + enc->dq_uv_dc_, 0, 117)];256m->uv_.q_[1] = kAcTable[clip(q + enc->dq_uv_ac_, 0, 127)];257258q_i4 = ExpandMatrix(&m->y1_, 0);259q_i16 = ExpandMatrix(&m->y2_, 1);260q_uv = ExpandMatrix(&m->uv_, 2);261262m->lambda_i4_ = (3 * q_i4 * q_i4) >> 7;263m->lambda_i16_ = (3 * q_i16 * q_i16);264m->lambda_uv_ = (3 * q_uv * q_uv) >> 6;265m->lambda_mode_ = (1 * q_i4 * q_i4) >> 7;266m->lambda_trellis_i4_ = (7 * q_i4 * q_i4) >> 3;267m->lambda_trellis_i16_ = (q_i16 * q_i16) >> 2;268m->lambda_trellis_uv_ = (q_uv * q_uv) << 1;269m->tlambda_ = (tlambda_scale * q_i4) >> 5;270271// none of these constants should be < 1272CheckLambdaValue(&m->lambda_i4_);273CheckLambdaValue(&m->lambda_i16_);274CheckLambdaValue(&m->lambda_uv_);275CheckLambdaValue(&m->lambda_mode_);276CheckLambdaValue(&m->lambda_trellis_i4_);277CheckLambdaValue(&m->lambda_trellis_i16_);278CheckLambdaValue(&m->lambda_trellis_uv_);279CheckLambdaValue(&m->tlambda_);280281m->min_disto_ = 20 * m->y1_.q_[0]; // quantization-aware min disto282m->max_edge_ = 0;283284m->i4_penalty_ = 1000 * q_i4 * q_i4;285}286}287288//------------------------------------------------------------------------------289// Initialize filtering parameters290291// Very small filter-strength values have close to no visual effect. So we can292// save a little decoding-CPU by turning filtering off for these.293#define FSTRENGTH_CUTOFF 2294295static void SetupFilterStrength(VP8Encoder* const enc) {296int i;297// level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering.298const int level0 = 5 * enc->config_->filter_strength;299for (i = 0; i < NUM_MB_SEGMENTS; ++i) {300VP8SegmentInfo* const m = &enc->dqm_[i];301// We focus on the quantization of AC coeffs.302const int qstep = kAcTable[clip(m->quant_, 0, 127)] >> 2;303const int base_strength =304VP8FilterStrengthFromDelta(enc->filter_hdr_.sharpness_, qstep);305// Segments with lower complexity ('beta') will be less filtered.306const int f = base_strength * level0 / (256 + m->beta_);307m->fstrength_ = (f < FSTRENGTH_CUTOFF) ? 0 : (f > 63) ? 63 : f;308}309// We record the initial strength (mainly for the case of 1-segment only).310enc->filter_hdr_.level_ = enc->dqm_[0].fstrength_;311enc->filter_hdr_.simple_ = (enc->config_->filter_type == 0);312enc->filter_hdr_.sharpness_ = enc->config_->filter_sharpness;313}314315//------------------------------------------------------------------------------316317// Note: if you change the values below, remember that the max range318// allowed by the syntax for DQ_UV is [-16,16].319#define MAX_DQ_UV (6)320#define MIN_DQ_UV (-4)321322// We want to emulate jpeg-like behaviour where the expected "good" quality323// is around q=75. Internally, our "good" middle is around c=50. So we324// map accordingly using linear piece-wise function325static double QualityToCompression(double c) {326const double linear_c = (c < 0.75) ? c * (2. / 3.) : 2. * c - 1.;327// The file size roughly scales as pow(quantizer, 3.). Actually, the328// exponent is somewhere between 2.8 and 3.2, but we're mostly interested329// in the mid-quant range. So we scale the compressibility inversely to330// this power-law: quant ~= compression ^ 1/3. This law holds well for331// low quant. Finer modeling for high-quant would make use of kAcTable[]332// more explicitly.333const double v = pow(linear_c, 1 / 3.);334return v;335}336337static double QualityToJPEGCompression(double c, double alpha) {338// We map the complexity 'alpha' and quality setting 'c' to a compression339// exponent empirically matched to the compression curve of libjpeg6b.340// On average, the WebP output size will be roughly similar to that of a341// JPEG file compressed with same quality factor.342const double amin = 0.30;343const double amax = 0.85;344const double exp_min = 0.4;345const double exp_max = 0.9;346const double slope = (exp_min - exp_max) / (amax - amin);347// Linearly interpolate 'expn' from exp_min to exp_max348// in the [amin, amax] range.349const double expn = (alpha > amax) ? exp_min350: (alpha < amin) ? exp_max351: exp_max + slope * (alpha - amin);352const double v = pow(c, expn);353return v;354}355356static int SegmentsAreEquivalent(const VP8SegmentInfo* const S1,357const VP8SegmentInfo* const S2) {358return (S1->quant_ == S2->quant_) && (S1->fstrength_ == S2->fstrength_);359}360361static void SimplifySegments(VP8Encoder* const enc) {362int map[NUM_MB_SEGMENTS] = { 0, 1, 2, 3 };363// 'num_segments_' is previously validated and <= NUM_MB_SEGMENTS, but an364// explicit check is needed to avoid a spurious warning about 'i' exceeding365// array bounds of 'dqm_' with some compilers (noticed with gcc-4.9).366const int num_segments = (enc->segment_hdr_.num_segments_ < NUM_MB_SEGMENTS)367? enc->segment_hdr_.num_segments_368: NUM_MB_SEGMENTS;369int num_final_segments = 1;370int s1, s2;371for (s1 = 1; s1 < num_segments; ++s1) { // find similar segments372const VP8SegmentInfo* const S1 = &enc->dqm_[s1];373int found = 0;374// check if we already have similar segment375for (s2 = 0; s2 < num_final_segments; ++s2) {376const VP8SegmentInfo* const S2 = &enc->dqm_[s2];377if (SegmentsAreEquivalent(S1, S2)) {378found = 1;379break;380}381}382map[s1] = s2;383if (!found) {384if (num_final_segments != s1) {385enc->dqm_[num_final_segments] = enc->dqm_[s1];386}387++num_final_segments;388}389}390if (num_final_segments < num_segments) { // Remap391int i = enc->mb_w_ * enc->mb_h_;392while (i-- > 0) enc->mb_info_[i].segment_ = map[enc->mb_info_[i].segment_];393enc->segment_hdr_.num_segments_ = num_final_segments;394// Replicate the trailing segment infos (it's mostly cosmetics)395for (i = num_final_segments; i < num_segments; ++i) {396enc->dqm_[i] = enc->dqm_[num_final_segments - 1];397}398}399}400401void VP8SetSegmentParams(VP8Encoder* const enc, float quality) {402int i;403int dq_uv_ac, dq_uv_dc;404const int num_segments = enc->segment_hdr_.num_segments_;405const double amp = SNS_TO_DQ * enc->config_->sns_strength / 100. / 128.;406const double Q = quality / 100.;407const double c_base = enc->config_->emulate_jpeg_size ?408QualityToJPEGCompression(Q, enc->alpha_ / 255.) :409QualityToCompression(Q);410for (i = 0; i < num_segments; ++i) {411// We modulate the base coefficient to accommodate for the quantization412// susceptibility and allow denser segments to be quantized more.413const double expn = 1. - amp * enc->dqm_[i].alpha_;414const double c = pow(c_base, expn);415const int q = (int)(127. * (1. - c));416assert(expn > 0.);417enc->dqm_[i].quant_ = clip(q, 0, 127);418}419420// purely indicative in the bitstream (except for the 1-segment case)421enc->base_quant_ = enc->dqm_[0].quant_;422423// fill-in values for the unused segments (required by the syntax)424for (i = num_segments; i < NUM_MB_SEGMENTS; ++i) {425enc->dqm_[i].quant_ = enc->base_quant_;426}427428// uv_alpha_ is normally spread around ~60. The useful range is429// typically ~30 (quite bad) to ~100 (ok to decimate UV more).430// We map it to the safe maximal range of MAX/MIN_DQ_UV for dq_uv.431dq_uv_ac = (enc->uv_alpha_ - MID_ALPHA) * (MAX_DQ_UV - MIN_DQ_UV)432/ (MAX_ALPHA - MIN_ALPHA);433// we rescale by the user-defined strength of adaptation434dq_uv_ac = dq_uv_ac * enc->config_->sns_strength / 100;435// and make it safe.436dq_uv_ac = clip(dq_uv_ac, MIN_DQ_UV, MAX_DQ_UV);437// We also boost the dc-uv-quant a little, based on sns-strength, since438// U/V channels are quite more reactive to high quants (flat DC-blocks439// tend to appear, and are unpleasant).440dq_uv_dc = -4 * enc->config_->sns_strength / 100;441dq_uv_dc = clip(dq_uv_dc, -15, 15); // 4bit-signed max allowed442443enc->dq_y1_dc_ = 0; // TODO(skal): dq-lum444enc->dq_y2_dc_ = 0;445enc->dq_y2_ac_ = 0;446enc->dq_uv_dc_ = dq_uv_dc;447enc->dq_uv_ac_ = dq_uv_ac;448449SetupFilterStrength(enc); // initialize segments' filtering, eventually450451if (num_segments > 1) SimplifySegments(enc);452453SetupMatrices(enc); // finalize quantization matrices454}455456//------------------------------------------------------------------------------457// Form the predictions in cache458459// Must be ordered using {DC_PRED, TM_PRED, V_PRED, H_PRED} as index460const uint16_t VP8I16ModeOffsets[4] = { I16DC16, I16TM16, I16VE16, I16HE16 };461const uint16_t VP8UVModeOffsets[4] = { C8DC8, C8TM8, C8VE8, C8HE8 };462463// Must be indexed using {B_DC_PRED -> B_HU_PRED} as index464static const uint16_t VP8I4ModeOffsets[NUM_BMODES] = {465I4DC4, I4TM4, I4VE4, I4HE4, I4RD4, I4VR4, I4LD4, I4VL4, I4HD4, I4HU4466};467468void VP8MakeLuma16Preds(const VP8EncIterator* const it) {469const uint8_t* const left = it->x_ ? it->y_left_ : NULL;470const uint8_t* const top = it->y_ ? it->y_top_ : NULL;471VP8EncPredLuma16(it->yuv_p_, left, top);472}473474void VP8MakeChroma8Preds(const VP8EncIterator* const it) {475const uint8_t* const left = it->x_ ? it->u_left_ : NULL;476const uint8_t* const top = it->y_ ? it->uv_top_ : NULL;477VP8EncPredChroma8(it->yuv_p_, left, top);478}479480// Form all the ten Intra4x4 predictions in the yuv_p_ cache481// for the 4x4 block it->i4_482static void MakeIntra4Preds(const VP8EncIterator* const it) {483VP8EncPredLuma4(it->yuv_p_, it->i4_top_);484}485486//------------------------------------------------------------------------------487// Quantize488489// Layout:490// +----+----+491// |YYYY|UUVV| 0492// |YYYY|UUVV| 4493// |YYYY|....| 8494// |YYYY|....| 12495// +----+----+496497const uint16_t VP8Scan[16] = { // Luma4980 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS,4990 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS,5000 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS,5010 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS,502};503504static const uint16_t VP8ScanUV[4 + 4] = {5050 + 0 * BPS, 4 + 0 * BPS, 0 + 4 * BPS, 4 + 4 * BPS, // U5068 + 0 * BPS, 12 + 0 * BPS, 8 + 4 * BPS, 12 + 4 * BPS // V507};508509//------------------------------------------------------------------------------510// Distortion measurement511512static const uint16_t kWeightY[16] = {51338, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2514};515516static const uint16_t kWeightTrellis[16] = {517#if USE_TDISTO == 051816, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16519#else52030, 27, 19, 11,52127, 24, 17, 10,52219, 17, 12, 8,52311, 10, 8, 6524#endif525};526527// Init/Copy the common fields in score.528static void InitScore(VP8ModeScore* const rd) {529rd->D = 0;530rd->SD = 0;531rd->R = 0;532rd->H = 0;533rd->nz = 0;534rd->score = MAX_COST;535}536537static void CopyScore(VP8ModeScore* WEBP_RESTRICT const dst,538const VP8ModeScore* WEBP_RESTRICT const src) {539dst->D = src->D;540dst->SD = src->SD;541dst->R = src->R;542dst->H = src->H;543dst->nz = src->nz; // note that nz is not accumulated, but just copied.544dst->score = src->score;545}546547static void AddScore(VP8ModeScore* WEBP_RESTRICT const dst,548const VP8ModeScore* WEBP_RESTRICT const src) {549dst->D += src->D;550dst->SD += src->SD;551dst->R += src->R;552dst->H += src->H;553dst->nz |= src->nz; // here, new nz bits are accumulated.554dst->score += src->score;555}556557//------------------------------------------------------------------------------558// Performs trellis-optimized quantization.559560// Prevents Visual Studio debugger from using this Node struct in place of the Godot Node class.561#define Node Node_libwebp_quant562563// Trellis node564typedef struct {565int8_t prev; // best previous node566int8_t sign; // sign of coeff_i567int16_t level; // level568} Node;569570// Score state571typedef struct {572score_t score; // partial RD score573const uint16_t* costs; // shortcut to cost tables574} ScoreState;575576// If a coefficient was quantized to a value Q (using a neutral bias),577// we test all alternate possibilities between [Q-MIN_DELTA, Q+MAX_DELTA]578// We don't test negative values though.579#define MIN_DELTA 0 // how much lower level to try580#define MAX_DELTA 1 // how much higher581#define NUM_NODES (MIN_DELTA + 1 + MAX_DELTA)582#define NODE(n, l) (nodes[(n)][(l) + MIN_DELTA])583#define SCORE_STATE(n, l) (score_states[n][(l) + MIN_DELTA])584585static WEBP_INLINE void SetRDScore(int lambda, VP8ModeScore* const rd) {586rd->score = (rd->R + rd->H) * lambda + RD_DISTO_MULT * (rd->D + rd->SD);587}588589static WEBP_INLINE score_t RDScoreTrellis(int lambda, score_t rate,590score_t distortion) {591return rate * lambda + RD_DISTO_MULT * distortion;592}593594// Coefficient type.595enum { TYPE_I16_AC = 0, TYPE_I16_DC = 1, TYPE_CHROMA_A = 2, TYPE_I4_AC = 3 };596597static int TrellisQuantizeBlock(const VP8Encoder* WEBP_RESTRICT const enc,598int16_t in[16], int16_t out[16],599int ctx0, int coeff_type,600const VP8Matrix* WEBP_RESTRICT const mtx,601int lambda) {602const ProbaArray* const probas = enc->proba_.coeffs_[coeff_type];603CostArrayPtr const costs =604(CostArrayPtr)enc->proba_.remapped_costs_[coeff_type];605const int first = (coeff_type == TYPE_I16_AC) ? 1 : 0;606Node nodes[16][NUM_NODES];607ScoreState score_states[2][NUM_NODES];608ScoreState* ss_cur = &SCORE_STATE(0, MIN_DELTA);609ScoreState* ss_prev = &SCORE_STATE(1, MIN_DELTA);610int best_path[3] = {-1, -1, -1}; // store best-last/best-level/best-previous611score_t best_score;612int n, m, p, last;613614{615score_t cost;616const int thresh = mtx->q_[1] * mtx->q_[1] / 4;617const int last_proba = probas[VP8EncBands[first]][ctx0][0];618619// compute the position of the last interesting coefficient620last = first - 1;621for (n = 15; n >= first; --n) {622const int j = kZigzag[n];623const int err = in[j] * in[j];624if (err > thresh) {625last = n;626break;627}628}629// we don't need to go inspect up to n = 16 coeffs. We can just go up630// to last + 1 (inclusive) without losing much.631if (last < 15) ++last;632633// compute 'skip' score. This is the max score one can do.634cost = VP8BitCost(0, last_proba);635best_score = RDScoreTrellis(lambda, cost, 0);636637// initialize source node.638for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {639const score_t rate = (ctx0 == 0) ? VP8BitCost(1, last_proba) : 0;640ss_cur[m].score = RDScoreTrellis(lambda, rate, 0);641ss_cur[m].costs = costs[first][ctx0];642}643}644645// traverse trellis.646for (n = first; n <= last; ++n) {647const int j = kZigzag[n];648const uint32_t Q = mtx->q_[j];649const uint32_t iQ = mtx->iq_[j];650const uint32_t B = BIAS(0x00); // neutral bias651// note: it's important to take sign of the _original_ coeff,652// so we don't have to consider level < 0 afterward.653const int sign = (in[j] < 0);654const uint32_t coeff0 = (sign ? -in[j] : in[j]) + mtx->sharpen_[j];655int level0 = QUANTDIV(coeff0, iQ, B);656int thresh_level = QUANTDIV(coeff0, iQ, BIAS(0x80));657if (thresh_level > MAX_LEVEL) thresh_level = MAX_LEVEL;658if (level0 > MAX_LEVEL) level0 = MAX_LEVEL;659660{ // Swap current and previous score states661ScoreState* const tmp = ss_cur;662ss_cur = ss_prev;663ss_prev = tmp;664}665666// test all alternate level values around level0.667for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {668Node* const cur = &NODE(n, m);669const int level = level0 + m;670const int ctx = (level > 2) ? 2 : level;671const int band = VP8EncBands[n + 1];672score_t base_score;673score_t best_cur_score;674int best_prev;675score_t cost, score;676677ss_cur[m].costs = costs[n + 1][ctx];678if (level < 0 || level > thresh_level) {679ss_cur[m].score = MAX_COST;680// Node is dead.681continue;682}683684{685// Compute delta_error = how much coding this level will686// subtract to max_error as distortion.687// Here, distortion = sum of (|coeff_i| - level_i * Q_i)^2688const int new_error = coeff0 - level * Q;689const int delta_error =690kWeightTrellis[j] * (new_error * new_error - coeff0 * coeff0);691base_score = RDScoreTrellis(lambda, 0, delta_error);692}693694// Inspect all possible non-dead predecessors. Retain only the best one.695// The base_score is added to all scores so it is only added for the final696// value after the loop.697cost = VP8LevelCost(ss_prev[-MIN_DELTA].costs, level);698best_cur_score =699ss_prev[-MIN_DELTA].score + RDScoreTrellis(lambda, cost, 0);700best_prev = -MIN_DELTA;701for (p = -MIN_DELTA + 1; p <= MAX_DELTA; ++p) {702// Dead nodes (with ss_prev[p].score >= MAX_COST) are automatically703// eliminated since their score can't be better than the current best.704cost = VP8LevelCost(ss_prev[p].costs, level);705// Examine node assuming it's a non-terminal one.706score = ss_prev[p].score + RDScoreTrellis(lambda, cost, 0);707if (score < best_cur_score) {708best_cur_score = score;709best_prev = p;710}711}712best_cur_score += base_score;713// Store best finding in current node.714cur->sign = sign;715cur->level = level;716cur->prev = best_prev;717ss_cur[m].score = best_cur_score;718719// Now, record best terminal node (and thus best entry in the graph).720if (level != 0 && best_cur_score < best_score) {721const score_t last_pos_cost =722(n < 15) ? VP8BitCost(0, probas[band][ctx][0]) : 0;723const score_t last_pos_score = RDScoreTrellis(lambda, last_pos_cost, 0);724score = best_cur_score + last_pos_score;725if (score < best_score) {726best_score = score;727best_path[0] = n; // best eob position728best_path[1] = m; // best node index729best_path[2] = best_prev; // best predecessor730}731}732}733}734735// Fresh start736// Beware! We must preserve in[0]/out[0] value for TYPE_I16_AC case.737if (coeff_type == TYPE_I16_AC) {738memset(in + 1, 0, 15 * sizeof(*in));739memset(out + 1, 0, 15 * sizeof(*out));740} else {741memset(in, 0, 16 * sizeof(*in));742memset(out, 0, 16 * sizeof(*out));743}744if (best_path[0] == -1) {745return 0; // skip!746}747748{749// Unwind the best path.750// Note: best-prev on terminal node is not necessarily equal to the751// best_prev for non-terminal. So we patch best_path[2] in.752int nz = 0;753int best_node = best_path[1];754n = best_path[0];755NODE(n, best_node).prev = best_path[2]; // force best-prev for terminal756757for (; n >= first; --n) {758const Node* const node = &NODE(n, best_node);759const int j = kZigzag[n];760out[n] = node->sign ? -node->level : node->level;761nz |= node->level;762in[j] = out[n] * mtx->q_[j];763best_node = node->prev;764}765return (nz != 0);766}767}768769#undef NODE770771//------------------------------------------------------------------------------772// Performs: difference, transform, quantize, back-transform, add773// all at once. Output is the reconstructed block in *yuv_out, and the774// quantized levels in *levels.775776static int ReconstructIntra16(VP8EncIterator* WEBP_RESTRICT const it,777VP8ModeScore* WEBP_RESTRICT const rd,778uint8_t* WEBP_RESTRICT const yuv_out,779int mode) {780const VP8Encoder* const enc = it->enc_;781const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];782const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC;783const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];784int nz = 0;785int n;786int16_t tmp[16][16], dc_tmp[16];787788for (n = 0; n < 16; n += 2) {789VP8FTransform2(src + VP8Scan[n], ref + VP8Scan[n], tmp[n]);790}791VP8FTransformWHT(tmp[0], dc_tmp);792nz |= VP8EncQuantizeBlockWHT(dc_tmp, rd->y_dc_levels, &dqm->y2_) << 24;793794if (DO_TRELLIS_I16 && it->do_trellis_) {795int x, y;796VP8IteratorNzToBytes(it);797for (y = 0, n = 0; y < 4; ++y) {798for (x = 0; x < 4; ++x, ++n) {799const int ctx = it->top_nz_[x] + it->left_nz_[y];800const int non_zero = TrellisQuantizeBlock(801enc, tmp[n], rd->y_ac_levels[n], ctx, TYPE_I16_AC, &dqm->y1_,802dqm->lambda_trellis_i16_);803it->top_nz_[x] = it->left_nz_[y] = non_zero;804rd->y_ac_levels[n][0] = 0;805nz |= non_zero << n;806}807}808} else {809for (n = 0; n < 16; n += 2) {810// Zero-out the first coeff, so that: a) nz is correct below, and811// b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified.812tmp[n][0] = tmp[n + 1][0] = 0;813nz |= VP8EncQuantize2Blocks(tmp[n], rd->y_ac_levels[n], &dqm->y1_) << n;814assert(rd->y_ac_levels[n + 0][0] == 0);815assert(rd->y_ac_levels[n + 1][0] == 0);816}817}818819// Transform back820VP8TransformWHT(dc_tmp, tmp[0]);821for (n = 0; n < 16; n += 2) {822VP8ITransform(ref + VP8Scan[n], tmp[n], yuv_out + VP8Scan[n], 1);823}824825return nz;826}827828static int ReconstructIntra4(VP8EncIterator* WEBP_RESTRICT const it,829int16_t levels[16],830const uint8_t* WEBP_RESTRICT const src,831uint8_t* WEBP_RESTRICT const yuv_out,832int mode) {833const VP8Encoder* const enc = it->enc_;834const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];835const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];836int nz = 0;837int16_t tmp[16];838839VP8FTransform(src, ref, tmp);840if (DO_TRELLIS_I4 && it->do_trellis_) {841const int x = it->i4_ & 3, y = it->i4_ >> 2;842const int ctx = it->top_nz_[x] + it->left_nz_[y];843nz = TrellisQuantizeBlock(enc, tmp, levels, ctx, TYPE_I4_AC, &dqm->y1_,844dqm->lambda_trellis_i4_);845} else {846nz = VP8EncQuantizeBlock(tmp, levels, &dqm->y1_);847}848VP8ITransform(ref, tmp, yuv_out, 0);849return nz;850}851852//------------------------------------------------------------------------------853// DC-error diffusion854855// Diffusion weights. We under-correct a bit (15/16th of the error is actually856// diffused) to avoid 'rainbow' chessboard pattern of blocks at q~=0.857#define C1 7 // fraction of error sent to the 4x4 block below858#define C2 8 // fraction of error sent to the 4x4 block on the right859#define DSHIFT 4860#define DSCALE 1 // storage descaling, needed to make the error fit int8_t861862// Quantize as usual, but also compute and return the quantization error.863// Error is already divided by DSHIFT.864static int QuantizeSingle(int16_t* WEBP_RESTRICT const v,865const VP8Matrix* WEBP_RESTRICT const mtx) {866int V = *v;867const int sign = (V < 0);868if (sign) V = -V;869if (V > (int)mtx->zthresh_[0]) {870const int qV = QUANTDIV(V, mtx->iq_[0], mtx->bias_[0]) * mtx->q_[0];871const int err = (V - qV);872*v = sign ? -qV : qV;873return (sign ? -err : err) >> DSCALE;874}875*v = 0;876return (sign ? -V : V) >> DSCALE;877}878879static void CorrectDCValues(const VP8EncIterator* WEBP_RESTRICT const it,880const VP8Matrix* WEBP_RESTRICT const mtx,881int16_t tmp[][16],882VP8ModeScore* WEBP_RESTRICT const rd) {883// | top[0] | top[1]884// --------+--------+---------885// left[0] | tmp[0] tmp[1] <-> err0 err1886// left[1] | tmp[2] tmp[3] err2 err3887//888// Final errors {err1,err2,err3} are preserved and later restored889// as top[]/left[] on the next block.890int ch;891for (ch = 0; ch <= 1; ++ch) {892const int8_t* const top = it->top_derr_[it->x_][ch];893const int8_t* const left = it->left_derr_[ch];894int16_t (* const c)[16] = &tmp[ch * 4];895int err0, err1, err2, err3;896c[0][0] += (C1 * top[0] + C2 * left[0]) >> (DSHIFT - DSCALE);897err0 = QuantizeSingle(&c[0][0], mtx);898c[1][0] += (C1 * top[1] + C2 * err0) >> (DSHIFT - DSCALE);899err1 = QuantizeSingle(&c[1][0], mtx);900c[2][0] += (C1 * err0 + C2 * left[1]) >> (DSHIFT - DSCALE);901err2 = QuantizeSingle(&c[2][0], mtx);902c[3][0] += (C1 * err1 + C2 * err2) >> (DSHIFT - DSCALE);903err3 = QuantizeSingle(&c[3][0], mtx);904// error 'err' is bounded by mtx->q_[0] which is 132 at max. Hence905// err >> DSCALE will fit in an int8_t type if DSCALE>=1.906assert(abs(err1) <= 127 && abs(err2) <= 127 && abs(err3) <= 127);907rd->derr[ch][0] = (int8_t)err1;908rd->derr[ch][1] = (int8_t)err2;909rd->derr[ch][2] = (int8_t)err3;910}911}912913static void StoreDiffusionErrors(VP8EncIterator* WEBP_RESTRICT const it,914const VP8ModeScore* WEBP_RESTRICT const rd) {915int ch;916for (ch = 0; ch <= 1; ++ch) {917int8_t* const top = it->top_derr_[it->x_][ch];918int8_t* const left = it->left_derr_[ch];919left[0] = rd->derr[ch][0]; // restore err1920left[1] = 3 * rd->derr[ch][2] >> 2; // ... 3/4th of err3921top[0] = rd->derr[ch][1]; // ... err2922top[1] = rd->derr[ch][2] - left[1]; // ... 1/4th of err3.923}924}925926#undef C1927#undef C2928#undef DSHIFT929#undef DSCALE930931//------------------------------------------------------------------------------932933static int ReconstructUV(VP8EncIterator* WEBP_RESTRICT const it,934VP8ModeScore* WEBP_RESTRICT const rd,935uint8_t* WEBP_RESTRICT const yuv_out, int mode) {936const VP8Encoder* const enc = it->enc_;937const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode];938const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;939const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];940int nz = 0;941int n;942int16_t tmp[8][16];943944for (n = 0; n < 8; n += 2) {945VP8FTransform2(src + VP8ScanUV[n], ref + VP8ScanUV[n], tmp[n]);946}947if (it->top_derr_ != NULL) CorrectDCValues(it, &dqm->uv_, tmp, rd);948949if (DO_TRELLIS_UV && it->do_trellis_) {950int ch, x, y;951for (ch = 0, n = 0; ch <= 2; ch += 2) {952for (y = 0; y < 2; ++y) {953for (x = 0; x < 2; ++x, ++n) {954const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y];955const int non_zero = TrellisQuantizeBlock(956enc, tmp[n], rd->uv_levels[n], ctx, TYPE_CHROMA_A, &dqm->uv_,957dqm->lambda_trellis_uv_);958it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = non_zero;959nz |= non_zero << n;960}961}962}963} else {964for (n = 0; n < 8; n += 2) {965nz |= VP8EncQuantize2Blocks(tmp[n], rd->uv_levels[n], &dqm->uv_) << n;966}967}968969for (n = 0; n < 8; n += 2) {970VP8ITransform(ref + VP8ScanUV[n], tmp[n], yuv_out + VP8ScanUV[n], 1);971}972return (nz << 16);973}974975//------------------------------------------------------------------------------976// RD-opt decision. Reconstruct each modes, evalue distortion and bit-cost.977// Pick the mode is lower RD-cost = Rate + lambda * Distortion.978979static void StoreMaxDelta(VP8SegmentInfo* const dqm, const int16_t DCs[16]) {980// We look at the first three AC coefficients to determine what is the average981// delta between each sub-4x4 block.982const int v0 = abs(DCs[1]);983const int v1 = abs(DCs[2]);984const int v2 = abs(DCs[4]);985int max_v = (v1 > v0) ? v1 : v0;986max_v = (v2 > max_v) ? v2 : max_v;987if (max_v > dqm->max_edge_) dqm->max_edge_ = max_v;988}989990static void SwapModeScore(VP8ModeScore** a, VP8ModeScore** b) {991VP8ModeScore* const tmp = *a;992*a = *b;993*b = tmp;994}995996static void SwapPtr(uint8_t** a, uint8_t** b) {997uint8_t* const tmp = *a;998*a = *b;999*b = tmp;1000}10011002static void SwapOut(VP8EncIterator* const it) {1003SwapPtr(&it->yuv_out_, &it->yuv_out2_);1004}10051006static void PickBestIntra16(VP8EncIterator* WEBP_RESTRICT const it,1007VP8ModeScore* WEBP_RESTRICT rd) {1008const int kNumBlocks = 16;1009VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];1010const int lambda = dqm->lambda_i16_;1011const int tlambda = dqm->tlambda_;1012const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC;1013VP8ModeScore rd_tmp;1014VP8ModeScore* rd_cur = &rd_tmp;1015VP8ModeScore* rd_best = rd;1016int mode;1017int is_flat = IsFlatSource16(it->yuv_in_ + Y_OFF_ENC);10181019rd->mode_i16 = -1;1020for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1021uint8_t* const tmp_dst = it->yuv_out2_ + Y_OFF_ENC; // scratch buffer1022rd_cur->mode_i16 = mode;10231024// Reconstruct1025rd_cur->nz = ReconstructIntra16(it, rd_cur, tmp_dst, mode);10261027// Measure RD-score1028rd_cur->D = VP8SSE16x16(src, tmp_dst);1029rd_cur->SD =1030tlambda ? MULT_8B(tlambda, VP8TDisto16x16(src, tmp_dst, kWeightY)) : 0;1031rd_cur->H = VP8FixedCostsI16[mode];1032rd_cur->R = VP8GetCostLuma16(it, rd_cur);1033if (is_flat) {1034// refine the first impression (which was in pixel space)1035is_flat = IsFlat(rd_cur->y_ac_levels[0], kNumBlocks, FLATNESS_LIMIT_I16);1036if (is_flat) {1037// Block is very flat. We put emphasis on the distortion being very low!1038rd_cur->D *= 2;1039rd_cur->SD *= 2;1040}1041}10421043// Since we always examine Intra16 first, we can overwrite *rd directly.1044SetRDScore(lambda, rd_cur);1045if (mode == 0 || rd_cur->score < rd_best->score) {1046SwapModeScore(&rd_cur, &rd_best);1047SwapOut(it);1048}1049}1050if (rd_best != rd) {1051memcpy(rd, rd_best, sizeof(*rd));1052}1053SetRDScore(dqm->lambda_mode_, rd); // finalize score for mode decision.1054VP8SetIntra16Mode(it, rd->mode_i16);10551056// we have a blocky macroblock (only DCs are non-zero) with fairly high1057// distortion, record max delta so we can later adjust the minimal filtering1058// strength needed to smooth these blocks out.1059if ((rd->nz & 0x100ffff) == 0x1000000 && rd->D > dqm->min_disto_) {1060StoreMaxDelta(dqm, rd->y_dc_levels);1061}1062}10631064//------------------------------------------------------------------------------10651066// return the cost array corresponding to the surrounding prediction modes.1067static const uint16_t* GetCostModeI4(VP8EncIterator* WEBP_RESTRICT const it,1068const uint8_t modes[16]) {1069const int preds_w = it->enc_->preds_w_;1070const int x = (it->i4_ & 3), y = it->i4_ >> 2;1071const int left = (x == 0) ? it->preds_[y * preds_w - 1] : modes[it->i4_ - 1];1072const int top = (y == 0) ? it->preds_[-preds_w + x] : modes[it->i4_ - 4];1073return VP8FixedCostsI4[top][left];1074}10751076static int PickBestIntra4(VP8EncIterator* WEBP_RESTRICT const it,1077VP8ModeScore* WEBP_RESTRICT const rd) {1078const VP8Encoder* const enc = it->enc_;1079const VP8SegmentInfo* const dqm = &enc->dqm_[it->mb_->segment_];1080const int lambda = dqm->lambda_i4_;1081const int tlambda = dqm->tlambda_;1082const uint8_t* const src0 = it->yuv_in_ + Y_OFF_ENC;1083uint8_t* const best_blocks = it->yuv_out2_ + Y_OFF_ENC;1084int total_header_bits = 0;1085VP8ModeScore rd_best;10861087if (enc->max_i4_header_bits_ == 0) {1088return 0;1089}10901091InitScore(&rd_best);1092rd_best.H = 211; // '211' is the value of VP8BitCost(0, 145)1093SetRDScore(dqm->lambda_mode_, &rd_best);1094VP8IteratorStartI4(it);1095do {1096const int kNumBlocks = 1;1097VP8ModeScore rd_i4;1098int mode;1099int best_mode = -1;1100const uint8_t* const src = src0 + VP8Scan[it->i4_];1101const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);1102uint8_t* best_block = best_blocks + VP8Scan[it->i4_];1103uint8_t* tmp_dst = it->yuv_p_ + I4TMP; // scratch buffer.11041105InitScore(&rd_i4);1106MakeIntra4Preds(it);1107for (mode = 0; mode < NUM_BMODES; ++mode) {1108VP8ModeScore rd_tmp;1109int16_t tmp_levels[16];11101111// Reconstruct1112rd_tmp.nz =1113ReconstructIntra4(it, tmp_levels, src, tmp_dst, mode) << it->i4_;11141115// Compute RD-score1116rd_tmp.D = VP8SSE4x4(src, tmp_dst);1117rd_tmp.SD =1118tlambda ? MULT_8B(tlambda, VP8TDisto4x4(src, tmp_dst, kWeightY))1119: 0;1120rd_tmp.H = mode_costs[mode];11211122// Add flatness penalty, to avoid flat area to be mispredicted1123// by a complex mode.1124if (mode > 0 && IsFlat(tmp_levels, kNumBlocks, FLATNESS_LIMIT_I4)) {1125rd_tmp.R = FLATNESS_PENALTY * kNumBlocks;1126} else {1127rd_tmp.R = 0;1128}11291130// early-out check1131SetRDScore(lambda, &rd_tmp);1132if (best_mode >= 0 && rd_tmp.score >= rd_i4.score) continue;11331134// finish computing score1135rd_tmp.R += VP8GetCostLuma4(it, tmp_levels);1136SetRDScore(lambda, &rd_tmp);11371138if (best_mode < 0 || rd_tmp.score < rd_i4.score) {1139CopyScore(&rd_i4, &rd_tmp);1140best_mode = mode;1141SwapPtr(&tmp_dst, &best_block);1142memcpy(rd_best.y_ac_levels[it->i4_], tmp_levels,1143sizeof(rd_best.y_ac_levels[it->i4_]));1144}1145}1146SetRDScore(dqm->lambda_mode_, &rd_i4);1147AddScore(&rd_best, &rd_i4);1148if (rd_best.score >= rd->score) {1149return 0;1150}1151total_header_bits += (int)rd_i4.H; // <- equal to mode_costs[best_mode];1152if (total_header_bits > enc->max_i4_header_bits_) {1153return 0;1154}1155// Copy selected samples if not in the right place already.1156if (best_block != best_blocks + VP8Scan[it->i4_]) {1157VP8Copy4x4(best_block, best_blocks + VP8Scan[it->i4_]);1158}1159rd->modes_i4[it->i4_] = best_mode;1160it->top_nz_[it->i4_ & 3] = it->left_nz_[it->i4_ >> 2] = (rd_i4.nz ? 1 : 0);1161} while (VP8IteratorRotateI4(it, best_blocks));11621163// finalize state1164CopyScore(rd, &rd_best);1165VP8SetIntra4Mode(it, rd->modes_i4);1166SwapOut(it);1167memcpy(rd->y_ac_levels, rd_best.y_ac_levels, sizeof(rd->y_ac_levels));1168return 1; // select intra4x4 over intra16x161169}11701171//------------------------------------------------------------------------------11721173static void PickBestUV(VP8EncIterator* WEBP_RESTRICT const it,1174VP8ModeScore* WEBP_RESTRICT const rd) {1175const int kNumBlocks = 8;1176const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];1177const int lambda = dqm->lambda_uv_;1178const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;1179uint8_t* tmp_dst = it->yuv_out2_ + U_OFF_ENC; // scratch buffer1180uint8_t* dst0 = it->yuv_out_ + U_OFF_ENC;1181uint8_t* dst = dst0;1182VP8ModeScore rd_best;1183int mode;11841185rd->mode_uv = -1;1186InitScore(&rd_best);1187for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1188VP8ModeScore rd_uv;11891190// Reconstruct1191rd_uv.nz = ReconstructUV(it, &rd_uv, tmp_dst, mode);11921193// Compute RD-score1194rd_uv.D = VP8SSE16x8(src, tmp_dst);1195rd_uv.SD = 0; // not calling TDisto here: it tends to flatten areas.1196rd_uv.H = VP8FixedCostsUV[mode];1197rd_uv.R = VP8GetCostUV(it, &rd_uv);1198if (mode > 0 && IsFlat(rd_uv.uv_levels[0], kNumBlocks, FLATNESS_LIMIT_UV)) {1199rd_uv.R += FLATNESS_PENALTY * kNumBlocks;1200}12011202SetRDScore(lambda, &rd_uv);1203if (mode == 0 || rd_uv.score < rd_best.score) {1204CopyScore(&rd_best, &rd_uv);1205rd->mode_uv = mode;1206memcpy(rd->uv_levels, rd_uv.uv_levels, sizeof(rd->uv_levels));1207if (it->top_derr_ != NULL) {1208memcpy(rd->derr, rd_uv.derr, sizeof(rd_uv.derr));1209}1210SwapPtr(&dst, &tmp_dst);1211}1212}1213VP8SetIntraUVMode(it, rd->mode_uv);1214AddScore(rd, &rd_best);1215if (dst != dst0) { // copy 16x8 block if needed1216VP8Copy16x8(dst, dst0);1217}1218if (it->top_derr_ != NULL) { // store diffusion errors for next block1219StoreDiffusionErrors(it, rd);1220}1221}12221223//------------------------------------------------------------------------------1224// Final reconstruction and quantization.12251226static void SimpleQuantize(VP8EncIterator* WEBP_RESTRICT const it,1227VP8ModeScore* WEBP_RESTRICT const rd) {1228const VP8Encoder* const enc = it->enc_;1229const int is_i16 = (it->mb_->type_ == 1);1230int nz = 0;12311232if (is_i16) {1233nz = ReconstructIntra16(it, rd, it->yuv_out_ + Y_OFF_ENC, it->preds_[0]);1234} else {1235VP8IteratorStartI4(it);1236do {1237const int mode =1238it->preds_[(it->i4_ & 3) + (it->i4_ >> 2) * enc->preds_w_];1239const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_];1240uint8_t* const dst = it->yuv_out_ + Y_OFF_ENC + VP8Scan[it->i4_];1241MakeIntra4Preds(it);1242nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4_],1243src, dst, mode) << it->i4_;1244} while (VP8IteratorRotateI4(it, it->yuv_out_ + Y_OFF_ENC));1245}12461247nz |= ReconstructUV(it, rd, it->yuv_out_ + U_OFF_ENC, it->mb_->uv_mode_);1248rd->nz = nz;1249}12501251// Refine intra16/intra4 sub-modes based on distortion only (not rate).1252static void RefineUsingDistortion(VP8EncIterator* WEBP_RESTRICT const it,1253int try_both_modes, int refine_uv_mode,1254VP8ModeScore* WEBP_RESTRICT const rd) {1255score_t best_score = MAX_COST;1256int nz = 0;1257int mode;1258int is_i16 = try_both_modes || (it->mb_->type_ == 1);12591260const VP8SegmentInfo* const dqm = &it->enc_->dqm_[it->mb_->segment_];1261// Some empiric constants, of approximate order of magnitude.1262const int lambda_d_i16 = 106;1263const int lambda_d_i4 = 11;1264const int lambda_d_uv = 120;1265score_t score_i4 = dqm->i4_penalty_;1266score_t i4_bit_sum = 0;1267const score_t bit_limit = try_both_modes ? it->enc_->mb_header_limit_1268: MAX_COST; // no early-out allowed12691270if (is_i16) { // First, evaluate Intra16 distortion1271int best_mode = -1;1272const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC;1273for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1274const uint8_t* const ref = it->yuv_p_ + VP8I16ModeOffsets[mode];1275const score_t score = (score_t)VP8SSE16x16(src, ref) * RD_DISTO_MULT1276+ VP8FixedCostsI16[mode] * lambda_d_i16;1277if (mode > 0 && VP8FixedCostsI16[mode] > bit_limit) {1278continue;1279}12801281if (score < best_score) {1282best_mode = mode;1283best_score = score;1284}1285}1286if (it->x_ == 0 || it->y_ == 0) {1287// avoid starting a checkerboard resonance from the border. See bug #432.1288if (IsFlatSource16(src)) {1289best_mode = (it->x_ == 0) ? 0 : 2;1290try_both_modes = 0; // stick to i161291}1292}1293VP8SetIntra16Mode(it, best_mode);1294// we'll reconstruct later, if i16 mode actually gets selected1295}12961297// Next, evaluate Intra41298if (try_both_modes || !is_i16) {1299// We don't evaluate the rate here, but just account for it through a1300// constant penalty (i4 mode usually needs more bits compared to i16).1301is_i16 = 0;1302VP8IteratorStartI4(it);1303do {1304int best_i4_mode = -1;1305score_t best_i4_score = MAX_COST;1306const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_];1307const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);13081309MakeIntra4Preds(it);1310for (mode = 0; mode < NUM_BMODES; ++mode) {1311const uint8_t* const ref = it->yuv_p_ + VP8I4ModeOffsets[mode];1312const score_t score = VP8SSE4x4(src, ref) * RD_DISTO_MULT1313+ mode_costs[mode] * lambda_d_i4;1314if (score < best_i4_score) {1315best_i4_mode = mode;1316best_i4_score = score;1317}1318}1319i4_bit_sum += mode_costs[best_i4_mode];1320rd->modes_i4[it->i4_] = best_i4_mode;1321score_i4 += best_i4_score;1322if (score_i4 >= best_score || i4_bit_sum > bit_limit) {1323// Intra4 won't be better than Intra16. Bail out and pick Intra16.1324is_i16 = 1;1325break;1326} else { // reconstruct partial block inside yuv_out2_ buffer1327uint8_t* const tmp_dst = it->yuv_out2_ + Y_OFF_ENC + VP8Scan[it->i4_];1328nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4_],1329src, tmp_dst, best_i4_mode) << it->i4_;1330}1331} while (VP8IteratorRotateI4(it, it->yuv_out2_ + Y_OFF_ENC));1332}13331334// Final reconstruction, depending on which mode is selected.1335if (!is_i16) {1336VP8SetIntra4Mode(it, rd->modes_i4);1337SwapOut(it);1338best_score = score_i4;1339} else {1340nz = ReconstructIntra16(it, rd, it->yuv_out_ + Y_OFF_ENC, it->preds_[0]);1341}13421343// ... and UV!1344if (refine_uv_mode) {1345int best_mode = -1;1346score_t best_uv_score = MAX_COST;1347const uint8_t* const src = it->yuv_in_ + U_OFF_ENC;1348for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1349const uint8_t* const ref = it->yuv_p_ + VP8UVModeOffsets[mode];1350const score_t score = VP8SSE16x8(src, ref) * RD_DISTO_MULT1351+ VP8FixedCostsUV[mode] * lambda_d_uv;1352if (score < best_uv_score) {1353best_mode = mode;1354best_uv_score = score;1355}1356}1357VP8SetIntraUVMode(it, best_mode);1358}1359nz |= ReconstructUV(it, rd, it->yuv_out_ + U_OFF_ENC, it->mb_->uv_mode_);13601361rd->nz = nz;1362rd->score = best_score;1363}13641365//------------------------------------------------------------------------------1366// Entry point13671368int VP8Decimate(VP8EncIterator* WEBP_RESTRICT const it,1369VP8ModeScore* WEBP_RESTRICT const rd,1370VP8RDLevel rd_opt) {1371int is_skipped;1372const int method = it->enc_->method_;13731374InitScore(rd);13751376// We can perform predictions for Luma16x16 and Chroma8x8 already.1377// Luma4x4 predictions needs to be done as-we-go.1378VP8MakeLuma16Preds(it);1379VP8MakeChroma8Preds(it);13801381if (rd_opt > RD_OPT_NONE) {1382it->do_trellis_ = (rd_opt >= RD_OPT_TRELLIS_ALL);1383PickBestIntra16(it, rd);1384if (method >= 2) {1385PickBestIntra4(it, rd);1386}1387PickBestUV(it, rd);1388if (rd_opt == RD_OPT_TRELLIS) { // finish off with trellis-optim now1389it->do_trellis_ = 1;1390SimpleQuantize(it, rd);1391}1392} else {1393// At this point we have heuristically decided intra16 / intra4.1394// For method >= 2, pick the best intra4/intra16 based on SSE (~tad slower).1395// For method <= 1, we don't re-examine the decision but just go ahead with1396// quantization/reconstruction.1397RefineUsingDistortion(it, (method >= 2), (method >= 1), rd);1398}1399is_skipped = (rd->nz == 0);1400VP8SetSkip(it, is_skipped);1401return is_skipped;1402}140314041405