Path: blob/master/thirdparty/libwebp/src/enc/quant_enc.c
20952 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()16#include <string.h>1718#include "src/dec/common_dec.h"19#include "src/dsp/dsp.h"20#include "src/dsp/quant.h"21#include "src/enc/cost_enc.h"22#include "src/enc/vp8i_enc.h"23#include "src/webp/types.h"2425#define DO_TRELLIS_I4 126#define DO_TRELLIS_I16 1 // not a huge gain, but ok at low bitrate.27#define DO_TRELLIS_UV 0 // disable trellis for UV. Risky. Not worth.28#define USE_TDISTO 12930#define MID_ALPHA 64 // neutral value for susceptibility31#define MIN_ALPHA 30 // lowest usable value for susceptibility32#define MAX_ALPHA 100 // higher meaningful value for susceptibility3334#define SNS_TO_DQ 0.9 // Scaling constant between the sns value and the QP35// power-law modulation. Must be strictly less than 1.3637// number of non-zero coeffs below which we consider the block very flat38// (and apply a penalty to complex predictions)39#define FLATNESS_LIMIT_I16 0 // I16 mode (special case)40#define FLATNESS_LIMIT_I4 3 // I4 mode41#define FLATNESS_LIMIT_UV 2 // UV mode42#define FLATNESS_PENALTY 140 // roughly ~1bit per block4344#define MULT_8B(a, b) (((a) * (b) + 128) >> 8)4546#define RD_DISTO_MULT 256 // distortion multiplier (equivalent of lambda)4748// #define DEBUG_BLOCK4950//------------------------------------------------------------------------------5152#if defined(DEBUG_BLOCK)5354#include <stdio.h>55#include <stdlib.h>5657static void PrintBlockInfo(const VP8EncIterator* const it,58const VP8ModeScore* const rd) {59int i, j;60const int is_i16 = (it->mb->type == 1);61const uint8_t* const y_in = it->yuv_in + Y_OFF_ENC;62const uint8_t* const y_out = it->yuv_out + Y_OFF_ENC;63const uint8_t* const uv_in = it->yuv_in + U_OFF_ENC;64const uint8_t* const uv_out = it->yuv_out + U_OFF_ENC;65printf("SOURCE / OUTPUT / ABS DELTA\n");66for (j = 0; j < 16; ++j) {67for (i = 0; i < 16; ++i) printf("%3d ", y_in[i + j * BPS]);68printf(" ");69for (i = 0; i < 16; ++i) printf("%3d ", y_out[i + j * BPS]);70printf(" ");71for (i = 0; i < 16; ++i) {72printf("%1d ", abs(y_in[i + j * BPS] - y_out[i + j * BPS]));73}74printf("\n");75}76printf("\n"); // newline before the U/V block77for (j = 0; j < 8; ++j) {78for (i = 0; i < 8; ++i) printf("%3d ", uv_in[i + j * BPS]);79printf(" ");80for (i = 8; i < 16; ++i) printf("%3d ", uv_in[i + j * BPS]);81printf(" ");82for (i = 0; i < 8; ++i) printf("%3d ", uv_out[i + j * BPS]);83printf(" ");84for (i = 8; i < 16; ++i) printf("%3d ", uv_out[i + j * BPS]);85printf(" ");86for (i = 0; i < 8; ++i) {87printf("%1d ", abs(uv_out[i + j * BPS] - uv_in[i + j * BPS]));88}89printf(" ");90for (i = 8; i < 16; ++i) {91printf("%1d ", abs(uv_out[i + j * BPS] - uv_in[i + j * BPS]));92}93printf("\n");94}95printf("\nD:%d SD:%d R:%d H:%d nz:0x%x score:%d\n",96(int)rd->D, (int)rd->SD, (int)rd->R, (int)rd->H, (int)rd->nz,97(int)rd->score);98if (is_i16) {99printf("Mode: %d\n", rd->mode_i16);100printf("y_dc_levels:");101for (i = 0; i < 16; ++i) printf("%3d ", rd->y_dc_levels[i]);102printf("\n");103} else {104printf("Modes[16]: ");105for (i = 0; i < 16; ++i) printf("%d ", rd->modes_i4[i]);106printf("\n");107}108printf("y_ac_levels:\n");109for (j = 0; j < 16; ++j) {110for (i = is_i16 ? 1 : 0; i < 16; ++i) {111printf("%4d ", rd->y_ac_levels[j][i]);112}113printf("\n");114}115printf("\n");116printf("uv_levels (mode=%d):\n", rd->mode_uv);117for (j = 0; j < 8; ++j) {118for (i = 0; i < 16; ++i) {119printf("%4d ", rd->uv_levels[j][i]);120}121printf("\n");122}123}124125#endif // DEBUG_BLOCK126127//------------------------------------------------------------------------------128129static WEBP_INLINE int clip(int v, int m, int M) {130return v < m ? m : v > M ? M : v;131}132133static const uint8_t kZigzag[16] = {1340, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15135};136137static const uint8_t kDcTable[128] = {1384, 5, 6, 7, 8, 9, 10, 10,13911, 12, 13, 14, 15, 16, 17, 17,14018, 19, 20, 20, 21, 21, 22, 22,14123, 23, 24, 25, 25, 26, 27, 28,14229, 30, 31, 32, 33, 34, 35, 36,14337, 37, 38, 39, 40, 41, 42, 43,14444, 45, 46, 46, 47, 48, 49, 50,14551, 52, 53, 54, 55, 56, 57, 58,14659, 60, 61, 62, 63, 64, 65, 66,14767, 68, 69, 70, 71, 72, 73, 74,14875, 76, 76, 77, 78, 79, 80, 81,14982, 83, 84, 85, 86, 87, 88, 89,15091, 93, 95, 96, 98, 100, 101, 102,151104, 106, 108, 110, 112, 114, 116, 118,152122, 124, 126, 128, 130, 132, 134, 136,153138, 140, 143, 145, 148, 151, 154, 157154};155156static const uint16_t kAcTable[128] = {1574, 5, 6, 7, 8, 9, 10, 11,15812, 13, 14, 15, 16, 17, 18, 19,15920, 21, 22, 23, 24, 25, 26, 27,16028, 29, 30, 31, 32, 33, 34, 35,16136, 37, 38, 39, 40, 41, 42, 43,16244, 45, 46, 47, 48, 49, 50, 51,16352, 53, 54, 55, 56, 57, 58, 60,16462, 64, 66, 68, 70, 72, 74, 76,16578, 80, 82, 84, 86, 88, 90, 92,16694, 96, 98, 100, 102, 104, 106, 108,167110, 112, 114, 116, 119, 122, 125, 128,168131, 134, 137, 140, 143, 146, 149, 152,169155, 158, 161, 164, 167, 170, 173, 177,170181, 185, 189, 193, 197, 201, 205, 209,171213, 217, 221, 225, 229, 234, 239, 245,172249, 254, 259, 264, 269, 274, 279, 284173};174175static const uint16_t kAcTable2[128] = {1768, 8, 9, 10, 12, 13, 15, 17,17718, 20, 21, 23, 24, 26, 27, 29,17831, 32, 34, 35, 37, 38, 40, 41,17943, 44, 46, 48, 49, 51, 52, 54,18055, 57, 58, 60, 62, 63, 65, 66,18168, 69, 71, 72, 74, 75, 77, 79,18280, 82, 83, 85, 86, 88, 89, 93,18396, 99, 102, 105, 108, 111, 114, 117,184120, 124, 127, 130, 133, 136, 139, 142,185145, 148, 151, 155, 158, 161, 164, 167,186170, 173, 176, 179, 184, 189, 193, 198,187203, 207, 212, 217, 221, 226, 230, 235,188240, 244, 249, 254, 258, 263, 268, 274,189280, 286, 292, 299, 305, 311, 317, 323,190330, 336, 342, 348, 354, 362, 370, 379,191385, 393, 401, 409, 416, 424, 432, 440192};193194static const uint8_t kBiasMatrices[3][2] = { // [luma-ac,luma-dc,chroma][dc,ac]195{ 96, 110 }, { 96, 108 }, { 110, 115 }196};197198// Sharpening by (slightly) raising the hi-frequency coeffs.199// Hack-ish but helpful for mid-bitrate range. Use with care.200#define SHARPEN_BITS 11 // number of descaling bits for sharpening bias201static const uint8_t kFreqSharpening[16] = {2020, 30, 60, 90,20330, 60, 90, 90,20460, 90, 90, 90,20590, 90, 90, 90206};207208//------------------------------------------------------------------------------209// Initialize quantization parameters in VP8Matrix210211// Returns the average quantizer212static int ExpandMatrix(VP8Matrix* const m, int type) {213int i, sum;214for (i = 0; i < 2; ++i) {215const int is_ac_coeff = (i > 0);216const int bias = kBiasMatrices[type][is_ac_coeff];217m->iq[i] = (1 << QFIX) / m->q[i];218m->bias[i] = BIAS(bias);219// zthresh is the exact value such that QUANTDIV(coeff, iQ, B) is:220// * zero if coeff <= zthresh221// * non-zero if coeff > zthresh222m->zthresh[i] = ((1 << QFIX) - 1 - m->bias[i]) / m->iq[i];223}224for (i = 2; i < 16; ++i) {225m->q[i] = m->q[1];226m->iq[i] = m->iq[1];227m->bias[i] = m->bias[1];228m->zthresh[i] = m->zthresh[1];229}230for (sum = 0, i = 0; i < 16; ++i) {231if (type == 0) { // we only use sharpening for AC luma coeffs232m->sharpen[i] = (kFreqSharpening[i] * m->q[i]) >> SHARPEN_BITS;233} else {234m->sharpen[i] = 0;235}236sum += m->q[i];237}238return (sum + 8) >> 4;239}240241static void CheckLambdaValue(int* const v) { if (*v < 1) *v = 1; }242243static void SetupMatrices(VP8Encoder* enc) {244int i;245const int tlambda_scale =246(enc->method >= 4) ? enc->config->sns_strength247: 0;248const int num_segments = enc->segment_hdr.num_segments;249for (i = 0; i < num_segments; ++i) {250VP8SegmentInfo* const m = &enc->dqm[i];251const int q = m->quant;252int q_i4, q_i16, q_uv;253m->y1.q[0] = kDcTable[clip(q + enc->dq_y1_dc, 0, 127)];254m->y1.q[1] = kAcTable[clip(q, 0, 127)];255256m->y2.q[0] = kDcTable[ clip(q + enc->dq_y2_dc, 0, 127)] * 2;257m->y2.q[1] = kAcTable2[clip(q + enc->dq_y2_ac, 0, 127)];258259m->uv.q[0] = kDcTable[clip(q + enc->dq_uv_dc, 0, 117)];260m->uv.q[1] = kAcTable[clip(q + enc->dq_uv_ac, 0, 127)];261262q_i4 = ExpandMatrix(&m->y1, 0);263q_i16 = ExpandMatrix(&m->y2, 1);264q_uv = ExpandMatrix(&m->uv, 2);265266m->lambda_i4 = (3 * q_i4 * q_i4) >> 7;267m->lambda_i16 = (3 * q_i16 * q_i16);268m->lambda_uv = (3 * q_uv * q_uv) >> 6;269m->lambda_mode = (1 * q_i4 * q_i4) >> 7;270m->lambda_trellis_i4 = (7 * q_i4 * q_i4) >> 3;271m->lambda_trellis_i16 = (q_i16 * q_i16) >> 2;272m->lambda_trellis_uv = (q_uv * q_uv) << 1;273m->tlambda = (tlambda_scale * q_i4) >> 5;274275// none of these constants should be < 1276CheckLambdaValue(&m->lambda_i4);277CheckLambdaValue(&m->lambda_i16);278CheckLambdaValue(&m->lambda_uv);279CheckLambdaValue(&m->lambda_mode);280CheckLambdaValue(&m->lambda_trellis_i4);281CheckLambdaValue(&m->lambda_trellis_i16);282CheckLambdaValue(&m->lambda_trellis_uv);283CheckLambdaValue(&m->tlambda);284285m->min_disto = 20 * m->y1.q[0]; // quantization-aware min disto286m->max_edge = 0;287288m->i4_penalty = 1000 * q_i4 * q_i4;289}290}291292//------------------------------------------------------------------------------293// Initialize filtering parameters294295// Very small filter-strength values have close to no visual effect. So we can296// save a little decoding-CPU by turning filtering off for these.297#define FSTRENGTH_CUTOFF 2298299static void SetupFilterStrength(VP8Encoder* const enc) {300int i;301// level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering.302const int level0 = 5 * enc->config->filter_strength;303for (i = 0; i < NUM_MB_SEGMENTS; ++i) {304VP8SegmentInfo* const m = &enc->dqm[i];305// We focus on the quantization of AC coeffs.306const int qstep = kAcTable[clip(m->quant, 0, 127)] >> 2;307const int base_strength =308VP8FilterStrengthFromDelta(enc->filter_hdr.sharpness, qstep);309// Segments with lower complexity ('beta') will be less filtered.310const int f = base_strength * level0 / (256 + m->beta);311m->fstrength = (f < FSTRENGTH_CUTOFF) ? 0 : (f > 63) ? 63 : f;312}313// We record the initial strength (mainly for the case of 1-segment only).314enc->filter_hdr.level = enc->dqm[0].fstrength;315enc->filter_hdr.simple = (enc->config->filter_type == 0);316enc->filter_hdr.sharpness = enc->config->filter_sharpness;317}318319//------------------------------------------------------------------------------320321// Note: if you change the values below, remember that the max range322// allowed by the syntax for DQ_UV is [-16,16].323#define MAX_DQ_UV (6)324#define MIN_DQ_UV (-4)325326// We want to emulate jpeg-like behaviour where the expected "good" quality327// is around q=75. Internally, our "good" middle is around c=50. So we328// map accordingly using linear piece-wise function329static double QualityToCompression(double c) {330const double linear_c = (c < 0.75) ? c * (2. / 3.) : 2. * c - 1.;331// The file size roughly scales as pow(quantizer, 3.). Actually, the332// exponent is somewhere between 2.8 and 3.2, but we're mostly interested333// in the mid-quant range. So we scale the compressibility inversely to334// this power-law: quant ~= compression ^ 1/3. This law holds well for335// low quant. Finer modeling for high-quant would make use of kAcTable[]336// more explicitly.337const double v = pow(linear_c, 1 / 3.);338return v;339}340341static double QualityToJPEGCompression(double c, double alpha) {342// We map the complexity 'alpha' and quality setting 'c' to a compression343// exponent empirically matched to the compression curve of libjpeg6b.344// On average, the WebP output size will be roughly similar to that of a345// JPEG file compressed with same quality factor.346const double amin = 0.30;347const double amax = 0.85;348const double exp_min = 0.4;349const double exp_max = 0.9;350const double slope = (exp_min - exp_max) / (amax - amin);351// Linearly interpolate 'expn' from exp_min to exp_max352// in the [amin, amax] range.353const double expn = (alpha > amax) ? exp_min354: (alpha < amin) ? exp_max355: exp_max + slope * (alpha - amin);356const double v = pow(c, expn);357return v;358}359360static int SegmentsAreEquivalent(const VP8SegmentInfo* const S1,361const VP8SegmentInfo* const S2) {362return (S1->quant == S2->quant) && (S1->fstrength == S2->fstrength);363}364365static void SimplifySegments(VP8Encoder* const enc) {366int map[NUM_MB_SEGMENTS] = { 0, 1, 2, 3 };367// 'num_segments' is previously validated and <= NUM_MB_SEGMENTS, but an368// explicit check is needed to avoid a spurious warning about 'i' exceeding369// array bounds of 'dqm' with some compilers (noticed with gcc-4.9).370const int num_segments = (enc->segment_hdr.num_segments < NUM_MB_SEGMENTS)371? enc->segment_hdr.num_segments372: NUM_MB_SEGMENTS;373int num_final_segments = 1;374int s1, s2;375for (s1 = 1; s1 < num_segments; ++s1) { // find similar segments376const VP8SegmentInfo* const S1 = &enc->dqm[s1];377int found = 0;378// check if we already have similar segment379for (s2 = 0; s2 < num_final_segments; ++s2) {380const VP8SegmentInfo* const S2 = &enc->dqm[s2];381if (SegmentsAreEquivalent(S1, S2)) {382found = 1;383break;384}385}386map[s1] = s2;387if (!found) {388if (num_final_segments != s1) {389enc->dqm[num_final_segments] = enc->dqm[s1];390}391++num_final_segments;392}393}394if (num_final_segments < num_segments) { // Remap395int i = enc->mb_w * enc->mb_h;396while (i-- > 0) enc->mb_info[i].segment = map[enc->mb_info[i].segment];397enc->segment_hdr.num_segments = num_final_segments;398// Replicate the trailing segment infos (it's mostly cosmetics)399for (i = num_final_segments; i < num_segments; ++i) {400enc->dqm[i] = enc->dqm[num_final_segments - 1];401}402}403}404405void VP8SetSegmentParams(VP8Encoder* const enc, float quality) {406int i;407int dq_uv_ac, dq_uv_dc;408const int num_segments = enc->segment_hdr.num_segments;409const double amp = SNS_TO_DQ * enc->config->sns_strength / 100. / 128.;410const double Q = quality / 100.;411const double c_base = enc->config->emulate_jpeg_size ?412QualityToJPEGCompression(Q, enc->alpha / 255.) :413QualityToCompression(Q);414for (i = 0; i < num_segments; ++i) {415// We modulate the base coefficient to accommodate for the quantization416// susceptibility and allow denser segments to be quantized more.417const double expn = 1. - amp * enc->dqm[i].alpha;418const double c = pow(c_base, expn);419const int q = (int)(127. * (1. - c));420assert(expn > 0.);421enc->dqm[i].quant = clip(q, 0, 127);422}423424// purely indicative in the bitstream (except for the 1-segment case)425enc->base_quant = enc->dqm[0].quant;426427// fill-in values for the unused segments (required by the syntax)428for (i = num_segments; i < NUM_MB_SEGMENTS; ++i) {429enc->dqm[i].quant = enc->base_quant;430}431432// uv_alpha is normally spread around ~60. The useful range is433// typically ~30 (quite bad) to ~100 (ok to decimate UV more).434// We map it to the safe maximal range of MAX/MIN_DQ_UV for dq_uv.435dq_uv_ac = (enc->uv_alpha - MID_ALPHA) * (MAX_DQ_UV - MIN_DQ_UV)436/ (MAX_ALPHA - MIN_ALPHA);437// we rescale by the user-defined strength of adaptation438dq_uv_ac = dq_uv_ac * enc->config->sns_strength / 100;439// and make it safe.440dq_uv_ac = clip(dq_uv_ac, MIN_DQ_UV, MAX_DQ_UV);441// We also boost the dc-uv-quant a little, based on sns-strength, since442// U/V channels are quite more reactive to high quants (flat DC-blocks443// tend to appear, and are unpleasant).444dq_uv_dc = -4 * enc->config->sns_strength / 100;445dq_uv_dc = clip(dq_uv_dc, -15, 15); // 4bit-signed max allowed446447enc->dq_y1_dc = 0; // TODO(skal): dq-lum448enc->dq_y2_dc = 0;449enc->dq_y2_ac = 0;450enc->dq_uv_dc = dq_uv_dc;451enc->dq_uv_ac = dq_uv_ac;452453SetupFilterStrength(enc); // initialize segments' filtering, eventually454455if (num_segments > 1) SimplifySegments(enc);456457SetupMatrices(enc); // finalize quantization matrices458}459460//------------------------------------------------------------------------------461// Form the predictions in cache462463// Must be ordered using {DC_PRED, TM_PRED, V_PRED, H_PRED} as index464const uint16_t VP8I16ModeOffsets[4] = { I16DC16, I16TM16, I16VE16, I16HE16 };465const uint16_t VP8UVModeOffsets[4] = { C8DC8, C8TM8, C8VE8, C8HE8 };466467// Must be indexed using {B_DC_PRED -> B_HU_PRED} as index468static const uint16_t VP8I4ModeOffsets[NUM_BMODES] = {469I4DC4, I4TM4, I4VE4, I4HE4, I4RD4, I4VR4, I4LD4, I4VL4, I4HD4, I4HU4470};471472void VP8MakeLuma16Preds(const VP8EncIterator* const it) {473const uint8_t* const left = it->x ? it->y_left : NULL;474const uint8_t* const top = it->y ? it->y_top : NULL;475VP8EncPredLuma16(it->yuv_p, left, top);476}477478void VP8MakeChroma8Preds(const VP8EncIterator* const it) {479const uint8_t* const left = it->x ? it->u_left : NULL;480const uint8_t* const top = it->y ? it->uv_top : NULL;481VP8EncPredChroma8(it->yuv_p, left, top);482}483484// Form all the ten Intra4x4 predictions in the 'yuv_p' cache485// for the 4x4 block it->i4486static void MakeIntra4Preds(const VP8EncIterator* const it) {487VP8EncPredLuma4(it->yuv_p, it->i4_top);488}489490//------------------------------------------------------------------------------491// Quantize492493// Layout:494// +----+----+495// |YYYY|UUVV| 0496// |YYYY|UUVV| 4497// |YYYY|....| 8498// |YYYY|....| 12499// +----+----+500501const uint16_t VP8Scan[16] = { // Luma5020 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS,5030 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS,5040 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS,5050 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS,506};507508static const uint16_t VP8ScanUV[4 + 4] = {5090 + 0 * BPS, 4 + 0 * BPS, 0 + 4 * BPS, 4 + 4 * BPS, // U5108 + 0 * BPS, 12 + 0 * BPS, 8 + 4 * BPS, 12 + 4 * BPS // V511};512513//------------------------------------------------------------------------------514// Distortion measurement515516static const uint16_t kWeightY[16] = {51738, 32, 20, 9, 32, 28, 17, 7, 20, 17, 10, 4, 9, 7, 4, 2518};519520static const uint16_t kWeightTrellis[16] = {521#if USE_TDISTO == 052216, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16523#else52430, 27, 19, 11,52527, 24, 17, 10,52619, 17, 12, 8,52711, 10, 8, 6528#endif529};530531// Init/Copy the common fields in score.532static void InitScore(VP8ModeScore* const rd) {533rd->D = 0;534rd->SD = 0;535rd->R = 0;536rd->H = 0;537rd->nz = 0;538rd->score = MAX_COST;539}540541static void CopyScore(VP8ModeScore* WEBP_RESTRICT const dst,542const VP8ModeScore* WEBP_RESTRICT const src) {543dst->D = src->D;544dst->SD = src->SD;545dst->R = src->R;546dst->H = src->H;547dst->nz = src->nz; // note that nz is not accumulated, but just copied.548dst->score = src->score;549}550551static void AddScore(VP8ModeScore* WEBP_RESTRICT const dst,552const VP8ModeScore* WEBP_RESTRICT const src) {553dst->D += src->D;554dst->SD += src->SD;555dst->R += src->R;556dst->H += src->H;557dst->nz |= src->nz; // here, new nz bits are accumulated.558dst->score += src->score;559}560561//------------------------------------------------------------------------------562// Performs trellis-optimized quantization.563564// Prevents Visual Studio debugger from using this Node struct in place of the Godot Node class.565#define Node Node_libwebp_quant566567// Trellis node568typedef struct {569int8_t prev; // best previous node570int8_t sign; // sign of coeff_i571int16_t level; // level572} Node;573574// Score state575typedef struct {576score_t score; // partial RD score577const uint16_t* costs; // shortcut to cost tables578} ScoreState;579580// If a coefficient was quantized to a value Q (using a neutral bias),581// we test all alternate possibilities between [Q-MIN_DELTA, Q+MAX_DELTA]582// We don't test negative values though.583#define MIN_DELTA 0 // how much lower level to try584#define MAX_DELTA 1 // how much higher585#define NUM_NODES (MIN_DELTA + 1 + MAX_DELTA)586#define NODE(n, l) (nodes[(n)][(l) + MIN_DELTA])587#define SCORE_STATE(n, l) (score_states[n][(l) + MIN_DELTA])588589static WEBP_INLINE void SetRDScore(int lambda, VP8ModeScore* const rd) {590rd->score = (rd->R + rd->H) * lambda + RD_DISTO_MULT * (rd->D + rd->SD);591}592593static WEBP_INLINE score_t RDScoreTrellis(int lambda, score_t rate,594score_t distortion) {595return rate * lambda + RD_DISTO_MULT * distortion;596}597598// Coefficient type.599enum { TYPE_I16_AC = 0, TYPE_I16_DC = 1, TYPE_CHROMA_A = 2, TYPE_I4_AC = 3 };600601static int TrellisQuantizeBlock(const VP8Encoder* WEBP_RESTRICT const enc,602int16_t in[16], int16_t out[16],603int ctx0, int coeff_type,604const VP8Matrix* WEBP_RESTRICT const mtx,605int lambda) {606const ProbaArray* const probas = enc->proba.coeffs[coeff_type];607CostArrayPtr const costs =608(CostArrayPtr)enc->proba.remapped_costs[coeff_type];609const int first = (coeff_type == TYPE_I16_AC) ? 1 : 0;610Node nodes[16][NUM_NODES];611ScoreState score_states[2][NUM_NODES];612ScoreState* ss_cur = &SCORE_STATE(0, MIN_DELTA);613ScoreState* ss_prev = &SCORE_STATE(1, MIN_DELTA);614int best_path[3] = {-1, -1, -1}; // store best-last/best-level/best-previous615score_t best_score;616int n, m, p, last;617618{619score_t cost;620const int thresh = mtx->q[1] * mtx->q[1] / 4;621const int last_proba = probas[VP8EncBands[first]][ctx0][0];622623// compute the position of the last interesting coefficient624last = first - 1;625for (n = 15; n >= first; --n) {626const int j = kZigzag[n];627const int err = in[j] * in[j];628if (err > thresh) {629last = n;630break;631}632}633// we don't need to go inspect up to n = 16 coeffs. We can just go up634// to last + 1 (inclusive) without losing much.635if (last < 15) ++last;636637// compute 'skip' score. This is the max score one can do.638cost = VP8BitCost(0, last_proba);639best_score = RDScoreTrellis(lambda, cost, 0);640641// initialize source node.642for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {643const score_t rate = (ctx0 == 0) ? VP8BitCost(1, last_proba) : 0;644ss_cur[m].score = RDScoreTrellis(lambda, rate, 0);645ss_cur[m].costs = costs[first][ctx0];646}647}648649// traverse trellis.650for (n = first; n <= last; ++n) {651const int j = kZigzag[n];652const uint32_t Q = mtx->q[j];653const uint32_t iQ = mtx->iq[j];654const uint32_t B = BIAS(0x00); // neutral bias655// note: it's important to take sign of the _original_ coeff,656// so we don't have to consider level < 0 afterward.657const int sign = (in[j] < 0);658const uint32_t coeff0 = (sign ? -in[j] : in[j]) + mtx->sharpen[j];659int level0 = QUANTDIV(coeff0, iQ, B);660int thresh_level = QUANTDIV(coeff0, iQ, BIAS(0x80));661if (thresh_level > MAX_LEVEL) thresh_level = MAX_LEVEL;662if (level0 > MAX_LEVEL) level0 = MAX_LEVEL;663664{ // Swap current and previous score states665ScoreState* const tmp = ss_cur;666ss_cur = ss_prev;667ss_prev = tmp;668}669670// test all alternate level values around level0.671for (m = -MIN_DELTA; m <= MAX_DELTA; ++m) {672Node* const cur = &NODE(n, m);673const int level = level0 + m;674const int ctx = (level > 2) ? 2 : level;675const int band = VP8EncBands[n + 1];676score_t base_score;677score_t best_cur_score;678int best_prev;679score_t cost, score;680681ss_cur[m].costs = costs[n + 1][ctx];682if (level < 0 || level > thresh_level) {683ss_cur[m].score = MAX_COST;684// Node is dead.685continue;686}687688{689// Compute delta_error = how much coding this level will690// subtract to max_error as distortion.691// Here, distortion = sum of (|coeff_i| - level_i * Q_i)^2692const int new_error = coeff0 - level * Q;693const int delta_error =694kWeightTrellis[j] * (new_error * new_error - coeff0 * coeff0);695base_score = RDScoreTrellis(lambda, 0, delta_error);696}697698// Inspect all possible non-dead predecessors. Retain only the best one.699// The base_score is added to all scores so it is only added for the final700// value after the loop.701cost = VP8LevelCost(ss_prev[-MIN_DELTA].costs, level);702best_cur_score =703ss_prev[-MIN_DELTA].score + RDScoreTrellis(lambda, cost, 0);704best_prev = -MIN_DELTA;705for (p = -MIN_DELTA + 1; p <= MAX_DELTA; ++p) {706// Dead nodes (with ss_prev[p].score >= MAX_COST) are automatically707// eliminated since their score can't be better than the current best.708cost = VP8LevelCost(ss_prev[p].costs, level);709// Examine node assuming it's a non-terminal one.710score = ss_prev[p].score + RDScoreTrellis(lambda, cost, 0);711if (score < best_cur_score) {712best_cur_score = score;713best_prev = p;714}715}716best_cur_score += base_score;717// Store best finding in current node.718cur->sign = sign;719cur->level = level;720cur->prev = best_prev;721ss_cur[m].score = best_cur_score;722723// Now, record best terminal node (and thus best entry in the graph).724if (level != 0 && best_cur_score < best_score) {725const score_t last_pos_cost =726(n < 15) ? VP8BitCost(0, probas[band][ctx][0]) : 0;727const score_t last_pos_score = RDScoreTrellis(lambda, last_pos_cost, 0);728score = best_cur_score + last_pos_score;729if (score < best_score) {730best_score = score;731best_path[0] = n; // best eob position732best_path[1] = m; // best node index733best_path[2] = best_prev; // best predecessor734}735}736}737}738739// Fresh start740// Beware! We must preserve in[0]/out[0] value for TYPE_I16_AC case.741if (coeff_type == TYPE_I16_AC) {742memset(in + 1, 0, 15 * sizeof(*in));743memset(out + 1, 0, 15 * sizeof(*out));744} else {745memset(in, 0, 16 * sizeof(*in));746memset(out, 0, 16 * sizeof(*out));747}748if (best_path[0] == -1) {749return 0; // skip!750}751752{753// Unwind the best path.754// Note: best-prev on terminal node is not necessarily equal to the755// best_prev for non-terminal. So we patch best_path[2] in.756int nz = 0;757int best_node = best_path[1];758n = best_path[0];759NODE(n, best_node).prev = best_path[2]; // force best-prev for terminal760761for (; n >= first; --n) {762const Node* const node = &NODE(n, best_node);763const int j = kZigzag[n];764out[n] = node->sign ? -node->level : node->level;765nz |= node->level;766in[j] = out[n] * mtx->q[j];767best_node = node->prev;768}769return (nz != 0);770}771}772773#undef NODE774775//------------------------------------------------------------------------------776// Performs: difference, transform, quantize, back-transform, add777// all at once. Output is the reconstructed block in *yuv_out, and the778// quantized levels in *levels.779780static int ReconstructIntra16(VP8EncIterator* WEBP_RESTRICT const it,781VP8ModeScore* WEBP_RESTRICT const rd,782uint8_t* WEBP_RESTRICT const yuv_out,783int mode) {784const VP8Encoder* const enc = it->enc;785const uint8_t* const ref = it->yuv_p + VP8I16ModeOffsets[mode];786const uint8_t* const src = it->yuv_in + Y_OFF_ENC;787const VP8SegmentInfo* const dqm = &enc->dqm[it->mb->segment];788int nz = 0;789int n;790int16_t tmp[16][16], dc_tmp[16];791792for (n = 0; n < 16; n += 2) {793VP8FTransform2(src + VP8Scan[n], ref + VP8Scan[n], tmp[n]);794}795VP8FTransformWHT(tmp[0], dc_tmp);796nz |= VP8EncQuantizeBlockWHT(dc_tmp, rd->y_dc_levels, &dqm->y2) << 24;797798if (DO_TRELLIS_I16 && it->do_trellis) {799int x, y;800VP8IteratorNzToBytes(it);801for (y = 0, n = 0; y < 4; ++y) {802for (x = 0; x < 4; ++x, ++n) {803const int ctx = it->top_nz[x] + it->left_nz[y];804const int non_zero = TrellisQuantizeBlock(805enc, tmp[n], rd->y_ac_levels[n], ctx, TYPE_I16_AC, &dqm->y1,806dqm->lambda_trellis_i16);807it->top_nz[x] = it->left_nz[y] = non_zero;808rd->y_ac_levels[n][0] = 0;809nz |= non_zero << n;810}811}812} else {813for (n = 0; n < 16; n += 2) {814// Zero-out the first coeff, so that: a) nz is correct below, and815// b) finding 'last' non-zero coeffs in SetResidualCoeffs() is simplified.816tmp[n][0] = tmp[n + 1][0] = 0;817nz |= VP8EncQuantize2Blocks(tmp[n], rd->y_ac_levels[n], &dqm->y1) << n;818assert(rd->y_ac_levels[n + 0][0] == 0);819assert(rd->y_ac_levels[n + 1][0] == 0);820}821}822823// Transform back824VP8TransformWHT(dc_tmp, tmp[0]);825for (n = 0; n < 16; n += 2) {826VP8ITransform(ref + VP8Scan[n], tmp[n], yuv_out + VP8Scan[n], 1);827}828829return nz;830}831832static int ReconstructIntra4(VP8EncIterator* WEBP_RESTRICT const it,833int16_t levels[16],834const uint8_t* WEBP_RESTRICT const src,835uint8_t* WEBP_RESTRICT const yuv_out,836int mode) {837const VP8Encoder* const enc = it->enc;838const uint8_t* const ref = it->yuv_p + VP8I4ModeOffsets[mode];839const VP8SegmentInfo* const dqm = &enc->dqm[it->mb->segment];840int nz = 0;841int16_t tmp[16];842843VP8FTransform(src, ref, tmp);844if (DO_TRELLIS_I4 && it->do_trellis) {845const int x = it->i4 & 3, y = it->i4 >> 2;846const int ctx = it->top_nz[x] + it->left_nz[y];847nz = TrellisQuantizeBlock(enc, tmp, levels, ctx, TYPE_I4_AC, &dqm->y1,848dqm->lambda_trellis_i4);849} else {850nz = VP8EncQuantizeBlock(tmp, levels, &dqm->y1);851}852VP8ITransform(ref, tmp, yuv_out, 0);853return nz;854}855856//------------------------------------------------------------------------------857// DC-error diffusion858859// Diffusion weights. We under-correct a bit (15/16th of the error is actually860// diffused) to avoid 'rainbow' chessboard pattern of blocks at q~=0.861#define C1 7 // fraction of error sent to the 4x4 block below862#define C2 8 // fraction of error sent to the 4x4 block on the right863#define DSHIFT 4864#define DSCALE 1 // storage descaling, needed to make the error fit int8_t865866// Quantize as usual, but also compute and return the quantization error.867// Error is already divided by DSHIFT.868static int QuantizeSingle(int16_t* WEBP_RESTRICT const v,869const VP8Matrix* WEBP_RESTRICT const mtx) {870int V = *v;871const int sign = (V < 0);872if (sign) V = -V;873if (V > (int)mtx->zthresh[0]) {874const int qV = QUANTDIV(V, mtx->iq[0], mtx->bias[0]) * mtx->q[0];875const int err = (V - qV);876*v = sign ? -qV : qV;877return (sign ? -err : err) >> DSCALE;878}879*v = 0;880return (sign ? -V : V) >> DSCALE;881}882883static void CorrectDCValues(const VP8EncIterator* WEBP_RESTRICT const it,884const VP8Matrix* WEBP_RESTRICT const mtx,885int16_t tmp[][16],886VP8ModeScore* WEBP_RESTRICT const rd) {887// | top[0] | top[1]888// --------+--------+---------889// left[0] | tmp[0] tmp[1] <-> err0 err1890// left[1] | tmp[2] tmp[3] err2 err3891//892// Final errors {err1,err2,err3} are preserved and later restored893// as top[]/left[] on the next block.894int ch;895for (ch = 0; ch <= 1; ++ch) {896const int8_t* const top = it->top_derr[it->x][ch];897const int8_t* const left = it->left_derr[ch];898int16_t (* const c)[16] = &tmp[ch * 4];899int err0, err1, err2, err3;900c[0][0] += (C1 * top[0] + C2 * left[0]) >> (DSHIFT - DSCALE);901err0 = QuantizeSingle(&c[0][0], mtx);902c[1][0] += (C1 * top[1] + C2 * err0) >> (DSHIFT - DSCALE);903err1 = QuantizeSingle(&c[1][0], mtx);904c[2][0] += (C1 * err0 + C2 * left[1]) >> (DSHIFT - DSCALE);905err2 = QuantizeSingle(&c[2][0], mtx);906c[3][0] += (C1 * err1 + C2 * err2) >> (DSHIFT - DSCALE);907err3 = QuantizeSingle(&c[3][0], mtx);908// error 'err' is bounded by mtx->q[0] which is 132 at max. Hence909// err >> DSCALE will fit in an int8_t type if DSCALE>=1.910assert(abs(err1) <= 127 && abs(err2) <= 127 && abs(err3) <= 127);911rd->derr[ch][0] = (int8_t)err1;912rd->derr[ch][1] = (int8_t)err2;913rd->derr[ch][2] = (int8_t)err3;914}915}916917static void StoreDiffusionErrors(VP8EncIterator* WEBP_RESTRICT const it,918const VP8ModeScore* WEBP_RESTRICT const rd) {919int ch;920for (ch = 0; ch <= 1; ++ch) {921int8_t* const top = it->top_derr[it->x][ch];922int8_t* const left = it->left_derr[ch];923left[0] = rd->derr[ch][0]; // restore err1924left[1] = 3 * rd->derr[ch][2] >> 2; // ... 3/4th of err3925top[0] = rd->derr[ch][1]; // ... err2926top[1] = rd->derr[ch][2] - left[1]; // ... 1/4th of err3.927}928}929930#undef C1931#undef C2932#undef DSHIFT933#undef DSCALE934935//------------------------------------------------------------------------------936937static int ReconstructUV(VP8EncIterator* WEBP_RESTRICT const it,938VP8ModeScore* WEBP_RESTRICT const rd,939uint8_t* WEBP_RESTRICT const yuv_out, int mode) {940const VP8Encoder* const enc = it->enc;941const uint8_t* const ref = it->yuv_p + VP8UVModeOffsets[mode];942const uint8_t* const src = it->yuv_in + U_OFF_ENC;943const VP8SegmentInfo* const dqm = &enc->dqm[it->mb->segment];944int nz = 0;945int n;946int16_t tmp[8][16];947948for (n = 0; n < 8; n += 2) {949VP8FTransform2(src + VP8ScanUV[n], ref + VP8ScanUV[n], tmp[n]);950}951if (it->top_derr != NULL) CorrectDCValues(it, &dqm->uv, tmp, rd);952953if (DO_TRELLIS_UV && it->do_trellis) {954int ch, x, y;955for (ch = 0, n = 0; ch <= 2; ch += 2) {956for (y = 0; y < 2; ++y) {957for (x = 0; x < 2; ++x, ++n) {958const int ctx = it->top_nz[4 + ch + x] + it->left_nz[4 + ch + y];959const int non_zero = TrellisQuantizeBlock(960enc, tmp[n], rd->uv_levels[n], ctx, TYPE_CHROMA_A, &dqm->uv,961dqm->lambda_trellis_uv);962it->top_nz[4 + ch + x] = it->left_nz[4 + ch + y] = non_zero;963nz |= non_zero << n;964}965}966}967} else {968for (n = 0; n < 8; n += 2) {969nz |= VP8EncQuantize2Blocks(tmp[n], rd->uv_levels[n], &dqm->uv) << n;970}971}972973for (n = 0; n < 8; n += 2) {974VP8ITransform(ref + VP8ScanUV[n], tmp[n], yuv_out + VP8ScanUV[n], 1);975}976return (nz << 16);977}978979//------------------------------------------------------------------------------980// RD-opt decision. Reconstruct each modes, evalue distortion and bit-cost.981// Pick the mode is lower RD-cost = Rate + lambda * Distortion.982983static void StoreMaxDelta(VP8SegmentInfo* const dqm, const int16_t DCs[16]) {984// We look at the first three AC coefficients to determine what is the average985// delta between each sub-4x4 block.986const int v0 = abs(DCs[1]);987const int v1 = abs(DCs[2]);988const int v2 = abs(DCs[4]);989int max_v = (v1 > v0) ? v1 : v0;990max_v = (v2 > max_v) ? v2 : max_v;991if (max_v > dqm->max_edge) dqm->max_edge = max_v;992}993994static void SwapModeScore(VP8ModeScore** a, VP8ModeScore** b) {995VP8ModeScore* const tmp = *a;996*a = *b;997*b = tmp;998}9991000static void SwapPtr(uint8_t** a, uint8_t** b) {1001uint8_t* const tmp = *a;1002*a = *b;1003*b = tmp;1004}10051006static void SwapOut(VP8EncIterator* const it) {1007SwapPtr(&it->yuv_out, &it->yuv_out2);1008}10091010static void PickBestIntra16(VP8EncIterator* WEBP_RESTRICT const it,1011VP8ModeScore* WEBP_RESTRICT rd) {1012const int kNumBlocks = 16;1013VP8SegmentInfo* const dqm = &it->enc->dqm[it->mb->segment];1014const int lambda = dqm->lambda_i16;1015const int tlambda = dqm->tlambda;1016const uint8_t* const src = it->yuv_in + Y_OFF_ENC;1017VP8ModeScore rd_tmp;1018VP8ModeScore* rd_cur = &rd_tmp;1019VP8ModeScore* rd_best = rd;1020int mode;1021int is_flat = IsFlatSource16(it->yuv_in + Y_OFF_ENC);10221023rd->mode_i16 = -1;1024for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1025uint8_t* const tmp_dst = it->yuv_out2 + Y_OFF_ENC; // scratch buffer1026rd_cur->mode_i16 = mode;10271028// Reconstruct1029rd_cur->nz = ReconstructIntra16(it, rd_cur, tmp_dst, mode);10301031// Measure RD-score1032rd_cur->D = VP8SSE16x16(src, tmp_dst);1033rd_cur->SD =1034tlambda ? MULT_8B(tlambda, VP8TDisto16x16(src, tmp_dst, kWeightY)) : 0;1035rd_cur->H = VP8FixedCostsI16[mode];1036rd_cur->R = VP8GetCostLuma16(it, rd_cur);1037if (is_flat) {1038// refine the first impression (which was in pixel space)1039is_flat = IsFlat(rd_cur->y_ac_levels[0], kNumBlocks, FLATNESS_LIMIT_I16);1040if (is_flat) {1041// Block is very flat. We put emphasis on the distortion being very low!1042rd_cur->D *= 2;1043rd_cur->SD *= 2;1044}1045}10461047// Since we always examine Intra16 first, we can overwrite *rd directly.1048SetRDScore(lambda, rd_cur);1049if (mode == 0 || rd_cur->score < rd_best->score) {1050SwapModeScore(&rd_cur, &rd_best);1051SwapOut(it);1052}1053}1054if (rd_best != rd) {1055memcpy(rd, rd_best, sizeof(*rd));1056}1057SetRDScore(dqm->lambda_mode, rd); // finalize score for mode decision.1058VP8SetIntra16Mode(it, rd->mode_i16);10591060// we have a blocky macroblock (only DCs are non-zero) with fairly high1061// distortion, record max delta so we can later adjust the minimal filtering1062// strength needed to smooth these blocks out.1063if ((rd->nz & 0x100ffff) == 0x1000000 && rd->D > dqm->min_disto) {1064StoreMaxDelta(dqm, rd->y_dc_levels);1065}1066}10671068//------------------------------------------------------------------------------10691070// return the cost array corresponding to the surrounding prediction modes.1071static const uint16_t* GetCostModeI4(VP8EncIterator* WEBP_RESTRICT const it,1072const uint8_t modes[16]) {1073const int preds_w = it->enc->preds_w;1074const int x = (it->i4 & 3), y = it->i4 >> 2;1075const int left = (x == 0) ? it->preds[y * preds_w - 1] : modes[it->i4 - 1];1076const int top = (y == 0) ? it->preds[-preds_w + x] : modes[it->i4 - 4];1077return VP8FixedCostsI4[top][left];1078}10791080static int PickBestIntra4(VP8EncIterator* WEBP_RESTRICT const it,1081VP8ModeScore* WEBP_RESTRICT const rd) {1082const VP8Encoder* const enc = it->enc;1083const VP8SegmentInfo* const dqm = &enc->dqm[it->mb->segment];1084const int lambda = dqm->lambda_i4;1085const int tlambda = dqm->tlambda;1086const uint8_t* const src0 = it->yuv_in + Y_OFF_ENC;1087uint8_t* const best_blocks = it->yuv_out2 + Y_OFF_ENC;1088int total_header_bits = 0;1089VP8ModeScore rd_best;10901091if (enc->max_i4_header_bits == 0) {1092return 0;1093}10941095InitScore(&rd_best);1096rd_best.H = 211; // '211' is the value of VP8BitCost(0, 145)1097SetRDScore(dqm->lambda_mode, &rd_best);1098VP8IteratorStartI4(it);1099do {1100const int kNumBlocks = 1;1101VP8ModeScore rd_i4;1102int mode;1103int best_mode = -1;1104const uint8_t* const src = src0 + VP8Scan[it->i4];1105const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);1106uint8_t* best_block = best_blocks + VP8Scan[it->i4];1107uint8_t* tmp_dst = it->yuv_p + I4TMP; // scratch buffer.11081109InitScore(&rd_i4);1110MakeIntra4Preds(it);1111for (mode = 0; mode < NUM_BMODES; ++mode) {1112VP8ModeScore rd_tmp;1113int16_t tmp_levels[16];11141115// Reconstruct1116rd_tmp.nz =1117ReconstructIntra4(it, tmp_levels, src, tmp_dst, mode) << it->i4;11181119// Compute RD-score1120rd_tmp.D = VP8SSE4x4(src, tmp_dst);1121rd_tmp.SD =1122tlambda ? MULT_8B(tlambda, VP8TDisto4x4(src, tmp_dst, kWeightY))1123: 0;1124rd_tmp.H = mode_costs[mode];11251126// Add flatness penalty, to avoid flat area to be mispredicted1127// by a complex mode.1128if (mode > 0 && IsFlat(tmp_levels, kNumBlocks, FLATNESS_LIMIT_I4)) {1129rd_tmp.R = FLATNESS_PENALTY * kNumBlocks;1130} else {1131rd_tmp.R = 0;1132}11331134// early-out check1135SetRDScore(lambda, &rd_tmp);1136if (best_mode >= 0 && rd_tmp.score >= rd_i4.score) continue;11371138// finish computing score1139rd_tmp.R += VP8GetCostLuma4(it, tmp_levels);1140SetRDScore(lambda, &rd_tmp);11411142if (best_mode < 0 || rd_tmp.score < rd_i4.score) {1143CopyScore(&rd_i4, &rd_tmp);1144best_mode = mode;1145SwapPtr(&tmp_dst, &best_block);1146memcpy(rd_best.y_ac_levels[it->i4], tmp_levels,1147sizeof(rd_best.y_ac_levels[it->i4]));1148}1149}1150SetRDScore(dqm->lambda_mode, &rd_i4);1151AddScore(&rd_best, &rd_i4);1152if (rd_best.score >= rd->score) {1153return 0;1154}1155total_header_bits += (int)rd_i4.H; // <- equal to mode_costs[best_mode];1156if (total_header_bits > enc->max_i4_header_bits) {1157return 0;1158}1159// Copy selected samples if not in the right place already.1160if (best_block != best_blocks + VP8Scan[it->i4]) {1161VP8Copy4x4(best_block, best_blocks + VP8Scan[it->i4]);1162}1163rd->modes_i4[it->i4] = best_mode;1164it->top_nz[it->i4 & 3] = it->left_nz[it->i4 >> 2] = (rd_i4.nz ? 1 : 0);1165} while (VP8IteratorRotateI4(it, best_blocks));11661167// finalize state1168CopyScore(rd, &rd_best);1169VP8SetIntra4Mode(it, rd->modes_i4);1170SwapOut(it);1171memcpy(rd->y_ac_levels, rd_best.y_ac_levels, sizeof(rd->y_ac_levels));1172return 1; // select intra4x4 over intra16x161173}11741175//------------------------------------------------------------------------------11761177static void PickBestUV(VP8EncIterator* WEBP_RESTRICT const it,1178VP8ModeScore* WEBP_RESTRICT const rd) {1179const int kNumBlocks = 8;1180const VP8SegmentInfo* const dqm = &it->enc->dqm[it->mb->segment];1181const int lambda = dqm->lambda_uv;1182const uint8_t* const src = it->yuv_in + U_OFF_ENC;1183uint8_t* tmp_dst = it->yuv_out2 + U_OFF_ENC; // scratch buffer1184uint8_t* dst0 = it->yuv_out + U_OFF_ENC;1185uint8_t* dst = dst0;1186VP8ModeScore rd_best;1187int mode;11881189rd->mode_uv = -1;1190InitScore(&rd_best);1191for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1192VP8ModeScore rd_uv;11931194// Reconstruct1195rd_uv.nz = ReconstructUV(it, &rd_uv, tmp_dst, mode);11961197// Compute RD-score1198rd_uv.D = VP8SSE16x8(src, tmp_dst);1199rd_uv.SD = 0; // not calling TDisto here: it tends to flatten areas.1200rd_uv.H = VP8FixedCostsUV[mode];1201rd_uv.R = VP8GetCostUV(it, &rd_uv);1202if (mode > 0 && IsFlat(rd_uv.uv_levels[0], kNumBlocks, FLATNESS_LIMIT_UV)) {1203rd_uv.R += FLATNESS_PENALTY * kNumBlocks;1204}12051206SetRDScore(lambda, &rd_uv);1207if (mode == 0 || rd_uv.score < rd_best.score) {1208CopyScore(&rd_best, &rd_uv);1209rd->mode_uv = mode;1210memcpy(rd->uv_levels, rd_uv.uv_levels, sizeof(rd->uv_levels));1211if (it->top_derr != NULL) {1212memcpy(rd->derr, rd_uv.derr, sizeof(rd_uv.derr));1213}1214SwapPtr(&dst, &tmp_dst);1215}1216}1217VP8SetIntraUVMode(it, rd->mode_uv);1218AddScore(rd, &rd_best);1219if (dst != dst0) { // copy 16x8 block if needed1220VP8Copy16x8(dst, dst0);1221}1222if (it->top_derr != NULL) { // store diffusion errors for next block1223StoreDiffusionErrors(it, rd);1224}1225}12261227//------------------------------------------------------------------------------1228// Final reconstruction and quantization.12291230static void SimpleQuantize(VP8EncIterator* WEBP_RESTRICT const it,1231VP8ModeScore* WEBP_RESTRICT const rd) {1232const VP8Encoder* const enc = it->enc;1233const int is_i16 = (it->mb->type == 1);1234int nz = 0;12351236if (is_i16) {1237nz = ReconstructIntra16(it, rd, it->yuv_out + Y_OFF_ENC, it->preds[0]);1238} else {1239VP8IteratorStartI4(it);1240do {1241const int mode =1242it->preds[(it->i4 & 3) + (it->i4 >> 2) * enc->preds_w];1243const uint8_t* const src = it->yuv_in + Y_OFF_ENC + VP8Scan[it->i4];1244uint8_t* const dst = it->yuv_out + Y_OFF_ENC + VP8Scan[it->i4];1245MakeIntra4Preds(it);1246nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4],1247src, dst, mode) << it->i4;1248} while (VP8IteratorRotateI4(it, it->yuv_out + Y_OFF_ENC));1249}12501251nz |= ReconstructUV(it, rd, it->yuv_out + U_OFF_ENC, it->mb->uv_mode);1252rd->nz = nz;1253}12541255// Refine intra16/intra4 sub-modes based on distortion only (not rate).1256static void RefineUsingDistortion(VP8EncIterator* WEBP_RESTRICT const it,1257int try_both_modes, int refine_uv_mode,1258VP8ModeScore* WEBP_RESTRICT const rd) {1259score_t best_score = MAX_COST;1260int nz = 0;1261int mode;1262int is_i16 = try_both_modes || (it->mb->type == 1);12631264const VP8SegmentInfo* const dqm = &it->enc->dqm[it->mb->segment];1265// Some empiric constants, of approximate order of magnitude.1266const int lambda_d_i16 = 106;1267const int lambda_d_i4 = 11;1268const int lambda_d_uv = 120;1269score_t score_i4 = dqm->i4_penalty;1270score_t i4_bit_sum = 0;1271const score_t bit_limit = try_both_modes ? it->enc->mb_header_limit1272: MAX_COST; // no early-out allowed12731274if (is_i16) { // First, evaluate Intra16 distortion1275int best_mode = -1;1276const uint8_t* const src = it->yuv_in + Y_OFF_ENC;1277for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1278const uint8_t* const ref = it->yuv_p + VP8I16ModeOffsets[mode];1279const score_t score = (score_t)VP8SSE16x16(src, ref) * RD_DISTO_MULT1280+ VP8FixedCostsI16[mode] * lambda_d_i16;1281if (mode > 0 && VP8FixedCostsI16[mode] > bit_limit) {1282continue;1283}12841285if (score < best_score) {1286best_mode = mode;1287best_score = score;1288}1289}1290if (it->x == 0 || it->y == 0) {1291// avoid starting a checkerboard resonance from the border. See bug #432.1292if (IsFlatSource16(src)) {1293best_mode = (it->x == 0) ? 0 : 2;1294try_both_modes = 0; // stick to i161295}1296}1297VP8SetIntra16Mode(it, best_mode);1298// we'll reconstruct later, if i16 mode actually gets selected1299}13001301// Next, evaluate Intra41302if (try_both_modes || !is_i16) {1303// We don't evaluate the rate here, but just account for it through a1304// constant penalty (i4 mode usually needs more bits compared to i16).1305is_i16 = 0;1306VP8IteratorStartI4(it);1307do {1308int best_i4_mode = -1;1309score_t best_i4_score = MAX_COST;1310const uint8_t* const src = it->yuv_in + Y_OFF_ENC + VP8Scan[it->i4];1311const uint16_t* const mode_costs = GetCostModeI4(it, rd->modes_i4);13121313MakeIntra4Preds(it);1314for (mode = 0; mode < NUM_BMODES; ++mode) {1315const uint8_t* const ref = it->yuv_p + VP8I4ModeOffsets[mode];1316const score_t score = VP8SSE4x4(src, ref) * RD_DISTO_MULT1317+ mode_costs[mode] * lambda_d_i4;1318if (score < best_i4_score) {1319best_i4_mode = mode;1320best_i4_score = score;1321}1322}1323i4_bit_sum += mode_costs[best_i4_mode];1324rd->modes_i4[it->i4] = best_i4_mode;1325score_i4 += best_i4_score;1326if (score_i4 >= best_score || i4_bit_sum > bit_limit) {1327// Intra4 won't be better than Intra16. Bail out and pick Intra16.1328is_i16 = 1;1329break;1330} else { // reconstruct partial block inside yuv_out2 buffer1331uint8_t* const tmp_dst = it->yuv_out2 + Y_OFF_ENC + VP8Scan[it->i4];1332nz |= ReconstructIntra4(it, rd->y_ac_levels[it->i4],1333src, tmp_dst, best_i4_mode) << it->i4;1334}1335} while (VP8IteratorRotateI4(it, it->yuv_out2 + Y_OFF_ENC));1336}13371338// Final reconstruction, depending on which mode is selected.1339if (!is_i16) {1340VP8SetIntra4Mode(it, rd->modes_i4);1341SwapOut(it);1342best_score = score_i4;1343} else {1344nz = ReconstructIntra16(it, rd, it->yuv_out + Y_OFF_ENC, it->preds[0]);1345}13461347// ... and UV!1348if (refine_uv_mode) {1349int best_mode = -1;1350score_t best_uv_score = MAX_COST;1351const uint8_t* const src = it->yuv_in + U_OFF_ENC;1352for (mode = 0; mode < NUM_PRED_MODES; ++mode) {1353const uint8_t* const ref = it->yuv_p + VP8UVModeOffsets[mode];1354const score_t score = VP8SSE16x8(src, ref) * RD_DISTO_MULT1355+ VP8FixedCostsUV[mode] * lambda_d_uv;1356if (score < best_uv_score) {1357best_mode = mode;1358best_uv_score = score;1359}1360}1361VP8SetIntraUVMode(it, best_mode);1362}1363nz |= ReconstructUV(it, rd, it->yuv_out + U_OFF_ENC, it->mb->uv_mode);13641365rd->nz = nz;1366rd->score = best_score;1367}13681369//------------------------------------------------------------------------------1370// Entry point13711372int VP8Decimate(VP8EncIterator* WEBP_RESTRICT const it,1373VP8ModeScore* WEBP_RESTRICT const rd,1374VP8RDLevel rd_opt) {1375int is_skipped;1376const int method = it->enc->method;13771378InitScore(rd);13791380// We can perform predictions for Luma16x16 and Chroma8x8 already.1381// Luma4x4 predictions needs to be done as-we-go.1382VP8MakeLuma16Preds(it);1383VP8MakeChroma8Preds(it);13841385if (rd_opt > RD_OPT_NONE) {1386it->do_trellis = (rd_opt >= RD_OPT_TRELLIS_ALL);1387PickBestIntra16(it, rd);1388if (method >= 2) {1389PickBestIntra4(it, rd);1390}1391PickBestUV(it, rd);1392if (rd_opt == RD_OPT_TRELLIS) { // finish off with trellis-optim now1393it->do_trellis = 1;1394SimpleQuantize(it, rd);1395}1396} else {1397// At this point we have heuristically decided intra16 / intra4.1398// For method >= 2, pick the best intra4/intra16 based on SSE (~tad slower).1399// For method <= 1, we don't re-examine the decision but just go ahead with1400// quantization/reconstruction.1401RefineUsingDistortion(it, (method >= 2), (method >= 1), rd);1402}1403is_skipped = (rd->nz == 0);1404VP8SetSkip(it, is_skipped);1405return is_skipped;1406}140714081409