Path: blob/master/thirdparty/libwebp/src/enc/analysis_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// Macroblock analysis10//11// Author: Skal ([email protected])1213#include <stdlib.h>14#include <string.h>15#include <assert.h>1617#include "src/enc/vp8i_enc.h"18#include "src/enc/cost_enc.h"19#include "src/utils/utils.h"2021#define MAX_ITERS_K_MEANS 62223//------------------------------------------------------------------------------24// Smooth the segment map by replacing isolated block by the majority of its25// neighbours.2627static void SmoothSegmentMap(VP8Encoder* const enc) {28int n, x, y;29const int w = enc->mb_w_;30const int h = enc->mb_h_;31const int majority_cnt_3_x_3_grid = 5;32uint8_t* const tmp = (uint8_t*)WebPSafeMalloc(w * h, sizeof(*tmp));33assert((uint64_t)(w * h) == (uint64_t)w * h); // no overflow, as per spec3435if (tmp == NULL) return;36for (y = 1; y < h - 1; ++y) {37for (x = 1; x < w - 1; ++x) {38int cnt[NUM_MB_SEGMENTS] = { 0 };39const VP8MBInfo* const mb = &enc->mb_info_[x + w * y];40int majority_seg = mb->segment_;41// Check the 8 neighbouring segment values.42cnt[mb[-w - 1].segment_]++; // top-left43cnt[mb[-w + 0].segment_]++; // top44cnt[mb[-w + 1].segment_]++; // top-right45cnt[mb[ - 1].segment_]++; // left46cnt[mb[ + 1].segment_]++; // right47cnt[mb[ w - 1].segment_]++; // bottom-left48cnt[mb[ w + 0].segment_]++; // bottom49cnt[mb[ w + 1].segment_]++; // bottom-right50for (n = 0; n < NUM_MB_SEGMENTS; ++n) {51if (cnt[n] >= majority_cnt_3_x_3_grid) {52majority_seg = n;53break;54}55}56tmp[x + y * w] = majority_seg;57}58}59for (y = 1; y < h - 1; ++y) {60for (x = 1; x < w - 1; ++x) {61VP8MBInfo* const mb = &enc->mb_info_[x + w * y];62mb->segment_ = tmp[x + y * w];63}64}65WebPSafeFree(tmp);66}6768//------------------------------------------------------------------------------69// set segment susceptibility alpha_ / beta_7071static WEBP_INLINE int clip(int v, int m, int M) {72return (v < m) ? m : (v > M) ? M : v;73}7475static void SetSegmentAlphas(VP8Encoder* const enc,76const int centers[NUM_MB_SEGMENTS],77int mid) {78const int nb = enc->segment_hdr_.num_segments_;79int min = centers[0], max = centers[0];80int n;8182if (nb > 1) {83for (n = 0; n < nb; ++n) {84if (min > centers[n]) min = centers[n];85if (max < centers[n]) max = centers[n];86}87}88if (max == min) max = min + 1;89assert(mid <= max && mid >= min);90for (n = 0; n < nb; ++n) {91const int alpha = 255 * (centers[n] - mid) / (max - min);92const int beta = 255 * (centers[n] - min) / (max - min);93enc->dqm_[n].alpha_ = clip(alpha, -127, 127);94enc->dqm_[n].beta_ = clip(beta, 0, 255);95}96}9798//------------------------------------------------------------------------------99// Compute susceptibility based on DCT-coeff histograms:100// the higher, the "easier" the macroblock is to compress.101102#define MAX_ALPHA 255 // 8b of precision for susceptibilities.103#define ALPHA_SCALE (2 * MAX_ALPHA) // scaling factor for alpha.104#define DEFAULT_ALPHA (-1)105#define IS_BETTER_ALPHA(alpha, best_alpha) ((alpha) > (best_alpha))106107static int FinalAlphaValue(int alpha) {108alpha = MAX_ALPHA - alpha;109return clip(alpha, 0, MAX_ALPHA);110}111112static int GetAlpha(const VP8Histogram* const histo) {113// 'alpha' will later be clipped to [0..MAX_ALPHA] range, clamping outer114// values which happen to be mostly noise. This leaves the maximum precision115// for handling the useful small values which contribute most.116const int max_value = histo->max_value;117const int last_non_zero = histo->last_non_zero;118const int alpha =119(max_value > 1) ? ALPHA_SCALE * last_non_zero / max_value : 0;120return alpha;121}122123static void InitHistogram(VP8Histogram* const histo) {124histo->max_value = 0;125histo->last_non_zero = 1;126}127128//------------------------------------------------------------------------------129// Simplified k-Means, to assign Nb segments based on alpha-histogram130131static void AssignSegments(VP8Encoder* const enc,132const int alphas[MAX_ALPHA + 1]) {133// 'num_segments_' is previously validated and <= NUM_MB_SEGMENTS, but an134// explicit check is needed to avoid spurious warning about 'n + 1' exceeding135// array bounds of 'centers' with some compilers (noticed with gcc-4.9).136const int nb = (enc->segment_hdr_.num_segments_ < NUM_MB_SEGMENTS) ?137enc->segment_hdr_.num_segments_ : NUM_MB_SEGMENTS;138int centers[NUM_MB_SEGMENTS];139int weighted_average = 0;140int map[MAX_ALPHA + 1];141int a, n, k;142int min_a = 0, max_a = MAX_ALPHA, range_a;143// 'int' type is ok for histo, and won't overflow144int accum[NUM_MB_SEGMENTS], dist_accum[NUM_MB_SEGMENTS];145146assert(nb >= 1);147assert(nb <= NUM_MB_SEGMENTS);148149// bracket the input150for (n = 0; n <= MAX_ALPHA && alphas[n] == 0; ++n) {}151min_a = n;152for (n = MAX_ALPHA; n > min_a && alphas[n] == 0; --n) {}153max_a = n;154range_a = max_a - min_a;155156// Spread initial centers evenly157for (k = 0, n = 1; k < nb; ++k, n += 2) {158assert(n < 2 * nb);159centers[k] = min_a + (n * range_a) / (2 * nb);160}161162for (k = 0; k < MAX_ITERS_K_MEANS; ++k) { // few iters are enough163int total_weight;164int displaced;165// Reset stats166for (n = 0; n < nb; ++n) {167accum[n] = 0;168dist_accum[n] = 0;169}170// Assign nearest center for each 'a'171n = 0; // track the nearest center for current 'a'172for (a = min_a; a <= max_a; ++a) {173if (alphas[a]) {174while (n + 1 < nb && abs(a - centers[n + 1]) < abs(a - centers[n])) {175n++;176}177map[a] = n;178// accumulate contribution into best centroid179dist_accum[n] += a * alphas[a];180accum[n] += alphas[a];181}182}183// All point are classified. Move the centroids to the184// center of their respective cloud.185displaced = 0;186weighted_average = 0;187total_weight = 0;188for (n = 0; n < nb; ++n) {189if (accum[n]) {190const int new_center = (dist_accum[n] + accum[n] / 2) / accum[n];191displaced += abs(centers[n] - new_center);192centers[n] = new_center;193weighted_average += new_center * accum[n];194total_weight += accum[n];195}196}197weighted_average = (weighted_average + total_weight / 2) / total_weight;198if (displaced < 5) break; // no need to keep on looping...199}200201// Map each original value to the closest centroid202for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {203VP8MBInfo* const mb = &enc->mb_info_[n];204const int alpha = mb->alpha_;205mb->segment_ = map[alpha];206mb->alpha_ = centers[map[alpha]]; // for the record.207}208209if (nb > 1) {210const int smooth = (enc->config_->preprocessing & 1);211if (smooth) SmoothSegmentMap(enc);212}213214SetSegmentAlphas(enc, centers, weighted_average); // pick some alphas.215}216217//------------------------------------------------------------------------------218// Macroblock analysis: collect histogram for each mode, deduce the maximal219// susceptibility and set best modes for this macroblock.220// Segment assignment is done later.221222// Number of modes to inspect for alpha_ evaluation. We don't need to test all223// the possible modes during the analysis phase: we risk falling into a local224// optimum, or be subject to boundary effect225#define MAX_INTRA16_MODE 2226#define MAX_INTRA4_MODE 2227#define MAX_UV_MODE 2228229static int MBAnalyzeBestIntra16Mode(VP8EncIterator* const it) {230const int max_mode = MAX_INTRA16_MODE;231int mode;232int best_alpha = DEFAULT_ALPHA;233int best_mode = 0;234235VP8MakeLuma16Preds(it);236for (mode = 0; mode < max_mode; ++mode) {237VP8Histogram histo;238int alpha;239240InitHistogram(&histo);241VP8CollectHistogram(it->yuv_in_ + Y_OFF_ENC,242it->yuv_p_ + VP8I16ModeOffsets[mode],2430, 16, &histo);244alpha = GetAlpha(&histo);245if (IS_BETTER_ALPHA(alpha, best_alpha)) {246best_alpha = alpha;247best_mode = mode;248}249}250VP8SetIntra16Mode(it, best_mode);251return best_alpha;252}253254static int FastMBAnalyze(VP8EncIterator* const it) {255// Empirical cut-off value, should be around 16 (~=block size). We use the256// [8-17] range and favor intra4 at high quality, intra16 for low quality.257const int q = (int)it->enc_->config_->quality;258const uint32_t kThreshold = 8 + (17 - 8) * q / 100;259int k;260uint32_t dc[16], m, m2;261for (k = 0; k < 16; k += 4) {262VP8Mean16x4(it->yuv_in_ + Y_OFF_ENC + k * BPS, &dc[k]);263}264for (m = 0, m2 = 0, k = 0; k < 16; ++k) {265m += dc[k];266m2 += dc[k] * dc[k];267}268if (kThreshold * m2 < m * m) {269VP8SetIntra16Mode(it, 0); // DC16270} else {271const uint8_t modes[16] = { 0 }; // DC4272VP8SetIntra4Mode(it, modes);273}274return 0;275}276277static int MBAnalyzeBestUVMode(VP8EncIterator* const it) {278int best_alpha = DEFAULT_ALPHA;279int smallest_alpha = 0;280int best_mode = 0;281const int max_mode = MAX_UV_MODE;282int mode;283284VP8MakeChroma8Preds(it);285for (mode = 0; mode < max_mode; ++mode) {286VP8Histogram histo;287int alpha;288InitHistogram(&histo);289VP8CollectHistogram(it->yuv_in_ + U_OFF_ENC,290it->yuv_p_ + VP8UVModeOffsets[mode],29116, 16 + 4 + 4, &histo);292alpha = GetAlpha(&histo);293if (IS_BETTER_ALPHA(alpha, best_alpha)) {294best_alpha = alpha;295}296// The best prediction mode tends to be the one with the smallest alpha.297if (mode == 0 || alpha < smallest_alpha) {298smallest_alpha = alpha;299best_mode = mode;300}301}302VP8SetIntraUVMode(it, best_mode);303return best_alpha;304}305306static void MBAnalyze(VP8EncIterator* const it,307int alphas[MAX_ALPHA + 1],308int* const alpha, int* const uv_alpha) {309const VP8Encoder* const enc = it->enc_;310int best_alpha, best_uv_alpha;311312VP8SetIntra16Mode(it, 0); // default: Intra16, DC_PRED313VP8SetSkip(it, 0); // not skipped314VP8SetSegment(it, 0); // default segment, spec-wise.315316if (enc->method_ <= 1) {317best_alpha = FastMBAnalyze(it);318} else {319best_alpha = MBAnalyzeBestIntra16Mode(it);320}321best_uv_alpha = MBAnalyzeBestUVMode(it);322323// Final susceptibility mix324best_alpha = (3 * best_alpha + best_uv_alpha + 2) >> 2;325best_alpha = FinalAlphaValue(best_alpha);326alphas[best_alpha]++;327it->mb_->alpha_ = best_alpha; // for later remapping.328329// Accumulate for later complexity analysis.330*alpha += best_alpha; // mixed susceptibility (not just luma)331*uv_alpha += best_uv_alpha;332}333334static void DefaultMBInfo(VP8MBInfo* const mb) {335mb->type_ = 1; // I16x16336mb->uv_mode_ = 0;337mb->skip_ = 0; // not skipped338mb->segment_ = 0; // default segment339mb->alpha_ = 0;340}341342//------------------------------------------------------------------------------343// Main analysis loop:344// Collect all susceptibilities for each macroblock and record their345// distribution in alphas[]. Segments is assigned a-posteriori, based on346// this histogram.347// We also pick an intra16 prediction mode, which shouldn't be considered348// final except for fast-encode settings. We can also pick some intra4 modes349// and decide intra4/intra16, but that's usually almost always a bad choice at350// this stage.351352static void ResetAllMBInfo(VP8Encoder* const enc) {353int n;354for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {355DefaultMBInfo(&enc->mb_info_[n]);356}357// Default susceptibilities.358enc->dqm_[0].alpha_ = 0;359enc->dqm_[0].beta_ = 0;360// Note: we can't compute this alpha_ / uv_alpha_ -> set to default value.361enc->alpha_ = 0;362enc->uv_alpha_ = 0;363WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);364}365366// struct used to collect job result367typedef struct {368WebPWorker worker;369int alphas[MAX_ALPHA + 1];370int alpha, uv_alpha;371VP8EncIterator it;372int delta_progress;373} SegmentJob;374375// main work call376static int DoSegmentsJob(void* arg1, void* arg2) {377SegmentJob* const job = (SegmentJob*)arg1;378VP8EncIterator* const it = (VP8EncIterator*)arg2;379int ok = 1;380if (!VP8IteratorIsDone(it)) {381uint8_t tmp[32 + WEBP_ALIGN_CST];382uint8_t* const scratch = (uint8_t*)WEBP_ALIGN(tmp);383do {384// Let's pretend we have perfect lossless reconstruction.385VP8IteratorImport(it, scratch);386MBAnalyze(it, job->alphas, &job->alpha, &job->uv_alpha);387ok = VP8IteratorProgress(it, job->delta_progress);388} while (ok && VP8IteratorNext(it));389}390return ok;391}392393#ifdef WEBP_USE_THREAD394static void MergeJobs(const SegmentJob* const src, SegmentJob* const dst) {395int i;396for (i = 0; i <= MAX_ALPHA; ++i) dst->alphas[i] += src->alphas[i];397dst->alpha += src->alpha;398dst->uv_alpha += src->uv_alpha;399}400#endif401402// initialize the job struct with some tasks to perform403static void InitSegmentJob(VP8Encoder* const enc, SegmentJob* const job,404int start_row, int end_row) {405WebPGetWorkerInterface()->Init(&job->worker);406job->worker.data1 = job;407job->worker.data2 = &job->it;408job->worker.hook = DoSegmentsJob;409VP8IteratorInit(enc, &job->it);410VP8IteratorSetRow(&job->it, start_row);411VP8IteratorSetCountDown(&job->it, (end_row - start_row) * enc->mb_w_);412memset(job->alphas, 0, sizeof(job->alphas));413job->alpha = 0;414job->uv_alpha = 0;415// only one of both jobs can record the progress, since we don't416// expect the user's hook to be multi-thread safe417job->delta_progress = (start_row == 0) ? 20 : 0;418}419420// main entry point421int VP8EncAnalyze(VP8Encoder* const enc) {422int ok = 1;423const int do_segments =424enc->config_->emulate_jpeg_size || // We need the complexity evaluation.425(enc->segment_hdr_.num_segments_ > 1) ||426(enc->method_ <= 1); // for method 0 - 1, we need preds_[] to be filled.427if (do_segments) {428const int last_row = enc->mb_h_;429const int total_mb = last_row * enc->mb_w_;430#ifdef WEBP_USE_THREAD431// We give a little more than a half work to the main thread.432const int split_row = (9 * last_row + 15) >> 4;433const int kMinSplitRow = 2; // minimal rows needed for mt to be worth it434const int do_mt = (enc->thread_level_ > 0) && (split_row >= kMinSplitRow);435#else436const int do_mt = 0;437#endif438const WebPWorkerInterface* const worker_interface =439WebPGetWorkerInterface();440SegmentJob main_job;441if (do_mt) {442#ifdef WEBP_USE_THREAD443SegmentJob side_job;444// Note the use of '&' instead of '&&' because we must call the functions445// no matter what.446InitSegmentJob(enc, &main_job, 0, split_row);447InitSegmentJob(enc, &side_job, split_row, last_row);448// we don't need to call Reset() on main_job.worker, since we're calling449// WebPWorkerExecute() on it450ok &= worker_interface->Reset(&side_job.worker);451// launch the two jobs in parallel452if (ok) {453worker_interface->Launch(&side_job.worker);454worker_interface->Execute(&main_job.worker);455ok &= worker_interface->Sync(&side_job.worker);456ok &= worker_interface->Sync(&main_job.worker);457}458worker_interface->End(&side_job.worker);459if (ok) MergeJobs(&side_job, &main_job); // merge results together460#endif // WEBP_USE_THREAD461} else {462// Even for single-thread case, we use the generic Worker tools.463InitSegmentJob(enc, &main_job, 0, last_row);464worker_interface->Execute(&main_job.worker);465ok &= worker_interface->Sync(&main_job.worker);466}467worker_interface->End(&main_job.worker);468if (ok) {469enc->alpha_ = main_job.alpha / total_mb;470enc->uv_alpha_ = main_job.uv_alpha / total_mb;471AssignSegments(enc, main_job.alphas);472}473} else { // Use only one default segment.474ResetAllMBInfo(enc);475}476if (!ok) {477return WebPEncodingSetError(enc->pic_,478VP8_ENC_ERROR_OUT_OF_MEMORY); // imprecise479}480return ok;481}482483484485