Coverage Report

Created: 2025-09-27 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/src/enc/frame_enc.c
Line
Count
Source
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
//   frame coding and analysis
11
//
12
// Author: Skal (pascal.massimino@gmail.com)
13
14
#include <assert.h>
15
#include <math.h>
16
#include <string.h>
17
18
#include "src/dec/common_dec.h"
19
#include "src/dsp/dsp.h"
20
#include "src/enc/cost_enc.h"
21
#include "src/enc/vp8i_enc.h"
22
#include "src/utils/bit_writer_utils.h"
23
#include "src/webp/encode.h"
24
#include "src/webp/format_constants.h"  // RIFF constants
25
#include "src/webp/types.h"
26
27
#define SEGMENT_VISU 0
28
#define DEBUG_SEARCH 0  // useful to track search convergence
29
30
//------------------------------------------------------------------------------
31
// multi-pass convergence
32
33
#define HEADER_SIZE_ESTIMATE \
34
0
  (RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8_FRAME_HEADER_SIZE)
35
0
#define DQ_LIMIT 0.4  // convergence is considered reached if dq < DQ_LIMIT
36
// we allow 2k of extra head-room in PARTITION0 limit.
37
0
#define PARTITION0_SIZE_LIMIT ((VP8_MAX_PARTITION0_SIZE - 2048ULL) << 11)
38
39
0
static float Clamp(float v, float min, float max) {
40
0
  return (v < min) ? min : (v > max) ? max : v;
41
0
}
42
43
typedef struct {  // struct for organizing convergence in either size or PSNR
44
  int is_first;
45
  float dq;
46
  float q, last_q;
47
  float qmin, qmax;
48
  double value, last_value;  // PSNR or size
49
  double target;
50
  int do_size_search;
51
} PassStats;
52
53
0
static int InitPassStats(const VP8Encoder* const enc, PassStats* const s) {
54
0
  const uint64_t target_size = (uint64_t)enc->config->target_size;
55
0
  const int do_size_search = (target_size != 0);
56
0
  const float target_PSNR = enc->config->target_PSNR;
57
58
0
  s->is_first = 1;
59
0
  s->dq = 10.f;
60
0
  s->qmin = 1.f * enc->config->qmin;
61
0
  s->qmax = 1.f * enc->config->qmax;
62
0
  s->q = s->last_q = Clamp(enc->config->quality, s->qmin, s->qmax);
63
0
  s->target = do_size_search       ? (double)target_size
64
0
              : (target_PSNR > 0.) ? target_PSNR
65
0
                                   : 40.;  // default, just in case
66
0
  s->value = s->last_value = 0.;
67
0
  s->do_size_search = do_size_search;
68
0
  return do_size_search;
69
0
}
70
71
0
static float ComputeNextQ(PassStats* const s) {
72
0
  float dq;
73
0
  if (s->is_first) {
74
0
    dq = (s->value > s->target) ? -s->dq : s->dq;
75
0
    s->is_first = 0;
76
0
  } else if (s->value != s->last_value) {
77
0
    const double slope = (s->target - s->value) / (s->last_value - s->value);
78
0
    dq = (float)(slope * (s->last_q - s->q));
79
0
  } else {
80
0
    dq = 0.;  // we're done?!
81
0
  }
82
  // Limit variable to avoid large swings.
83
0
  s->dq = Clamp(dq, -30.f, 30.f);
84
0
  s->last_q = s->q;
85
0
  s->last_value = s->value;
86
0
  s->q = Clamp(s->q + s->dq, s->qmin, s->qmax);
87
0
  return s->q;
88
0
}
89
90
//------------------------------------------------------------------------------
91
// Tables for level coding
92
93
const uint8_t VP8Cat3[] = {173, 148, 140};
94
const uint8_t VP8Cat4[] = {176, 155, 140, 135};
95
const uint8_t VP8Cat5[] = {180, 157, 141, 134, 130};
96
const uint8_t VP8Cat6[] = {254, 254, 243, 230, 196, 177,
97
                           153, 140, 133, 130, 129};
98
99
//------------------------------------------------------------------------------
100
// Reset the statistics about: number of skips, token proba, level cost,...
101
102
0
static void ResetStats(VP8Encoder* const enc) {
103
0
  VP8EncProba* const proba = &enc->proba;
104
0
  VP8CalculateLevelCosts(proba);
105
0
  proba->nb_skip = 0;
106
0
}
107
108
//------------------------------------------------------------------------------
109
// Skip decision probability
110
111
0
#define SKIP_PROBA_THRESHOLD 250  // value below which using skip_proba is OK.
112
113
0
static int CalcSkipProba(uint64_t nb, uint64_t total) {
114
0
  return (int)(total ? (total - nb) * 255 / total : 255);
115
0
}
116
117
// Returns the bit-cost for coding the skip probability.
118
0
static int FinalizeSkipProba(VP8Encoder* const enc) {
119
0
  VP8EncProba* const proba = &enc->proba;
120
0
  const int nb_mbs = enc->mb_w * enc->mb_h;
121
0
  const int nb_events = proba->nb_skip;
122
0
  int size;
123
0
  proba->skip_proba = CalcSkipProba(nb_events, nb_mbs);
124
0
  proba->use_skip_proba = (proba->skip_proba < SKIP_PROBA_THRESHOLD);
125
0
  size = 256;  // 'use_skip_proba' bit
126
0
  if (proba->use_skip_proba) {
127
0
    size += nb_events * VP8BitCost(1, proba->skip_proba) +
128
0
            (nb_mbs - nb_events) * VP8BitCost(0, proba->skip_proba);
129
0
    size += 8 * 256;  // cost of signaling the 'skip_proba' itself.
130
0
  }
131
0
  return size;
132
0
}
133
134
// Collect statistics and deduce probabilities for next coding pass.
135
// Return the total bit-cost for coding the probability updates.
136
0
static int CalcTokenProba(int nb, int total) {
137
0
  assert(nb <= total);
138
0
  return nb ? (255 - nb * 255 / total) : 255;
139
0
}
140
141
// Cost of coding 'nb' 1's and 'total-nb' 0's using 'proba' probability.
142
0
static int BranchCost(int nb, int total, int proba) {
143
0
  return nb * VP8BitCost(1, proba) + (total - nb) * VP8BitCost(0, proba);
144
0
}
145
146
0
static void ResetTokenStats(VP8Encoder* const enc) {
147
0
  VP8EncProba* const proba = &enc->proba;
148
0
  memset(proba->stats, 0, sizeof(proba->stats));
149
0
}
150
151
0
static int FinalizeTokenProbas(VP8EncProba* const proba) {
152
0
  int has_changed = 0;
153
0
  int size = 0;
154
0
  int t, b, c, p;
155
0
  for (t = 0; t < NUM_TYPES; ++t) {
156
0
    for (b = 0; b < NUM_BANDS; ++b) {
157
0
      for (c = 0; c < NUM_CTX; ++c) {
158
0
        for (p = 0; p < NUM_PROBAS; ++p) {
159
0
          const proba_t stats = proba->stats[t][b][c][p];
160
0
          const int nb = (stats >> 0) & 0xffff;
161
0
          const int total = (stats >> 16) & 0xffff;
162
0
          const int update_proba = VP8CoeffsUpdateProba[t][b][c][p];
163
0
          const int old_p = VP8CoeffsProba0[t][b][c][p];
164
0
          const int new_p = CalcTokenProba(nb, total);
165
0
          const int old_cost =
166
0
              BranchCost(nb, total, old_p) + VP8BitCost(0, update_proba);
167
0
          const int new_cost = BranchCost(nb, total, new_p) +
168
0
                               VP8BitCost(1, update_proba) + 8 * 256;
169
0
          const int use_new_p = (old_cost > new_cost);
170
0
          size += VP8BitCost(use_new_p, update_proba);
171
0
          if (use_new_p) {  // only use proba that seem meaningful enough.
172
0
            proba->coeffs[t][b][c][p] = new_p;
173
0
            has_changed |= (new_p != old_p);
174
0
            size += 8 * 256;
175
0
          } else {
176
0
            proba->coeffs[t][b][c][p] = old_p;
177
0
          }
178
0
        }
179
0
      }
180
0
    }
181
0
  }
182
0
  proba->dirty = has_changed;
183
0
  return size;
184
0
}
185
186
//------------------------------------------------------------------------------
187
// Finalize Segment probability based on the coding tree
188
189
0
static int GetProba(int a, int b) {
190
0
  const int total = a + b;
191
0
  return (total == 0) ? 255  // that's the default probability.
192
0
                      : (255 * a + total / 2) / total;  // rounded proba
193
0
}
194
195
0
static void ResetSegments(VP8Encoder* const enc) {
196
0
  int n;
197
0
  for (n = 0; n < enc->mb_w * enc->mb_h; ++n) {
198
0
    enc->mb_info[n].segment = 0;
199
0
  }
200
0
}
201
202
0
static void SetSegmentProbas(VP8Encoder* const enc) {
203
0
  int p[NUM_MB_SEGMENTS] = {0};
204
0
  int n;
205
206
0
  for (n = 0; n < enc->mb_w * enc->mb_h; ++n) {
207
0
    const VP8MBInfo* const mb = &enc->mb_info[n];
208
0
    ++p[mb->segment];
209
0
  }
210
0
#if !defined(WEBP_DISABLE_STATS)
211
0
  if (enc->pic->stats != NULL) {
212
0
    for (n = 0; n < NUM_MB_SEGMENTS; ++n) {
213
0
      enc->pic->stats->segment_size[n] = p[n];
214
0
    }
215
0
  }
216
0
#endif
217
0
  if (enc->segment_hdr.num_segments > 1) {
218
0
    uint8_t* const probas = enc->proba.segments;
219
0
    probas[0] = GetProba(p[0] + p[1], p[2] + p[3]);
220
0
    probas[1] = GetProba(p[0], p[1]);
221
0
    probas[2] = GetProba(p[2], p[3]);
222
223
0
    enc->segment_hdr.update_map =
224
0
        (probas[0] != 255) || (probas[1] != 255) || (probas[2] != 255);
225
0
    if (!enc->segment_hdr.update_map) ResetSegments(enc);
226
0
    enc->segment_hdr.size =
227
0
        p[0] * (VP8BitCost(0, probas[0]) + VP8BitCost(0, probas[1])) +
228
0
        p[1] * (VP8BitCost(0, probas[0]) + VP8BitCost(1, probas[1])) +
229
0
        p[2] * (VP8BitCost(1, probas[0]) + VP8BitCost(0, probas[2])) +
230
0
        p[3] * (VP8BitCost(1, probas[0]) + VP8BitCost(1, probas[2]));
231
0
  } else {
232
0
    enc->segment_hdr.update_map = 0;
233
0
    enc->segment_hdr.size = 0;
234
0
  }
235
0
}
236
237
//------------------------------------------------------------------------------
238
// Coefficient coding
239
240
0
static int PutCoeffs(VP8BitWriter* const bw, int ctx, const VP8Residual* res) {
241
0
  int n = res->first;
242
  // should be prob[VP8EncBands[n]], but it's equivalent for n=0 or 1
243
0
  const uint8_t* p = res->prob[n][ctx];
244
0
  if (!VP8PutBit(bw, res->last >= 0, p[0])) {
245
0
    return 0;
246
0
  }
247
248
0
  while (n < 16) {
249
0
    const int c = res->coeffs[n++];
250
0
    const int sign = c < 0;
251
0
    int v = sign ? -c : c;
252
0
    if (!VP8PutBit(bw, v != 0, p[1])) {
253
0
      p = res->prob[VP8EncBands[n]][0];
254
0
      continue;
255
0
    }
256
0
    if (!VP8PutBit(bw, v > 1, p[2])) {
257
0
      p = res->prob[VP8EncBands[n]][1];
258
0
    } else {
259
0
      if (!VP8PutBit(bw, v > 4, p[3])) {
260
0
        if (VP8PutBit(bw, v != 2, p[4])) {
261
0
          VP8PutBit(bw, v == 4, p[5]);
262
0
        }
263
0
      } else if (!VP8PutBit(bw, v > 10, p[6])) {
264
0
        if (!VP8PutBit(bw, v > 6, p[7])) {
265
0
          VP8PutBit(bw, v == 6, 159);
266
0
        } else {
267
0
          VP8PutBit(bw, v >= 9, 165);
268
0
          VP8PutBit(bw, !(v & 1), 145);
269
0
        }
270
0
      } else {
271
0
        int mask;
272
0
        const uint8_t* tab;
273
0
        if (v < 3 + (8 << 1)) {  // VP8Cat3  (3b)
274
0
          VP8PutBit(bw, 0, p[8]);
275
0
          VP8PutBit(bw, 0, p[9]);
276
0
          v -= 3 + (8 << 0);
277
0
          mask = 1 << 2;
278
0
          tab = VP8Cat3;
279
0
        } else if (v < 3 + (8 << 2)) {  // VP8Cat4  (4b)
280
0
          VP8PutBit(bw, 0, p[8]);
281
0
          VP8PutBit(bw, 1, p[9]);
282
0
          v -= 3 + (8 << 1);
283
0
          mask = 1 << 3;
284
0
          tab = VP8Cat4;
285
0
        } else if (v < 3 + (8 << 3)) {  // VP8Cat5  (5b)
286
0
          VP8PutBit(bw, 1, p[8]);
287
0
          VP8PutBit(bw, 0, p[10]);
288
0
          v -= 3 + (8 << 2);
289
0
          mask = 1 << 4;
290
0
          tab = VP8Cat5;
291
0
        } else {  // VP8Cat6 (11b)
292
0
          VP8PutBit(bw, 1, p[8]);
293
0
          VP8PutBit(bw, 1, p[10]);
294
0
          v -= 3 + (8 << 3);
295
0
          mask = 1 << 10;
296
0
          tab = VP8Cat6;
297
0
        }
298
0
        while (mask) {
299
0
          VP8PutBit(bw, !!(v & mask), *tab++);
300
0
          mask >>= 1;
301
0
        }
302
0
      }
303
0
      p = res->prob[VP8EncBands[n]][2];
304
0
    }
305
0
    VP8PutBitUniform(bw, sign);
306
0
    if (n == 16 || !VP8PutBit(bw, n <= res->last, p[0])) {
307
0
      return 1;  // EOB
308
0
    }
309
0
  }
310
0
  return 1;
311
0
}
312
313
static void CodeResiduals(VP8BitWriter* const bw, VP8EncIterator* const it,
314
0
                          const VP8ModeScore* const rd) {
315
0
  int x, y, ch;
316
0
  VP8Residual res;
317
0
  uint64_t pos1, pos2, pos3;
318
0
  const int i16 = (it->mb->type == 1);
319
0
  const int segment = it->mb->segment;
320
0
  VP8Encoder* const enc = it->enc;
321
322
0
  VP8IteratorNzToBytes(it);
323
324
0
  pos1 = VP8BitWriterPos(bw);
325
0
  if (i16) {
326
0
    VP8InitResidual(0, 1, enc, &res);
327
0
    VP8SetResidualCoeffs(rd->y_dc_levels, &res);
328
0
    it->top_nz[8] = it->left_nz[8] =
329
0
        PutCoeffs(bw, it->top_nz[8] + it->left_nz[8], &res);
330
0
    VP8InitResidual(1, 0, enc, &res);
331
0
  } else {
332
0
    VP8InitResidual(0, 3, enc, &res);
333
0
  }
334
335
  // luma-AC
336
0
  for (y = 0; y < 4; ++y) {
337
0
    for (x = 0; x < 4; ++x) {
338
0
      const int ctx = it->top_nz[x] + it->left_nz[y];
339
0
      VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);
340
0
      it->top_nz[x] = it->left_nz[y] = PutCoeffs(bw, ctx, &res);
341
0
    }
342
0
  }
343
0
  pos2 = VP8BitWriterPos(bw);
344
345
  // U/V
346
0
  VP8InitResidual(0, 2, enc, &res);
347
0
  for (ch = 0; ch <= 2; ch += 2) {
348
0
    for (y = 0; y < 2; ++y) {
349
0
      for (x = 0; x < 2; ++x) {
350
0
        const int ctx = it->top_nz[4 + ch + x] + it->left_nz[4 + ch + y];
351
0
        VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);
352
0
        it->top_nz[4 + ch + x] = it->left_nz[4 + ch + y] =
353
0
            PutCoeffs(bw, ctx, &res);
354
0
      }
355
0
    }
356
0
  }
357
0
  pos3 = VP8BitWriterPos(bw);
358
0
  it->luma_bits = pos2 - pos1;
359
0
  it->uv_bits = pos3 - pos2;
360
0
  it->bit_count[segment][i16] += it->luma_bits;
361
0
  it->bit_count[segment][2] += it->uv_bits;
362
0
  VP8IteratorBytesToNz(it);
363
0
}
364
365
// Same as CodeResiduals, but doesn't actually write anything.
366
// Instead, it just records the event distribution.
367
static void RecordResiduals(VP8EncIterator* const it,
368
0
                            const VP8ModeScore* const rd) {
369
0
  int x, y, ch;
370
0
  VP8Residual res;
371
0
  VP8Encoder* const enc = it->enc;
372
373
0
  VP8IteratorNzToBytes(it);
374
375
0
  if (it->mb->type == 1) {  // i16x16
376
0
    VP8InitResidual(0, 1, enc, &res);
377
0
    VP8SetResidualCoeffs(rd->y_dc_levels, &res);
378
0
    it->top_nz[8] = it->left_nz[8] =
379
0
        VP8RecordCoeffs(it->top_nz[8] + it->left_nz[8], &res);
380
0
    VP8InitResidual(1, 0, enc, &res);
381
0
  } else {
382
0
    VP8InitResidual(0, 3, enc, &res);
383
0
  }
384
385
  // luma-AC
386
0
  for (y = 0; y < 4; ++y) {
387
0
    for (x = 0; x < 4; ++x) {
388
0
      const int ctx = it->top_nz[x] + it->left_nz[y];
389
0
      VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);
390
0
      it->top_nz[x] = it->left_nz[y] = VP8RecordCoeffs(ctx, &res);
391
0
    }
392
0
  }
393
394
  // U/V
395
0
  VP8InitResidual(0, 2, enc, &res);
396
0
  for (ch = 0; ch <= 2; ch += 2) {
397
0
    for (y = 0; y < 2; ++y) {
398
0
      for (x = 0; x < 2; ++x) {
399
0
        const int ctx = it->top_nz[4 + ch + x] + it->left_nz[4 + ch + y];
400
0
        VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);
401
0
        it->top_nz[4 + ch + x] = it->left_nz[4 + ch + y] =
402
0
            VP8RecordCoeffs(ctx, &res);
403
0
      }
404
0
    }
405
0
  }
406
407
0
  VP8IteratorBytesToNz(it);
408
0
}
409
410
//------------------------------------------------------------------------------
411
// Token buffer
412
413
#if !defined(DISABLE_TOKEN_BUFFER)
414
415
static int RecordTokens(VP8EncIterator* const it, const VP8ModeScore* const rd,
416
0
                        VP8TBuffer* const tokens) {
417
0
  int x, y, ch;
418
0
  VP8Residual res;
419
0
  VP8Encoder* const enc = it->enc;
420
421
0
  VP8IteratorNzToBytes(it);
422
0
  if (it->mb->type == 1) {  // i16x16
423
0
    const int ctx = it->top_nz[8] + it->left_nz[8];
424
0
    VP8InitResidual(0, 1, enc, &res);
425
0
    VP8SetResidualCoeffs(rd->y_dc_levels, &res);
426
0
    it->top_nz[8] = it->left_nz[8] = VP8RecordCoeffTokens(ctx, &res, tokens);
427
0
    VP8InitResidual(1, 0, enc, &res);
428
0
  } else {
429
0
    VP8InitResidual(0, 3, enc, &res);
430
0
  }
431
432
  // luma-AC
433
0
  for (y = 0; y < 4; ++y) {
434
0
    for (x = 0; x < 4; ++x) {
435
0
      const int ctx = it->top_nz[x] + it->left_nz[y];
436
0
      VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res);
437
0
      it->top_nz[x] = it->left_nz[y] = VP8RecordCoeffTokens(ctx, &res, tokens);
438
0
    }
439
0
  }
440
441
  // U/V
442
0
  VP8InitResidual(0, 2, enc, &res);
443
0
  for (ch = 0; ch <= 2; ch += 2) {
444
0
    for (y = 0; y < 2; ++y) {
445
0
      for (x = 0; x < 2; ++x) {
446
0
        const int ctx = it->top_nz[4 + ch + x] + it->left_nz[4 + ch + y];
447
0
        VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res);
448
0
        it->top_nz[4 + ch + x] = it->left_nz[4 + ch + y] =
449
0
            VP8RecordCoeffTokens(ctx, &res, tokens);
450
0
      }
451
0
    }
452
0
  }
453
0
  VP8IteratorBytesToNz(it);
454
0
  return !tokens->error;
455
0
}
456
457
#endif  // !DISABLE_TOKEN_BUFFER
458
459
//------------------------------------------------------------------------------
460
// ExtraInfo map / Debug function
461
462
#if !defined(WEBP_DISABLE_STATS)
463
464
#if SEGMENT_VISU
465
static void SetBlock(uint8_t* p, int value, int size) {
466
  int y;
467
  for (y = 0; y < size; ++y) {
468
    memset(p, value, size);
469
    p += BPS;
470
  }
471
}
472
#endif
473
474
0
static void ResetSSE(VP8Encoder* const enc) {
475
0
  enc->sse[0] = 0;
476
0
  enc->sse[1] = 0;
477
0
  enc->sse[2] = 0;
478
  // Note: enc->sse[3] is managed by alpha.c
479
0
  enc->sse_count = 0;
480
0
}
481
482
0
static void StoreSSE(const VP8EncIterator* const it) {
483
0
  VP8Encoder* const enc = it->enc;
484
0
  const uint8_t* const in = it->yuv_in;
485
0
  const uint8_t* const out = it->yuv_out;
486
  // Note: not totally accurate at boundary. And doesn't include in-loop filter.
487
0
  enc->sse[0] += VP8SSE16x16(in + Y_OFF_ENC, out + Y_OFF_ENC);
488
0
  enc->sse[1] += VP8SSE8x8(in + U_OFF_ENC, out + U_OFF_ENC);
489
0
  enc->sse[2] += VP8SSE8x8(in + V_OFF_ENC, out + V_OFF_ENC);
490
0
  enc->sse_count += 16 * 16;
491
0
}
492
493
0
static void StoreSideInfo(const VP8EncIterator* const it) {
494
0
  VP8Encoder* const enc = it->enc;
495
0
  const VP8MBInfo* const mb = it->mb;
496
0
  WebPPicture* const pic = enc->pic;
497
498
0
  if (pic->stats != NULL) {
499
0
    StoreSSE(it);
500
0
    enc->block_count[0] += (mb->type == 0);
501
0
    enc->block_count[1] += (mb->type == 1);
502
0
    enc->block_count[2] += (mb->skip != 0);
503
0
  }
504
505
0
  if (pic->extra_info != NULL) {
506
0
    uint8_t* const info = &pic->extra_info[it->x + it->y * enc->mb_w];
507
0
    switch (pic->extra_info_type) {
508
0
      case 1:
509
0
        *info = mb->type;
510
0
        break;
511
0
      case 2:
512
0
        *info = mb->segment;
513
0
        break;
514
0
      case 3:
515
0
        *info = enc->dqm[mb->segment].quant;
516
0
        break;
517
0
      case 4:
518
0
        *info = (mb->type == 1) ? it->preds[0] : 0xff;
519
0
        break;
520
0
      case 5:
521
0
        *info = mb->uv_mode;
522
0
        break;
523
0
      case 6: {
524
0
        const int b = (int)((it->luma_bits + it->uv_bits + 7) >> 3);
525
0
        *info = (b > 255) ? 255 : b;
526
0
        break;
527
0
      }
528
0
      case 7:
529
0
        *info = mb->alpha;
530
0
        break;
531
0
      default:
532
0
        *info = 0;
533
0
        break;
534
0
    }
535
0
  }
536
#if SEGMENT_VISU  // visualize segments and prediction modes
537
  SetBlock(it->yuv_out + Y_OFF_ENC, mb->segment * 64, 16);
538
  SetBlock(it->yuv_out + U_OFF_ENC, it->preds[0] * 64, 8);
539
  SetBlock(it->yuv_out + V_OFF_ENC, mb->uv_mode * 64, 8);
540
#endif
541
0
}
542
543
0
static void ResetSideInfo(const VP8EncIterator* const it) {
544
0
  VP8Encoder* const enc = it->enc;
545
0
  WebPPicture* const pic = enc->pic;
546
0
  if (pic->stats != NULL) {
547
0
    memset(enc->block_count, 0, sizeof(enc->block_count));
548
0
  }
549
0
  ResetSSE(enc);
550
0
}
551
#else   // defined(WEBP_DISABLE_STATS)
552
static void ResetSSE(VP8Encoder* const enc) { (void)enc; }
553
static void StoreSideInfo(const VP8EncIterator* const it) {
554
  VP8Encoder* const enc = it->enc;
555
  WebPPicture* const pic = enc->pic;
556
  if (pic->extra_info != NULL) {
557
    if (it->x == 0 && it->y == 0) {  // only do it once, at start
558
      memset(pic->extra_info, 0,
559
             enc->mb_w * enc->mb_h * sizeof(*pic->extra_info));
560
    }
561
  }
562
}
563
564
static void ResetSideInfo(const VP8EncIterator* const it) { (void)it; }
565
#endif  // !defined(WEBP_DISABLE_STATS)
566
567
0
static double GetPSNR(uint64_t mse, uint64_t size) {
568
0
  return (mse > 0 && size > 0) ? 10. * log10(255. * 255. * size / mse) : 99;
569
0
}
570
571
//------------------------------------------------------------------------------
572
//  StatLoop(): only collect statistics (number of skips, token usage, ...).
573
//  This is used for deciding optimal probabilities. It also modifies the
574
//  quantizer value if some target (size, PSNR) was specified.
575
576
0
static void SetLoopParams(VP8Encoder* const enc, float q) {
577
  // Make sure the quality parameter is inside valid bounds
578
0
  q = Clamp(q, 0.f, 100.f);
579
580
0
  VP8SetSegmentParams(enc, q);  // setup segment quantizations and filters
581
0
  SetSegmentProbas(enc);        // compute segment probabilities
582
583
0
  ResetStats(enc);
584
0
  ResetSSE(enc);
585
0
}
586
587
static uint64_t OneStatPass(VP8Encoder* const enc, VP8RDLevel rd_opt,
588
0
                            int nb_mbs, int percent_delta, PassStats* const s) {
589
0
  VP8EncIterator it;
590
0
  uint64_t size = 0;
591
0
  uint64_t size_p0 = 0;
592
0
  uint64_t distortion = 0;
593
0
  const uint64_t pixel_count = (uint64_t)nb_mbs * 384;
594
595
0
  VP8IteratorInit(enc, &it);
596
0
  SetLoopParams(enc, s->q);
597
0
  do {
598
0
    VP8ModeScore info;
599
0
    VP8IteratorImport(&it, NULL);
600
0
    if (VP8Decimate(&it, &info, rd_opt)) {
601
      // Just record the number of skips and act like skip_proba is not used.
602
0
      ++enc->proba.nb_skip;
603
0
    }
604
0
    RecordResiduals(&it, &info);
605
0
    size += info.R + info.H;
606
0
    size_p0 += info.H;
607
0
    distortion += info.D;
608
0
    if (percent_delta && !VP8IteratorProgress(&it, percent_delta)) {
609
0
      return 0;
610
0
    }
611
0
    VP8IteratorSaveBoundary(&it);
612
0
  } while (VP8IteratorNext(&it) && --nb_mbs > 0);
613
614
0
  size_p0 += enc->segment_hdr.size;
615
0
  if (s->do_size_search) {
616
0
    size += FinalizeSkipProba(enc);
617
0
    size += FinalizeTokenProbas(&enc->proba);
618
0
    size = ((size + size_p0 + 1024) >> 11) + HEADER_SIZE_ESTIMATE;
619
0
    s->value = (double)size;
620
0
  } else {
621
0
    s->value = GetPSNR(distortion, pixel_count);
622
0
  }
623
0
  return size_p0;
624
0
}
625
626
0
static int StatLoop(VP8Encoder* const enc) {
627
0
  const int method = enc->method;
628
0
  const int do_search = enc->do_search;
629
0
  const int fast_probe = ((method == 0 || method == 3) && !do_search);
630
0
  int num_pass_left = enc->config->pass;
631
0
  const int task_percent = 20;
632
0
  const int percent_per_pass =
633
0
      (task_percent + num_pass_left / 2) / num_pass_left;
634
0
  const int final_percent = enc->percent + task_percent;
635
0
  const VP8RDLevel rd_opt =
636
0
      (method >= 3 || do_search) ? RD_OPT_BASIC : RD_OPT_NONE;
637
0
  int nb_mbs = enc->mb_w * enc->mb_h;
638
0
  PassStats stats;
639
640
0
  InitPassStats(enc, &stats);
641
0
  ResetTokenStats(enc);
642
643
  // Fast mode: quick analysis pass over few mbs. Better than nothing.
644
0
  if (fast_probe) {
645
0
    if (method == 3) {  // we need more stats for method 3 to be reliable.
646
0
      nb_mbs = (nb_mbs > 200) ? nb_mbs >> 1 : 100;
647
0
    } else {
648
0
      nb_mbs = (nb_mbs > 200) ? nb_mbs >> 2 : 50;
649
0
    }
650
0
  }
651
652
0
  while (num_pass_left-- > 0) {
653
0
    const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) ||
654
0
                             (num_pass_left == 0) ||
655
0
                             (enc->max_i4_header_bits == 0);
656
0
    const uint64_t size_p0 =
657
0
        OneStatPass(enc, rd_opt, nb_mbs, percent_per_pass, &stats);
658
0
    if (size_p0 == 0) return 0;
659
#if (DEBUG_SEARCH > 0)
660
    printf("#%d value:%.1lf -> %.1lf   q:%.2f -> %.2f\n", num_pass_left,
661
           stats.last_value, stats.value, stats.last_q, stats.q);
662
#endif
663
0
    if (enc->max_i4_header_bits > 0 && size_p0 > PARTITION0_SIZE_LIMIT) {
664
0
      ++num_pass_left;
665
0
      enc->max_i4_header_bits >>= 1;  // strengthen header bit limitation...
666
0
      continue;                       // ...and start over
667
0
    }
668
0
    if (is_last_pass) {
669
0
      break;
670
0
    }
671
    // If no target size: just do several pass without changing 'q'
672
0
    if (do_search) {
673
0
      ComputeNextQ(&stats);
674
0
      if (fabs(stats.dq) <= DQ_LIMIT) break;
675
0
    }
676
0
  }
677
0
  if (!do_search || !stats.do_size_search) {
678
    // Need to finalize probas now, since it wasn't done during the search.
679
0
    FinalizeSkipProba(enc);
680
0
    FinalizeTokenProbas(&enc->proba);
681
0
  }
682
0
  VP8CalculateLevelCosts(&enc->proba);  // finalize costs
683
0
  return WebPReportProgress(enc->pic, final_percent, &enc->percent);
684
0
}
685
686
//------------------------------------------------------------------------------
687
// Main loops
688
//
689
690
static const uint8_t kAverageBytesPerMB[8] = {50, 24, 16, 9, 7, 5, 3, 2};
691
692
0
static int PreLoopInitialize(VP8Encoder* const enc) {
693
0
  int p;
694
0
  int ok = 1;
695
0
  const int average_bytes_per_MB = kAverageBytesPerMB[enc->base_quant >> 4];
696
0
  const int bytes_per_parts =
697
0
      enc->mb_w * enc->mb_h * average_bytes_per_MB / enc->num_parts;
698
  // Initialize the bit-writers
699
0
  for (p = 0; ok && p < enc->num_parts; ++p) {
700
0
    ok = VP8BitWriterInit(enc->parts + p, bytes_per_parts);
701
0
  }
702
0
  if (!ok) {
703
0
    VP8EncFreeBitWriters(enc);  // malloc error occurred
704
0
    return WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
705
0
  }
706
0
  return ok;
707
0
}
708
709
0
static int PostLoopFinalize(VP8EncIterator* const it, int ok) {
710
0
  VP8Encoder* const enc = it->enc;
711
0
  if (ok) {  // Finalize the partitions, check for extra errors.
712
0
    int p;
713
0
    for (p = 0; p < enc->num_parts; ++p) {
714
0
      VP8BitWriterFinish(enc->parts + p);
715
0
      ok &= !enc->parts[p].error;
716
0
    }
717
0
  }
718
719
0
  if (ok) {  // All good. Finish up.
720
0
#if !defined(WEBP_DISABLE_STATS)
721
0
    if (enc->pic->stats != NULL) {  // finalize byte counters...
722
0
      int i, s;
723
0
      for (i = 0; i <= 2; ++i) {
724
0
        for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
725
0
          enc->residual_bytes[i][s] = (int)((it->bit_count[s][i] + 7) >> 3);
726
0
        }
727
0
      }
728
0
    }
729
0
#endif
730
0
    VP8AdjustFilterStrength(it);  // ...and store filter stats.
731
0
  } else {
732
    // Something bad happened -> need to do some memory cleanup.
733
0
    VP8EncFreeBitWriters(enc);
734
0
    return WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
735
0
  }
736
0
  return ok;
737
0
}
738
739
//------------------------------------------------------------------------------
740
//  VP8EncLoop(): does the final bitstream coding.
741
742
0
static void ResetAfterSkip(VP8EncIterator* const it) {
743
0
  if (it->mb->type == 1) {
744
0
    *it->nz = 0;  // reset all predictors
745
0
    it->left_nz[8] = 0;
746
0
  } else {
747
0
    *it->nz &= (1 << 24);  // preserve the dc_nz bit
748
0
  }
749
0
}
750
751
0
int VP8EncLoop(VP8Encoder* const enc) {
752
0
  VP8EncIterator it;
753
0
  int ok = PreLoopInitialize(enc);
754
0
  if (!ok) return 0;
755
756
0
  StatLoop(enc);  // stats-collection loop
757
758
0
  VP8IteratorInit(enc, &it);
759
0
  VP8InitFilter(&it);
760
0
  do {
761
0
    VP8ModeScore info;
762
0
    const int dont_use_skip = !enc->proba.use_skip_proba;
763
0
    const VP8RDLevel rd_opt = enc->rd_opt_level;
764
765
0
    VP8IteratorImport(&it, NULL);
766
    // Warning! order is important: first call VP8Decimate() and
767
    // *then* decide how to code the skip decision if there's one.
768
0
    if (!VP8Decimate(&it, &info, rd_opt) || dont_use_skip) {
769
0
      CodeResiduals(it.bw, &it, &info);
770
0
      if (it.bw->error) {
771
        // enc->pic->error_code is set in PostLoopFinalize().
772
0
        ok = 0;
773
0
        break;
774
0
      }
775
0
    } else {  // reset predictors after a skip
776
0
      ResetAfterSkip(&it);
777
0
    }
778
0
    StoreSideInfo(&it);
779
0
    VP8StoreFilterStats(&it);
780
0
    VP8IteratorExport(&it);
781
0
    ok = VP8IteratorProgress(&it, 20);
782
0
    VP8IteratorSaveBoundary(&it);
783
0
  } while (ok && VP8IteratorNext(&it));
784
785
0
  return PostLoopFinalize(&it, ok);
786
0
}
787
788
//------------------------------------------------------------------------------
789
// Single pass using Token Buffer.
790
791
#if !defined(DISABLE_TOKEN_BUFFER)
792
793
0
#define MIN_COUNT 96  // minimum number of macroblocks before updating stats
794
795
0
int VP8EncTokenLoop(VP8Encoder* const enc) {
796
  // Roughly refresh the proba eight times per pass
797
0
  int max_count = (enc->mb_w * enc->mb_h) >> 3;
798
0
  int num_pass_left = enc->config->pass;
799
0
  int remaining_progress = 40;  // percents
800
0
  const int do_search = enc->do_search;
801
0
  VP8EncIterator it;
802
0
  VP8EncProba* const proba = &enc->proba;
803
0
  const VP8RDLevel rd_opt = enc->rd_opt_level;
804
0
  const uint64_t pixel_count = (uint64_t)enc->mb_w * enc->mb_h * 384;
805
0
  PassStats stats;
806
0
  int ok;
807
808
0
  InitPassStats(enc, &stats);
809
0
  ok = PreLoopInitialize(enc);
810
0
  if (!ok) return 0;
811
812
0
  if (max_count < MIN_COUNT) max_count = MIN_COUNT;
813
814
0
  assert(enc->num_parts == 1);
815
0
  assert(enc->use_tokens);
816
0
  assert(proba->use_skip_proba == 0);
817
0
  assert(rd_opt >= RD_OPT_BASIC);  // otherwise, token-buffer won't be useful
818
0
  assert(num_pass_left > 0);
819
820
0
  while (ok && num_pass_left-- > 0) {
821
0
    const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) ||
822
0
                             (num_pass_left == 0) ||
823
0
                             (enc->max_i4_header_bits == 0);
824
0
    uint64_t size_p0 = 0;
825
0
    uint64_t distortion = 0;
826
0
    int cnt = max_count;
827
    // The final number of passes is not trivial to know in advance.
828
0
    const int pass_progress = remaining_progress / (2 + num_pass_left);
829
0
    remaining_progress -= pass_progress;
830
0
    VP8IteratorInit(enc, &it);
831
0
    SetLoopParams(enc, stats.q);
832
0
    if (is_last_pass) {
833
0
      ResetTokenStats(enc);
834
0
      VP8InitFilter(&it);  // don't collect stats until last pass (too costly)
835
0
    }
836
0
    VP8TBufferClear(&enc->tokens);
837
0
    do {
838
0
      VP8ModeScore info;
839
0
      VP8IteratorImport(&it, NULL);
840
0
      if (--cnt < 0) {
841
0
        FinalizeTokenProbas(proba);
842
0
        VP8CalculateLevelCosts(proba);  // refresh cost tables for rd-opt
843
0
        cnt = max_count;
844
0
      }
845
0
      VP8Decimate(&it, &info, rd_opt);
846
0
      ok = RecordTokens(&it, &info, &enc->tokens);
847
0
      if (!ok) {
848
0
        WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
849
0
        break;
850
0
      }
851
0
      size_p0 += info.H;
852
0
      distortion += info.D;
853
0
      if (is_last_pass) {
854
0
        StoreSideInfo(&it);
855
0
        VP8StoreFilterStats(&it);
856
0
        VP8IteratorExport(&it);
857
0
        ok = VP8IteratorProgress(&it, pass_progress);
858
0
      }
859
0
      VP8IteratorSaveBoundary(&it);
860
0
    } while (ok && VP8IteratorNext(&it));
861
0
    if (!ok) break;
862
863
0
    size_p0 += enc->segment_hdr.size;
864
0
    if (stats.do_size_search) {
865
0
      uint64_t size = FinalizeTokenProbas(&enc->proba);
866
0
      size += VP8EstimateTokenSize(&enc->tokens, (const uint8_t*)proba->coeffs);
867
0
      size = (size + size_p0 + 1024) >> 11;  // -> size in bytes
868
0
      size += HEADER_SIZE_ESTIMATE;
869
0
      stats.value = (double)size;
870
0
    } else {  // compute and store PSNR
871
0
      stats.value = GetPSNR(distortion, pixel_count);
872
0
    }
873
874
#if (DEBUG_SEARCH > 0)
875
    printf(
876
        "#%2d metric:%.1lf -> %.1lf   last_q=%.2lf q=%.2lf dq=%.2lf "
877
        " range:[%.1f, %.1f]\n",
878
        num_pass_left, stats.last_value, stats.value, stats.last_q, stats.q,
879
        stats.dq, stats.qmin, stats.qmax);
880
#endif
881
0
    if (enc->max_i4_header_bits > 0 && size_p0 > PARTITION0_SIZE_LIMIT) {
882
0
      ++num_pass_left;
883
0
      enc->max_i4_header_bits >>= 1;  // strengthen header bit limitation...
884
0
      if (is_last_pass) {
885
0
        ResetSideInfo(&it);
886
0
      }
887
0
      continue;  // ...and start over
888
0
    }
889
0
    if (is_last_pass) {
890
0
      break;  // done
891
0
    }
892
0
    if (do_search) {
893
0
      ComputeNextQ(&stats);  // Adjust q
894
0
    }
895
0
  }
896
0
  if (ok) {
897
0
    if (!stats.do_size_search) {
898
0
      FinalizeTokenProbas(&enc->proba);
899
0
    }
900
0
    ok = VP8EmitTokens(&enc->tokens, enc->parts + 0,
901
0
                       (const uint8_t*)proba->coeffs, 1);
902
0
  }
903
0
  ok = ok && WebPReportProgress(enc->pic, enc->percent + remaining_progress,
904
0
                                &enc->percent);
905
0
  return PostLoopFinalize(&it, ok);
906
0
}
907
908
#else
909
910
int VP8EncTokenLoop(VP8Encoder* const enc) {
911
  (void)enc;
912
  return 0;  // we shouldn't be here.
913
}
914
915
#endif  // DISABLE_TOKEN_BUFFER
916
917
//------------------------------------------------------------------------------