analysis.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // Copyright 2011 Google Inc. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the COPYING file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. // -----------------------------------------------------------------------------
  9. //
  10. // Macroblock analysis
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <assert.h>
  16. #include "./vp8enci.h"
  17. #include "./cost.h"
  18. #include "../utils/utils.h"
  19. #define MAX_ITERS_K_MEANS 6
  20. //------------------------------------------------------------------------------
  21. // Smooth the segment map by replacing isolated block by the majority of its
  22. // neighbours.
  23. static void SmoothSegmentMap(VP8Encoder* const enc) {
  24. int n, x, y;
  25. const int w = enc->mb_w_;
  26. const int h = enc->mb_h_;
  27. const int majority_cnt_3_x_3_grid = 5;
  28. uint8_t* const tmp = (uint8_t*)WebPSafeMalloc(w * h, sizeof(*tmp));
  29. assert((uint64_t)(w * h) == (uint64_t)w * h); // no overflow, as per spec
  30. if (tmp == NULL) return;
  31. for (y = 1; y < h - 1; ++y) {
  32. for (x = 1; x < w - 1; ++x) {
  33. int cnt[NUM_MB_SEGMENTS] = { 0 };
  34. const VP8MBInfo* const mb = &enc->mb_info_[x + w * y];
  35. int majority_seg = mb->segment_;
  36. // Check the 8 neighbouring segment values.
  37. cnt[mb[-w - 1].segment_]++; // top-left
  38. cnt[mb[-w + 0].segment_]++; // top
  39. cnt[mb[-w + 1].segment_]++; // top-right
  40. cnt[mb[ - 1].segment_]++; // left
  41. cnt[mb[ + 1].segment_]++; // right
  42. cnt[mb[ w - 1].segment_]++; // bottom-left
  43. cnt[mb[ w + 0].segment_]++; // bottom
  44. cnt[mb[ w + 1].segment_]++; // bottom-right
  45. for (n = 0; n < NUM_MB_SEGMENTS; ++n) {
  46. if (cnt[n] >= majority_cnt_3_x_3_grid) {
  47. majority_seg = n;
  48. break;
  49. }
  50. }
  51. tmp[x + y * w] = majority_seg;
  52. }
  53. }
  54. for (y = 1; y < h - 1; ++y) {
  55. for (x = 1; x < w - 1; ++x) {
  56. VP8MBInfo* const mb = &enc->mb_info_[x + w * y];
  57. mb->segment_ = tmp[x + y * w];
  58. }
  59. }
  60. WebPSafeFree(tmp);
  61. }
  62. //------------------------------------------------------------------------------
  63. // set segment susceptibility alpha_ / beta_
  64. static WEBP_INLINE int clip(int v, int m, int M) {
  65. return (v < m) ? m : (v > M) ? M : v;
  66. }
  67. static void SetSegmentAlphas(VP8Encoder* const enc,
  68. const int centers[NUM_MB_SEGMENTS],
  69. int mid) {
  70. const int nb = enc->segment_hdr_.num_segments_;
  71. int min = centers[0], max = centers[0];
  72. int n;
  73. if (nb > 1) {
  74. for (n = 0; n < nb; ++n) {
  75. if (min > centers[n]) min = centers[n];
  76. if (max < centers[n]) max = centers[n];
  77. }
  78. }
  79. if (max == min) max = min + 1;
  80. assert(mid <= max && mid >= min);
  81. for (n = 0; n < nb; ++n) {
  82. const int alpha = 255 * (centers[n] - mid) / (max - min);
  83. const int beta = 255 * (centers[n] - min) / (max - min);
  84. enc->dqm_[n].alpha_ = clip(alpha, -127, 127);
  85. enc->dqm_[n].beta_ = clip(beta, 0, 255);
  86. }
  87. }
  88. //------------------------------------------------------------------------------
  89. // Compute susceptibility based on DCT-coeff histograms:
  90. // the higher, the "easier" the macroblock is to compress.
  91. #define MAX_ALPHA 255 // 8b of precision for susceptibilities.
  92. #define ALPHA_SCALE (2 * MAX_ALPHA) // scaling factor for alpha.
  93. #define DEFAULT_ALPHA (-1)
  94. #define IS_BETTER_ALPHA(alpha, best_alpha) ((alpha) > (best_alpha))
  95. static int FinalAlphaValue(int alpha) {
  96. alpha = MAX_ALPHA - alpha;
  97. return clip(alpha, 0, MAX_ALPHA);
  98. }
  99. static int GetAlpha(const VP8Histogram* const histo) {
  100. int max_value = 0, last_non_zero = 1;
  101. int k;
  102. int alpha;
  103. for (k = 0; k <= MAX_COEFF_THRESH; ++k) {
  104. const int value = histo->distribution[k];
  105. if (value > 0) {
  106. if (value > max_value) max_value = value;
  107. last_non_zero = k;
  108. }
  109. }
  110. // 'alpha' will later be clipped to [0..MAX_ALPHA] range, clamping outer
  111. // values which happen to be mostly noise. This leaves the maximum precision
  112. // for handling the useful small values which contribute most.
  113. alpha = (max_value > 1) ? ALPHA_SCALE * last_non_zero / max_value : 0;
  114. return alpha;
  115. }
  116. static void MergeHistograms(const VP8Histogram* const in,
  117. VP8Histogram* const out) {
  118. int i;
  119. for (i = 0; i <= MAX_COEFF_THRESH; ++i) {
  120. out->distribution[i] += in->distribution[i];
  121. }
  122. }
  123. //------------------------------------------------------------------------------
  124. // Simplified k-Means, to assign Nb segments based on alpha-histogram
  125. static void AssignSegments(VP8Encoder* const enc,
  126. const int alphas[MAX_ALPHA + 1]) {
  127. // 'num_segments_' is previously validated and <= NUM_MB_SEGMENTS, but an
  128. // explicit check is needed to avoid spurious warning about 'n + 1' exceeding
  129. // array bounds of 'centers' with some compilers (noticed with gcc-4.9).
  130. const int nb = (enc->segment_hdr_.num_segments_ < NUM_MB_SEGMENTS) ?
  131. enc->segment_hdr_.num_segments_ : NUM_MB_SEGMENTS;
  132. int centers[NUM_MB_SEGMENTS];
  133. int weighted_average = 0;
  134. int map[MAX_ALPHA + 1];
  135. int a, n, k;
  136. int min_a = 0, max_a = MAX_ALPHA, range_a;
  137. // 'int' type is ok for histo, and won't overflow
  138. int accum[NUM_MB_SEGMENTS], dist_accum[NUM_MB_SEGMENTS];
  139. assert(nb >= 1);
  140. assert(nb <= NUM_MB_SEGMENTS);
  141. // bracket the input
  142. for (n = 0; n <= MAX_ALPHA && alphas[n] == 0; ++n) {}
  143. min_a = n;
  144. for (n = MAX_ALPHA; n > min_a && alphas[n] == 0; --n) {}
  145. max_a = n;
  146. range_a = max_a - min_a;
  147. // Spread initial centers evenly
  148. for (k = 0, n = 1; k < nb; ++k, n += 2) {
  149. assert(n < 2 * nb);
  150. centers[k] = min_a + (n * range_a) / (2 * nb);
  151. }
  152. for (k = 0; k < MAX_ITERS_K_MEANS; ++k) { // few iters are enough
  153. int total_weight;
  154. int displaced;
  155. // Reset stats
  156. for (n = 0; n < nb; ++n) {
  157. accum[n] = 0;
  158. dist_accum[n] = 0;
  159. }
  160. // Assign nearest center for each 'a'
  161. n = 0; // track the nearest center for current 'a'
  162. for (a = min_a; a <= max_a; ++a) {
  163. if (alphas[a]) {
  164. while (n + 1 < nb && abs(a - centers[n + 1]) < abs(a - centers[n])) {
  165. n++;
  166. }
  167. map[a] = n;
  168. // accumulate contribution into best centroid
  169. dist_accum[n] += a * alphas[a];
  170. accum[n] += alphas[a];
  171. }
  172. }
  173. // All point are classified. Move the centroids to the
  174. // center of their respective cloud.
  175. displaced = 0;
  176. weighted_average = 0;
  177. total_weight = 0;
  178. for (n = 0; n < nb; ++n) {
  179. if (accum[n]) {
  180. const int new_center = (dist_accum[n] + accum[n] / 2) / accum[n];
  181. displaced += abs(centers[n] - new_center);
  182. centers[n] = new_center;
  183. weighted_average += new_center * accum[n];
  184. total_weight += accum[n];
  185. }
  186. }
  187. weighted_average = (weighted_average + total_weight / 2) / total_weight;
  188. if (displaced < 5) break; // no need to keep on looping...
  189. }
  190. // Map each original value to the closest centroid
  191. for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {
  192. VP8MBInfo* const mb = &enc->mb_info_[n];
  193. const int alpha = mb->alpha_;
  194. mb->segment_ = map[alpha];
  195. mb->alpha_ = centers[map[alpha]]; // for the record.
  196. }
  197. if (nb > 1) {
  198. const int smooth = (enc->config_->preprocessing & 1);
  199. if (smooth) SmoothSegmentMap(enc);
  200. }
  201. SetSegmentAlphas(enc, centers, weighted_average); // pick some alphas.
  202. }
  203. //------------------------------------------------------------------------------
  204. // Macroblock analysis: collect histogram for each mode, deduce the maximal
  205. // susceptibility and set best modes for this macroblock.
  206. // Segment assignment is done later.
  207. // Number of modes to inspect for alpha_ evaluation. We don't need to test all
  208. // the possible modes during the analysis phase: we risk falling into a local
  209. // optimum, or be subject to boundary effect
  210. #define MAX_INTRA16_MODE 2
  211. #define MAX_INTRA4_MODE 2
  212. #define MAX_UV_MODE 2
  213. static int MBAnalyzeBestIntra16Mode(VP8EncIterator* const it) {
  214. const int max_mode = MAX_INTRA16_MODE;
  215. int mode;
  216. int best_alpha = DEFAULT_ALPHA;
  217. int best_mode = 0;
  218. VP8MakeLuma16Preds(it);
  219. for (mode = 0; mode < max_mode; ++mode) {
  220. VP8Histogram histo = { { 0 } };
  221. int alpha;
  222. VP8CollectHistogram(it->yuv_in_ + Y_OFF,
  223. it->yuv_p_ + VP8I16ModeOffsets[mode],
  224. 0, 16, &histo);
  225. alpha = GetAlpha(&histo);
  226. if (IS_BETTER_ALPHA(alpha, best_alpha)) {
  227. best_alpha = alpha;
  228. best_mode = mode;
  229. }
  230. }
  231. VP8SetIntra16Mode(it, best_mode);
  232. return best_alpha;
  233. }
  234. static int MBAnalyzeBestIntra4Mode(VP8EncIterator* const it,
  235. int best_alpha) {
  236. uint8_t modes[16];
  237. const int max_mode = MAX_INTRA4_MODE;
  238. int i4_alpha;
  239. VP8Histogram total_histo = { { 0 } };
  240. int cur_histo = 0;
  241. VP8IteratorStartI4(it);
  242. do {
  243. int mode;
  244. int best_mode_alpha = DEFAULT_ALPHA;
  245. VP8Histogram histos[2];
  246. const uint8_t* const src = it->yuv_in_ + Y_OFF + VP8Scan[it->i4_];
  247. VP8MakeIntra4Preds(it);
  248. for (mode = 0; mode < max_mode; ++mode) {
  249. int alpha;
  250. memset(&histos[cur_histo], 0, sizeof(histos[cur_histo]));
  251. VP8CollectHistogram(src, it->yuv_p_ + VP8I4ModeOffsets[mode],
  252. 0, 1, &histos[cur_histo]);
  253. alpha = GetAlpha(&histos[cur_histo]);
  254. if (IS_BETTER_ALPHA(alpha, best_mode_alpha)) {
  255. best_mode_alpha = alpha;
  256. modes[it->i4_] = mode;
  257. cur_histo ^= 1; // keep track of best histo so far.
  258. }
  259. }
  260. // accumulate best histogram
  261. MergeHistograms(&histos[cur_histo ^ 1], &total_histo);
  262. // Note: we reuse the original samples for predictors
  263. } while (VP8IteratorRotateI4(it, it->yuv_in_ + Y_OFF));
  264. i4_alpha = GetAlpha(&total_histo);
  265. if (IS_BETTER_ALPHA(i4_alpha, best_alpha)) {
  266. VP8SetIntra4Mode(it, modes);
  267. best_alpha = i4_alpha;
  268. }
  269. return best_alpha;
  270. }
  271. static int MBAnalyzeBestUVMode(VP8EncIterator* const it) {
  272. int best_alpha = DEFAULT_ALPHA;
  273. int best_mode = 0;
  274. const int max_mode = MAX_UV_MODE;
  275. int mode;
  276. VP8MakeChroma8Preds(it);
  277. for (mode = 0; mode < max_mode; ++mode) {
  278. VP8Histogram histo = { { 0 } };
  279. int alpha;
  280. VP8CollectHistogram(it->yuv_in_ + U_OFF,
  281. it->yuv_p_ + VP8UVModeOffsets[mode],
  282. 16, 16 + 4 + 4, &histo);
  283. alpha = GetAlpha(&histo);
  284. if (IS_BETTER_ALPHA(alpha, best_alpha)) {
  285. best_alpha = alpha;
  286. best_mode = mode;
  287. }
  288. }
  289. VP8SetIntraUVMode(it, best_mode);
  290. return best_alpha;
  291. }
  292. static void MBAnalyze(VP8EncIterator* const it,
  293. int alphas[MAX_ALPHA + 1],
  294. int* const alpha, int* const uv_alpha) {
  295. const VP8Encoder* const enc = it->enc_;
  296. int best_alpha, best_uv_alpha;
  297. VP8SetIntra16Mode(it, 0); // default: Intra16, DC_PRED
  298. VP8SetSkip(it, 0); // not skipped
  299. VP8SetSegment(it, 0); // default segment, spec-wise.
  300. best_alpha = MBAnalyzeBestIntra16Mode(it);
  301. if (enc->method_ >= 5) {
  302. // We go and make a fast decision for intra4/intra16.
  303. // It's usually not a good and definitive pick, but helps seeding the stats
  304. // about level bit-cost.
  305. // TODO(skal): improve criterion.
  306. best_alpha = MBAnalyzeBestIntra4Mode(it, best_alpha);
  307. }
  308. best_uv_alpha = MBAnalyzeBestUVMode(it);
  309. // Final susceptibility mix
  310. best_alpha = (3 * best_alpha + best_uv_alpha + 2) >> 2;
  311. best_alpha = FinalAlphaValue(best_alpha);
  312. alphas[best_alpha]++;
  313. it->mb_->alpha_ = best_alpha; // for later remapping.
  314. // Accumulate for later complexity analysis.
  315. *alpha += best_alpha; // mixed susceptibility (not just luma)
  316. *uv_alpha += best_uv_alpha;
  317. }
  318. static void DefaultMBInfo(VP8MBInfo* const mb) {
  319. mb->type_ = 1; // I16x16
  320. mb->uv_mode_ = 0;
  321. mb->skip_ = 0; // not skipped
  322. mb->segment_ = 0; // default segment
  323. mb->alpha_ = 0;
  324. }
  325. //------------------------------------------------------------------------------
  326. // Main analysis loop:
  327. // Collect all susceptibilities for each macroblock and record their
  328. // distribution in alphas[]. Segments is assigned a-posteriori, based on
  329. // this histogram.
  330. // We also pick an intra16 prediction mode, which shouldn't be considered
  331. // final except for fast-encode settings. We can also pick some intra4 modes
  332. // and decide intra4/intra16, but that's usually almost always a bad choice at
  333. // this stage.
  334. static void ResetAllMBInfo(VP8Encoder* const enc) {
  335. int n;
  336. for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) {
  337. DefaultMBInfo(&enc->mb_info_[n]);
  338. }
  339. // Default susceptibilities.
  340. enc->dqm_[0].alpha_ = 0;
  341. enc->dqm_[0].beta_ = 0;
  342. // Note: we can't compute this alpha_ / uv_alpha_ -> set to default value.
  343. enc->alpha_ = 0;
  344. enc->uv_alpha_ = 0;
  345. WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
  346. }
  347. // struct used to collect job result
  348. typedef struct {
  349. WebPWorker worker;
  350. int alphas[MAX_ALPHA + 1];
  351. int alpha, uv_alpha;
  352. VP8EncIterator it;
  353. int delta_progress;
  354. } SegmentJob;
  355. // main work call
  356. static int DoSegmentsJob(SegmentJob* const job, VP8EncIterator* const it) {
  357. int ok = 1;
  358. if (!VP8IteratorIsDone(it)) {
  359. uint8_t tmp[32 + ALIGN_CST];
  360. uint8_t* const scratch = (uint8_t*)DO_ALIGN(tmp);
  361. do {
  362. // Let's pretend we have perfect lossless reconstruction.
  363. VP8IteratorImport(it, scratch);
  364. MBAnalyze(it, job->alphas, &job->alpha, &job->uv_alpha);
  365. ok = VP8IteratorProgress(it, job->delta_progress);
  366. } while (ok && VP8IteratorNext(it));
  367. }
  368. return ok;
  369. }
  370. static void MergeJobs(const SegmentJob* const src, SegmentJob* const dst) {
  371. int i;
  372. for (i = 0; i <= MAX_ALPHA; ++i) dst->alphas[i] += src->alphas[i];
  373. dst->alpha += src->alpha;
  374. dst->uv_alpha += src->uv_alpha;
  375. }
  376. // initialize the job struct with some TODOs
  377. static void InitSegmentJob(VP8Encoder* const enc, SegmentJob* const job,
  378. int start_row, int end_row) {
  379. WebPGetWorkerInterface()->Init(&job->worker);
  380. job->worker.data1 = job;
  381. job->worker.data2 = &job->it;
  382. job->worker.hook = (WebPWorkerHook)DoSegmentsJob;
  383. VP8IteratorInit(enc, &job->it);
  384. VP8IteratorSetRow(&job->it, start_row);
  385. VP8IteratorSetCountDown(&job->it, (end_row - start_row) * enc->mb_w_);
  386. memset(job->alphas, 0, sizeof(job->alphas));
  387. job->alpha = 0;
  388. job->uv_alpha = 0;
  389. // only one of both jobs can record the progress, since we don't
  390. // expect the user's hook to be multi-thread safe
  391. job->delta_progress = (start_row == 0) ? 20 : 0;
  392. }
  393. // main entry point
  394. int VP8EncAnalyze(VP8Encoder* const enc) {
  395. int ok = 1;
  396. const int do_segments =
  397. enc->config_->emulate_jpeg_size || // We need the complexity evaluation.
  398. (enc->segment_hdr_.num_segments_ > 1) ||
  399. (enc->method_ == 0); // for method 0, we need preds_[] to be filled.
  400. if (do_segments) {
  401. const int last_row = enc->mb_h_;
  402. // We give a little more than a half work to the main thread.
  403. const int split_row = (9 * last_row + 15) >> 4;
  404. const int total_mb = last_row * enc->mb_w_;
  405. #ifdef WEBP_USE_THREAD
  406. const int kMinSplitRow = 2; // minimal rows needed for mt to be worth it
  407. const int do_mt = (enc->thread_level_ > 0) && (split_row >= kMinSplitRow);
  408. #else
  409. const int do_mt = 0;
  410. #endif
  411. const WebPWorkerInterface* const worker_interface =
  412. WebPGetWorkerInterface();
  413. SegmentJob main_job;
  414. if (do_mt) {
  415. SegmentJob side_job;
  416. // Note the use of '&' instead of '&&' because we must call the functions
  417. // no matter what.
  418. InitSegmentJob(enc, &main_job, 0, split_row);
  419. InitSegmentJob(enc, &side_job, split_row, last_row);
  420. // we don't need to call Reset() on main_job.worker, since we're calling
  421. // WebPWorkerExecute() on it
  422. ok &= worker_interface->Reset(&side_job.worker);
  423. // launch the two jobs in parallel
  424. if (ok) {
  425. worker_interface->Launch(&side_job.worker);
  426. worker_interface->Execute(&main_job.worker);
  427. ok &= worker_interface->Sync(&side_job.worker);
  428. ok &= worker_interface->Sync(&main_job.worker);
  429. }
  430. worker_interface->End(&side_job.worker);
  431. if (ok) MergeJobs(&side_job, &main_job); // merge results together
  432. } else {
  433. // Even for single-thread case, we use the generic Worker tools.
  434. InitSegmentJob(enc, &main_job, 0, last_row);
  435. worker_interface->Execute(&main_job.worker);
  436. ok &= worker_interface->Sync(&main_job.worker);
  437. }
  438. worker_interface->End(&main_job.worker);
  439. if (ok) {
  440. enc->alpha_ = main_job.alpha / total_mb;
  441. enc->uv_alpha_ = main_job.uv_alpha / total_mb;
  442. AssignSegments(enc, main_job.alphas);
  443. }
  444. } else { // Use only one default segment.
  445. ResetAllMBInfo(enc);
  446. }
  447. return ok;
  448. }