Coverage Report

Created: 2026-07-25 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp8/encoder/ratectrl.c
Line
Count
Source
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
11
#include <stdlib.h>
12
#include <stdio.h>
13
#include <string.h>
14
#include <limits.h>
15
#include <assert.h>
16
17
#include "math.h"
18
#include "vp8/common/common.h"
19
#include "ratectrl.h"
20
#include "vp8/common/entropymode.h"
21
#include "vpx_mem/vpx_mem.h"
22
#include "vp8/common/systemdependent.h"
23
#include "encodemv.h"
24
#include "vpx_dsp/vpx_dsp_common.h"
25
#include "vpx_ports/system_state.h"
26
27
54.9k
#define MIN_BPB_FACTOR 0.01
28
76.2k
#define MAX_BPB_FACTOR 50
29
30
extern const MB_PREDICTION_MODE vp8_mode_order[MAX_MODES];
31
32
#ifdef MODE_STATS
33
extern int y_modes[5];
34
extern int uv_modes[4];
35
extern int b_modes[10];
36
37
extern int inter_y_modes[10];
38
extern int inter_uv_modes[4];
39
extern int inter_b_modes[10];
40
#endif
41
42
/* Bits Per MB at different Q (Multiplied by 512) */
43
409k
#define BPER_MB_NORMBITS 9
44
45
/* Work in progress recalibration of baseline rate tables based on
46
 * the assumption that bits per mb is inversely proportional to the
47
 * quantizer value.
48
 */
49
const int vp8_bits_per_mb[2][QINDEX_RANGE] = {
50
  /* Intra case 450000/Qintra */
51
  {
52
      1125000, 900000, 750000, 642857, 562500, 500000, 450000, 450000, 409090,
53
      375000,  346153, 321428, 300000, 281250, 264705, 264705, 250000, 236842,
54
      225000,  225000, 214285, 214285, 204545, 204545, 195652, 195652, 187500,
55
      180000,  180000, 173076, 166666, 160714, 155172, 150000, 145161, 140625,
56
      136363,  132352, 128571, 125000, 121621, 121621, 118421, 115384, 112500,
57
      109756,  107142, 104651, 102272, 100000, 97826,  97826,  95744,  93750,
58
      91836,   90000,  88235,  86538,  84905,  83333,  81818,  80357,  78947,
59
      77586,   76271,  75000,  73770,  72580,  71428,  70312,  69230,  68181,
60
      67164,   66176,  65217,  64285,  63380,  62500,  61643,  60810,  60000,
61
      59210,   59210,  58441,  57692,  56962,  56250,  55555,  54878,  54216,
62
      53571,   52941,  52325,  51724,  51136,  50561,  49450,  48387,  47368,
63
      46875,   45918,  45000,  44554,  44117,  43269,  42452,  41666,  40909,
64
      40178,   39473,  38793,  38135,  36885,  36290,  35714,  35156,  34615,
65
      34090,   33582,  33088,  32608,  32142,  31468,  31034,  30405,  29801,
66
      29220,   28662,
67
  },
68
  /* Inter case 285000/Qinter */
69
  {
70
      712500, 570000, 475000, 407142, 356250, 316666, 285000, 259090, 237500,
71
      219230, 203571, 190000, 178125, 167647, 158333, 150000, 142500, 135714,
72
      129545, 123913, 118750, 114000, 109615, 105555, 101785, 98275,  95000,
73
      91935,  89062,  86363,  83823,  81428,  79166,  77027,  75000,  73076,
74
      71250,  69512,  67857,  66279,  64772,  63333,  61956,  60638,  59375,
75
      58163,  57000,  55882,  54807,  53773,  52777,  51818,  50892,  50000,
76
      49137,  47500,  45967,  44531,  43181,  41911,  40714,  39583,  38513,
77
      37500,  36538,  35625,  34756,  33928,  33139,  32386,  31666,  30978,
78
      30319,  29687,  29081,  28500,  27941,  27403,  26886,  26388,  25909,
79
      25446,  25000,  24568,  23949,  23360,  22800,  22265,  21755,  21268,
80
      20802,  20357,  19930,  19520,  19127,  18750,  18387,  18037,  17701,
81
      17378,  17065,  16764,  16473,  16101,  15745,  15405,  15079,  14766,
82
      14467,  14179,  13902,  13636,  13380,  13133,  12895,  12666,  12445,
83
      12179,  11924,  11632,  11445,  11220,  11003,  10795,  10594,  10401,
84
      10215,  10035,
85
  }
86
};
87
88
static const int kf_boost_qadjustment[QINDEX_RANGE] = {
89
  128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
90
  143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
91
  158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172,
92
  173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
93
  188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 200, 201,
94
  201, 202, 203, 203, 203, 204, 204, 205, 205, 206, 206, 207, 207, 208, 208,
95
  209, 209, 210, 210, 211, 211, 212, 212, 213, 213, 214, 214, 215, 215, 216,
96
  216, 217, 217, 218, 218, 219, 219, 220, 220, 220, 220, 220, 220, 220, 220,
97
  220, 220, 220, 220, 220, 220, 220, 220,
98
};
99
100
/* #define GFQ_ADJUSTMENT (Q+100) */
101
7.98k
#define GFQ_ADJUSTMENT vp8_gf_boost_qadjustment[Q]
102
const int vp8_gf_boost_qadjustment[QINDEX_RANGE] = {
103
  80,  82,  84,  86,  88,  90,  92,  94,  96,  97,  98,  99,  100, 101, 102,
104
  103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
105
  118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
106
  133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147,
107
  148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162,
108
  163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
109
  178, 179, 180, 181, 182, 183, 184, 184, 185, 185, 186, 186, 187, 187, 188,
110
  188, 189, 189, 190, 190, 191, 191, 192, 192, 193, 193, 194, 194, 194, 194,
111
  195, 195, 196, 196, 197, 197, 198, 198
112
};
113
114
/*
115
const int vp8_gf_boost_qadjustment[QINDEX_RANGE] =
116
{
117
    100,101,102,103,104,105,105,106,
118
    106,107,107,108,109,109,110,111,
119
    112,113,114,115,116,117,118,119,
120
    120,121,122,123,124,125,126,127,
121
    128,129,130,131,132,133,134,135,
122
    136,137,138,139,140,141,142,143,
123
    144,145,146,147,148,149,150,151,
124
    152,153,154,155,156,157,158,159,
125
    160,161,162,163,164,165,166,167,
126
    168,169,170,170,171,171,172,172,
127
    173,173,173,174,174,174,175,175,
128
    175,176,176,176,177,177,177,177,
129
    178,178,179,179,180,180,181,181,
130
    182,182,183,183,184,184,185,185,
131
    186,186,187,187,188,188,189,189,
132
    190,190,191,191,192,192,193,193,
133
};
134
*/
135
136
static const int kf_gf_boost_qlimits[QINDEX_RANGE] = {
137
  150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 215, 220,
138
  225, 230, 235, 240, 245, 250, 255, 260, 265, 270, 275, 280, 285, 290, 295,
139
  300, 305, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430,
140
  440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580,
141
  590, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
142
  600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
143
  600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
144
  600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
145
  600, 600, 600, 600, 600, 600, 600, 600,
146
};
147
148
static const int gf_adjust_table[101] = {
149
  100, 115, 130, 145, 160, 175, 190, 200, 210, 220, 230, 240, 260, 270, 280,
150
  290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 400, 400, 400,
151
  400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
152
  400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
153
  400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
154
  400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
155
  400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
156
};
157
158
static const int gf_intra_usage_adjustment[20] = {
159
  125, 120, 115, 110, 105, 100, 95, 85, 80, 75,
160
  70,  65,  60,  55,  50,  50,  50, 50, 50, 50,
161
};
162
163
static const int gf_interval_table[101] = {
164
  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,
165
  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  8,  8,  8,
166
  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
167
  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,  9,
168
  9,  9,  9,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
169
  10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
170
};
171
172
static const unsigned int prior_key_frame_weight[KEY_FRAME_CONTEXT] = { 1, 2, 3,
173
                                                                        4, 5 };
174
175
103k
void vp8_save_coding_context(VP8_COMP *cpi) {
176
103k
  CODING_CONTEXT *const cc = &cpi->coding_context;
177
178
  /* Stores a snapshot of key state variables which can subsequently be
179
   * restored with a call to vp8_restore_coding_context. These functions are
180
   * intended for use in a re-code loop in vp8_compress_frame where the
181
   * quantizer value is adjusted between loop iterations.
182
   */
183
184
103k
  cc->frames_since_key = cpi->frames_since_key;
185
103k
  cc->filter_level = cpi->common.filter_level;
186
103k
  cc->frames_till_gf_update_due = cpi->frames_till_gf_update_due;
187
103k
  cc->frames_since_golden = cpi->frames_since_golden;
188
189
103k
  vp8_copy(cc->mvc, cpi->common.fc.mvc);
190
103k
  vp8_copy(cc->mvcosts, cpi->rd_costs.mvcosts);
191
192
103k
  vp8_copy(cc->ymode_prob, cpi->common.fc.ymode_prob);
193
103k
  vp8_copy(cc->uv_mode_prob, cpi->common.fc.uv_mode_prob);
194
195
103k
  vp8_copy(cc->ymode_count, cpi->mb.ymode_count);
196
103k
  vp8_copy(cc->uv_mode_count, cpi->mb.uv_mode_count);
197
198
/* Stats */
199
#ifdef MODE_STATS
200
  vp8_copy(cc->y_modes, y_modes);
201
  vp8_copy(cc->uv_modes, uv_modes);
202
  vp8_copy(cc->b_modes, b_modes);
203
  vp8_copy(cc->inter_y_modes, inter_y_modes);
204
  vp8_copy(cc->inter_uv_modes, inter_uv_modes);
205
  vp8_copy(cc->inter_b_modes, inter_b_modes);
206
#endif
207
208
103k
  cc->this_frame_percent_intra = cpi->this_frame_percent_intra;
209
103k
}
210
211
29.9k
void vp8_restore_coding_context(VP8_COMP *cpi) {
212
29.9k
  CODING_CONTEXT *const cc = &cpi->coding_context;
213
214
  /* Restore key state variables to the snapshot state stored in the
215
   * previous call to vp8_save_coding_context.
216
   */
217
218
29.9k
  cpi->frames_since_key = cc->frames_since_key;
219
29.9k
  cpi->common.filter_level = cc->filter_level;
220
29.9k
  cpi->frames_till_gf_update_due = cc->frames_till_gf_update_due;
221
29.9k
  cpi->frames_since_golden = cc->frames_since_golden;
222
223
29.9k
  vp8_copy(cpi->common.fc.mvc, cc->mvc);
224
225
29.9k
  vp8_copy(cpi->rd_costs.mvcosts, cc->mvcosts);
226
227
29.9k
  vp8_copy(cpi->common.fc.ymode_prob, cc->ymode_prob);
228
29.9k
  vp8_copy(cpi->common.fc.uv_mode_prob, cc->uv_mode_prob);
229
230
29.9k
  vp8_copy(cpi->mb.ymode_count, cc->ymode_count);
231
29.9k
  vp8_copy(cpi->mb.uv_mode_count, cc->uv_mode_count);
232
233
/* Stats */
234
#ifdef MODE_STATS
235
  vp8_copy(y_modes, cc->y_modes);
236
  vp8_copy(uv_modes, cc->uv_modes);
237
  vp8_copy(b_modes, cc->b_modes);
238
  vp8_copy(inter_y_modes, cc->inter_y_modes);
239
  vp8_copy(inter_uv_modes, cc->inter_uv_modes);
240
  vp8_copy(inter_b_modes, cc->inter_b_modes);
241
#endif
242
243
29.9k
  cpi->this_frame_percent_intra = cc->this_frame_percent_intra;
244
29.9k
}
245
246
30.6k
void vp8_setup_key_frame(VP8_COMP *cpi) {
247
  /* Setup for Key frame: */
248
249
30.6k
  vp8_default_coef_probs(&cpi->common);
250
251
30.6k
  memcpy(cpi->common.fc.mvc, vp8_default_mv_context,
252
30.6k
         sizeof(vp8_default_mv_context));
253
30.6k
  {
254
30.6k
    int flag[2] = { 1, 1 };
255
30.6k
    vp8_build_component_cost_table(
256
30.6k
        cpi->mb.mvcost, (const MV_CONTEXT *)cpi->common.fc.mvc, flag);
257
30.6k
  }
258
259
  /* Make sure we initialize separate contexts for altref,gold, and normal.
260
   * TODO shouldn't need 3 different copies of structure to do this!
261
   */
262
30.6k
  cpi->lfc_a = cpi->common.fc;
263
30.6k
  cpi->lfc_g = cpi->common.fc;
264
30.6k
  cpi->lfc_n = cpi->common.fc;
265
266
30.6k
  cpi->common.filter_level = cpi->common.base_qindex * 3 / 8;
267
268
  /* Provisional interval before next GF */
269
30.6k
  if (cpi->auto_gold) {
270
30.6k
    cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
271
30.6k
  } else {
272
0
    cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
273
0
  }
274
275
30.6k
  cpi->common.refresh_golden_frame = 1;
276
30.6k
  cpi->common.refresh_alt_ref_frame = 1;
277
30.6k
}
278
279
static int estimate_bits_at_q(int frame_kind, int Q, int MBs,
280
0
                              double correction_factor) {
281
0
  int Bpm = (int)(.5 + correction_factor * vp8_bits_per_mb[frame_kind][Q]);
282
283
  /* Attempt to retain reasonable accuracy without overflow. The cutoff is
284
   * chosen such that the maximum product of Bpm and MBs fits 31 bits. The
285
   * largest Bpm takes 20 bits.
286
   */
287
0
  if (MBs > (1 << 11)) {
288
0
    return (Bpm >> BPER_MB_NORMBITS) * MBs;
289
0
  } else {
290
0
    return (Bpm * MBs) >> BPER_MB_NORMBITS;
291
0
  }
292
0
}
293
294
18.2k
static void calc_iframe_target_size(VP8_COMP *cpi) {
295
  /* boost defaults to half second */
296
18.2k
  int kf_boost;
297
18.2k
  uint64_t target;
298
299
  /* Clear down mmx registers to allow floating point in what follows */
300
18.2k
  vpx_clear_system_state();
301
302
18.2k
  if (cpi->oxcf.fixed_q >= 0) {
303
0
    int Q = cpi->oxcf.key_q;
304
305
0
    target = estimate_bits_at_q(INTRA_FRAME, Q, cpi->common.MBs,
306
0
                                cpi->key_frame_rate_correction_factor);
307
18.2k
  } else if (cpi->pass == 2) {
308
    /* New Two pass RC */
309
0
    target = cpi->per_frame_bandwidth;
310
0
  }
311
  /* First Frame is a special case */
312
18.2k
  else if (cpi->common.current_video_frame == 0) {
313
    /* 1 Pass there is no information on which to base size so use
314
     * bandwidth per second * fraction of the initial buffer
315
     * level
316
     */
317
5.04k
    target = (uint64_t)cpi->oxcf.starting_buffer_level / 2;
318
319
5.04k
    if (target > cpi->oxcf.target_bandwidth * 3 / 2) {
320
4.91k
      target = cpi->oxcf.target_bandwidth * 3 / 2;
321
4.91k
    }
322
13.1k
  } else {
323
    /* if this keyframe was forced, use a more recent Q estimate */
324
13.1k
    int Q = (cpi->common.frame_flags & FRAMEFLAGS_KEY) ? cpi->avg_frame_qindex
325
13.1k
                                                       : cpi->ni_av_qi;
326
327
13.1k
    int initial_boost = 32; /* |3.0 * per_frame_bandwidth| */
328
    /* Boost depends somewhat on frame rate: only used for 1 layer case. */
329
13.1k
    if (cpi->oxcf.number_of_layers == 1) {
330
13.1k
      kf_boost =
331
13.1k
          VPXMAX(initial_boost, (int)round(2 * cpi->output_framerate - 16));
332
      // cpi->output_framerate may be as large as 10M. Keep kf_boost small
333
      // enough to allow for integer math when multiplying by values in
334
      // kf_boost_qadjustment[].
335
13.1k
      const int kMaxKfBoost = 2000;
336
13.1k
      if (kf_boost > kMaxKfBoost) kf_boost = kMaxKfBoost;
337
13.1k
    } else {
338
      /* Initial factor: set target size to: |3.0 * per_frame_bandwidth|. */
339
0
      kf_boost = initial_boost;
340
0
    }
341
342
    /* adjustment up based on q: this factor ranges from ~1.2 to 2.2. */
343
13.1k
    kf_boost = kf_boost * kf_boost_qadjustment[Q] / 100;
344
345
    /* frame separation adjustment ( down) */
346
13.1k
    if (cpi->frames_since_key < cpi->output_framerate / 2) {
347
8.96k
      kf_boost =
348
8.96k
          (int)(kf_boost * cpi->frames_since_key / (cpi->output_framerate / 2));
349
8.96k
    }
350
351
    /* Minimal target size is |2* per_frame_bandwidth|. */
352
13.1k
    if (kf_boost < 16) kf_boost = 16;
353
354
13.1k
    target = ((uint64_t)(16 + kf_boost) * cpi->per_frame_bandwidth) >> 4;
355
13.1k
    target = VPXMIN(INT_MAX, target);
356
13.1k
  }
357
358
18.2k
  if (cpi->oxcf.rc_max_intra_bitrate_pct) {
359
0
    unsigned int max_rate;
360
    // This product may overflow unsigned int
361
0
    uint64_t product = cpi->per_frame_bandwidth;
362
0
    product *= cpi->oxcf.rc_max_intra_bitrate_pct;
363
0
    product /= 100;
364
0
    max_rate = (unsigned int)VPXMIN(INT_MAX, product);
365
366
0
    if (target > max_rate) target = max_rate;
367
0
  }
368
369
18.2k
  cpi->this_frame_target = (int)target;
370
371
  /* TODO: if we separate rate targeting from Q targeting, move this.
372
   * Reset the active worst quality to the baseline value for key frames.
373
   */
374
18.2k
  if (cpi->pass != 2) cpi->active_worst_quality = cpi->worst_quality;
375
376
#if 0
377
    {
378
        FILE *f;
379
380
        f = fopen("kf_boost.stt", "a");
381
        fprintf(f, " %8u %10d %10d %10d\n",
382
                cpi->common.current_video_frame,  cpi->gfu_boost, cpi->baseline_gf_interval, cpi->source_alt_ref_pending);
383
384
        fclose(f);
385
    }
386
#endif
387
18.2k
}
388
389
/* Do the best we can to define the parameters for the next GF based on what
390
 * information we have available.
391
 */
392
7.98k
static void calc_gf_params(VP8_COMP *cpi) {
393
7.98k
  int Q =
394
7.98k
      (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
395
7.98k
  int Boost = 0;
396
397
7.98k
  int gf_frame_usage = 0; /* Golden frame usage since last GF */
398
7.98k
  int tot_mbs = cpi->recent_ref_frame_usage[INTRA_FRAME] +
399
7.98k
                cpi->recent_ref_frame_usage[LAST_FRAME] +
400
7.98k
                cpi->recent_ref_frame_usage[GOLDEN_FRAME] +
401
7.98k
                cpi->recent_ref_frame_usage[ALTREF_FRAME];
402
403
7.98k
  int pct_gf_active = (100 * cpi->gf_active_count) /
404
7.98k
                      (cpi->common.mb_rows * cpi->common.mb_cols);
405
406
7.98k
  if (tot_mbs) {
407
7.98k
    gf_frame_usage = (cpi->recent_ref_frame_usage[GOLDEN_FRAME] +
408
7.98k
                      cpi->recent_ref_frame_usage[ALTREF_FRAME]) *
409
7.98k
                     100 / tot_mbs;
410
7.98k
  }
411
412
7.98k
  if (pct_gf_active > gf_frame_usage) gf_frame_usage = pct_gf_active;
413
414
  /* Not two pass */
415
7.98k
  if (cpi->pass != 2) {
416
    /* Single Pass lagged mode: TBD */
417
7.98k
    if (0) {
418
0
    }
419
420
    /* Single Pass compression: Has to use current and historical data */
421
7.98k
    else {
422
#if 0
423
            /* Experimental code */
424
            int index = cpi->one_pass_frame_index;
425
            int frames_to_scan = (cpi->max_gf_interval <= MAX_LAG_BUFFERS) ? cpi->max_gf_interval : MAX_LAG_BUFFERS;
426
427
            /* ************** Experimental code - incomplete */
428
            /*
429
            double decay_val = 1.0;
430
            double IIAccumulator = 0.0;
431
            double last_iiaccumulator = 0.0;
432
            double IIRatio;
433
434
            cpi->one_pass_frame_index = cpi->common.current_video_frame%MAX_LAG_BUFFERS;
435
436
            for ( i = 0; i < (frames_to_scan - 1); i++ )
437
            {
438
                if ( index < 0 )
439
                    index = MAX_LAG_BUFFERS;
440
                index --;
441
442
                if ( cpi->one_pass_frame_stats[index].frame_coded_error > 0.0 )
443
                {
444
                    IIRatio = cpi->one_pass_frame_stats[index].frame_intra_error / cpi->one_pass_frame_stats[index].frame_coded_error;
445
446
                    if ( IIRatio > 30.0 )
447
                        IIRatio = 30.0;
448
                }
449
                else
450
                    IIRatio = 30.0;
451
452
                IIAccumulator += IIRatio * decay_val;
453
454
                decay_val = decay_val * cpi->one_pass_frame_stats[index].frame_pcnt_inter;
455
456
                if (    (i > MIN_GF_INTERVAL) &&
457
                        ((IIAccumulator - last_iiaccumulator) < 2.0) )
458
                {
459
                    break;
460
                }
461
                last_iiaccumulator = IIAccumulator;
462
            }
463
464
            Boost = IIAccumulator*100.0/16.0;
465
            cpi->baseline_gf_interval = i;
466
467
            */
468
#else
469
470
      /*************************************************************/
471
      /* OLD code */
472
473
      /* Adjust boost based upon ambient Q */
474
7.98k
      Boost = GFQ_ADJUSTMENT;
475
476
      /* Adjust based upon most recently measure intra usage */
477
7.98k
      Boost = Boost *
478
7.98k
              gf_intra_usage_adjustment[(cpi->this_frame_percent_intra < 15)
479
7.98k
                                            ? cpi->this_frame_percent_intra
480
7.98k
                                            : 14] /
481
7.98k
              100;
482
483
      /* Adjust gf boost based upon GF usage since last GF */
484
7.98k
      Boost = Boost * gf_adjust_table[gf_frame_usage] / 100;
485
7.98k
#endif
486
7.98k
    }
487
488
    /* golden frame boost without recode loop often goes awry.  be
489
     * safe by keeping numbers down.
490
     */
491
7.98k
    if (!cpi->sf.recode_loop) {
492
4.93k
      if (cpi->compressor_speed == 2) Boost = Boost / 2;
493
4.93k
    }
494
495
    /* Apply an upper limit based on Q for 1 pass encodes */
496
7.98k
    if (Boost > kf_gf_boost_qlimits[Q] && (cpi->pass == 0)) {
497
3.44k
      Boost = kf_gf_boost_qlimits[Q];
498
499
      /* Apply lower limits to boost. */
500
4.54k
    } else if (Boost < 110) {
501
1.40k
      Boost = 110;
502
1.40k
    }
503
504
    /* Note the boost used */
505
7.98k
    cpi->last_boost = Boost;
506
7.98k
  }
507
508
  /* Estimate next interval
509
   * This is updated once the real frame size/boost is known.
510
   */
511
7.98k
  if (cpi->oxcf.fixed_q == -1) {
512
7.98k
    if (cpi->pass == 2) { /* 2 Pass */
513
0
      cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
514
7.98k
    } else { /* 1 Pass */
515
7.98k
      cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
516
517
7.98k
      if (cpi->last_boost > 750) cpi->frames_till_gf_update_due++;
518
519
7.98k
      if (cpi->last_boost > 1000) cpi->frames_till_gf_update_due++;
520
521
7.98k
      if (cpi->last_boost > 1250) cpi->frames_till_gf_update_due++;
522
523
7.98k
      if (cpi->last_boost >= 1500) cpi->frames_till_gf_update_due++;
524
525
7.98k
      if (gf_interval_table[gf_frame_usage] > cpi->frames_till_gf_update_due) {
526
4.25k
        cpi->frames_till_gf_update_due = gf_interval_table[gf_frame_usage];
527
4.25k
      }
528
529
7.98k
      if (cpi->frames_till_gf_update_due > cpi->max_gf_interval) {
530
25
        cpi->frames_till_gf_update_due = cpi->max_gf_interval;
531
25
      }
532
7.98k
    }
533
7.98k
  } else {
534
0
    cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
535
0
  }
536
537
  /* ARF on or off */
538
7.98k
  if (cpi->pass != 2) {
539
    /* For now Alt ref is not allowed except in 2 pass modes. */
540
7.98k
    cpi->source_alt_ref_pending = 0;
541
542
    /*if ( cpi->oxcf.fixed_q == -1)
543
    {
544
        if ( cpi->oxcf.play_alternate && (cpi->last_boost > (100 +
545
    (AF_THRESH*cpi->frames_till_gf_update_due)) ) )
546
            cpi->source_alt_ref_pending = 1;
547
        else
548
            cpi->source_alt_ref_pending = 0;
549
    }*/
550
7.98k
  }
551
7.98k
}
552
553
87.8k
static void calc_pframe_target_size(VP8_COMP *cpi) {
554
87.8k
  int min_frame_target;
555
87.8k
  int old_per_frame_bandwidth = cpi->per_frame_bandwidth;
556
557
87.8k
  if (cpi->current_layer > 0) {
558
0
    cpi->per_frame_bandwidth =
559
0
        cpi->layer_context[cpi->current_layer].avg_frame_size_for_layer;
560
0
  }
561
562
87.8k
  min_frame_target = 0;
563
564
87.8k
  if (cpi->pass == 2) {
565
0
    min_frame_target = cpi->min_frame_bandwidth;
566
567
0
    if (min_frame_target < (cpi->av_per_frame_bandwidth >> 5)) {
568
0
      min_frame_target = cpi->av_per_frame_bandwidth >> 5;
569
0
    }
570
87.8k
  } else if (min_frame_target < cpi->per_frame_bandwidth / 4) {
571
84.0k
    min_frame_target = cpi->per_frame_bandwidth / 4;
572
84.0k
  }
573
574
  /* Special alt reference frame case */
575
87.8k
  if ((cpi->common.refresh_alt_ref_frame) &&
576
0
      (cpi->oxcf.number_of_layers == 1)) {
577
0
    if (cpi->pass == 2) {
578
      /* Per frame bit target for the alt ref frame */
579
0
      cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
580
0
      cpi->this_frame_target = cpi->per_frame_bandwidth;
581
0
    }
582
583
    /* One Pass ??? TBD */
584
0
  }
585
586
  /* Normal frames (gf,and inter) */
587
87.8k
  else {
588
    /* 2 pass */
589
87.8k
    if (cpi->pass == 2) {
590
0
      cpi->this_frame_target = cpi->per_frame_bandwidth;
591
0
    }
592
    /* 1 pass */
593
87.8k
    else {
594
87.8k
      int Adjustment;
595
      /* Make rate adjustment to recover bits spent in key frame
596
       * Test to see if the key frame inter data rate correction
597
       * should still be in force
598
       */
599
87.8k
      if (cpi->kf_overspend_bits > 0) {
600
37.0k
        Adjustment = (cpi->kf_bitrate_adjustment <= cpi->kf_overspend_bits)
601
37.0k
                         ? cpi->kf_bitrate_adjustment
602
37.0k
                         : cpi->kf_overspend_bits;
603
604
37.0k
        if (Adjustment > (cpi->per_frame_bandwidth - min_frame_target)) {
605
5.58k
          Adjustment = (cpi->per_frame_bandwidth - min_frame_target);
606
5.58k
        }
607
608
37.0k
        cpi->kf_overspend_bits -= Adjustment;
609
610
        /* Calculate an inter frame bandwidth target for the next
611
         * few frames designed to recover any extra bits spent on
612
         * the key frame.
613
         */
614
37.0k
        cpi->this_frame_target = cpi->per_frame_bandwidth - Adjustment;
615
616
37.0k
        if (cpi->this_frame_target < min_frame_target) {
617
0
          cpi->this_frame_target = min_frame_target;
618
0
        }
619
50.8k
      } else {
620
50.8k
        cpi->this_frame_target = cpi->per_frame_bandwidth;
621
50.8k
      }
622
623
      /* If appropriate make an adjustment to recover bits spent on a
624
       * recent GF
625
       */
626
87.8k
      if ((cpi->gf_overspend_bits > 0) &&
627
46.5k
          (cpi->this_frame_target > min_frame_target)) {
628
40.5k
        Adjustment = (cpi->non_gf_bitrate_adjustment <= cpi->gf_overspend_bits)
629
40.5k
                         ? cpi->non_gf_bitrate_adjustment
630
40.5k
                         : cpi->gf_overspend_bits;
631
632
40.5k
        if (Adjustment > (cpi->this_frame_target - min_frame_target)) {
633
2.85k
          Adjustment = (cpi->this_frame_target - min_frame_target);
634
2.85k
        }
635
636
40.5k
        cpi->gf_overspend_bits -= Adjustment;
637
40.5k
        cpi->this_frame_target -= Adjustment;
638
40.5k
      }
639
640
      /* Apply small + and - boosts for non gf frames */
641
87.8k
      if ((cpi->last_boost > 150) && (cpi->frames_till_gf_update_due > 0) &&
642
49.7k
          (cpi->current_gf_interval >= (MIN_GF_INTERVAL << 1))) {
643
        /* % Adjustment limited to the range 1% to 10% */
644
31.8k
        Adjustment = (cpi->last_boost - 100) >> 5;
645
646
31.8k
        if (Adjustment > 10) {
647
10.6k
          Adjustment = 10;
648
10.6k
        }
649
31.8k
        assert(Adjustment >= 1);
650
651
        /* Convert to bits */
652
31.8k
        Adjustment = (cpi->this_frame_target * Adjustment) / 100;
653
654
31.8k
        if (Adjustment > (cpi->this_frame_target - min_frame_target)) {
655
938
          Adjustment = (cpi->this_frame_target - min_frame_target);
656
938
        }
657
658
31.8k
        if (cpi->frames_since_golden == (cpi->current_gf_interval >> 1)) {
659
3.50k
          Adjustment = (cpi->current_gf_interval - 1) * Adjustment;
660
          // Limit adjustment to 10% of current target.
661
3.50k
          if (Adjustment > (10 * cpi->this_frame_target) / 100) {
662
3.26k
            Adjustment = (10 * cpi->this_frame_target) / 100;
663
3.26k
          }
664
3.50k
          cpi->this_frame_target += Adjustment;
665
28.3k
        } else {
666
28.3k
          cpi->this_frame_target -= Adjustment;
667
28.3k
        }
668
31.8k
      }
669
87.8k
    }
670
87.8k
  }
671
672
  /* Sanity check that the total sum of adjustments is not above the
673
   * maximum allowed That is that having allowed for KF and GF penalties
674
   * we have not pushed the current interframe target to low. If the
675
   * adjustment we apply here is not capable of recovering all the extra
676
   * bits we have spent in the KF or GF then the remainder will have to
677
   * be recovered over a longer time span via other buffer / rate control
678
   * mechanisms.
679
   */
680
87.8k
  if (cpi->this_frame_target < min_frame_target) {
681
0
    cpi->this_frame_target = min_frame_target;
682
0
  }
683
684
87.8k
  if (!cpi->common.refresh_alt_ref_frame) {
685
    /* Note the baseline target data rate for this inter frame. */
686
87.8k
    cpi->inter_frame_target = cpi->this_frame_target;
687
87.8k
  }
688
689
  /* One Pass specific code */
690
87.8k
  if (cpi->pass == 0) {
691
    /* Adapt target frame size with respect to any buffering constraints: */
692
87.8k
    if (cpi->buffered_mode) {
693
84.5k
      int one_percent_bits = (int)(1 + cpi->oxcf.optimal_buffer_level / 100);
694
695
84.5k
      if ((cpi->buffer_level < cpi->oxcf.optimal_buffer_level) ||
696
52.1k
          (cpi->bits_off_target < cpi->oxcf.optimal_buffer_level)) {
697
52.1k
        int percent_low = 0;
698
699
        /* Decide whether or not we need to adjust the frame data
700
         * rate target.
701
         *
702
         * If we are are below the optimal buffer fullness level
703
         * and adherence to buffering constraints is important to
704
         * the end usage then adjust the per frame target.
705
         */
706
52.1k
        if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
707
0
            (cpi->buffer_level < cpi->oxcf.optimal_buffer_level)) {
708
0
          percent_low =
709
0
              (int)((cpi->oxcf.optimal_buffer_level - cpi->buffer_level) /
710
0
                    one_percent_bits);
711
0
        }
712
        /* Are we overshooting the long term clip data rate... */
713
52.1k
        else if (cpi->bits_off_target < 0) {
714
          /* Adjust per frame data target downwards to compensate. */
715
16.5k
          percent_low =
716
16.5k
              (int)(100 * -cpi->bits_off_target / (cpi->total_byte_count * 8));
717
16.5k
        }
718
719
52.1k
        if (percent_low > cpi->oxcf.under_shoot_pct) {
720
0
          percent_low = cpi->oxcf.under_shoot_pct;
721
52.1k
        } else if (percent_low < 0) {
722
0
          percent_low = 0;
723
0
        }
724
725
        /* lower the target bandwidth for this frame. */
726
52.1k
        cpi->this_frame_target -=
727
52.1k
            (int)(((int64_t)cpi->this_frame_target * percent_low) / 200);
728
729
        /* Are we using allowing control of active_worst_allowed_q
730
         * according to buffer level.
731
         */
732
52.1k
        if (cpi->auto_worst_q && cpi->ni_frames > 150) {
733
5.53k
          int64_t critical_buffer_level;
734
735
          /* For streaming applications the most important factor is
736
           * cpi->buffer_level as this takes into account the
737
           * specified short term buffering constraints. However,
738
           * hitting the long term clip data rate target is also
739
           * important.
740
           */
741
5.53k
          if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
742
            /* Take the smaller of cpi->buffer_level and
743
             * cpi->bits_off_target
744
             */
745
0
            critical_buffer_level = (cpi->buffer_level < cpi->bits_off_target)
746
0
                                        ? cpi->buffer_level
747
0
                                        : cpi->bits_off_target;
748
0
          }
749
          /* For local file playback short term buffering constraints
750
           * are less of an issue
751
           */
752
5.53k
          else {
753
            /* Consider only how we are doing for the clip as a
754
             * whole
755
             */
756
5.53k
            critical_buffer_level = cpi->bits_off_target;
757
5.53k
          }
758
759
          /* Set the active worst quality based upon the selected
760
           * buffer fullness number.
761
           */
762
5.53k
          if (critical_buffer_level < cpi->oxcf.optimal_buffer_level) {
763
5.53k
            if (critical_buffer_level > (cpi->oxcf.optimal_buffer_level >> 2)) {
764
2.52k
              int64_t qadjustment_range = cpi->worst_quality - cpi->ni_av_qi;
765
2.52k
              int64_t above_base = (critical_buffer_level -
766
2.52k
                                    (cpi->oxcf.optimal_buffer_level >> 2));
767
768
              /* Step active worst quality down from
769
               * cpi->ni_av_qi when (critical_buffer_level ==
770
               * cpi->optimal_buffer_level) to
771
               * cpi->worst_quality when
772
               * (critical_buffer_level ==
773
               *     cpi->optimal_buffer_level >> 2)
774
               */
775
2.52k
              cpi->active_worst_quality =
776
2.52k
                  cpi->worst_quality -
777
2.52k
                  (int)((qadjustment_range * above_base) /
778
2.52k
                        (cpi->oxcf.optimal_buffer_level * 3 >> 2));
779
3.00k
            } else {
780
3.00k
              cpi->active_worst_quality = cpi->worst_quality;
781
3.00k
            }
782
5.53k
          } else {
783
0
            cpi->active_worst_quality = cpi->ni_av_qi;
784
0
          }
785
46.5k
        } else {
786
46.5k
          cpi->active_worst_quality = cpi->worst_quality;
787
46.5k
        }
788
52.1k
      } else {
789
32.4k
        int percent_high = 0;
790
32.4k
        int64_t target = cpi->this_frame_target;
791
792
32.4k
        if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
793
0
            (cpi->buffer_level > cpi->oxcf.optimal_buffer_level)) {
794
0
          percent_high =
795
0
              (int)((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) /
796
0
                    one_percent_bits);
797
32.4k
        } else if (cpi->bits_off_target > cpi->oxcf.optimal_buffer_level) {
798
31.8k
          if (cpi->total_byte_count > 0) {
799
31.8k
            percent_high = (int)((100 * cpi->bits_off_target) /
800
31.8k
                                 (cpi->total_byte_count * 8));
801
31.8k
          } else {
802
0
            percent_high = cpi->oxcf.over_shoot_pct;
803
0
          }
804
31.8k
        }
805
806
32.4k
        if (percent_high > cpi->oxcf.over_shoot_pct) {
807
30.3k
          percent_high = cpi->oxcf.over_shoot_pct;
808
30.3k
        } else if (percent_high < 0) {
809
0
          percent_high = 0;
810
0
        }
811
812
32.4k
        target += (target * percent_high) / 200;
813
32.4k
        target = VPXMIN(target, INT_MAX);
814
32.4k
        cpi->this_frame_target = (int)target;
815
816
        /* Are we allowing control of active_worst_allowed_q according
817
         * to buffer level.
818
         */
819
32.4k
        if (cpi->auto_worst_q && cpi->ni_frames > 150) {
820
          /* When using the relaxed buffer model stick to the
821
           * user specified value
822
           */
823
2.82k
          cpi->active_worst_quality = cpi->ni_av_qi;
824
29.6k
        } else {
825
29.6k
          cpi->active_worst_quality = cpi->worst_quality;
826
29.6k
        }
827
32.4k
      }
828
829
      /* Set active_best_quality to prevent quality rising too high */
830
84.5k
      cpi->active_best_quality = cpi->best_quality;
831
832
      /* Worst quality obviously must not be better than best quality */
833
84.5k
      if (cpi->active_worst_quality <= cpi->active_best_quality) {
834
1.17k
        cpi->active_worst_quality = cpi->active_best_quality + 1;
835
1.17k
      }
836
837
84.5k
      if (cpi->active_worst_quality > 127) cpi->active_worst_quality = 127;
838
84.5k
    }
839
    /* Unbuffered mode (eg. video conferencing) */
840
3.29k
    else {
841
      /* Set the active worst quality */
842
3.29k
      cpi->active_worst_quality = cpi->worst_quality;
843
3.29k
    }
844
845
    /* Special trap for constrained quality mode
846
     * "active_worst_quality" may never drop below cq level
847
     * for any frame type.
848
     */
849
87.8k
    if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY &&
850
18.0k
        cpi->active_worst_quality < cpi->cq_target_quality) {
851
0
      cpi->active_worst_quality = cpi->cq_target_quality;
852
0
    }
853
87.8k
  }
854
855
  /* Test to see if we have to drop a frame
856
   * The auto-drop frame code is only used in buffered mode.
857
   * In unbufferd mode (eg vide conferencing) the descision to
858
   * code or drop a frame is made outside the codec in response to real
859
   * world comms or buffer considerations.
860
   */
861
87.8k
  if (cpi->drop_frames_allowed &&
862
0
      (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
863
0
      ((cpi->common.frame_type != KEY_FRAME))) {
864
    /* Check for a buffer underun-crisis in which case we have to drop
865
     * a frame
866
     */
867
0
    if ((cpi->buffer_level < 0)) {
868
#if 0
869
            FILE *f = fopen("dec.stt", "a");
870
            fprintf(f, "%10d %10d %10d %10d ***** BUFFER EMPTY\n",
871
                    (int) cpi->common.current_video_frame,
872
                    cpi->decimation_factor, cpi->common.horiz_scale,
873
                    (cpi->buffer_level * 100) / cpi->oxcf.optimal_buffer_level);
874
            fclose(f);
875
#endif
876
0
      cpi->drop_frame = 1;
877
878
      /* Update the buffer level variable. */
879
0
      cpi->bits_off_target += cpi->av_per_frame_bandwidth;
880
0
      if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
881
0
        cpi->bits_off_target = (int)cpi->oxcf.maximum_buffer_size;
882
0
      }
883
0
      cpi->buffer_level = cpi->bits_off_target;
884
885
0
      if (cpi->oxcf.number_of_layers > 1) {
886
0
        unsigned int i;
887
888
        // Propagate bits saved by dropping the frame to higher layers.
889
0
        for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
890
0
          LAYER_CONTEXT *lc = &cpi->layer_context[i];
891
0
          lc->bits_off_target += (int)(lc->target_bandwidth / lc->framerate);
892
0
          if (lc->bits_off_target > lc->maximum_buffer_size) {
893
0
            lc->bits_off_target = lc->maximum_buffer_size;
894
0
          }
895
0
          lc->buffer_level = lc->bits_off_target;
896
0
        }
897
0
      }
898
0
    }
899
0
  }
900
901
  /* Adjust target frame size for Golden Frames: */
902
87.8k
  if (cpi->oxcf.error_resilient_mode == 0 &&
903
87.8k
      (cpi->frames_till_gf_update_due == 0) && !cpi->drop_frame) {
904
9.13k
    if (!cpi->gf_update_onepass_cbr) {
905
9.13k
      int Q = (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME]
906
9.13k
                                      : cpi->oxcf.fixed_q;
907
908
9.13k
      int gf_frame_usage = 0; /* Golden frame usage since last GF */
909
9.13k
      int tot_mbs = cpi->recent_ref_frame_usage[INTRA_FRAME] +
910
9.13k
                    cpi->recent_ref_frame_usage[LAST_FRAME] +
911
9.13k
                    cpi->recent_ref_frame_usage[GOLDEN_FRAME] +
912
9.13k
                    cpi->recent_ref_frame_usage[ALTREF_FRAME];
913
914
9.13k
      int pct_gf_active = (100 * cpi->gf_active_count) /
915
9.13k
                          (cpi->common.mb_rows * cpi->common.mb_cols);
916
917
9.13k
      if (tot_mbs) {
918
9.13k
        gf_frame_usage = (cpi->recent_ref_frame_usage[GOLDEN_FRAME] +
919
9.13k
                          cpi->recent_ref_frame_usage[ALTREF_FRAME]) *
920
9.13k
                         100 / tot_mbs;
921
9.13k
      }
922
923
9.13k
      if (pct_gf_active > gf_frame_usage) gf_frame_usage = pct_gf_active;
924
925
      /* Is a fixed manual GF frequency being used */
926
9.13k
      if (cpi->auto_gold) {
927
        /* For one pass throw a GF if recent frame intra usage is
928
         * low or the GF usage is high
929
         */
930
9.13k
        if ((cpi->pass == 0) &&
931
9.13k
            (cpi->this_frame_percent_intra < 15 || gf_frame_usage >= 5)) {
932
7.98k
          cpi->common.refresh_golden_frame = 1;
933
934
          /* Two pass GF descision */
935
7.98k
        } else if (cpi->pass == 2) {
936
0
          cpi->common.refresh_golden_frame = 1;
937
0
        }
938
9.13k
      }
939
940
#if 0
941
942
          /* Debug stats */
943
          if (0) {
944
              FILE *f;
945
946
              f = fopen("gf_usaget.stt", "a");
947
              fprintf(f, " %8ld %10ld %10ld %10ld %10ld\n",
948
                      cpi->common.current_video_frame,  cpi->gfu_boost,
949
                      GFQ_ADJUSTMENT, cpi->gfu_boost, gf_frame_usage);
950
              fclose(f);
951
          }
952
953
#endif
954
955
9.13k
      if (cpi->common.refresh_golden_frame == 1) {
956
#if 0
957
958
            if (0) {
959
                FILE *f;
960
961
                f = fopen("GFexit.stt", "a");
962
                fprintf(f, "%8ld GF coded\n", cpi->common.current_video_frame);
963
                fclose(f);
964
            }
965
966
#endif
967
968
7.98k
        if (cpi->auto_adjust_gold_quantizer) {
969
7.98k
          calc_gf_params(cpi);
970
7.98k
        }
971
972
        /* If we are using alternate ref instead of gf then do not apply the
973
         * boost It will instead be applied to the altref update Jims
974
         * modified boost
975
         */
976
7.98k
        if (!cpi->source_alt_ref_active) {
977
7.98k
          if (cpi->oxcf.fixed_q < 0) {
978
7.98k
            if (cpi->pass == 2) {
979
              /* The spend on the GF is defined in the two pass
980
               * code for two pass encodes
981
               */
982
0
              cpi->this_frame_target = cpi->per_frame_bandwidth;
983
7.98k
            } else {
984
7.98k
              int Boost = cpi->last_boost;
985
7.98k
              int frames_in_section = cpi->frames_till_gf_update_due + 1;
986
7.98k
              int allocation_chunks = (frames_in_section * 100) + (Boost - 100);
987
7.98k
              int bits_in_section =
988
7.98k
                  (int)VPXMIN(INT_MAX, (int64_t)cpi->inter_frame_target *
989
7.98k
                                           frames_in_section);
990
991
              /* Normalize Altboost and allocations chunck down to
992
               * prevent overflow
993
               */
994
7.98k
              while (Boost > 1000) {
995
0
                Boost /= 2;
996
0
                allocation_chunks /= 2;
997
0
              }
998
999
              /* Avoid loss of precision but avoid overflow */
1000
7.98k
              if ((bits_in_section >> 7) > allocation_chunks) {
1001
1.90k
                cpi->this_frame_target =
1002
1.90k
                    Boost * (bits_in_section / allocation_chunks);
1003
6.07k
              } else {
1004
6.07k
                cpi->this_frame_target =
1005
6.07k
                    (Boost * bits_in_section) / allocation_chunks;
1006
6.07k
              }
1007
7.98k
            }
1008
7.98k
          } else {
1009
0
            cpi->this_frame_target =
1010
0
                (estimate_bits_at_q(1, Q, cpi->common.MBs, 1.0) *
1011
0
                 cpi->last_boost) /
1012
0
                100;
1013
0
          }
1014
7.98k
        } else {
1015
          /* If there is an active ARF at this location use the minimum
1016
           * bits on this frame even if it is a contructed arf.
1017
           * The active maximum quantizer insures that an appropriate
1018
           * number of bits will be spent if needed for contstructed ARFs.
1019
           */
1020
0
          cpi->this_frame_target = 0;
1021
0
        }
1022
1023
7.98k
        cpi->current_gf_interval = cpi->frames_till_gf_update_due;
1024
7.98k
      }
1025
9.13k
    } else {
1026
      // Special case for 1 pass CBR: fixed gf period.
1027
      // TODO(marpan): Adjust this boost/interval logic.
1028
      // If gf_cbr_boost_pct is small (below threshold) set the flag
1029
      // gf_noboost_onepass_cbr = 1, which forces the gf to use the same
1030
      // rate correction factor as last.
1031
0
      cpi->gf_noboost_onepass_cbr = (cpi->oxcf.gf_cbr_boost_pct <= 100);
1032
0
      cpi->baseline_gf_interval = cpi->gf_interval_onepass_cbr;
1033
      // Skip this update if the zero_mvcount is low.
1034
0
      if (cpi->zeromv_count > (cpi->common.MBs >> 1)) {
1035
0
        cpi->common.refresh_golden_frame = 1;
1036
0
        cpi->this_frame_target =
1037
0
            (cpi->this_frame_target * (100 + cpi->oxcf.gf_cbr_boost_pct)) / 100;
1038
0
      }
1039
0
      cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
1040
0
      cpi->current_gf_interval = cpi->frames_till_gf_update_due;
1041
0
    }
1042
9.13k
  }
1043
1044
87.8k
  cpi->per_frame_bandwidth = old_per_frame_bandwidth;
1045
87.8k
}
1046
1047
134k
void vp8_update_rate_correction_factors(VP8_COMP *cpi, int damp_var) {
1048
134k
  int Q = cpi->common.base_qindex;
1049
134k
  int correction_factor = 100;
1050
134k
  double rate_correction_factor;
1051
134k
  double adjustment_limit;
1052
1053
134k
  int projected_size_based_on_q = 0;
1054
1055
  /* Clear down mmx registers to allow floating point in what follows */
1056
134k
  vpx_clear_system_state();
1057
1058
134k
  if (cpi->common.frame_type == KEY_FRAME) {
1059
31.3k
    rate_correction_factor = cpi->key_frame_rate_correction_factor;
1060
103k
  } else {
1061
103k
    if (cpi->oxcf.number_of_layers == 1 && !cpi->gf_noboost_onepass_cbr &&
1062
103k
        (cpi->common.refresh_alt_ref_frame ||
1063
103k
         cpi->common.refresh_golden_frame)) {
1064
9.94k
      rate_correction_factor = cpi->gf_rate_correction_factor;
1065
93.1k
    } else {
1066
93.1k
      rate_correction_factor = cpi->rate_correction_factor;
1067
93.1k
    }
1068
103k
  }
1069
1070
  /* Work out how big we would have expected the frame to be at this Q
1071
   * given the current correction factor. Stay in double to avoid int
1072
   * overflow when values are large
1073
   */
1074
134k
  projected_size_based_on_q =
1075
134k
      (int)(((.5 + rate_correction_factor *
1076
134k
                       vp8_bits_per_mb[cpi->common.frame_type][Q]) *
1077
134k
             cpi->common.MBs) /
1078
134k
            (1 << BPER_MB_NORMBITS));
1079
1080
  /* Make some allowance for cpi->zbin_over_quant */
1081
134k
  if (cpi->mb.zbin_over_quant > 0) {
1082
31.8k
    int Z = cpi->mb.zbin_over_quant;
1083
31.8k
    double Factor = 0.99;
1084
31.8k
    double factor_adjustment = 0.01 / 256.0;
1085
1086
5.11M
    while (Z > 0) {
1087
5.08M
      Z--;
1088
5.08M
      projected_size_based_on_q = (int)(Factor * projected_size_based_on_q);
1089
5.08M
      Factor += factor_adjustment;
1090
1091
5.08M
      if (Factor >= 0.999) Factor = 0.999;
1092
5.08M
    }
1093
31.8k
  }
1094
1095
  /* Work out a size correction factor. */
1096
134k
  if (projected_size_based_on_q > 0) {
1097
126k
    correction_factor = (int)((100 * (int64_t)cpi->projected_frame_size) /
1098
126k
                              projected_size_based_on_q);
1099
126k
  }
1100
1101
  /* More heavily damped adjustment used if we have been oscillating
1102
   * either side of target
1103
   */
1104
134k
  switch (damp_var) {
1105
29.6k
    case 0: adjustment_limit = 0.75; break;
1106
2.20k
    case 1: adjustment_limit = 0.375; break;
1107
102k
    case 2:
1108
102k
    default: adjustment_limit = 0.25; break;
1109
134k
  }
1110
1111
134k
  if (correction_factor > 102) {
1112
    /* We are not already at the worst allowable quality */
1113
65.6k
    correction_factor =
1114
65.6k
        (int)(100.5 + ((correction_factor - 100) * adjustment_limit));
1115
65.6k
    rate_correction_factor =
1116
65.6k
        ((rate_correction_factor * correction_factor) / 100);
1117
1118
    /* Keep rate_correction_factor within limits */
1119
65.6k
    if (rate_correction_factor > MAX_BPB_FACTOR) {
1120
10.6k
      rate_correction_factor = MAX_BPB_FACTOR;
1121
10.6k
    }
1122
68.8k
  } else if (correction_factor < 99) {
1123
    /* We are not already at the best allowable quality */
1124
54.7k
    correction_factor =
1125
54.7k
        (int)(100.5 - ((100 - correction_factor) * adjustment_limit));
1126
54.7k
    rate_correction_factor =
1127
54.7k
        ((rate_correction_factor * correction_factor) / 100);
1128
1129
    /* Keep rate_correction_factor within limits */
1130
54.7k
    if (rate_correction_factor < MIN_BPB_FACTOR) {
1131
203
      rate_correction_factor = MIN_BPB_FACTOR;
1132
203
    }
1133
54.7k
  }
1134
1135
134k
  if (cpi->common.frame_type == KEY_FRAME) {
1136
31.3k
    cpi->key_frame_rate_correction_factor = rate_correction_factor;
1137
103k
  } else {
1138
103k
    if (cpi->oxcf.number_of_layers == 1 && !cpi->gf_noboost_onepass_cbr &&
1139
103k
        (cpi->common.refresh_alt_ref_frame ||
1140
103k
         cpi->common.refresh_golden_frame)) {
1141
9.94k
      cpi->gf_rate_correction_factor = rate_correction_factor;
1142
93.1k
    } else {
1143
93.1k
      cpi->rate_correction_factor = rate_correction_factor;
1144
93.1k
    }
1145
103k
  }
1146
134k
}
1147
1148
0
static int limit_q_cbr_inter(int last_q, int current_q) {
1149
0
  int limit_down = 12;
1150
0
  if (last_q - current_q > limit_down)
1151
0
    return (last_q - limit_down);
1152
0
  else
1153
0
    return current_q;
1154
0
}
1155
1156
136k
int vp8_regulate_q(VP8_COMP *cpi, int target_bits_per_frame) {
1157
136k
  int Q = cpi->active_worst_quality;
1158
1159
136k
  if (cpi->force_maxqp == 1) {
1160
0
    cpi->active_worst_quality = cpi->worst_quality;
1161
0
    return cpi->worst_quality;
1162
0
  }
1163
  /* Reset Zbin OQ value */
1164
136k
  cpi->mb.zbin_over_quant = 0;
1165
1166
136k
  if (cpi->oxcf.fixed_q >= 0) {
1167
0
    Q = cpi->oxcf.fixed_q;
1168
1169
0
    if (cpi->common.frame_type == KEY_FRAME) {
1170
0
      Q = cpi->oxcf.key_q;
1171
0
    } else if (cpi->oxcf.number_of_layers == 1 &&
1172
0
               cpi->common.refresh_alt_ref_frame &&
1173
0
               !cpi->gf_noboost_onepass_cbr) {
1174
0
      Q = cpi->oxcf.alt_q;
1175
0
    } else if (cpi->oxcf.number_of_layers == 1 &&
1176
0
               cpi->common.refresh_golden_frame &&
1177
0
               !cpi->gf_noboost_onepass_cbr) {
1178
0
      Q = cpi->oxcf.gold_q;
1179
0
    }
1180
136k
  } else {
1181
136k
    int i;
1182
136k
    int last_error = INT_MAX;
1183
136k
    int target_bits_per_mb;
1184
136k
    int bits_per_mb_at_this_q;
1185
136k
    double correction_factor;
1186
1187
    /* Select the appropriate correction factor based upon type of frame. */
1188
136k
    if (cpi->common.frame_type == KEY_FRAME) {
1189
29.6k
      correction_factor = cpi->key_frame_rate_correction_factor;
1190
106k
    } else {
1191
106k
      if (cpi->oxcf.number_of_layers == 1 && !cpi->gf_noboost_onepass_cbr &&
1192
106k
          (cpi->common.refresh_alt_ref_frame ||
1193
106k
           cpi->common.refresh_golden_frame)) {
1194
10.2k
        correction_factor = cpi->gf_rate_correction_factor;
1195
96.3k
      } else {
1196
96.3k
        correction_factor = cpi->rate_correction_factor;
1197
96.3k
      }
1198
106k
    }
1199
1200
    /* Calculate required scaling factor based on target frame size and
1201
     * size of frame produced using previous Q
1202
     */
1203
136k
    if (target_bits_per_frame > (INT_MAX >> BPER_MB_NORMBITS)) {
1204
4.14k
      int temp = target_bits_per_frame / cpi->common.MBs;
1205
4.14k
      if (temp > (INT_MAX >> BPER_MB_NORMBITS)) {
1206
1.61k
        target_bits_per_mb = INT_MAX;
1207
2.53k
      } else {
1208
2.53k
        target_bits_per_mb = temp << BPER_MB_NORMBITS;
1209
2.53k
      }
1210
132k
    } else {
1211
132k
      target_bits_per_mb =
1212
132k
          (target_bits_per_frame << BPER_MB_NORMBITS) / cpi->common.MBs;
1213
132k
    }
1214
1215
136k
    i = cpi->active_best_quality;
1216
1217
5.93M
    do {
1218
5.93M
      bits_per_mb_at_this_q =
1219
5.93M
          (int)(.5 +
1220
5.93M
                correction_factor * vp8_bits_per_mb[cpi->common.frame_type][i]);
1221
1222
5.93M
      if (bits_per_mb_at_this_q <= target_bits_per_mb) {
1223
98.1k
        if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error) {
1224
76.4k
          Q = i;
1225
76.4k
        } else {
1226
21.7k
          Q = i - 1;
1227
21.7k
        }
1228
1229
98.1k
        break;
1230
5.84M
      } else {
1231
5.84M
        last_error = bits_per_mb_at_this_q - target_bits_per_mb;
1232
5.84M
      }
1233
5.93M
    } while (++i <= cpi->active_worst_quality);
1234
1235
    /* If we are at MAXQ then enable Q over-run which seeks to claw
1236
     * back additional bits through things like the RD multiplier
1237
     * and zero bin size.
1238
     */
1239
136k
    if (Q >= MAXQ) {
1240
36.8k
      int zbin_oqmax;
1241
1242
36.8k
      double Factor = 0.99;
1243
36.8k
      double factor_adjustment = 0.01 / 256.0;
1244
1245
36.8k
      if (cpi->common.frame_type == KEY_FRAME) {
1246
3.93k
        zbin_oqmax = 0;
1247
32.9k
      } else if (cpi->oxcf.number_of_layers == 1 &&
1248
32.9k
                 !cpi->gf_noboost_onepass_cbr &&
1249
32.9k
                 (cpi->common.refresh_alt_ref_frame ||
1250
32.9k
                  (cpi->common.refresh_golden_frame &&
1251
959
                   !cpi->source_alt_ref_active))) {
1252
959
        zbin_oqmax = 16;
1253
31.9k
      } else {
1254
31.9k
        zbin_oqmax = ZBIN_OQ_MAX;
1255
31.9k
      }
1256
1257
      /*{
1258
          double Factor =
1259
      (double)target_bits_per_mb/(double)bits_per_mb_at_this_q;
1260
          double Oq;
1261
1262
          Factor = Factor/1.2683;
1263
1264
          Oq = pow( Factor, (1.0/-0.165) );
1265
1266
          if ( Oq > zbin_oqmax )
1267
              Oq = zbin_oqmax;
1268
1269
          cpi->zbin_over_quant = (int)Oq;
1270
      }*/
1271
1272
      /* Each incrment in the zbin is assumed to have a fixed effect
1273
       * on bitrate. This is not of course true. The effect will be
1274
       * highly clip dependent and may well have sudden steps. The
1275
       * idea here is to acheive higher effective quantizers than the
1276
       * normal maximum by expanding the zero bin and hence
1277
       * decreasing the number of low magnitude non zero coefficients.
1278
       */
1279
5.24M
      while (cpi->mb.zbin_over_quant < zbin_oqmax) {
1280
5.21M
        cpi->mb.zbin_over_quant++;
1281
1282
5.21M
        if (cpi->mb.zbin_over_quant > zbin_oqmax) {
1283
0
          cpi->mb.zbin_over_quant = zbin_oqmax;
1284
0
        }
1285
1286
        /* Adjust bits_per_mb_at_this_q estimate */
1287
5.21M
        bits_per_mb_at_this_q = (int)(Factor * bits_per_mb_at_this_q);
1288
5.21M
        Factor += factor_adjustment;
1289
1290
5.21M
        if (Factor >= 0.999) Factor = 0.999;
1291
1292
        /* Break out if we get down to the target rate */
1293
5.21M
        if (bits_per_mb_at_this_q <= target_bits_per_mb) break;
1294
5.21M
      }
1295
36.8k
    }
1296
136k
  }
1297
1298
  // Limit decrease in Q for 1 pass CBR screen content mode.
1299
136k
  if (cpi->common.frame_type != KEY_FRAME && cpi->pass == 0 &&
1300
106k
      cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
1301
0
      cpi->oxcf.screen_content_mode)
1302
0
    Q = limit_q_cbr_inter(cpi->last_q[1], Q);
1303
1304
136k
  return Q;
1305
136k
}
1306
1307
13.2k
static int estimate_keyframe_frequency(VP8_COMP *cpi) {
1308
13.2k
  int i;
1309
1310
  /* Average key frame frequency */
1311
13.2k
  int av_key_frame_frequency = 0;
1312
1313
  /* First key frame at start of sequence is a special case. We have no
1314
   * frequency data.
1315
   */
1316
13.2k
  if (cpi->key_frame_count == 1) {
1317
    /* Assume a default of 1 kf every 2 seconds, or the max kf interval,
1318
     * whichever is smaller.
1319
     */
1320
2.82k
    int key_freq = cpi->oxcf.key_freq > 0 ? cpi->oxcf.key_freq : 1;
1321
2.82k
    av_key_frame_frequency = 1 + (int)cpi->output_framerate * 2;
1322
1323
2.82k
    if (cpi->oxcf.auto_key && av_key_frame_frequency > key_freq) {
1324
369
      av_key_frame_frequency = key_freq;
1325
369
    }
1326
1327
2.82k
    cpi->prior_key_frame_distance[KEY_FRAME_CONTEXT - 1] =
1328
2.82k
        av_key_frame_frequency;
1329
10.3k
  } else {
1330
10.3k
    unsigned int total_weight = 0;
1331
10.3k
    int last_kf_interval =
1332
10.3k
        (cpi->frames_since_key > 0) ? cpi->frames_since_key : 1;
1333
1334
    /* reset keyframe context and calculate weighted average of last
1335
     * KEY_FRAME_CONTEXT keyframes
1336
     */
1337
62.3k
    for (i = 0; i < KEY_FRAME_CONTEXT; ++i) {
1338
51.9k
      if (i < KEY_FRAME_CONTEXT - 1) {
1339
41.5k
        cpi->prior_key_frame_distance[i] = cpi->prior_key_frame_distance[i + 1];
1340
41.5k
      } else {
1341
10.3k
        cpi->prior_key_frame_distance[i] = last_kf_interval;
1342
10.3k
      }
1343
1344
51.9k
      av_key_frame_frequency +=
1345
51.9k
          prior_key_frame_weight[i] * cpi->prior_key_frame_distance[i];
1346
51.9k
      total_weight += prior_key_frame_weight[i];
1347
51.9k
    }
1348
1349
10.3k
    av_key_frame_frequency /= total_weight;
1350
10.3k
  }
1351
  // TODO (marpan): Given the checks above, |av_key_frame_frequency|
1352
  // should always be above 0. But for now we keep the sanity check in.
1353
13.2k
  if (av_key_frame_frequency == 0) av_key_frame_frequency = 1;
1354
13.2k
  return av_key_frame_frequency;
1355
13.2k
}
1356
1357
18.2k
void vp8_adjust_key_frame_context(VP8_COMP *cpi) {
1358
  /* Clear down mmx registers to allow floating point in what follows */
1359
18.2k
  vpx_clear_system_state();
1360
1361
  /* Do we have any key frame overspend to recover? */
1362
  /* Two-pass overspend handled elsewhere. */
1363
18.2k
  if ((cpi->pass != 2) &&
1364
18.2k
      (cpi->projected_frame_size > cpi->per_frame_bandwidth)) {
1365
13.2k
    int overspend;
1366
1367
    /* Update the count of key frame overspend to be recovered in
1368
     * subsequent frames. A portion of the KF overspend is treated as gf
1369
     * overspend (and hence recovered more quickly) as the kf is also a
1370
     * gf. Otherwise the few frames following each kf tend to get more
1371
     * bits allocated than those following other gfs.
1372
     */
1373
13.2k
    overspend = (cpi->projected_frame_size - cpi->per_frame_bandwidth);
1374
1375
13.2k
    if (cpi->oxcf.number_of_layers > 1) {
1376
0
      cpi->kf_overspend_bits += overspend;
1377
13.2k
    } else {
1378
13.2k
      cpi->kf_overspend_bits += overspend * 7 / 8;
1379
13.2k
      cpi->gf_overspend_bits += overspend * 1 / 8;
1380
13.2k
    }
1381
1382
    /* Work out how much to try and recover per frame. */
1383
13.2k
    cpi->kf_bitrate_adjustment =
1384
13.2k
        cpi->kf_overspend_bits / estimate_keyframe_frequency(cpi);
1385
13.2k
  }
1386
1387
18.2k
  cpi->frames_since_key = 0;
1388
18.2k
  cpi->key_frame_count++;
1389
18.2k
}
1390
1391
void vp8_compute_frame_size_bounds(VP8_COMP *cpi, int *frame_under_shoot_limit,
1392
106k
                                   int *frame_over_shoot_limit) {
1393
  /* Set-up bounds on acceptable frame size: */
1394
106k
  if (cpi->oxcf.fixed_q >= 0) {
1395
    /* Fixed Q scenario: frame size never outranges target
1396
     * (there is no target!)
1397
     */
1398
0
    *frame_under_shoot_limit = 0;
1399
0
    *frame_over_shoot_limit = INT_MAX;
1400
106k
  } else {
1401
106k
    const int64_t this_frame_target = cpi->this_frame_target;
1402
106k
    int64_t over_shoot_limit, under_shoot_limit;
1403
1404
106k
    if (cpi->common.frame_type == KEY_FRAME) {
1405
18.2k
      over_shoot_limit = this_frame_target * 9 / 8;
1406
18.2k
      under_shoot_limit = this_frame_target * 7 / 8;
1407
87.8k
    } else {
1408
87.8k
      if (cpi->oxcf.number_of_layers > 1 || cpi->common.refresh_alt_ref_frame ||
1409
87.8k
          cpi->common.refresh_golden_frame) {
1410
7.98k
        over_shoot_limit = this_frame_target * 9 / 8;
1411
7.98k
        under_shoot_limit = this_frame_target * 7 / 8;
1412
79.9k
      } else {
1413
        /* For CBR take buffer fullness into account */
1414
79.9k
        if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
1415
0
          if (cpi->buffer_level >= ((cpi->oxcf.optimal_buffer_level +
1416
0
                                     cpi->oxcf.maximum_buffer_size) >>
1417
0
                                    1)) {
1418
            /* Buffer is too full so relax overshoot and tighten
1419
             * undershoot
1420
             */
1421
0
            over_shoot_limit = this_frame_target * 12 / 8;
1422
0
            under_shoot_limit = this_frame_target * 6 / 8;
1423
0
          } else if (cpi->buffer_level <=
1424
0
                     (cpi->oxcf.optimal_buffer_level >> 1)) {
1425
            /* Buffer is too low so relax undershoot and tighten
1426
             * overshoot
1427
             */
1428
0
            over_shoot_limit = this_frame_target * 10 / 8;
1429
0
            under_shoot_limit = this_frame_target * 4 / 8;
1430
0
          } else {
1431
0
            over_shoot_limit = this_frame_target * 11 / 8;
1432
0
            under_shoot_limit = this_frame_target * 5 / 8;
1433
0
          }
1434
0
        }
1435
        /* VBR and CQ mode */
1436
        /* Note that tighter restrictions here can help quality
1437
         * but hurt encode speed
1438
         */
1439
79.9k
        else {
1440
          /* Stron overshoot limit for constrained quality */
1441
79.9k
          if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
1442
16.4k
            over_shoot_limit = this_frame_target * 11 / 8;
1443
16.4k
            under_shoot_limit = this_frame_target * 2 / 8;
1444
63.4k
          } else {
1445
63.4k
            over_shoot_limit = this_frame_target * 11 / 8;
1446
63.4k
            under_shoot_limit = this_frame_target * 5 / 8;
1447
63.4k
          }
1448
79.9k
        }
1449
79.9k
      }
1450
87.8k
    }
1451
1452
    /* For very small rate targets where the fractional adjustment
1453
     * (eg * 7/8) may be tiny make sure there is at least a minimum
1454
     * range.
1455
     */
1456
106k
    over_shoot_limit += 200;
1457
106k
    under_shoot_limit -= 200;
1458
106k
    if (under_shoot_limit < 0) under_shoot_limit = 0;
1459
106k
    if (under_shoot_limit > INT_MAX) under_shoot_limit = INT_MAX;
1460
106k
    if (over_shoot_limit > INT_MAX) over_shoot_limit = INT_MAX;
1461
106k
    *frame_under_shoot_limit = (int)under_shoot_limit;
1462
106k
    *frame_over_shoot_limit = (int)over_shoot_limit;
1463
106k
  }
1464
106k
}
1465
1466
/* return of 0 means drop frame */
1467
106k
int vp8_pick_frame_size(VP8_COMP *cpi) {
1468
106k
  VP8_COMMON *cm = &cpi->common;
1469
1470
106k
  if (cm->frame_type == KEY_FRAME) {
1471
18.2k
    calc_iframe_target_size(cpi);
1472
87.8k
  } else {
1473
87.8k
    calc_pframe_target_size(cpi);
1474
1475
    /* Check if we're dropping the frame: */
1476
87.8k
    if (cpi->drop_frame) {
1477
0
      cpi->drop_frame = 0;
1478
0
      return 0;
1479
0
    }
1480
87.8k
  }
1481
106k
  return 1;
1482
106k
}
1483
// If this just encoded frame (mcomp/transform/quant, but before loopfilter and
1484
// pack_bitstream) has large overshoot, and was not being encoded close to the
1485
// max QP, then drop this frame and force next frame to be encoded at max QP.
1486
// Allow this for screen_content_mode = 2, or if drop frames is allowed.
1487
// TODO(marpan): Should do this exit condition during the encode_frame
1488
// (i.e., halfway during the encoding of the frame) to save cycles.
1489
0
int vp8_drop_encodedframe_overshoot(VP8_COMP *cpi, int Q) {
1490
0
  int force_drop_overshoot = 0;
1491
#if CONFIG_MULTI_RES_ENCODING
1492
  // Only check for dropping due to overshoot on the lowest stream.
1493
  // If the lowest stream of the multi-res encoding was dropped due to
1494
  // overshoot, then force dropping on all upper layer streams
1495
  // (mr_encoder_id > 0).
1496
  LOWER_RES_FRAME_INFO *low_res_frame_info =
1497
      (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
1498
  if (cpi->oxcf.mr_total_resolutions > 1 && cpi->oxcf.mr_encoder_id > 0) {
1499
    force_drop_overshoot = low_res_frame_info->is_frame_dropped_overshoot_maxqp;
1500
    if (!force_drop_overshoot) {
1501
      cpi->force_maxqp = 0;
1502
      cpi->frames_since_last_drop_overshoot++;
1503
      return 0;
1504
    }
1505
  }
1506
#endif
1507
0
  if (cpi->common.frame_type != KEY_FRAME &&
1508
0
      (cpi->oxcf.screen_content_mode == 2 ||
1509
0
       (cpi->drop_frames_allowed &&
1510
0
        (force_drop_overshoot ||
1511
0
         (cpi->rate_correction_factor < (8.0f * MIN_BPB_FACTOR) &&
1512
0
          cpi->frames_since_last_drop_overshoot > (int)cpi->framerate))))) {
1513
    // Note: the "projected_frame_size" from encode_frame() only gives estimate
1514
    // of mode/motion vector rate (in non-rd mode): so below we only require
1515
    // that projected_frame_size is somewhat greater than per-frame-bandwidth,
1516
    // but add additional condition with high threshold on prediction residual.
1517
1518
    // QP threshold: only allow dropping if we are not close to qp_max.
1519
0
    int thresh_qp = 3 * cpi->worst_quality >> 2;
1520
    // Rate threshold, in bytes.
1521
0
    int thresh_rate = 2 * (cpi->av_per_frame_bandwidth >> 3);
1522
    // Threshold for the average (over all macroblocks) of the pixel-sum
1523
    // residual error over 16x16 block.
1524
0
    int thresh_pred_err_mb = (200 << 4);
1525
0
    int pred_err_mb = (int)(cpi->mb.prediction_error / cpi->common.MBs);
1526
    // Reduce/ignore thresh_rate if pred_err_mb much larger than its threshold,
1527
    // give more weight to pred_err metric for overshoot detection.
1528
0
    if (cpi->drop_frames_allowed && pred_err_mb > (thresh_pred_err_mb << 4))
1529
0
      thresh_rate = thresh_rate >> 3;
1530
0
    if ((Q < thresh_qp && cpi->projected_frame_size > thresh_rate &&
1531
0
         pred_err_mb > thresh_pred_err_mb &&
1532
0
         pred_err_mb > 2 * cpi->last_pred_err_mb) ||
1533
0
        force_drop_overshoot) {
1534
0
      unsigned int i;
1535
0
      double new_correction_factor;
1536
0
      int target_bits_per_mb;
1537
0
      const int target_size = cpi->av_per_frame_bandwidth;
1538
      // Flag to indicate we will force next frame to be encoded at max QP.
1539
0
      cpi->force_maxqp = 1;
1540
      // Reset the buffer levels.
1541
0
      cpi->buffer_level = cpi->oxcf.optimal_buffer_level;
1542
0
      cpi->bits_off_target = cpi->oxcf.optimal_buffer_level;
1543
      // Compute a new rate correction factor, corresponding to the current
1544
      // target frame size and max_QP, and adjust the rate correction factor
1545
      // upwards, if needed.
1546
      // This is to prevent a bad state where the re-encoded frame at max_QP
1547
      // undershoots significantly, and then we end up dropping every other
1548
      // frame because the QP/rate_correction_factor may have been too low
1549
      // before the drop and then takes too long to come up.
1550
0
      if (target_size > (INT_MAX >> BPER_MB_NORMBITS)) {
1551
0
        int temp = target_size / cpi->common.MBs;
1552
0
        if (temp > (INT_MAX >> BPER_MB_NORMBITS)) {
1553
0
          target_bits_per_mb = INT_MAX;
1554
0
        } else {
1555
0
          target_bits_per_mb = temp << BPER_MB_NORMBITS;
1556
0
        }
1557
0
      } else {
1558
0
        target_bits_per_mb =
1559
0
            (target_size << BPER_MB_NORMBITS) / cpi->common.MBs;
1560
0
      }
1561
      // Rate correction factor based on target_size_per_mb and max_QP.
1562
0
      new_correction_factor =
1563
0
          (double)target_bits_per_mb /
1564
0
          (double)vp8_bits_per_mb[INTER_FRAME][cpi->worst_quality];
1565
0
      if (new_correction_factor > cpi->rate_correction_factor) {
1566
0
        cpi->rate_correction_factor =
1567
0
            VPXMIN(2.0 * cpi->rate_correction_factor, new_correction_factor);
1568
0
      }
1569
0
      if (cpi->rate_correction_factor > MAX_BPB_FACTOR) {
1570
0
        cpi->rate_correction_factor = MAX_BPB_FACTOR;
1571
0
      }
1572
      // Drop this frame: update frame counters.
1573
0
      cpi->common.current_video_frame++;
1574
0
      cpi->frames_since_key++;
1575
0
      cpi->temporal_pattern_counter++;
1576
0
      cpi->frames_since_last_drop_overshoot = 0;
1577
0
      if (cpi->oxcf.number_of_layers > 1) {
1578
        // Set max_qp and rate correction for all temporal layers if overshoot
1579
        // is detected.
1580
0
        for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
1581
0
          LAYER_CONTEXT *lc = &cpi->layer_context[i];
1582
0
          lc->force_maxqp = 1;
1583
0
          lc->frames_since_last_drop_overshoot = 0;
1584
0
          lc->rate_correction_factor = cpi->rate_correction_factor;
1585
0
        }
1586
0
      }
1587
#if CONFIG_MULTI_RES_ENCODING
1588
      if (cpi->oxcf.mr_total_resolutions > 1)
1589
        low_res_frame_info->is_frame_dropped_overshoot_maxqp = 1;
1590
#endif
1591
0
      return 1;
1592
0
    }
1593
0
    cpi->force_maxqp = 0;
1594
0
    cpi->frames_since_last_drop_overshoot++;
1595
#if CONFIG_MULTI_RES_ENCODING
1596
    if (cpi->oxcf.mr_total_resolutions > 1)
1597
      low_res_frame_info->is_frame_dropped_overshoot_maxqp = 0;
1598
#endif
1599
0
    return 0;
1600
0
  }
1601
0
  cpi->force_maxqp = 0;
1602
0
  cpi->frames_since_last_drop_overshoot++;
1603
#if CONFIG_MULTI_RES_ENCODING
1604
  if (cpi->oxcf.mr_total_resolutions > 1)
1605
    low_res_frame_info->is_frame_dropped_overshoot_maxqp = 0;
1606
#endif
1607
0
  return 0;
1608
0
}