vp9_ratectrl.c 31.1 KB
Newer Older
John Koleszar's avatar
John Koleszar committed
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar's avatar
John Koleszar committed
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
6
 *  that can be found in the LICENSE file in the root of the source
 *  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.
John Koleszar's avatar
John Koleszar committed
9
10
11
12
13
14
15
16
 */


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <assert.h>
Dmitry Kovalev's avatar
Dmitry Kovalev committed
17
#include <math.h>
John Koleszar's avatar
John Koleszar committed
18

19
20
#include "vp9/common/vp9_alloccommon.h"
#include "vp9/common/vp9_common.h"
21
#include "vp9/encoder/vp9_ratectrl.h"
22
#include "vp9/common/vp9_entropymode.h"
John Koleszar's avatar
John Koleszar committed
23
#include "vpx_mem/vpx_mem.h"
24
#include "vp9/common/vp9_systemdependent.h"
25
#include "vp9/encoder/vp9_encodemv.h"
26
#include "vp9/common/vp9_quant_common.h"
27
#include "vp9/common/vp9_seg_common.h"
John Koleszar's avatar
John Koleszar committed
28

Deb Mukherjee's avatar
Deb Mukherjee committed
29
#define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
30

Dmitry Kovalev's avatar
Dmitry Kovalev committed
31
32
#define MIN_BPB_FACTOR 0.005
#define MAX_BPB_FACTOR 50
John Koleszar's avatar
John Koleszar committed
33
34
35
36

// Bits Per MB at different Q (Multiplied by 512)
#define BPER_MB_NORMBITS    9

37
38
static const unsigned int prior_key_frame_weight[KEY_FRAME_CONTEXT] =
    { 1, 2, 3, 4, 5 };
John Koleszar's avatar
John Koleszar committed
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Tables relating active max Q to active min Q
static int kf_low_motion_minq[QINDEX_RANGE];
static int kf_high_motion_minq[QINDEX_RANGE];
static int gf_low_motion_minq[QINDEX_RANGE];
static int gf_high_motion_minq[QINDEX_RANGE];
static int inter_minq[QINDEX_RANGE];
static int afq_low_motion_minq[QINDEX_RANGE];
static int afq_high_motion_minq[QINDEX_RANGE];

// Functions to compute the active minq lookup table entries based on a
// formulaic approach to facilitate easier adjustment of the Q tables.
// The formulae were derived from computing a 3rd order polynomial best
// fit to the original data (after plotting real maxq vs minq (not q index))
static int calculate_minq_index(double maxq,
                                double x3, double x2, double x1, double c) {
  int i;
  const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq + c,
                                maxq);

  // Special case handling to deal with the step from q2.0
  // down to lossless mode represented by q 1.0.
  if (minqtarget <= 2.0)
    return 0;

  for (i = 0; i < QINDEX_RANGE; i++) {
    if (minqtarget <= vp9_convert_qindex_to_q(i))
      return i;
  }

  return QINDEX_RANGE - 1;
}

72
void vp9_rc_init_minq_luts(void) {
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
  int i;

  for (i = 0; i < QINDEX_RANGE; i++) {
    const double maxq = vp9_convert_qindex_to_q(i);


    kf_low_motion_minq[i] = calculate_minq_index(maxq,
                                                 0.000001,
                                                 -0.0004,
                                                 0.15,
                                                 0.0);
    kf_high_motion_minq[i] = calculate_minq_index(maxq,
                                                  0.000002,
                                                  -0.0012,
                                                  0.5,
                                                  0.0);

    gf_low_motion_minq[i] = calculate_minq_index(maxq,
                                                 0.0000015,
                                                 -0.0009,
                                                 0.32,
                                                 0.0);
    gf_high_motion_minq[i] = calculate_minq_index(maxq,
                                                  0.0000021,
                                                  -0.00125,
                                                  0.50,
                                                  0.0);
    inter_minq[i] = calculate_minq_index(maxq,
                                         0.00000271,
                                         -0.00113,
                                         0.75,
                                         0.0);
    afq_low_motion_minq[i] = calculate_minq_index(maxq,
                                                  0.0000015,
                                                  -0.0009,
                                                  0.33,
                                                  0.0);
    afq_high_motion_minq[i] = calculate_minq_index(maxq,
                                                   0.0000021,
                                                   -0.00125,
                                                   0.55,
                                                   0.0);
  }
}

Paul Wilkins's avatar
Paul Wilkins committed
118
119
120
// These functions use formulaic calculations to make playing with the
// quantizer tables easier. If necessary they can be replaced by lookup
// tables if and when things settle down in the experimental bitstream
121
double vp9_convert_qindex_to_q(int qindex) {
John Koleszar's avatar
John Koleszar committed
122
  // Convert the index to a real Q value (scaled down to match old Q values)
123
  return vp9_ac_quant(qindex, 0) / 4.0;
Paul Wilkins's avatar
Paul Wilkins committed
124
125
}

126
127
int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
                       double correction_factor) {
128
  const double q = vp9_convert_qindex_to_q(qindex);
129
  int enumerator = frame_type == KEY_FRAME ? 3300000 : 2250000;
Paul Wilkins's avatar
Paul Wilkins committed
130

131
  // q based adjustment to baseline enumerator
Paul Wilkins's avatar
Paul Wilkins committed
132
  enumerator += (int)(enumerator * q) >> 12;
133
134
  return (int)(0.5 + (enumerator * correction_factor / q));
}
John Koleszar's avatar
John Koleszar committed
135

136
void vp9_save_coding_context(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
137
  CODING_CONTEXT *const cc = &cpi->coding_context;
138
  VP9_COMMON *cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
139

John Koleszar's avatar
John Koleszar committed
140
  // Stores a snapshot of key state variables which can subsequently be
141
  // restored with a call to vp9_restore_coding_context. These functions are
142
  // intended for use in a re-code loop in vp9_compress_frame where the
John Koleszar's avatar
John Koleszar committed
143
  // quantizer value is adjusted between loop iterations.
144
145
146
147
  vp9_copy(cc->nmvjointcost,  cpi->mb.nmvjointcost);
  vp9_copy(cc->nmvcosts,  cpi->mb.nmvcosts);
  vp9_copy(cc->nmvcosts_hp,  cpi->mb.nmvcosts_hp);

148
  vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
149

John Koleszar's avatar
John Koleszar committed
150
  vpx_memcpy(cpi->coding_context.last_frame_seg_map_copy,
151
             cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
John Koleszar's avatar
John Koleszar committed
152

153
154
  vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
  vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
155

156
  cc->fc = cm->fc;
157
}
John Koleszar's avatar
John Koleszar committed
158

159
void vp9_restore_coding_context(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
160
  CODING_CONTEXT *const cc = &cpi->coding_context;
161
  VP9_COMMON *cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
162

John Koleszar's avatar
John Koleszar committed
163
  // Restore key state variables to the snapshot state stored in the
164
  // previous call to vp9_save_coding_context.
165
166
167
168
  vp9_copy(cpi->mb.nmvjointcost, cc->nmvjointcost);
  vp9_copy(cpi->mb.nmvcosts, cc->nmvcosts);
  vp9_copy(cpi->mb.nmvcosts_hp, cc->nmvcosts_hp);

169
  vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
170

John Koleszar's avatar
John Koleszar committed
171
172
  vpx_memcpy(cm->last_frame_seg_map,
             cpi->coding_context.last_frame_seg_map_copy,
173
             (cm->mi_rows * cm->mi_cols));
John Koleszar's avatar
John Koleszar committed
174

175
176
  vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
  vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
177

178
  cm->fc = cc->fc;
John Koleszar's avatar
John Koleszar committed
179
180
}

181
182
void vp9_setup_key_frame(VP9_COMP *cpi) {
  VP9_COMMON *cm = &cpi->common;
183

184
  vp9_setup_past_independence(cm);
John Koleszar's avatar
John Koleszar committed
185

John Koleszar's avatar
John Koleszar committed
186
  // interval before next GF
187
  cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
188
  /* All buffers are implicitly updated on key frames. */
189
190
  cpi->refresh_golden_frame = 1;
  cpi->refresh_alt_ref_frame = 1;
John Koleszar's avatar
John Koleszar committed
191
}
192

193
void vp9_setup_inter_frame(VP9_COMP *cpi) {
194
  VP9_COMMON *cm = &cpi->common;
Adrian Grange's avatar
Adrian Grange committed
195
  if (cm->error_resilient_mode || cm->intra_only)
196
    vp9_setup_past_independence(cm);
197

Dmitry Kovalev's avatar
Dmitry Kovalev committed
198
  assert(cm->frame_context_idx < FRAME_CONTEXTS);
199
  cm->fc = cm->frame_contexts[cm->frame_context_idx];
200
}
John Koleszar's avatar
John Koleszar committed
201

202
static int estimate_bits_at_q(int frame_kind, int q, int mbs,
John Koleszar's avatar
John Koleszar committed
203
                              double correction_factor) {
204
  const int bpm = (int)(vp9_rc_bits_per_mb(frame_kind, q, correction_factor));
John Koleszar's avatar
John Koleszar committed
205

206
207
208
209
210
  // Attempt to retain reasonable accuracy without overflow. The cutoff is
  // chosen such that the maximum product of Bpm and MBs fits 31 bits. The
  // largest Bpm takes 20 bits.
  return (mbs > (1 << 11)) ? (bpm >> BPER_MB_NORMBITS) * mbs
                           : (bpm * mbs) >> BPER_MB_NORMBITS;
211
}
212
213


214
static void calc_iframe_target_size(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
215
216
  // boost defaults to half second
  int target;
John Koleszar's avatar
John Koleszar committed
217

John Koleszar's avatar
John Koleszar committed
218
  // Clear down mmx registers to allow floating point in what follows
219
  vp9_clear_system_state();  // __asm emms;
John Koleszar's avatar
John Koleszar committed
220

John Koleszar's avatar
John Koleszar committed
221
  // New Two pass RC
222
  target = cpi->rc.per_frame_bandwidth;
John Koleszar's avatar
John Koleszar committed
223

John Koleszar's avatar
John Koleszar committed
224
  if (cpi->oxcf.rc_max_intra_bitrate_pct) {
225
    int max_rate = cpi->rc.per_frame_bandwidth
226
                 * cpi->oxcf.rc_max_intra_bitrate_pct / 100;
John Koleszar's avatar
John Koleszar committed
227

John Koleszar's avatar
John Koleszar committed
228
229
230
    if (target > max_rate)
      target = max_rate;
  }
231
  cpi->rc.this_frame_target = target;
John Koleszar's avatar
John Koleszar committed
232
233
}

234
//  Do the best we can to define the parameters for the next GF based
Paul Wilkins's avatar
Paul Wilkins committed
235
//  on what information we have available.
236
237
238
//
//  In this experimental code only two pass is supported
//  so we just use the interval determined in the two pass code.
239
static void calc_gf_params(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
240
  // Set the gf interval
241
  cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
John Koleszar's avatar
John Koleszar committed
242
243
244
}


245
static void calc_pframe_target_size(VP9_COMP *cpi) {
246
247
  const int min_frame_target = MAX(cpi->rc.min_frame_bandwidth,
                                   cpi->rc.av_per_frame_bandwidth >> 5);
248
  if (cpi->refresh_alt_ref_frame) {
249
    // Special alt reference frame case
John Koleszar's avatar
John Koleszar committed
250
    // Per frame bit target for the alt ref frame
251
252
    cpi->rc.per_frame_bandwidth = cpi->twopass.gf_bits;
    cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
253
254
  } else {
    // Normal frames (gf,and inter)
255
    cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
John Koleszar's avatar
John Koleszar committed
256
  }
John Koleszar's avatar
John Koleszar committed
257

258
259
260
261
262
263
  // Check that the total sum of adjustments is not above the maximum allowed.
  // That is, having allowed for the KF and GF penalties, we have not pushed
  // the current inter-frame target too low. If the adjustment we apply here is
  // not capable of recovering all the extra bits we have spent in the KF or GF,
  // then the remainder will have to be recovered over a longer time span via
  // other buffer / rate control mechanisms.
264
265
  if (cpi->rc.this_frame_target < min_frame_target)
    cpi->rc.this_frame_target = min_frame_target;
John Koleszar's avatar
John Koleszar committed
266
267

  // Adjust target frame size for Golden Frames:
268
  if (cpi->rc.frames_till_gf_update_due == 0) {
269
    cpi->refresh_golden_frame = 1;
John Koleszar's avatar
John Koleszar committed
270
271
272
273
274
    calc_gf_params(cpi);
    // If we are using alternate ref instead of gf then do not apply the boost
    // It will instead be applied to the altref update
    // Jims modified boost
    if (!cpi->source_alt_ref_active) {
275
276
277
      // The spend on the GF is defined in the two pass code
      // for two pass encodes
      cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
278
279
    } else {
      // If there is an active ARF at this location use the minimum
280
      // bits on this frame even if it is a constructed arf.
281
      // The active maximum quantizer insures that an appropriate
282
      // number of bits will be spent if needed for constructed ARFs.
283
      cpi->rc.this_frame_target = 0;
John Koleszar's avatar
John Koleszar committed
284
    }
John Koleszar's avatar
John Koleszar committed
285
  }
John Koleszar's avatar
John Koleszar committed
286
287
288
}


289
void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi, int damp_var) {
290
291
  const int q = cpi->common.base_qindex;
  int correction_factor = 100;
John Koleszar's avatar
John Koleszar committed
292
293
  double rate_correction_factor;
  double adjustment_limit;
John Koleszar's avatar
John Koleszar committed
294

295
  int projected_size_based_on_q = 0;
John Koleszar's avatar
John Koleszar committed
296

John Koleszar's avatar
John Koleszar committed
297
  // Clear down mmx registers to allow floating point in what follows
298
  vp9_clear_system_state();  // __asm emms;
John Koleszar's avatar
John Koleszar committed
299

John Koleszar's avatar
John Koleszar committed
300
  if (cpi->common.frame_type == KEY_FRAME) {
301
    rate_correction_factor = cpi->rc.key_frame_rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
302
  } else {
303
    if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
304
      rate_correction_factor = cpi->rc.gf_rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
305
    else
306
      rate_correction_factor = cpi->rc.rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
307
308
  }

309
310
  // Work out how big we would have expected the frame to be at this Q given
  // the current correction factor.
John Koleszar's avatar
John Koleszar committed
311
  // Stay in double to avoid int overflow when values are large
312
313
314
  projected_size_based_on_q = estimate_bits_at_q(cpi->common.frame_type, q,
                                                 cpi->common.MBs,
                                                 rate_correction_factor);
John Koleszar's avatar
John Koleszar committed
315
316
317

  // Work out a size correction factor.
  if (projected_size_based_on_q > 0)
318
    correction_factor =
319
        (100 * cpi->rc.projected_frame_size) / projected_size_based_on_q;
John Koleszar's avatar
John Koleszar committed
320

321
322
  // More heavily damped adjustment used if we have been oscillating either side
  // of target.
John Koleszar's avatar
John Koleszar committed
323
  switch (damp_var) {
John Koleszar's avatar
John Koleszar committed
324
    case 0:
John Koleszar's avatar
John Koleszar committed
325
326
      adjustment_limit = 0.75;
      break;
John Koleszar's avatar
John Koleszar committed
327
    case 1:
John Koleszar's avatar
John Koleszar committed
328
329
      adjustment_limit = 0.375;
      break;
John Koleszar's avatar
John Koleszar committed
330
331
    case 2:
    default:
John Koleszar's avatar
John Koleszar committed
332
333
334
335
      adjustment_limit = 0.25;
      break;
  }

336
  // if ( (correction_factor > 102) && (Q < cpi->rc.active_worst_quality) )
John Koleszar's avatar
John Koleszar committed
337
338
  if (correction_factor > 102) {
    // We are not already at the worst allowable quality
339
    correction_factor =
340
        (int)(100 + ((correction_factor - 100) * adjustment_limit));
341
342
    rate_correction_factor =
        ((rate_correction_factor * correction_factor) / 100);
John Koleszar's avatar
John Koleszar committed
343
344
345
346

    // Keep rate_correction_factor within limits
    if (rate_correction_factor > MAX_BPB_FACTOR)
      rate_correction_factor = MAX_BPB_FACTOR;
347
  } else if (correction_factor < 99) {
John Koleszar's avatar
John Koleszar committed
348
    // We are not already at the best allowable quality
349
    correction_factor =
350
        (int)(100 - ((100 - correction_factor) * adjustment_limit));
351
352
    rate_correction_factor =
        ((rate_correction_factor * correction_factor) / 100);
John Koleszar's avatar
John Koleszar committed
353
354
355
356
357
358

    // Keep rate_correction_factor within limits
    if (rate_correction_factor < MIN_BPB_FACTOR)
      rate_correction_factor = MIN_BPB_FACTOR;
  }

359
  if (cpi->common.frame_type == KEY_FRAME) {
360
    cpi->rc.key_frame_rate_correction_factor = rate_correction_factor;
361
  } else {
362
    if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
363
      cpi->rc.gf_rate_correction_factor = rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
364
    else
365
      cpi->rc.rate_correction_factor = rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
366
  }
John Koleszar's avatar
John Koleszar committed
367
368
369
}


370
int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame) {
371
  int q = cpi->rc.active_worst_quality;
John Koleszar's avatar
John Koleszar committed
372

John Koleszar's avatar
John Koleszar committed
373
374
375
376
377
  int i;
  int last_error = INT_MAX;
  int target_bits_per_mb;
  int bits_per_mb_at_this_q;
  double correction_factor;
378

John Koleszar's avatar
John Koleszar committed
379
  // Select the appropriate correction factor based upon type of frame.
380
  if (cpi->common.frame_type == KEY_FRAME) {
381
    correction_factor = cpi->rc.key_frame_rate_correction_factor;
382
  } else {
383
    if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
384
      correction_factor = cpi->rc.gf_rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
385
    else
386
      correction_factor = cpi->rc.rate_correction_factor;
John Koleszar's avatar
John Koleszar committed
387
  }
John Koleszar's avatar
John Koleszar committed
388

389
390
  // Calculate required scaling factor based on target frame size and size of
  // frame produced using previous Q.
John Koleszar's avatar
John Koleszar committed
391
  if (target_bits_per_frame >= (INT_MAX >> BPER_MB_NORMBITS))
392
393
394
    target_bits_per_mb =
        (target_bits_per_frame / cpi->common.MBs)
        << BPER_MB_NORMBITS;  // Case where we would overflow int
John Koleszar's avatar
John Koleszar committed
395
  else
396
397
    target_bits_per_mb =
        (target_bits_per_frame << BPER_MB_NORMBITS) / cpi->common.MBs;
John Koleszar's avatar
John Koleszar committed
398

399
  i = cpi->rc.active_best_quality;
John Koleszar's avatar
John Koleszar committed
400

John Koleszar's avatar
John Koleszar committed
401
  do {
402
403
    bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cpi->common.frame_type, i,
                                                    correction_factor);
John Koleszar's avatar
John Koleszar committed
404

John Koleszar's avatar
John Koleszar committed
405
406
    if (bits_per_mb_at_this_q <= target_bits_per_mb) {
      if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
407
        q = i;
John Koleszar's avatar
John Koleszar committed
408
      else
409
        q = i - 1;
John Koleszar's avatar
John Koleszar committed
410

John Koleszar's avatar
John Koleszar committed
411
      break;
412
    } else {
John Koleszar's avatar
John Koleszar committed
413
      last_error = bits_per_mb_at_this_q - target_bits_per_mb;
414
    }
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
  } while (++i <= cpi->rc.active_worst_quality);

  return q;
}

static int get_active_quality(int q,
                              int gfu_boost,
                              int low,
                              int high,
                              int *low_motion_minq,
                              int *high_motion_minq) {
  int active_best_quality;
  if (gfu_boost > high) {
    active_best_quality = low_motion_minq[q];
  } else if (gfu_boost < low) {
    active_best_quality = high_motion_minq[q];
  } else {
    const int gap = high - low;
    const int offset = high - gfu_boost;
    const int qdiff = high_motion_minq[q] - low_motion_minq[q];
    const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
    active_best_quality = low_motion_minq[q] + adjustment;
  }
  return active_best_quality;
}

441
442
443
int vp9_rc_pick_q_and_adjust_q_bounds(VP9_COMP *cpi,
                                      int *bottom_index,
                                      int *top_index) {
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
  // Set an active best quality and if necessary active worst quality
  int q = cpi->rc.active_worst_quality;
  VP9_COMMON *const cm = &cpi->common;

  if (frame_is_intra_only(cm)) {
#if !CONFIG_MULTIPLE_ARF
    // Handle the special case for key frames forced when we have75 reached
    // the maximum key frame interval. Here force the Q to a range
    // based on the ambient Q to reduce the risk of popping.
    if (cpi->this_key_frame_forced) {
      int delta_qindex;
      int qindex = cpi->rc.last_boosted_qindex;
      double last_boosted_q = vp9_convert_qindex_to_q(qindex);

      delta_qindex = vp9_compute_qdelta(cpi, last_boosted_q,
                                        (last_boosted_q * 0.75));

      cpi->rc.active_best_quality = MAX(qindex + delta_qindex,
462
463
464
465
466
467
                                        cpi->rc.best_quality);
    } else if (cpi->pass == 0 && cpi->common.current_video_frame == 0) {
      // If this is the first (key) frame in 1-pass, active best/worst is
      // the user best/worst-allowed, and leave the top_index to active_worst.
      cpi->rc.active_best_quality = cpi->oxcf.best_allowed_q;
      cpi->rc.active_worst_quality = cpi->oxcf.worst_allowed_q;
468
469
470
471
472
473
474
475
    } else {
      int high = 5000;
      int low = 400;
      double q_adj_factor = 1.0;
      double q_val;

      // Baseline value derived from cpi->active_worst_quality and kf boost
      cpi->rc.active_best_quality = get_active_quality(q, cpi->rc.kf_boost,
476
477
478
                                                       low, high,
                                                       kf_low_motion_minq,
                                                       kf_high_motion_minq);
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518

      // Allow somewhat lower kf minq with small image formats.
      if ((cm->width * cm->height) <= (352 * 288)) {
        q_adj_factor -= 0.25;
      }

      // Make a further adjustment based on the kf zero motion measure.
      q_adj_factor += 0.05 - (0.001 * (double)cpi->kf_zeromotion_pct);

      // Convert the adjustment factor to a qindex delta
      // on active_best_quality.
      q_val = vp9_convert_qindex_to_q(cpi->rc.active_best_quality);
      cpi->rc.active_best_quality +=
          vp9_compute_qdelta(cpi, q_val, (q_val * q_adj_factor));
    }
#else
    double current_q;
    // Force the KF quantizer to be 30% of the active_worst_quality.
    current_q = vp9_convert_qindex_to_q(cpi->rc.active_worst_quality);
    cpi->rc.active_best_quality = cpi->rc.active_worst_quality
        + vp9_compute_qdelta(cpi, current_q, current_q * 0.3);
#endif
  } else if (!cpi->is_src_frame_alt_ref &&
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
    int high = 2000;
    int low = 400;

    // Use the lower of cpi->rc.active_worst_quality and recent
    // average Q as basis for GF/ARF best Q limit unless last frame was
    // a key frame.
    if (cpi->frames_since_key > 1 &&
        cpi->rc.avg_frame_qindex < cpi->rc.active_worst_quality) {
      q = cpi->rc.avg_frame_qindex;
    }
    // For constrained quality dont allow Q less than the cq level
    if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
      if (q < cpi->cq_target_quality)
        q = cpi->cq_target_quality;
      if (cpi->frames_since_key > 1) {
        cpi->rc.active_best_quality = get_active_quality(q, cpi->rc.gfu_boost,
519
520
521
                                                         low, high,
                                                         afq_low_motion_minq,
                                                         afq_high_motion_minq);
522
523
      } else {
        cpi->rc.active_best_quality = get_active_quality(q, cpi->rc.gfu_boost,
524
525
526
                                                         low, high,
                                                         gf_low_motion_minq,
                                                         gf_high_motion_minq);
527
528
529
530
531
532
533
534
535
      }
      // Constrained quality use slightly lower active best.
      cpi->rc.active_best_quality = cpi->rc.active_best_quality * 15 / 16;

    } else if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
      if (!cpi->refresh_alt_ref_frame) {
        cpi->rc.active_best_quality = cpi->cq_target_quality;
      } else {
        if (cpi->frames_since_key > 1) {
536
537
538
          cpi->rc.active_best_quality = get_active_quality(
              q, cpi->rc.gfu_boost, low, high,
              afq_low_motion_minq, afq_high_motion_minq);
539
        } else {
540
541
542
          cpi->rc.active_best_quality = get_active_quality(
              q, cpi->rc.gfu_boost, low, high,
              gf_low_motion_minq, gf_high_motion_minq);
543
544
545
        }
      }
    } else {
546
547
548
        cpi->rc.active_best_quality = get_active_quality(
            q, cpi->rc.gfu_boost, low, high,
            gf_low_motion_minq, gf_high_motion_minq);
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
    }
  } else {
    if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
      cpi->rc.active_best_quality = cpi->cq_target_quality;
    } else {
      cpi->rc.active_best_quality = inter_minq[q];
      // 1-pass: for now, use the average Q for the active_best, if its lower
      // than active_worst.
      if (cpi->pass == 0 && (cpi->rc.avg_frame_qindex < q))
        cpi->rc.active_best_quality = inter_minq[cpi->rc.avg_frame_qindex];

      // For the constrained quality mode we don't want
      // q to fall below the cq level.
      if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
          (cpi->rc.active_best_quality < cpi->cq_target_quality)) {
        // If we are strongly undershooting the target rate in the last
        // frames then use the user passed in cq value not the auto
        // cq value.
        if (cpi->rc.rolling_actual_bits < cpi->rc.min_frame_bandwidth)
          cpi->rc.active_best_quality = cpi->oxcf.cq_level;
        else
          cpi->rc.active_best_quality = cpi->cq_target_quality;
      }
    }
  }

  // Clip the active best and worst quality values to limits
  if (cpi->rc.active_worst_quality > cpi->rc.worst_quality)
    cpi->rc.active_worst_quality = cpi->rc.worst_quality;

  if (cpi->rc.active_best_quality < cpi->rc.best_quality)
    cpi->rc.active_best_quality = cpi->rc.best_quality;

  if (cpi->rc.active_best_quality > cpi->rc.worst_quality)
    cpi->rc.active_best_quality = cpi->rc.worst_quality;

  if (cpi->rc.active_worst_quality < cpi->rc.active_best_quality)
    cpi->rc.active_worst_quality = cpi->rc.active_best_quality;

588
589
590
591
  *top_index = cpi->rc.active_worst_quality;
  *bottom_index = cpi->rc.active_best_quality;

#if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
592
593
  // Limit Q range for the adaptive loop.
  if (cm->frame_type == KEY_FRAME && !cpi->this_key_frame_forced) {
594
595
596
    if (!(cpi->pass == 0 && cpi->common.current_video_frame == 0)) {
      *top_index =
          (cpi->rc.active_worst_quality + cpi->rc.active_best_quality * 3) / 4;
597
598
599
600
601
602
603
    }
  } else if (!cpi->is_src_frame_alt_ref &&
             (cpi->oxcf.end_usage != USAGE_STREAM_FROM_SERVER) &&
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
    *top_index =
      (cpi->rc.active_worst_quality + cpi->rc.active_best_quality) / 2;
  }
604
#endif
605
606
607
608
609
610
611
612
613
614
615
616

  if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
    q = cpi->rc.active_best_quality;
  // Special case code to try and match quality with forced key frames
  } else if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
    q = cpi->rc.last_boosted_qindex;
  } else {
    // Determine initial Q to try.
    if (cpi->pass == 0) {
      // 1-pass: for now, use per-frame-bw for target size of frame, scaled
      // by |x| for key frame.
      int scale = (cm->frame_type == KEY_FRAME) ? 5 : 1;
617
      q = vp9_rc_regulate_q(cpi, scale * cpi->rc.av_per_frame_bandwidth);
618
    } else {
619
      q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target);
620
621
622
623
    }
    if (q > *top_index)
      q = *top_index;
  }
624
  return q;
John Koleszar's avatar
John Koleszar committed
625
626
}

627

628
static int estimate_keyframe_frequency(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
629
  int i;
John Koleszar's avatar
John Koleszar committed
630

John Koleszar's avatar
John Koleszar committed
631
632
  // Average key frame frequency
  int av_key_frame_frequency = 0;
John Koleszar's avatar
John Koleszar committed
633

John Koleszar's avatar
John Koleszar committed
634
635
636
  /* First key frame at start of sequence is a special case. We have no
   * frequency data.
   */
637
  if (cpi->rc.key_frame_count == 1) {
John Koleszar's avatar
John Koleszar committed
638
639
    /* Assume a default of 1 kf every 2 seconds, or the max kf interval,
     * whichever is smaller.
640
     */
John Koleszar's avatar
John Koleszar committed
641
    int key_freq = cpi->oxcf.key_freq > 0 ? cpi->oxcf.key_freq : 1;
James Zern's avatar
James Zern committed
642
    av_key_frame_frequency = (int)cpi->output_framerate * 2;
John Koleszar's avatar
John Koleszar committed
643

John Koleszar's avatar
John Koleszar committed
644
645
    if (cpi->oxcf.auto_key && av_key_frame_frequency > key_freq)
      av_key_frame_frequency = cpi->oxcf.key_freq;
John Koleszar's avatar
John Koleszar committed
646

647
    cpi->rc.prior_key_frame_distance[KEY_FRAME_CONTEXT - 1]
John Koleszar's avatar
John Koleszar committed
648
649
650
651
652
653
654
655
656
657
658
      = av_key_frame_frequency;
  } else {
    unsigned int total_weight = 0;
    int last_kf_interval =
      (cpi->frames_since_key > 0) ? cpi->frames_since_key : 1;

    /* reset keyframe context and calculate weighted average of last
     * KEY_FRAME_CONTEXT keyframes
     */
    for (i = 0; i < KEY_FRAME_CONTEXT; i++) {
      if (i < KEY_FRAME_CONTEXT - 1)
659
660
        cpi->rc.prior_key_frame_distance[i]
          = cpi->rc.prior_key_frame_distance[i + 1];
John Koleszar's avatar
John Koleszar committed
661
      else
662
        cpi->rc.prior_key_frame_distance[i] = last_kf_interval;
John Koleszar's avatar
John Koleszar committed
663
664

      av_key_frame_frequency += prior_key_frame_weight[i]
665
                                * cpi->rc.prior_key_frame_distance[i];
John Koleszar's avatar
John Koleszar committed
666
      total_weight += prior_key_frame_weight[i];
John Koleszar's avatar
John Koleszar committed
667
    }
John Koleszar's avatar
John Koleszar committed
668

669
    av_key_frame_frequency /= total_weight;
John Koleszar's avatar
John Koleszar committed
670
671
  }
  return av_key_frame_frequency;
672
673
674
}


675
static void adjust_key_frame_context(VP9_COMP *cpi) {
John Koleszar's avatar
John Koleszar committed
676
  // Clear down mmx registers to allow floating point in what follows
677
  vp9_clear_system_state();
John Koleszar's avatar
John Koleszar committed
678

John Koleszar's avatar
John Koleszar committed
679
  cpi->frames_since_key = 0;
680
  cpi->rc.key_frame_count++;
John Koleszar's avatar
John Koleszar committed
681
682
}

683

684
685
686
687
static void compute_frame_size_bounds(const VP9_COMP *cpi,
                                      int this_frame_target,
                                      int *frame_under_shoot_limit,
                                      int *frame_over_shoot_limit) {
John Koleszar's avatar
John Koleszar committed
688
  // Set-up bounds on acceptable frame size:
689
  if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
John Koleszar's avatar
John Koleszar committed
690
691
692
693
    *frame_under_shoot_limit = 0;
    *frame_over_shoot_limit  = INT_MAX;
  } else {
    if (cpi->common.frame_type == KEY_FRAME) {
694
695
      *frame_over_shoot_limit  = this_frame_target * 9 / 8;
      *frame_under_shoot_limit = this_frame_target * 7 / 8;
John Koleszar's avatar
John Koleszar committed
696
    } else {
697
      if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) {
698
699
        *frame_over_shoot_limit  = this_frame_target * 9 / 8;
        *frame_under_shoot_limit = this_frame_target * 7 / 8;
John Koleszar's avatar
John Koleszar committed
700
701
702
      } else {
        // Stron overshoot limit for constrained quality
        if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
703
704
          *frame_over_shoot_limit  = this_frame_target * 11 / 8;
          *frame_under_shoot_limit = this_frame_target * 2 / 8;
John Koleszar's avatar
John Koleszar committed
705
        } else {
706
707
          *frame_over_shoot_limit  = this_frame_target * 11 / 8;
          *frame_under_shoot_limit = this_frame_target * 5 / 8;
John Koleszar's avatar
John Koleszar committed
708
        }
John Koleszar's avatar
John Koleszar committed
709
      }
John Koleszar's avatar
John Koleszar committed
710
    }
John Koleszar's avatar
John Koleszar committed
711
712
713
714
715
716
717
718
719

    // For very small rate targets where the fractional adjustment
    // (eg * 7/8) may be tiny make sure there is at least a minimum
    // range.
    *frame_over_shoot_limit += 200;
    *frame_under_shoot_limit -= 200;
    if (*frame_under_shoot_limit < 0)
      *frame_under_shoot_limit = 0;
  }
John Koleszar's avatar
John Koleszar committed
720
}
721
722

// return of 0 means drop frame
723
724
725
int vp9_rc_pick_frame_size_and_bounds(VP9_COMP *cpi,
                                      int *frame_under_shoot_limit,
                                      int *frame_over_shoot_limit) {
726
  VP9_COMMON *cm = &cpi->common;
727

John Koleszar's avatar
John Koleszar committed
728
729
730
731
  if (cm->frame_type == KEY_FRAME)
    calc_iframe_target_size(cpi);
  else
    calc_pframe_target_size(cpi);
732

733
734
735
736
737
738
  // Target rate per SB64 (including partial SB64s.
  cpi->rc.sb64_target_rate = ((int64_t)cpi->rc.this_frame_target * 64 * 64) /
                             (cpi->common.width * cpi->common.height);
  compute_frame_size_bounds(cpi, cpi->rc.this_frame_target,
                            frame_under_shoot_limit, frame_over_shoot_limit);

John Koleszar's avatar
John Koleszar committed
739
  return 1;
740
}
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841

void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used, int q) {
  VP9_COMMON *const cm = &cpi->common;
  // Update rate control heuristics
  cpi->rc.projected_frame_size = (bytes_used << 3);

  // Post encode loop adjustment of Q prediction.
  vp9_rc_update_rate_correction_factors(
      cpi, (cpi->sf.recode_loop ||
            cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ? 2 : 0);

  cpi->rc.last_q[cm->frame_type] = cm->base_qindex;

  // Keep record of last boosted (KF/KF/ARF) Q value.
  // If the current frame is coded at a lower Q then we also update it.
  // If all mbs in this group are skipped only update if the Q value is
  // better than that already stored.
  // This is used to help set quality in forced key frames to reduce popping
  if ((cm->base_qindex < cpi->rc.last_boosted_qindex) ||
      ((cpi->static_mb_pct < 100) &&
       ((cm->frame_type == KEY_FRAME) || cpi->refresh_alt_ref_frame ||
        (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)))) {
    cpi->rc.last_boosted_qindex = cm->base_qindex;
  }

  if (cm->frame_type == KEY_FRAME) {
    adjust_key_frame_context(cpi);
  }

  // Keep a record of ambient average Q.
  if (cm->frame_type != KEY_FRAME)
    cpi->rc.avg_frame_qindex = (2 + 3 * cpi->rc.avg_frame_qindex +
                            cm->base_qindex) >> 2;

  // Keep a record from which we can calculate the average Q excluding GF
  // updates and key frames.
  if (cm->frame_type != KEY_FRAME &&
      !cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame) {
    cpi->rc.ni_frames++;
    cpi->rc.tot_q += vp9_convert_qindex_to_q(q);
    cpi->rc.avg_q = cpi->rc.tot_q / (double)cpi->rc.ni_frames;

    // Calculate the average Q for normal inter frames (not key or GFU frames).
    cpi->rc.ni_tot_qi += q;
    cpi->rc.ni_av_qi = cpi->rc.ni_tot_qi / cpi->rc.ni_frames;
  }

  // Update the buffer level variable.
  // Non-viewable frames are a special case and are treated as pure overhead.
  if (!cm->show_frame)
    cpi->rc.bits_off_target -= cpi->rc.projected_frame_size;
  else
    cpi->rc.bits_off_target += cpi->rc.av_per_frame_bandwidth -
                               cpi->rc.projected_frame_size;

  // Clip the buffer level at the maximum buffer size
  if (cpi->rc.bits_off_target > cpi->oxcf.maximum_buffer_size)
    cpi->rc.bits_off_target = cpi->oxcf.maximum_buffer_size;

  // Rolling monitors of whether we are over or underspending used to help
  // regulate min and Max Q in two pass.
  if (cm->frame_type != KEY_FRAME) {
    cpi->rc.rolling_target_bits =
        ((cpi->rc.rolling_target_bits * 3) +
         cpi->rc.this_frame_target + 2) / 4;
    cpi->rc.rolling_actual_bits =
        ((cpi->rc.rolling_actual_bits * 3) +
         cpi->rc.projected_frame_size + 2) / 4;
    cpi->rc.long_rolling_target_bits =
        ((cpi->rc.long_rolling_target_bits * 31) +
         cpi->rc.this_frame_target + 16) / 32;
    cpi->rc.long_rolling_actual_bits =
        ((cpi->rc.long_rolling_actual_bits * 31) +
         cpi->rc.projected_frame_size + 16) / 32;
  }

  // Actual bits spent
  cpi->rc.total_actual_bits += cpi->rc.projected_frame_size;

  // Debug stats
  cpi->rc.total_target_vs_actual += (cpi->rc.this_frame_target -
                                     cpi->rc.projected_frame_size);

  cpi->rc.buffer_level = cpi->rc.bits_off_target;

#ifndef DISABLE_RC_LONG_TERM_MEM
  // Update bits left to the kf and gf groups to account for overshoot or
  // undershoot on these frames
  if (cm->frame_type == KEY_FRAME) {
    cpi->twopass.kf_group_bits += cpi->rc.this_frame_target -
                                  cpi->rc.projected_frame_size;

    cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
  } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
    cpi->twopass.gf_group_bits += cpi->rc.this_frame_target -
                                  cpi->rc.projected_frame_size;

    cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);
  }
#endif
}