Path: blob/master/3rdparty/libwebp/src/enc/analysis_enc.c
16350 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}127128static void MergeHistograms(const VP8Histogram* const in,129VP8Histogram* const out) {130if (in->max_value > out->max_value) {131out->max_value = in->max_value;132}133if (in->last_non_zero > out->last_non_zero) {134out->last_non_zero = in->last_non_zero;135}136}137138//------------------------------------------------------------------------------139// Simplified k-Means, to assign Nb segments based on alpha-histogram140141static void AssignSegments(VP8Encoder* const enc,142const int alphas[MAX_ALPHA + 1]) {143// 'num_segments_' is previously validated and <= NUM_MB_SEGMENTS, but an144// explicit check is needed to avoid spurious warning about 'n + 1' exceeding145// array bounds of 'centers' with some compilers (noticed with gcc-4.9).146const int nb = (enc->segment_hdr_.num_segments_ < NUM_MB_SEGMENTS) ?147enc->segment_hdr_.num_segments_ : NUM_MB_SEGMENTS;148int centers[NUM_MB_SEGMENTS];149int weighted_average = 0;150int map[MAX_ALPHA + 1];151int a, n, k;152int min_a = 0, max_a = MAX_ALPHA, range_a;153// 'int' type is ok for histo, and won't overflow154int accum[NUM_MB_SEGMENTS], dist_accum[NUM_MB_SEGMENTS];155156assert(nb >= 1);157assert(nb <= NUM_MB_SEGMENTS);158159// bracket the input160for (n = 0; n <= MAX_ALPHA && alphas[n] == 0; ++n) {}161min_a = n;162for (n = MAX_ALPHA; n > min_a && alphas[n] == 0; --n) {}163max_a = n;164range_a = max_a - min_a;165166// Spread initial centers evenly167for (k = 0, n = 1; k < nb; ++k, n += 2) {168assert(n < 2 * nb);169centers[k] = min_a + (n * range_a) / (2 * nb);170}171172for (k = 0; k < MAX_ITERS_K_MEANS; ++k) { // few iters are enough173int total_weight;174int displaced;175// Reset stats176for (n = 0; n < nb; ++n) {177accum[n] = 0;178dist_accum[n] = 0;179}180// Assign nearest center for each 'a'181n = 0; // track the nearest center for current 'a'182for (a = min_a; a <= max_a; ++a) {183if (alphas[a]) {184while (n + 1 < nb && abs(a - centers[n + 1]) < abs(a - centers[n])) {185n++;186}187map[a] = n;188// accumulate contribution into best centroid189dist_accum[n] += a * alphas[a];190accum[n] += alphas[a];191}192}193// All point are classified. Move the centroids to the194// center of their respective cloud.195displaced = 0;196weighted_average = 0;197total_weight = 0;198for (n = 0; n < nb; ++n) {199if (accum[n]) {200const int new_center = (dist_accum[n] + accum[n] / 2) / accum[n];201displaced += abs(centers[n] - new_center);202centers[n] = new_center;203weighted_average += new_center * accum[n];204total_weight += accum[n];205}206}207weighted_average = (weighted_average + total_weight / 2) / total_weight;208if (displaced < 5) break; // no need to keep on looping...209}210211// Map each original value to the closest centroid212for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {213VP8MBInfo* const mb = &enc->mb_info_[n];214const int alpha = mb->alpha_;215mb->segment_ = map[alpha];216mb->alpha_ = centers[map[alpha]]; // for the record.217}218219if (nb > 1) {220const int smooth = (enc->config_->preprocessing & 1);221if (smooth) SmoothSegmentMap(enc);222}223224SetSegmentAlphas(enc, centers, weighted_average); // pick some alphas.225}226227//------------------------------------------------------------------------------228// Macroblock analysis: collect histogram for each mode, deduce the maximal229// susceptibility and set best modes for this macroblock.230// Segment assignment is done later.231232// Number of modes to inspect for alpha_ evaluation. We don't need to test all233// the possible modes during the analysis phase: we risk falling into a local234// optimum, or be subject to boundary effect235#define MAX_INTRA16_MODE 2236#define MAX_INTRA4_MODE 2237#define MAX_UV_MODE 2238239static int MBAnalyzeBestIntra16Mode(VP8EncIterator* const it) {240const int max_mode = MAX_INTRA16_MODE;241int mode;242int best_alpha = DEFAULT_ALPHA;243int best_mode = 0;244245VP8MakeLuma16Preds(it);246for (mode = 0; mode < max_mode; ++mode) {247VP8Histogram histo;248int alpha;249250InitHistogram(&histo);251VP8CollectHistogram(it->yuv_in_ + Y_OFF_ENC,252it->yuv_p_ + VP8I16ModeOffsets[mode],2530, 16, &histo);254alpha = GetAlpha(&histo);255if (IS_BETTER_ALPHA(alpha, best_alpha)) {256best_alpha = alpha;257best_mode = mode;258}259}260VP8SetIntra16Mode(it, best_mode);261return best_alpha;262}263264static int FastMBAnalyze(VP8EncIterator* const it) {265// Empirical cut-off value, should be around 16 (~=block size). We use the266// [8-17] range and favor intra4 at high quality, intra16 for low quality.267const int q = (int)it->enc_->config_->quality;268const uint32_t kThreshold = 8 + (17 - 8) * q / 100;269int k;270uint32_t dc[16], m, m2;271for (k = 0; k < 16; k += 4) {272VP8Mean16x4(it->yuv_in_ + Y_OFF_ENC + k * BPS, &dc[k]);273}274for (m = 0, m2 = 0, k = 0; k < 16; ++k) {275m += dc[k];276m2 += dc[k] * dc[k];277}278if (kThreshold * m2 < m * m) {279VP8SetIntra16Mode(it, 0); // DC16280} else {281const uint8_t modes[16] = { 0 }; // DC4282VP8SetIntra4Mode(it, modes);283}284return 0;285}286287static int MBAnalyzeBestIntra4Mode(VP8EncIterator* const it,288int best_alpha) {289uint8_t modes[16];290const int max_mode = MAX_INTRA4_MODE;291int i4_alpha;292VP8Histogram total_histo;293int cur_histo = 0;294InitHistogram(&total_histo);295296VP8IteratorStartI4(it);297do {298int mode;299int best_mode_alpha = DEFAULT_ALPHA;300VP8Histogram histos[2];301const uint8_t* const src = it->yuv_in_ + Y_OFF_ENC + VP8Scan[it->i4_];302303VP8MakeIntra4Preds(it);304for (mode = 0; mode < max_mode; ++mode) {305int alpha;306307InitHistogram(&histos[cur_histo]);308VP8CollectHistogram(src, it->yuv_p_ + VP8I4ModeOffsets[mode],3090, 1, &histos[cur_histo]);310alpha = GetAlpha(&histos[cur_histo]);311if (IS_BETTER_ALPHA(alpha, best_mode_alpha)) {312best_mode_alpha = alpha;313modes[it->i4_] = mode;314cur_histo ^= 1; // keep track of best histo so far.315}316}317// accumulate best histogram318MergeHistograms(&histos[cur_histo ^ 1], &total_histo);319// Note: we reuse the original samples for predictors320} while (VP8IteratorRotateI4(it, it->yuv_in_ + Y_OFF_ENC));321322i4_alpha = GetAlpha(&total_histo);323if (IS_BETTER_ALPHA(i4_alpha, best_alpha)) {324VP8SetIntra4Mode(it, modes);325best_alpha = i4_alpha;326}327return best_alpha;328}329330static int MBAnalyzeBestUVMode(VP8EncIterator* const it) {331int best_alpha = DEFAULT_ALPHA;332int smallest_alpha = 0;333int best_mode = 0;334const int max_mode = MAX_UV_MODE;335int mode;336337VP8MakeChroma8Preds(it);338for (mode = 0; mode < max_mode; ++mode) {339VP8Histogram histo;340int alpha;341InitHistogram(&histo);342VP8CollectHistogram(it->yuv_in_ + U_OFF_ENC,343it->yuv_p_ + VP8UVModeOffsets[mode],34416, 16 + 4 + 4, &histo);345alpha = GetAlpha(&histo);346if (IS_BETTER_ALPHA(alpha, best_alpha)) {347best_alpha = alpha;348}349// The best prediction mode tends to be the one with the smallest alpha.350if (mode == 0 || alpha < smallest_alpha) {351smallest_alpha = alpha;352best_mode = mode;353}354}355VP8SetIntraUVMode(it, best_mode);356return best_alpha;357}358359static void MBAnalyze(VP8EncIterator* const it,360int alphas[MAX_ALPHA + 1],361int* const alpha, int* const uv_alpha) {362const VP8Encoder* const enc = it->enc_;363int best_alpha, best_uv_alpha;364365VP8SetIntra16Mode(it, 0); // default: Intra16, DC_PRED366VP8SetSkip(it, 0); // not skipped367VP8SetSegment(it, 0); // default segment, spec-wise.368369if (enc->method_ <= 1) {370best_alpha = FastMBAnalyze(it);371} else {372best_alpha = MBAnalyzeBestIntra16Mode(it);373if (enc->method_ >= 5) {374// We go and make a fast decision for intra4/intra16.375// It's usually not a good and definitive pick, but helps seeding the376// stats about level bit-cost.377// TODO(skal): improve criterion.378best_alpha = MBAnalyzeBestIntra4Mode(it, best_alpha);379}380}381best_uv_alpha = MBAnalyzeBestUVMode(it);382383// Final susceptibility mix384best_alpha = (3 * best_alpha + best_uv_alpha + 2) >> 2;385best_alpha = FinalAlphaValue(best_alpha);386alphas[best_alpha]++;387it->mb_->alpha_ = best_alpha; // for later remapping.388389// Accumulate for later complexity analysis.390*alpha += best_alpha; // mixed susceptibility (not just luma)391*uv_alpha += best_uv_alpha;392}393394static void DefaultMBInfo(VP8MBInfo* const mb) {395mb->type_ = 1; // I16x16396mb->uv_mode_ = 0;397mb->skip_ = 0; // not skipped398mb->segment_ = 0; // default segment399mb->alpha_ = 0;400}401402//------------------------------------------------------------------------------403// Main analysis loop:404// Collect all susceptibilities for each macroblock and record their405// distribution in alphas[]. Segments is assigned a-posteriori, based on406// this histogram.407// We also pick an intra16 prediction mode, which shouldn't be considered408// final except for fast-encode settings. We can also pick some intra4 modes409// and decide intra4/intra16, but that's usually almost always a bad choice at410// this stage.411412static void ResetAllMBInfo(VP8Encoder* const enc) {413int n;414for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {415DefaultMBInfo(&enc->mb_info_[n]);416}417// Default susceptibilities.418enc->dqm_[0].alpha_ = 0;419enc->dqm_[0].beta_ = 0;420// Note: we can't compute this alpha_ / uv_alpha_ -> set to default value.421enc->alpha_ = 0;422enc->uv_alpha_ = 0;423WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);424}425426// struct used to collect job result427typedef struct {428WebPWorker worker;429int alphas[MAX_ALPHA + 1];430int alpha, uv_alpha;431VP8EncIterator it;432int delta_progress;433} SegmentJob;434435// main work call436static int DoSegmentsJob(void* arg1, void* arg2) {437SegmentJob* const job = (SegmentJob*)arg1;438VP8EncIterator* const it = (VP8EncIterator*)arg2;439int ok = 1;440if (!VP8IteratorIsDone(it)) {441uint8_t tmp[32 + WEBP_ALIGN_CST];442uint8_t* const scratch = (uint8_t*)WEBP_ALIGN(tmp);443do {444// Let's pretend we have perfect lossless reconstruction.445VP8IteratorImport(it, scratch);446MBAnalyze(it, job->alphas, &job->alpha, &job->uv_alpha);447ok = VP8IteratorProgress(it, job->delta_progress);448} while (ok && VP8IteratorNext(it));449}450return ok;451}452453static void MergeJobs(const SegmentJob* const src, SegmentJob* const dst) {454int i;455for (i = 0; i <= MAX_ALPHA; ++i) dst->alphas[i] += src->alphas[i];456dst->alpha += src->alpha;457dst->uv_alpha += src->uv_alpha;458}459460// initialize the job struct with some TODOs461static void InitSegmentJob(VP8Encoder* const enc, SegmentJob* const job,462int start_row, int end_row) {463WebPGetWorkerInterface()->Init(&job->worker);464job->worker.data1 = job;465job->worker.data2 = &job->it;466job->worker.hook = DoSegmentsJob;467VP8IteratorInit(enc, &job->it);468VP8IteratorSetRow(&job->it, start_row);469VP8IteratorSetCountDown(&job->it, (end_row - start_row) * enc->mb_w_);470memset(job->alphas, 0, sizeof(job->alphas));471job->alpha = 0;472job->uv_alpha = 0;473// only one of both jobs can record the progress, since we don't474// expect the user's hook to be multi-thread safe475job->delta_progress = (start_row == 0) ? 20 : 0;476}477478// main entry point479int VP8EncAnalyze(VP8Encoder* const enc) {480int ok = 1;481const int do_segments =482enc->config_->emulate_jpeg_size || // We need the complexity evaluation.483(enc->segment_hdr_.num_segments_ > 1) ||484(enc->method_ <= 1); // for method 0 - 1, we need preds_[] to be filled.485if (do_segments) {486const int last_row = enc->mb_h_;487// We give a little more than a half work to the main thread.488const int split_row = (9 * last_row + 15) >> 4;489const int total_mb = last_row * enc->mb_w_;490#ifdef WEBP_USE_THREAD491const int kMinSplitRow = 2; // minimal rows needed for mt to be worth it492const int do_mt = (enc->thread_level_ > 0) && (split_row >= kMinSplitRow);493#else494const int do_mt = 0;495#endif496const WebPWorkerInterface* const worker_interface =497WebPGetWorkerInterface();498SegmentJob main_job;499if (do_mt) {500SegmentJob side_job;501// Note the use of '&' instead of '&&' because we must call the functions502// no matter what.503InitSegmentJob(enc, &main_job, 0, split_row);504InitSegmentJob(enc, &side_job, split_row, last_row);505// we don't need to call Reset() on main_job.worker, since we're calling506// WebPWorkerExecute() on it507ok &= worker_interface->Reset(&side_job.worker);508// launch the two jobs in parallel509if (ok) {510worker_interface->Launch(&side_job.worker);511worker_interface->Execute(&main_job.worker);512ok &= worker_interface->Sync(&side_job.worker);513ok &= worker_interface->Sync(&main_job.worker);514}515worker_interface->End(&side_job.worker);516if (ok) MergeJobs(&side_job, &main_job); // merge results together517} else {518// Even for single-thread case, we use the generic Worker tools.519InitSegmentJob(enc, &main_job, 0, last_row);520worker_interface->Execute(&main_job.worker);521ok &= worker_interface->Sync(&main_job.worker);522}523worker_interface->End(&main_job.worker);524if (ok) {525enc->alpha_ = main_job.alpha / total_mb;526enc->uv_alpha_ = main_job.uv_alpha / total_mb;527AssignSegments(enc, main_job.alphas);528}529} else { // Use only one default segment.530ResetAllMBInfo(enc);531}532return ok;533}534535536537