Coverage Report

Created: 2025-06-13 06:48

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