Coverage Report

Created: 2025-06-13 06:48

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