Coverage Report

Created: 2026-09-14 08:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp8/encoder/onyx_if.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 "vpx_config.h"
12
#include "./vp8_rtcd.h"
13
#include "./vpx_dsp_rtcd.h"
14
#include "./vpx_scale_rtcd.h"
15
16
#include "vp8/common/alloccommon.h"
17
#include "vp8/common/blockd.h"
18
#include "vp8/common/extend.h"
19
#include "vp8/common/onyxc_int.h"
20
#include "vp8/common/quant_common.h"
21
#include "vp8/common/reconintra.h"
22
#include "vp8/common/swapyv12buffer.h"
23
#include "vp8/common/systemdependent.h"
24
#include "vp8/common/threading.h"
25
#include "vp8/common/vp8_skin_detection.h"
26
#if CONFIG_POSTPROC
27
#include "vp8/common/postproc.h"
28
#endif
29
30
#include "vp8/encoder/bitstream.h"
31
#include "vp8/encoder/block.h"
32
#include "vp8/encoder/encodeframe.h"
33
#include "vp8/encoder/firstpass.h"
34
#include "vp8/encoder/mcomp.h"
35
#include "vp8/encoder/onyx_int.h"
36
#include "vp8/encoder/quantize.h"
37
#include "vp8/encoder/ratectrl.h"
38
#include "vp8/encoder/segmentation.h"
39
#if CONFIG_MULTI_RES_ENCODING
40
#include "vp8/encoder/mr_dissim.h"
41
#endif
42
43
#include "vpx_dsp/psnr.h"
44
#include "vpx_dsp/vpx_dsp_common.h"
45
#include "vpx_mem/vpx_mem.h"
46
#include "vpx_ports/system_state.h"
47
#include "vpx_ports/vpx_once.h"
48
#include "vpx_ports/vpx_timer.h"
49
#include "vpx_scale/vpx_scale.h"
50
#include "vpx_util/vpx_write_yuv_frame.h"
51
#if VPX_ARCH_ARM
52
#include "vpx_ports/arm.h"
53
#endif
54
#if CONFIG_MULTITHREAD
55
#include "ethreading.h"
56
#endif
57
#include "picklpf.h"
58
#if !CONFIG_REALTIME_ONLY
59
#include "temporal_filter.h"
60
#endif
61
62
#include <assert.h>
63
#include <math.h>
64
#include <stdio.h>
65
#include <limits.h>
66
67
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
68
extern int vp8_update_coef_context(VP8_COMP *cpi);
69
#endif
70
71
extern unsigned int vp8_get_processor_freq(void);
72
73
int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest);
74
75
static void set_default_lf_deltas(VP8_COMP *cpi);
76
77
extern const int vp8_gf_interval_table[101];
78
79
#if CONFIG_INTERNAL_STATS
80
#include "math.h"
81
#include "vpx_dsp/ssim.h"
82
#endif
83
84
#ifdef OUTPUT_YUV_SRC
85
FILE *yuv_file;
86
#endif
87
#ifdef OUTPUT_YUV_DENOISED
88
FILE *yuv_denoised_file;
89
#endif
90
#ifdef OUTPUT_YUV_SKINMAP
91
static FILE *yuv_skinmap_file = NULL;
92
#endif
93
94
#if 0
95
FILE *framepsnr;
96
FILE *kf_list;
97
FILE *keyfile;
98
#endif
99
100
#if 0
101
extern int skip_true_count;
102
extern int skip_false_count;
103
#endif
104
105
#ifdef SPEEDSTATS
106
unsigned int frames_at_speed[16] = { 0, 0, 0, 0, 0, 0, 0, 0,
107
                                     0, 0, 0, 0, 0, 0, 0, 0 };
108
unsigned int tot_pm = 0;
109
unsigned int cnt_pm = 0;
110
unsigned int tot_ef = 0;
111
unsigned int cnt_ef = 0;
112
#endif
113
114
#ifdef MODE_STATS
115
extern unsigned __int64 Sectionbits[50];
116
extern int y_modes[5];
117
extern int uv_modes[4];
118
extern int b_modes[10];
119
120
extern int inter_y_modes[10];
121
extern int inter_uv_modes[4];
122
extern unsigned int inter_b_modes[15];
123
#endif
124
125
extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
126
127
extern const int qrounding_factors[129];
128
extern const int qzbin_factors[129];
129
extern void vp8cx_init_quantizer(VP8_COMP *cpi);
130
extern const int vp8cx_base_skip_false_prob[128];
131
132
/* Tables relating active max Q to active min Q */
133
static const unsigned char kf_low_motion_minq[QINDEX_RANGE] = {
134
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
135
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
136
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,
137
  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  4,  4,  4,  5,  5,  5,
138
  5,  5,  6,  6,  6,  6,  7,  7,  8,  8,  8,  8,  9,  9,  10, 10, 10, 10, 11,
139
  11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
140
  17, 17, 18, 18, 18, 18, 19, 20, 20, 21, 21, 22, 23, 23
141
};
142
static const unsigned char kf_high_motion_minq[QINDEX_RANGE] = {
143
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
144
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,
145
  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  5,
146
  5,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  8,  8,  8,  8,  9,  9,  10, 10,
147
  10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16,
148
  16, 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21,
149
  22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28, 29, 30
150
};
151
static const unsigned char gf_low_motion_minq[QINDEX_RANGE] = {
152
  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,
153
  3,  4,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,
154
  8,  8,  9,  9,  9,  9,  10, 10, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
155
  15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24,
156
  25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34,
157
  34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 44,
158
  45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58
159
};
160
static const unsigned char gf_mid_motion_minq[QINDEX_RANGE] = {
161
  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  2,  2,  3,  3,  3,  4,  4,  4,  5,
162
  5,  5,  6,  6,  6,  7,  7,  7,  8,  8,  8,  9,  9,  9,  10, 10, 10, 10, 11,
163
  11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18,
164
  18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
165
  28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37,
166
  37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50,
167
  51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64
168
};
169
static const unsigned char gf_high_motion_minq[QINDEX_RANGE] = {
170
  0,  0,  0,  0,  1,  1,  1,  1,  1,  2,  2,  2,  3,  3,  3,  4,  4,  4,  5,
171
  5,  5,  6,  6,  6,  7,  7,  7,  8,  8,  8,  9,  9,  9,  10, 10, 10, 11, 11,
172
  12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21,
173
  21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30,
174
  31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40,
175
  40, 41, 41, 42, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
176
  57, 58, 59, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80
177
};
178
static const unsigned char inter_minq[QINDEX_RANGE] = {
179
  0,  0,  1,  1,  2,  3,  3,  4,  4,  5,  6,  6,  7,  8,  8,  9,  9,  10, 11,
180
  11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24,
181
  24, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
182
  39, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 50, 51, 52, 53,
183
  54, 55, 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 67, 67, 68, 69,
184
  70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 86,
185
  87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
186
};
187
188
#ifdef PACKET_TESTING
189
extern FILE *vpxlogc;
190
#endif
191
192
0
void vp8_save_layer_context(VP8_COMP *cpi) {
193
0
  LAYER_CONTEXT *lc = &cpi->layer_context[cpi->current_layer];
194
195
  /* Save layer dependent coding state */
196
0
  lc->target_bandwidth = cpi->target_bandwidth;
197
0
  lc->starting_buffer_level = cpi->oxcf.starting_buffer_level;
198
0
  lc->optimal_buffer_level = cpi->oxcf.optimal_buffer_level;
199
0
  lc->maximum_buffer_size = cpi->oxcf.maximum_buffer_size;
200
0
  lc->starting_buffer_level_in_ms = cpi->oxcf.starting_buffer_level_in_ms;
201
0
  lc->optimal_buffer_level_in_ms = cpi->oxcf.optimal_buffer_level_in_ms;
202
0
  lc->maximum_buffer_size_in_ms = cpi->oxcf.maximum_buffer_size_in_ms;
203
0
  lc->buffer_level = cpi->buffer_level;
204
0
  lc->bits_off_target = cpi->bits_off_target;
205
0
  lc->total_actual_bits = cpi->total_actual_bits;
206
0
  lc->worst_quality = cpi->worst_quality;
207
0
  lc->active_worst_quality = cpi->active_worst_quality;
208
0
  lc->best_quality = cpi->best_quality;
209
0
  lc->active_best_quality = cpi->active_best_quality;
210
0
  lc->ni_av_qi = cpi->ni_av_qi;
211
0
  lc->ni_tot_qi = cpi->ni_tot_qi;
212
0
  lc->ni_frames = cpi->ni_frames;
213
0
  lc->avg_frame_qindex = cpi->avg_frame_qindex;
214
0
  lc->rate_correction_factor = cpi->rate_correction_factor;
215
0
  lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
216
0
  lc->gf_rate_correction_factor = cpi->gf_rate_correction_factor;
217
0
  lc->zbin_over_quant = cpi->mb.zbin_over_quant;
218
0
  lc->inter_frame_target = cpi->inter_frame_target;
219
0
  lc->total_byte_count = cpi->total_byte_count;
220
0
  lc->filter_level = cpi->common.filter_level;
221
0
  lc->frames_since_last_drop_overshoot = cpi->frames_since_last_drop_overshoot;
222
0
  lc->force_maxqp = cpi->force_maxqp;
223
0
  lc->last_frame_percent_intra = cpi->last_frame_percent_intra;
224
0
  lc->last_q[0] = cpi->last_q[0];
225
0
  lc->last_q[1] = cpi->last_q[1];
226
227
0
  memcpy(lc->count_mb_ref_frame_usage, cpi->mb.count_mb_ref_frame_usage,
228
0
         sizeof(cpi->mb.count_mb_ref_frame_usage));
229
0
}
230
231
0
void vp8_restore_layer_context(VP8_COMP *cpi, const int layer) {
232
0
  LAYER_CONTEXT *lc = &cpi->layer_context[layer];
233
234
  /* Restore layer dependent coding state */
235
0
  cpi->current_layer = layer;
236
0
  cpi->target_bandwidth = lc->target_bandwidth;
237
0
  cpi->oxcf.target_bandwidth = lc->target_bandwidth;
238
0
  cpi->oxcf.starting_buffer_level = lc->starting_buffer_level;
239
0
  cpi->oxcf.optimal_buffer_level = lc->optimal_buffer_level;
240
0
  cpi->oxcf.maximum_buffer_size = lc->maximum_buffer_size;
241
0
  cpi->oxcf.starting_buffer_level_in_ms = lc->starting_buffer_level_in_ms;
242
0
  cpi->oxcf.optimal_buffer_level_in_ms = lc->optimal_buffer_level_in_ms;
243
0
  cpi->oxcf.maximum_buffer_size_in_ms = lc->maximum_buffer_size_in_ms;
244
0
  cpi->buffer_level = lc->buffer_level;
245
0
  cpi->bits_off_target = lc->bits_off_target;
246
0
  cpi->total_actual_bits = lc->total_actual_bits;
247
0
  cpi->active_worst_quality = lc->active_worst_quality;
248
0
  cpi->active_best_quality = lc->active_best_quality;
249
0
  cpi->ni_av_qi = lc->ni_av_qi;
250
0
  cpi->ni_tot_qi = lc->ni_tot_qi;
251
0
  cpi->ni_frames = lc->ni_frames;
252
0
  cpi->avg_frame_qindex = lc->avg_frame_qindex;
253
0
  cpi->rate_correction_factor = lc->rate_correction_factor;
254
0
  cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
255
0
  cpi->gf_rate_correction_factor = lc->gf_rate_correction_factor;
256
0
  cpi->mb.zbin_over_quant = lc->zbin_over_quant;
257
0
  cpi->inter_frame_target = lc->inter_frame_target;
258
0
  cpi->total_byte_count = lc->total_byte_count;
259
0
  cpi->common.filter_level = lc->filter_level;
260
0
  cpi->frames_since_last_drop_overshoot = lc->frames_since_last_drop_overshoot;
261
0
  cpi->force_maxqp = lc->force_maxqp;
262
0
  cpi->last_frame_percent_intra = lc->last_frame_percent_intra;
263
0
  cpi->last_q[0] = lc->last_q[0];
264
0
  cpi->last_q[1] = lc->last_q[1];
265
266
0
  memcpy(cpi->mb.count_mb_ref_frame_usage, lc->count_mb_ref_frame_usage,
267
0
         sizeof(cpi->mb.count_mb_ref_frame_usage));
268
0
}
269
270
170k
static int rescale(int val, int num, int denom) {
271
170k
  int64_t llnum = num;
272
170k
  int64_t llden = denom;
273
170k
  int64_t llval = val;
274
275
170k
  int64_t result = (llval * llnum / llden);
276
170k
  if (result <= INT_MAX)
277
150k
    return (int)result;
278
20.8k
  else
279
20.8k
    return INT_MAX;
280
170k
}
281
282
void vp8_init_temporal_layer_context(VP8_COMP *cpi, const VP8_CONFIG *oxcf,
283
                                     const int layer,
284
0
                                     double prev_layer_framerate) {
285
0
  LAYER_CONTEXT *lc = &cpi->layer_context[layer];
286
287
0
  lc->framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[layer];
288
0
  if (cpi->oxcf.target_bitrate[layer] > INT_MAX / 1000)
289
0
    lc->target_bandwidth = INT_MAX;
290
0
  else
291
0
    lc->target_bandwidth = cpi->oxcf.target_bitrate[layer] * 1000;
292
293
0
  lc->starting_buffer_level_in_ms = oxcf->starting_buffer_level;
294
0
  lc->optimal_buffer_level_in_ms = oxcf->optimal_buffer_level;
295
0
  lc->maximum_buffer_size_in_ms = oxcf->maximum_buffer_size;
296
297
0
  lc->starting_buffer_level =
298
0
      rescale((int)(oxcf->starting_buffer_level), lc->target_bandwidth, 1000);
299
300
0
  if (oxcf->optimal_buffer_level == 0) {
301
0
    lc->optimal_buffer_level = lc->target_bandwidth / 8;
302
0
  } else {
303
0
    lc->optimal_buffer_level =
304
0
        rescale((int)(oxcf->optimal_buffer_level), lc->target_bandwidth, 1000);
305
0
  }
306
307
0
  if (oxcf->maximum_buffer_size == 0) {
308
0
    lc->maximum_buffer_size = lc->target_bandwidth / 8;
309
0
  } else {
310
0
    lc->maximum_buffer_size =
311
0
        rescale((int)(oxcf->maximum_buffer_size), lc->target_bandwidth, 1000);
312
0
  }
313
314
  /* Work out the average size of a frame within this layer */
315
0
  if (layer > 0) {
316
0
    lc->avg_frame_size_for_layer =
317
0
        (int)round((cpi->oxcf.target_bitrate[layer] -
318
0
                    cpi->oxcf.target_bitrate[layer - 1]) *
319
0
                   1000 / (lc->framerate - prev_layer_framerate));
320
0
  }
321
322
0
  lc->active_worst_quality = cpi->oxcf.worst_allowed_q;
323
0
  lc->active_best_quality = cpi->oxcf.best_allowed_q;
324
0
  lc->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
325
326
0
  lc->buffer_level = lc->starting_buffer_level;
327
0
  lc->bits_off_target = lc->starting_buffer_level;
328
329
0
  lc->total_actual_bits = 0;
330
0
  lc->ni_av_qi = 0;
331
0
  lc->ni_tot_qi = 0;
332
0
  lc->ni_frames = 0;
333
0
  lc->rate_correction_factor = 1.0;
334
0
  lc->key_frame_rate_correction_factor = 1.0;
335
0
  lc->gf_rate_correction_factor = 1.0;
336
0
  lc->inter_frame_target = 0;
337
0
}
338
339
// Upon a run-time change in temporal layers, reset the layer context parameters
340
// for any "new" layers. For "existing" layers, let them inherit the parameters
341
// from the previous layer state (at the same layer #). In future we may want
342
// to better map the previous layer state(s) to the "new" ones.
343
void vp8_reset_temporal_layer_change(VP8_COMP *cpi, const VP8_CONFIG *oxcf,
344
0
                                     const int prev_num_layers) {
345
0
  int i;
346
0
  double prev_layer_framerate = 0;
347
0
  const int curr_num_layers = cpi->oxcf.number_of_layers;
348
  // If the previous state was 1 layer, get current layer context from cpi.
349
  // We need this to set the layer context for the new layers below.
350
0
  if (prev_num_layers == 1) {
351
0
    cpi->current_layer = 0;
352
0
    vp8_save_layer_context(cpi);
353
0
  }
354
0
  for (i = 0; i < curr_num_layers; ++i) {
355
0
    LAYER_CONTEXT *lc = &cpi->layer_context[i];
356
0
    if (i >= prev_num_layers) {
357
0
      vp8_init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
358
0
    }
359
    // The initial buffer levels are set based on their starting levels.
360
    // We could set the buffer levels based on the previous state (normalized
361
    // properly by the layer bandwidths) but we would need to keep track of
362
    // the previous set of layer bandwidths (i.e., target_bitrate[i])
363
    // before the layer change. For now, reset to the starting levels.
364
0
    lc->buffer_level =
365
0
        cpi->oxcf.starting_buffer_level_in_ms * cpi->oxcf.target_bitrate[i];
366
0
    lc->bits_off_target = lc->buffer_level;
367
    // TDOD(marpan): Should we set the rate_correction_factor and
368
    // active_worst/best_quality to values derived from the previous layer
369
    // state (to smooth-out quality dips/rate fluctuation at transition)?
370
371
    // We need to treat the 1 layer case separately: oxcf.target_bitrate[i]
372
    // is not set for 1 layer, and the vp8_restore_layer_context/save_context()
373
    // are not called in the encoding loop, so we need to call it here to
374
    // pass the layer context state to |cpi|.
375
0
    if (curr_num_layers == 1) {
376
0
      lc->target_bandwidth = cpi->oxcf.target_bandwidth;
377
0
      lc->buffer_level =
378
0
          cpi->oxcf.starting_buffer_level_in_ms * lc->target_bandwidth / 1000;
379
0
      lc->bits_off_target = lc->buffer_level;
380
0
      vp8_restore_layer_context(cpi, 0);
381
0
    }
382
0
    prev_layer_framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[i];
383
0
  }
384
0
}
385
386
77.8k
static void setup_features(VP8_COMP *cpi) {
387
  // If segmentation enabled set the update flags
388
77.8k
  if (cpi->mb.e_mbd.segmentation_enabled) {
389
0
    cpi->mb.e_mbd.update_mb_segmentation_map = 1;
390
0
    cpi->mb.e_mbd.update_mb_segmentation_data = 1;
391
77.8k
  } else {
392
77.8k
    cpi->mb.e_mbd.update_mb_segmentation_map = 0;
393
77.8k
    cpi->mb.e_mbd.update_mb_segmentation_data = 0;
394
77.8k
  }
395
396
77.8k
  cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
397
77.8k
  cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
398
77.8k
  memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
399
77.8k
  memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
400
77.8k
  memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0,
401
77.8k
         sizeof(cpi->mb.e_mbd.ref_lf_deltas));
402
77.8k
  memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0,
403
77.8k
         sizeof(cpi->mb.e_mbd.mode_lf_deltas));
404
405
77.8k
  set_default_lf_deltas(cpi);
406
77.8k
}
407
408
static void dealloc_raw_frame_buffers(VP8_COMP *cpi);
409
410
1
static void initialize_enc(void) {
411
1
  vpx_dsp_rtcd();
412
1
  vp8_init_intra_predictors();
413
1
}
414
415
6.41k
void vp8_initialize_enc(void) { once(initialize_enc); }
416
417
6.35k
static void dealloc_compressor_data(VP8_COMP *cpi) {
418
6.35k
  vpx_free(cpi->tplist);
419
6.35k
  cpi->tplist = NULL;
420
421
  /* Delete last frame MV storage buffers */
422
6.35k
  vpx_free(cpi->lfmv);
423
6.35k
  cpi->lfmv = 0;
424
425
6.35k
  vpx_free(cpi->lf_ref_frame_sign_bias);
426
6.35k
  cpi->lf_ref_frame_sign_bias = 0;
427
428
6.35k
  vpx_free(cpi->lf_ref_frame);
429
6.35k
  cpi->lf_ref_frame = 0;
430
431
  /* Delete sementation map */
432
6.35k
  vpx_free(cpi->segmentation_map);
433
6.35k
  cpi->segmentation_map = 0;
434
435
6.35k
  vpx_free(cpi->active_map);
436
6.35k
  cpi->active_map = 0;
437
438
6.35k
  vp8_de_alloc_frame_buffers(&cpi->common);
439
440
6.35k
  vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
441
6.35k
  vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
442
6.35k
  dealloc_raw_frame_buffers(cpi);
443
444
6.35k
  vpx_free(cpi->tok);
445
6.35k
  cpi->tok = 0;
446
447
  /* Structure used to monitor GF usage */
448
6.35k
  vpx_free(cpi->gf_active_flags);
449
6.35k
  cpi->gf_active_flags = 0;
450
451
  /* Activity mask based per mb zbin adjustments */
452
6.35k
  vpx_free(cpi->mb_activity_map);
453
6.35k
  cpi->mb_activity_map = 0;
454
455
6.35k
  vpx_free(cpi->mb.pip);
456
6.35k
  cpi->mb.pip = 0;
457
6.35k
}
458
459
0
static void enable_segmentation(VP8_COMP *cpi) {
460
  /* Set the appropriate feature bit */
461
0
  cpi->mb.e_mbd.segmentation_enabled = 1;
462
0
  cpi->mb.e_mbd.update_mb_segmentation_map = 1;
463
0
  cpi->mb.e_mbd.update_mb_segmentation_data = 1;
464
0
}
465
0
static void disable_segmentation(VP8_COMP *cpi) {
466
  /* Clear the appropriate feature bit */
467
0
  cpi->mb.e_mbd.segmentation_enabled = 0;
468
0
}
469
470
/* Valid values for a segment are 0 to 3
471
 * Segmentation map is arrange as [Rows][Columns]
472
 */
473
static void set_segmentation_map(VP8_COMP *cpi,
474
0
                                 unsigned char *segmentation_map) {
475
  /* Copy in the new segmentation map */
476
0
  memcpy(cpi->segmentation_map, segmentation_map,
477
0
         (cpi->common.mb_rows * cpi->common.mb_cols));
478
479
  /* Signal that the map should be updated. */
480
0
  cpi->mb.e_mbd.update_mb_segmentation_map = 1;
481
0
  cpi->mb.e_mbd.update_mb_segmentation_data = 1;
482
0
}
483
484
/* The values given for each segment can be either deltas (from the default
485
 * value chosen for the frame) or absolute values.
486
 *
487
 * Valid range for abs values is:
488
 *    (0-127 for MB_LVL_ALT_Q), (0-63 for SEGMENT_ALT_LF)
489
 * Valid range for delta values are:
490
 *    (+/-127 for MB_LVL_ALT_Q), (+/-63 for SEGMENT_ALT_LF)
491
 *
492
 * abs_delta = SEGMENT_DELTADATA (deltas)
493
 * abs_delta = SEGMENT_ABSDATA (use the absolute values given).
494
 *
495
 */
496
static void set_segment_data(VP8_COMP *cpi, signed char *feature_data,
497
0
                             unsigned char abs_delta) {
498
0
  cpi->mb.e_mbd.mb_segment_abs_delta = abs_delta;
499
0
  memcpy(cpi->segment_feature_data, feature_data,
500
0
         sizeof(cpi->segment_feature_data));
501
0
}
502
503
/* A simple function to cyclically refresh the background at a lower Q */
504
0
static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment) {
505
0
  unsigned char *seg_map = cpi->segmentation_map;
506
0
  signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
507
0
  int i;
508
0
  int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
509
0
  int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
510
511
0
  cpi->cyclic_refresh_q = Q / 2;
512
513
0
  if (cpi->oxcf.screen_content_mode) {
514
    // Modify quality ramp-up based on Q. Above some Q level, increase the
515
    // number of blocks to be refreshed, and reduce it below the thredhold.
516
    // Turn-off under certain conditions (i.e., away from key frame, and if
517
    // we are at good quality (low Q) and most of the blocks were
518
    // skipped-encoded
519
    // in previous frame.
520
0
    int qp_thresh = (cpi->oxcf.screen_content_mode == 2) ? 80 : 100;
521
0
    if (Q >= qp_thresh) {
522
0
      cpi->cyclic_refresh_mode_max_mbs_perframe =
523
0
          (cpi->common.mb_rows * cpi->common.mb_cols) / 10;
524
0
    } else if (cpi->frames_since_key > 250 && Q < 20 &&
525
0
               cpi->mb.skip_true_count > (int)(0.95 * mbs_in_frame)) {
526
0
      cpi->cyclic_refresh_mode_max_mbs_perframe = 0;
527
0
    } else {
528
0
      cpi->cyclic_refresh_mode_max_mbs_perframe =
529
0
          (cpi->common.mb_rows * cpi->common.mb_cols) / 20;
530
0
    }
531
0
    block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
532
0
  }
533
534
  // Set every macroblock to be eligible for update.
535
  // For key frame this will reset seg map to 0.
536
0
  memset(cpi->segmentation_map, 0, mbs_in_frame);
537
538
0
  if (cpi->common.frame_type != KEY_FRAME && block_count > 0) {
539
    /* Cycle through the macro_block rows */
540
    /* MB loop to set local segmentation map */
541
0
    i = cpi->cyclic_refresh_mode_index;
542
0
    assert(i < mbs_in_frame);
543
0
    do {
544
      /* If the MB is as a candidate for clean up then mark it for
545
       * possible boost/refresh (segment 1) The segment id may get
546
       * reset to 0 later if the MB gets coded anything other than
547
       * last frame 0,0 as only (last frame 0,0) MBs are eligable for
548
       * refresh : that is to say Mbs likely to be background blocks.
549
       */
550
0
      if (cpi->cyclic_refresh_map[i] == 0) {
551
0
        seg_map[i] = 1;
552
0
        block_count--;
553
0
      } else if (cpi->cyclic_refresh_map[i] < 0) {
554
0
        cpi->cyclic_refresh_map[i]++;
555
0
      }
556
557
0
      i++;
558
0
      if (i == mbs_in_frame) i = 0;
559
560
0
    } while (block_count && i != cpi->cyclic_refresh_mode_index);
561
562
0
    cpi->cyclic_refresh_mode_index = i;
563
564
0
#if CONFIG_TEMPORAL_DENOISING
565
0
    if (cpi->oxcf.noise_sensitivity > 0) {
566
0
      if (cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive &&
567
0
          Q < (int)cpi->denoiser.denoise_pars.qp_thresh &&
568
0
          (cpi->frames_since_key >
569
0
           2 * cpi->denoiser.denoise_pars.consec_zerolast)) {
570
        // Under aggressive denoising, use segmentation to turn off loop
571
        // filter below some qp thresh. The filter is reduced for all
572
        // blocks that have been encoded as ZEROMV LAST x frames in a row,
573
        // where x is set by cpi->denoiser.denoise_pars.consec_zerolast.
574
        // This is to avoid "dot" artifacts that can occur from repeated
575
        // loop filtering on noisy input source.
576
0
        cpi->cyclic_refresh_q = Q;
577
        // lf_adjustment = -MAX_LOOP_FILTER;
578
0
        lf_adjustment = -40;
579
0
        for (i = 0; i < mbs_in_frame; ++i) {
580
0
          seg_map[i] = (cpi->consec_zero_last[i] >
581
0
                        cpi->denoiser.denoise_pars.consec_zerolast)
582
0
                           ? 1
583
0
                           : 0;
584
0
        }
585
0
      }
586
0
    }
587
0
#endif
588
0
  }
589
590
  /* Activate segmentation. */
591
0
  cpi->mb.e_mbd.update_mb_segmentation_map = 1;
592
0
  cpi->mb.e_mbd.update_mb_segmentation_data = 1;
593
0
  enable_segmentation(cpi);
594
595
  /* Set up the quant segment data */
596
0
  feature_data[MB_LVL_ALT_Q][0] = 0;
597
0
  feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
598
0
  feature_data[MB_LVL_ALT_Q][2] = 0;
599
0
  feature_data[MB_LVL_ALT_Q][3] = 0;
600
601
  /* Set up the loop segment data */
602
0
  feature_data[MB_LVL_ALT_LF][0] = 0;
603
0
  feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
604
0
  feature_data[MB_LVL_ALT_LF][2] = 0;
605
0
  feature_data[MB_LVL_ALT_LF][3] = 0;
606
607
  /* Initialise the feature data structure */
608
0
  set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
609
0
}
610
611
117k
static void compute_skin_map(VP8_COMP *cpi) {
612
117k
  int mb_row, mb_col, num_bl;
613
117k
  VP8_COMMON *cm = &cpi->common;
614
117k
  const uint8_t *src_y = cpi->Source->y_buffer;
615
117k
  const uint8_t *src_u = cpi->Source->u_buffer;
616
117k
  const uint8_t *src_v = cpi->Source->v_buffer;
617
117k
  const int src_ystride = cpi->Source->y_stride;
618
117k
  const int src_uvstride = cpi->Source->uv_stride;
619
620
117k
  const SKIN_DETECTION_BLOCK_SIZE bsize =
621
117k
      (cm->Width * cm->Height <= 352 * 288) ? SKIN_8X8 : SKIN_16X16;
622
623
474k
  for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
624
356k
    num_bl = 0;
625
2.30M
    for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
626
1.94M
      const int bl_index = mb_row * cm->mb_cols + mb_col;
627
1.94M
      cpi->skin_map[bl_index] =
628
1.94M
          vp8_compute_skin_block(src_y, src_u, src_v, src_ystride, src_uvstride,
629
1.94M
                                 bsize, cpi->consec_zero_last[bl_index], 0);
630
1.94M
      num_bl++;
631
1.94M
      src_y += 16;
632
1.94M
      src_u += 8;
633
1.94M
      src_v += 8;
634
1.94M
    }
635
356k
    src_y += (src_ystride << 4) - (num_bl << 4);
636
356k
    src_u += (src_uvstride << 3) - (num_bl << 3);
637
356k
    src_v += (src_uvstride << 3) - (num_bl << 3);
638
356k
  }
639
640
  // Remove isolated skin blocks (none of its neighbors are skin) and isolated
641
  // non-skin blocks (all of its neighbors are skin). Skip the boundary.
642
291k
  for (mb_row = 1; mb_row < cm->mb_rows - 1; mb_row++) {
643
928k
    for (mb_col = 1; mb_col < cm->mb_cols - 1; mb_col++) {
644
754k
      const int bl_index = mb_row * cm->mb_cols + mb_col;
645
754k
      int num_neighbor = 0;
646
754k
      int mi, mj;
647
754k
      int non_skin_threshold = 8;
648
649
3.01M
      for (mi = -1; mi <= 1; mi += 1) {
650
9.05M
        for (mj = -1; mj <= 1; mj += 1) {
651
6.79M
          int bl_neighbor_index = (mb_row + mi) * cm->mb_cols + mb_col + mj;
652
6.79M
          if (cpi->skin_map[bl_neighbor_index]) num_neighbor++;
653
6.79M
        }
654
2.26M
      }
655
656
754k
      if (cpi->skin_map[bl_index] && num_neighbor < 2)
657
1.43k
        cpi->skin_map[bl_index] = 0;
658
754k
      if (!cpi->skin_map[bl_index] && num_neighbor == non_skin_threshold)
659
30
        cpi->skin_map[bl_index] = 1;
660
754k
    }
661
174k
  }
662
117k
}
663
664
77.8k
static void set_default_lf_deltas(VP8_COMP *cpi) {
665
77.8k
  cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
666
77.8k
  cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
667
668
77.8k
  memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
669
77.8k
  memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
670
671
  /* Test of ref frame deltas */
672
77.8k
  cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
673
77.8k
  cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
674
77.8k
  cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
675
77.8k
  cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
676
677
77.8k
  cpi->mb.e_mbd.mode_lf_deltas[0] = 4; /* BPRED */
678
679
77.8k
  if (cpi->oxcf.Mode == MODE_REALTIME) {
680
9.47k
    cpi->mb.e_mbd.mode_lf_deltas[1] = -12; /* Zero */
681
68.3k
  } else {
682
68.3k
    cpi->mb.e_mbd.mode_lf_deltas[1] = -2; /* Zero */
683
68.3k
  }
684
685
77.8k
  cpi->mb.e_mbd.mode_lf_deltas[2] = 2; /* New mv */
686
77.8k
  cpi->mb.e_mbd.mode_lf_deltas[3] = 4; /* Split mv */
687
77.8k
}
688
689
/* Convenience macros for mapping speed and mode into a continuous
690
 * range
691
 */
692
91.5k
#define GOOD(x) ((x) + 1)
693
60.3k
#define RT(x) ((x) + 7)
694
695
2.37M
static int speed_map(int speed, const int *map) {
696
2.37M
  int res;
697
698
6.29M
  do {
699
6.29M
    res = *map++;
700
6.29M
  } while (speed >= *map++);
701
2.37M
  return res;
702
2.37M
}
703
704
static const int thresh_mult_map_znn[] = {
705
  /* map common to zero, nearest, and near */
706
  0, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(2), 2000, INT_MAX
707
};
708
709
static const int thresh_mult_map_vhpred[] = { 1000, GOOD(2), 1500,    GOOD(3),
710
                                              2000, RT(0),   1000,    RT(1),
711
                                              2000, RT(7),   INT_MAX, INT_MAX };
712
713
static const int thresh_mult_map_bpred[] = { 2000,    GOOD(0), 2500, GOOD(2),
714
                                             5000,    GOOD(3), 7500, RT(0),
715
                                             2500,    RT(1),   5000, RT(6),
716
                                             INT_MAX, INT_MAX };
717
718
static const int thresh_mult_map_tm[] = { 1000,    GOOD(2), 1500, GOOD(3),
719
                                          2000,    RT(0),   0,    RT(1),
720
                                          1000,    RT(2),   2000, RT(7),
721
                                          INT_MAX, INT_MAX };
722
723
static const int thresh_mult_map_new1[] = { 1000,  GOOD(2), 2000,
724
                                            RT(0), 2000,    INT_MAX };
725
726
static const int thresh_mult_map_new2[] = { 1000, GOOD(2), 2000, GOOD(3),
727
                                            2500, GOOD(5), 4000, RT(0),
728
                                            2000, RT(2),   2500, RT(5),
729
                                            4000, INT_MAX };
730
731
static const int thresh_mult_map_split1[] = {
732
  2500,  GOOD(0), 1700,  GOOD(2), 10000, GOOD(3), 25000, GOOD(4), INT_MAX,
733
  RT(0), 5000,    RT(1), 10000,   RT(2), 25000,   RT(3), INT_MAX, INT_MAX
734
};
735
736
static const int thresh_mult_map_split2[] = {
737
  5000,  GOOD(0), 4500,  GOOD(2), 20000, GOOD(3), 50000, GOOD(4), INT_MAX,
738
  RT(0), 10000,   RT(1), 20000,   RT(2), 50000,   RT(3), INT_MAX, INT_MAX
739
};
740
741
static const int mode_check_freq_map_zn2[] = {
742
  /* {zero,nearest}{2,3} */
743
  0, RT(10), 1 << 1, RT(11), 1 << 2, RT(12), 1 << 3, INT_MAX
744
};
745
746
static const int mode_check_freq_map_vhbpred[] = { 0, GOOD(5), 2, RT(0),
747
                                                   0, RT(3),   2, RT(5),
748
                                                   4, INT_MAX };
749
750
static const int mode_check_freq_map_near2[] = {
751
  0,      GOOD(5), 2,      RT(0),  0,      RT(3),  2,
752
  RT(10), 1 << 2,  RT(11), 1 << 3, RT(12), 1 << 4, INT_MAX
753
};
754
755
static const int mode_check_freq_map_new1[] = {
756
  0, RT(10), 1 << 1, RT(11), 1 << 2, RT(12), 1 << 3, INT_MAX
757
};
758
759
static const int mode_check_freq_map_new2[] = { 0,      GOOD(5), 4,      RT(0),
760
                                                0,      RT(3),   4,      RT(10),
761
                                                1 << 3, RT(11),  1 << 4, RT(12),
762
                                                1 << 5, INT_MAX };
763
764
static const int mode_check_freq_map_split1[] = { 0, GOOD(2), 2, GOOD(3),
765
                                                  7, RT(1),   2, RT(2),
766
                                                  7, INT_MAX };
767
768
static const int mode_check_freq_map_split2[] = { 0, GOOD(1), 2,  GOOD(2),
769
                                                  4, GOOD(3), 15, RT(1),
770
                                                  4, RT(2),   15, INT_MAX };
771
772
158k
void vp8_set_speed_features(VP8_COMP *cpi) {
773
158k
  SPEED_FEATURES *sf = &cpi->sf;
774
158k
  int Mode = cpi->compressor_speed;
775
158k
  int Speed = cpi->Speed;
776
158k
  int Speed2;
777
158k
  int i;
778
158k
  VP8_COMMON *cm = &cpi->common;
779
158k
  int last_improved_quant = sf->improved_quant;
780
158k
  int ref_frames;
781
782
  /* Initialise default mode frequency sampling variables */
783
3.32M
  for (i = 0; i < MAX_MODES; ++i) {
784
3.16M
    cpi->mode_check_freq[i] = 0;
785
3.16M
  }
786
787
158k
  cpi->mb.mbs_tested_so_far = 0;
788
158k
  cpi->mb.mbs_zero_last_dot_suppress = 0;
789
790
  /* best quality defaults */
791
158k
  sf->RD = 1;
792
158k
  sf->search_method = NSTEP;
793
158k
  sf->improved_quant = 1;
794
158k
  sf->improved_dct = 1;
795
158k
  sf->auto_filter = 1;
796
158k
  sf->recode_loop = 1;
797
158k
  sf->quarter_pixel_search = 1;
798
158k
  sf->half_pixel_search = 1;
799
158k
  sf->iterative_sub_pixel = 1;
800
158k
  sf->optimize_coefficients = 1;
801
158k
  sf->use_fastquant_for_pick = 0;
802
158k
  sf->no_skip_block4x4_search = 1;
803
804
158k
  sf->first_step = 0;
805
158k
  sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
806
158k
  sf->improved_mv_pred = 1;
807
808
  /* default thresholds to 0 */
809
3.32M
  for (i = 0; i < MAX_MODES; ++i) sf->thresh_mult[i] = 0;
810
811
  /* Count enabled references */
812
158k
  ref_frames = 1;
813
158k
  if (cpi->ref_frame_flags & VP8_LAST_FRAME) ref_frames++;
814
158k
  if (cpi->ref_frame_flags & VP8_GOLD_FRAME) ref_frames++;
815
158k
  if (cpi->ref_frame_flags & VP8_ALTR_FRAME) ref_frames++;
816
817
  /* Convert speed to continuous range, with clamping */
818
158k
  if (Mode == 0) {
819
6.35k
    Speed = 0;
820
151k
  } else if (Mode == 2) {
821
60.3k
    Speed = RT(Speed);
822
91.5k
  } else {
823
91.5k
    if (Speed > 5) Speed = 5;
824
91.5k
    Speed = GOOD(Speed);
825
91.5k
  }
826
827
158k
  sf->thresh_mult[THR_ZERO1] = sf->thresh_mult[THR_NEAREST1] =
828
158k
      sf->thresh_mult[THR_NEAR1] = sf->thresh_mult[THR_DC] = 0; /* always */
829
830
158k
  sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO3] =
831
158k
      sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST3] =
832
158k
          sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR3] =
833
158k
              speed_map(Speed, thresh_mult_map_znn);
834
835
158k
  sf->thresh_mult[THR_V_PRED] = sf->thresh_mult[THR_H_PRED] =
836
158k
      speed_map(Speed, thresh_mult_map_vhpred);
837
158k
  sf->thresh_mult[THR_B_PRED] = speed_map(Speed, thresh_mult_map_bpred);
838
158k
  sf->thresh_mult[THR_TM] = speed_map(Speed, thresh_mult_map_tm);
839
158k
  sf->thresh_mult[THR_NEW1] = speed_map(Speed, thresh_mult_map_new1);
840
158k
  sf->thresh_mult[THR_NEW2] = sf->thresh_mult[THR_NEW3] =
841
158k
      speed_map(Speed, thresh_mult_map_new2);
842
158k
  sf->thresh_mult[THR_SPLIT1] = speed_map(Speed, thresh_mult_map_split1);
843
158k
  sf->thresh_mult[THR_SPLIT2] = sf->thresh_mult[THR_SPLIT3] =
844
158k
      speed_map(Speed, thresh_mult_map_split2);
845
846
  // Special case for temporal layers.
847
  // Reduce the thresholds for zero/nearest/near for GOLDEN, if GOLDEN is
848
  // used as second reference. We don't modify thresholds for ALTREF case
849
  // since ALTREF is usually used as long-term reference in temporal layers.
850
158k
  if ((cpi->Speed <= 6) && (cpi->oxcf.number_of_layers > 1) &&
851
0
      (cpi->ref_frame_flags & VP8_LAST_FRAME) &&
852
0
      (cpi->ref_frame_flags & VP8_GOLD_FRAME)) {
853
0
    if (cpi->closest_reference_frame == GOLDEN_FRAME) {
854
0
      sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 3;
855
0
      sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 3;
856
0
      sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 3;
857
0
    } else {
858
0
      sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 1;
859
0
      sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 1;
860
0
      sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 1;
861
0
    }
862
0
  }
863
864
158k
  cpi->mode_check_freq[THR_ZERO1] = cpi->mode_check_freq[THR_NEAREST1] =
865
158k
      cpi->mode_check_freq[THR_NEAR1] = cpi->mode_check_freq[THR_TM] =
866
158k
          cpi->mode_check_freq[THR_DC] = 0; /* always */
867
868
158k
  cpi->mode_check_freq[THR_ZERO2] = cpi->mode_check_freq[THR_ZERO3] =
869
158k
      cpi->mode_check_freq[THR_NEAREST2] = cpi->mode_check_freq[THR_NEAREST3] =
870
158k
          speed_map(Speed, mode_check_freq_map_zn2);
871
872
158k
  cpi->mode_check_freq[THR_NEAR2] = cpi->mode_check_freq[THR_NEAR3] =
873
158k
      speed_map(Speed, mode_check_freq_map_near2);
874
875
158k
  cpi->mode_check_freq[THR_V_PRED] = cpi->mode_check_freq[THR_H_PRED] =
876
158k
      cpi->mode_check_freq[THR_B_PRED] =
877
158k
          speed_map(Speed, mode_check_freq_map_vhbpred);
878
879
  // For real-time mode at speed 10 keep the mode_check_freq threshold
880
  // for NEW1 similar to that of speed 9.
881
158k
  Speed2 = Speed;
882
158k
  if (cpi->Speed == 10 && Mode == 2) Speed2 = RT(9);
883
158k
  cpi->mode_check_freq[THR_NEW1] = speed_map(Speed2, mode_check_freq_map_new1);
884
885
158k
  cpi->mode_check_freq[THR_NEW2] = cpi->mode_check_freq[THR_NEW3] =
886
158k
      speed_map(Speed, mode_check_freq_map_new2);
887
888
158k
  cpi->mode_check_freq[THR_SPLIT1] =
889
158k
      speed_map(Speed, mode_check_freq_map_split1);
890
158k
  cpi->mode_check_freq[THR_SPLIT2] = cpi->mode_check_freq[THR_SPLIT3] =
891
158k
      speed_map(Speed, mode_check_freq_map_split2);
892
158k
  Speed = cpi->Speed;
893
158k
  switch (Mode) {
894
0
#if !CONFIG_REALTIME_ONLY
895
6.35k
    case 0: /* best quality mode */
896
6.35k
      sf->first_step = 0;
897
6.35k
      sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
898
6.35k
      break;
899
91.5k
    case 1:
900
91.5k
    case 3:
901
91.5k
      if (Speed > 0) {
902
        /* Disable coefficient optimization above speed 0 */
903
91.5k
        sf->optimize_coefficients = 0;
904
91.5k
        sf->use_fastquant_for_pick = 1;
905
91.5k
        sf->no_skip_block4x4_search = 0;
906
907
91.5k
        sf->first_step = 1;
908
91.5k
      }
909
910
91.5k
      if (Speed > 2) {
911
0
        sf->improved_quant = 0;
912
0
        sf->improved_dct = 0;
913
914
        /* Only do recode loop on key frames, golden frames and
915
         * alt ref frames
916
         */
917
0
        sf->recode_loop = 2;
918
0
      }
919
920
91.5k
      if (Speed > 3) {
921
0
        sf->auto_filter = 1;
922
0
        sf->recode_loop = 0; /* recode loop off */
923
0
        sf->RD = 0;          /* Turn rd off */
924
0
      }
925
926
91.5k
      if (Speed > 4) {
927
0
        sf->auto_filter = 0; /* Faster selection of loop filter */
928
0
      }
929
930
91.5k
      break;
931
0
#endif
932
60.3k
    case 2:
933
60.3k
      sf->optimize_coefficients = 0;
934
60.3k
      sf->recode_loop = 0;
935
60.3k
      sf->auto_filter = 1;
936
60.3k
      sf->iterative_sub_pixel = 1;
937
60.3k
      sf->search_method = NSTEP;
938
939
60.3k
      if (Speed > 0) {
940
60.3k
        sf->improved_quant = 0;
941
60.3k
        sf->improved_dct = 0;
942
943
60.3k
        sf->use_fastquant_for_pick = 1;
944
60.3k
        sf->no_skip_block4x4_search = 0;
945
60.3k
        sf->first_step = 1;
946
60.3k
      }
947
948
60.3k
      if (Speed > 2) sf->auto_filter = 0; /* Faster selection of loop filter */
949
950
60.3k
      if (Speed > 3) {
951
60.3k
        sf->RD = 0;
952
60.3k
        sf->auto_filter = 1;
953
60.3k
      }
954
955
60.3k
      if (Speed > 4) {
956
11
        sf->auto_filter = 0; /* Faster selection of loop filter */
957
11
        sf->search_method = HEX;
958
11
        sf->iterative_sub_pixel = 0;
959
11
      }
960
961
60.3k
      if (Speed > 6) {
962
2
        unsigned int sum = 0;
963
2
        unsigned int total_mbs = cm->MBs;
964
2
        int thresh;
965
2
        unsigned int total_skip;
966
967
2
        int min = 2000;
968
969
2
        if (cpi->oxcf.encode_breakout > 2000) min = cpi->oxcf.encode_breakout;
970
971
2
        min >>= 7;
972
2
        if (min >= MAX_ERROR_BINS) min = MAX_ERROR_BINS - 1;
973
974
32
        for (i = 0; i < min; ++i) {
975
30
          sum += cpi->mb.error_bins[i];
976
30
        }
977
978
2
        total_skip = sum;
979
2
        sum = 0;
980
981
        /* i starts from 2 to make sure thresh started from 2048 */
982
2.01k
        for (; i < 1024; ++i) {
983
2.01k
          sum += cpi->mb.error_bins[i];
984
985
2.01k
          if (10 * sum >=
986
2.01k
              (unsigned int)(cpi->Speed - 6) * (total_mbs - total_skip)) {
987
2
            break;
988
2
          }
989
2.01k
        }
990
991
2
        i--;
992
2
        thresh = (i << 7);
993
994
2
        if (thresh < 2000) thresh = 2000;
995
996
2
        if (ref_frames > 1) {
997
2
          sf->thresh_mult[THR_NEW1] = thresh;
998
2
          sf->thresh_mult[THR_NEAREST1] = thresh >> 1;
999
2
          sf->thresh_mult[THR_NEAR1] = thresh >> 1;
1000
2
        }
1001
1002
2
        if (ref_frames > 2) {
1003
2
          sf->thresh_mult[THR_NEW2] = thresh << 1;
1004
2
          sf->thresh_mult[THR_NEAREST2] = thresh;
1005
2
          sf->thresh_mult[THR_NEAR2] = thresh;
1006
2
        }
1007
1008
2
        if (ref_frames > 3) {
1009
0
          sf->thresh_mult[THR_NEW3] = thresh << 1;
1010
0
          sf->thresh_mult[THR_NEAREST3] = thresh;
1011
0
          sf->thresh_mult[THR_NEAR3] = thresh;
1012
0
        }
1013
1014
2
        sf->improved_mv_pred = 0;
1015
2
      }
1016
1017
60.3k
      if (Speed > 8) sf->quarter_pixel_search = 0;
1018
1019
60.3k
      if (cm->version == 0) {
1020
60.3k
        cm->filter_type = NORMAL_LOOPFILTER;
1021
1022
60.3k
        if (Speed >= 14) cm->filter_type = SIMPLE_LOOPFILTER;
1023
60.3k
      } else {
1024
0
        cm->filter_type = SIMPLE_LOOPFILTER;
1025
0
      }
1026
1027
      /* This has a big hit on quality. Last resort */
1028
60.3k
      if (Speed >= 15) sf->half_pixel_search = 0;
1029
1030
60.3k
      memset(cpi->mb.error_bins, 0, sizeof(cpi->mb.error_bins));
1031
1032
158k
  } /* switch */
1033
1034
  /* Slow quant, dct and trellis not worthwhile for first pass
1035
   * so make sure they are always turned off.
1036
   */
1037
158k
  if (cpi->pass == 1) {
1038
0
    sf->improved_quant = 0;
1039
0
    sf->optimize_coefficients = 0;
1040
0
    sf->improved_dct = 0;
1041
0
  }
1042
1043
158k
  if (cpi->sf.search_method == NSTEP) {
1044
158k
    vp8_init3smotion_compensation(&cpi->mb,
1045
158k
                                  cm->yv12_fb[cm->lst_fb_idx].y_stride);
1046
158k
  } else if (cpi->sf.search_method == DIAMOND) {
1047
0
    vp8_init_dsmotion_compensation(&cpi->mb,
1048
0
                                   cm->yv12_fb[cm->lst_fb_idx].y_stride);
1049
0
  }
1050
1051
158k
  if (cpi->sf.improved_dct) {
1052
97.8k
    cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
1053
97.8k
    cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
1054
97.8k
  } else {
1055
    /* No fast FDCT defined for any platform at this time. */
1056
60.3k
    cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
1057
60.3k
    cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
1058
60.3k
  }
1059
1060
158k
  cpi->mb.short_walsh4x4 = vp8_short_walsh4x4;
1061
1062
158k
  if (cpi->sf.improved_quant) {
1063
97.8k
    cpi->mb.quantize_b = vp8_regular_quantize_b;
1064
97.8k
  } else {
1065
60.3k
    cpi->mb.quantize_b = vp8_fast_quantize_b;
1066
60.3k
  }
1067
158k
  if (cpi->sf.improved_quant != last_improved_quant) vp8cx_init_quantizer(cpi);
1068
1069
158k
  if (cpi->sf.iterative_sub_pixel == 1) {
1070
158k
    cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
1071
158k
  } else if (cpi->sf.quarter_pixel_search) {
1072
11
    cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
1073
11
  } else if (cpi->sf.half_pixel_search) {
1074
0
    cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
1075
0
  } else {
1076
0
    cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1077
0
  }
1078
1079
158k
  if (cpi->sf.optimize_coefficients == 1 && cpi->pass != 1) {
1080
6.35k
    cpi->mb.optimize = 1;
1081
151k
  } else {
1082
151k
    cpi->mb.optimize = 0;
1083
151k
  }
1084
1085
158k
  if (cpi->common.full_pixel) {
1086
0
    cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
1087
0
  }
1088
1089
#ifdef SPEEDSTATS
1090
  frames_at_speed[cpi->Speed]++;
1091
#endif
1092
158k
}
1093
#undef GOOD
1094
#undef RT
1095
1096
6.35k
static void alloc_raw_frame_buffers(VP8_COMP *cpi) {
1097
6.35k
#if VP8_TEMPORAL_ALT_REF
1098
6.35k
  int width = (cpi->oxcf.Width + 15) & ~15;
1099
6.35k
  int height = (cpi->oxcf.Height + 15) & ~15;
1100
6.35k
#endif
1101
1102
6.35k
  cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
1103
6.35k
                                      cpi->oxcf.lag_in_frames);
1104
6.35k
  if (!cpi->lookahead) {
1105
0
    vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1106
0
                       "Failed to allocate lag buffers");
1107
0
  }
1108
1109
6.35k
#if VP8_TEMPORAL_ALT_REF
1110
1111
6.35k
  if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer, width, height,
1112
6.35k
                                  VP8BORDERINPIXELS)) {
1113
0
    vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1114
0
                       "Failed to allocate altref buffer");
1115
0
  }
1116
1117
6.35k
#endif
1118
6.35k
}
1119
1120
12.7k
static void dealloc_raw_frame_buffers(VP8_COMP *cpi) {
1121
12.7k
#if VP8_TEMPORAL_ALT_REF
1122
12.7k
  vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
1123
12.7k
#endif
1124
12.7k
  vp8_lookahead_destroy(cpi->lookahead);
1125
12.7k
#if CONFIG_TEMPORAL_DENOISING
1126
12.7k
  vp8_denoiser_free(&cpi->denoiser);
1127
12.7k
#endif
1128
12.7k
}
1129
1130
6.35k
static int vp8_alloc_partition_data(VP8_COMP *cpi) {
1131
6.35k
  vpx_free(cpi->mb.pip);
1132
1133
6.35k
  cpi->mb.pip =
1134
6.35k
      vpx_calloc((cpi->common.mb_cols + 1) * (cpi->common.mb_rows + 1),
1135
6.35k
                 sizeof(PARTITION_INFO));
1136
6.35k
  if (!cpi->mb.pip) return 1;
1137
1138
6.35k
  cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
1139
1140
6.35k
  return 0;
1141
6.35k
}
1142
1143
6.35k
void vp8_alloc_compressor_data(VP8_COMP *cpi) {
1144
6.35k
  VP8_COMMON *cm = &cpi->common;
1145
1146
6.35k
  int width = cm->Width;
1147
6.35k
  int height = cm->Height;
1148
1149
6.35k
  if (vp8_alloc_frame_buffers(cm, width, height)) {
1150
0
    vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1151
0
                       "Failed to allocate frame buffers");
1152
0
  }
1153
1154
6.35k
  if (vp8_alloc_partition_data(cpi)) {
1155
0
    vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1156
0
                       "Failed to allocate partition data");
1157
0
  }
1158
1159
6.35k
  if ((width & 0xf) != 0) width += 16 - (width & 0xf);
1160
1161
6.35k
  if ((height & 0xf) != 0) height += 16 - (height & 0xf);
1162
1163
6.35k
  if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame, width, height,
1164
6.35k
                                  VP8BORDERINPIXELS)) {
1165
0
    vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1166
0
                       "Failed to allocate last frame buffer");
1167
0
  }
1168
1169
6.35k
  if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source, width, height,
1170
6.35k
                                  VP8BORDERINPIXELS)) {
1171
0
    vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1172
0
                       "Failed to allocate scaled source buffer");
1173
0
  }
1174
1175
6.35k
  vpx_free(cpi->tok);
1176
1177
6.35k
  {
1178
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1179
    unsigned int tokens = 8 * 24 * 16; /* one MB for each thread */
1180
#else
1181
6.35k
    unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
1182
6.35k
#endif
1183
6.35k
    CHECK_MEM_ERROR(&cpi->common.error, cpi->tok,
1184
6.35k
                    vpx_calloc(tokens, sizeof(*cpi->tok)));
1185
6.35k
  }
1186
1187
  /* Data used for real time vc mode to see if gf needs refreshing */
1188
6.35k
  cpi->zeromv_count = 0;
1189
1190
  /* Structures used to monitor GF usage */
1191
6.35k
  vpx_free(cpi->gf_active_flags);
1192
6.35k
  CHECK_MEM_ERROR(
1193
6.35k
      &cpi->common.error, cpi->gf_active_flags,
1194
6.35k
      vpx_calloc(sizeof(*cpi->gf_active_flags), cm->mb_rows * cm->mb_cols));
1195
6.35k
  cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
1196
1197
6.35k
  vpx_free(cpi->mb_activity_map);
1198
6.35k
  CHECK_MEM_ERROR(
1199
6.35k
      &cpi->common.error, cpi->mb_activity_map,
1200
6.35k
      vpx_calloc(sizeof(*cpi->mb_activity_map), cm->mb_rows * cm->mb_cols));
1201
1202
  /* allocate memory for storing last frame's MVs for MV prediction. */
1203
6.35k
  vpx_free(cpi->lfmv);
1204
6.35k
  CHECK_MEM_ERROR(
1205
6.35k
      &cpi->common.error, cpi->lfmv,
1206
6.35k
      vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2), sizeof(*cpi->lfmv)));
1207
6.35k
  vpx_free(cpi->lf_ref_frame_sign_bias);
1208
6.35k
  CHECK_MEM_ERROR(&cpi->common.error, cpi->lf_ref_frame_sign_bias,
1209
6.35k
                  vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
1210
6.35k
                             sizeof(*cpi->lf_ref_frame_sign_bias)));
1211
6.35k
  vpx_free(cpi->lf_ref_frame);
1212
6.35k
  CHECK_MEM_ERROR(&cpi->common.error, cpi->lf_ref_frame,
1213
6.35k
                  vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
1214
6.35k
                             sizeof(*cpi->lf_ref_frame)));
1215
1216
  /* Create the encoder segmentation map and set all entries to 0 */
1217
6.35k
  vpx_free(cpi->segmentation_map);
1218
6.35k
  CHECK_MEM_ERROR(
1219
6.35k
      &cpi->common.error, cpi->segmentation_map,
1220
6.35k
      vpx_calloc(cm->mb_rows * cm->mb_cols, sizeof(*cpi->segmentation_map)));
1221
6.35k
  cpi->cyclic_refresh_mode_index = 0;
1222
6.35k
  vpx_free(cpi->active_map);
1223
6.35k
  CHECK_MEM_ERROR(
1224
6.35k
      &cpi->common.error, cpi->active_map,
1225
6.35k
      vpx_calloc(cm->mb_rows * cm->mb_cols, sizeof(*cpi->active_map)));
1226
6.35k
  memset(cpi->active_map, 1, (cm->mb_rows * cm->mb_cols));
1227
1228
6.35k
#if CONFIG_MULTITHREAD
1229
6.35k
  if (width < 640) {
1230
5.66k
    cpi->mt_sync_range = 1;
1231
5.66k
  } else if (width <= 1280) {
1232
288
    cpi->mt_sync_range = 4;
1233
406
  } else if (width <= 2560) {
1234
61
    cpi->mt_sync_range = 8;
1235
345
  } else {
1236
345
    cpi->mt_sync_range = 16;
1237
345
  }
1238
6.35k
#endif
1239
1240
6.35k
  vpx_free(cpi->tplist);
1241
6.35k
  CHECK_MEM_ERROR(&cpi->common.error, cpi->tplist,
1242
6.35k
                  vpx_malloc(sizeof(TOKENLIST) * cm->mb_rows));
1243
1244
6.35k
#if CONFIG_TEMPORAL_DENOISING
1245
6.35k
  if (cpi->oxcf.noise_sensitivity > 0) {
1246
0
    vp8_denoiser_free(&cpi->denoiser);
1247
0
    if (vp8_denoiser_allocate(&cpi->denoiser, width, height, cm->mb_rows,
1248
0
                              cm->mb_cols, cpi->oxcf.noise_sensitivity)) {
1249
0
      vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1250
0
                         "Failed to allocate denoiser");
1251
0
    }
1252
0
  }
1253
6.35k
#endif
1254
6.35k
}
1255
1256
/* Quant MOD */
1257
static const int q_trans[] = {
1258
  0,  1,  2,  3,  4,  5,  7,   8,   9,   10,  12,  13,  15,  17,  18,  19,
1259
  20, 21, 23, 24, 25, 26, 27,  28,  29,  30,  31,  33,  35,  37,  39,  41,
1260
  43, 45, 47, 49, 51, 53, 55,  57,  59,  61,  64,  67,  70,  73,  76,  79,
1261
  82, 85, 88, 91, 94, 97, 100, 103, 106, 109, 112, 115, 118, 121, 124, 127,
1262
};
1263
1264
117k
int vp8_reverse_trans(int x) {
1265
117k
  int i;
1266
1267
3.48M
  for (i = 0; i < 64; ++i) {
1268
3.48M
    if (q_trans[i] >= x) return i;
1269
3.48M
  }
1270
1271
0
  return 63;
1272
117k
}
1273
1274
290k
static double clamp_framerate(double framerate) {
1275
290k
  if (framerate < .1)
1276
27.9k
    return 30.0;
1277
263k
  else
1278
263k
    return framerate;
1279
290k
}
1280
1281
173k
void vp8_new_framerate(VP8_COMP *cpi, double framerate) {
1282
173k
  framerate = clamp_framerate(framerate);
1283
173k
  cpi->framerate = framerate;
1284
173k
  cpi->output_framerate = framerate;
1285
173k
  const double per_frame_bandwidth =
1286
173k
      round(cpi->oxcf.target_bandwidth / cpi->output_framerate);
1287
173k
  cpi->per_frame_bandwidth = (int)VPXMIN(per_frame_bandwidth, INT_MAX);
1288
173k
  cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
1289
173k
  const int64_t vbr_min_bits = (int64_t)cpi->av_per_frame_bandwidth *
1290
173k
                               cpi->oxcf.two_pass_vbrmin_section / 100;
1291
173k
  cpi->min_frame_bandwidth = (int)VPXMIN(vbr_min_bits, INT_MAX);
1292
1293
  /* Set Maximum gf/arf interval */
1294
173k
  cpi->max_gf_interval = ((int)(cpi->output_framerate / 2.0) + 2);
1295
1296
173k
  if (cpi->max_gf_interval < 12) cpi->max_gf_interval = 12;
1297
1298
  /* Extended interval for genuinely static scenes */
1299
173k
  cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1300
1301
  /* Special conditions when altr ref frame enabled in lagged compress mode */
1302
173k
  if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1303
0
    if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1) {
1304
0
      cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1305
0
    }
1306
1307
0
    if (cpi->twopass.static_scene_max_gf_interval >
1308
0
        cpi->oxcf.lag_in_frames - 1) {
1309
0
      cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1310
0
    }
1311
0
  }
1312
1313
173k
  if (cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval) {
1314
34.7k
    cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1315
34.7k
  }
1316
173k
}
1317
1318
6.35k
static void init_config(VP8_COMP *cpi, const VP8_CONFIG *oxcf) {
1319
6.35k
  VP8_COMMON *cm = &cpi->common;
1320
1321
6.35k
  cpi->oxcf = *oxcf;
1322
1323
6.35k
  cpi->auto_gold = 1;
1324
6.35k
  cpi->auto_adjust_gold_quantizer = 1;
1325
1326
6.35k
  cm->version = oxcf->Version;
1327
6.35k
  vp8_setup_version(cm);
1328
1329
  /* Frame rate is not available on the first frame, as it's derived from
1330
   * the observed timestamps. The actual value used here doesn't matter
1331
   * too much, as it will adapt quickly.
1332
   */
1333
6.35k
  if (oxcf->timebase.num > 0) {
1334
6.35k
    cpi->framerate =
1335
6.35k
        (double)(oxcf->timebase.den) / (double)(oxcf->timebase.num);
1336
6.35k
  } else {
1337
0
    cpi->framerate = 30;
1338
0
  }
1339
1340
  /* If the reciprocal of the timebase seems like a reasonable framerate,
1341
   * then use that as a guess, otherwise use 30.
1342
   */
1343
6.35k
  if (cpi->framerate > 180) cpi->framerate = 30;
1344
1345
6.35k
  cpi->ref_framerate = cpi->framerate;
1346
1347
6.35k
  cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;
1348
1349
6.35k
  cm->refresh_golden_frame = 0;
1350
6.35k
  cm->refresh_last_frame = 1;
1351
6.35k
  cm->refresh_entropy_probs = 1;
1352
1353
  /* change includes all joint functionality */
1354
6.35k
  vp8_change_config(cpi, oxcf);
1355
1356
  /* Initialize active best and worst q and average q values. */
1357
6.35k
  cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1358
6.35k
  cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1359
6.35k
  cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1360
1361
  /* Initialise the starting buffer levels */
1362
6.35k
  cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1363
6.35k
  cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1364
1365
6.35k
  cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1366
6.35k
  cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1367
6.35k
  cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1368
6.35k
  cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1369
1370
6.35k
  cpi->total_actual_bits = 0;
1371
6.35k
  cpi->total_target_vs_actual = 0;
1372
1373
  /* Temporal scalabilty */
1374
6.35k
  if (cpi->oxcf.number_of_layers > 1) {
1375
0
    unsigned int i;
1376
0
    double prev_layer_framerate = 0;
1377
1378
0
    for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
1379
0
      vp8_init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
1380
0
      prev_layer_framerate =
1381
0
          cpi->output_framerate / cpi->oxcf.rate_decimator[i];
1382
0
    }
1383
0
  }
1384
1385
6.35k
#if VP8_TEMPORAL_ALT_REF
1386
6.35k
  {
1387
6.35k
    int i;
1388
1389
6.35k
    cpi->fixed_divide[0] = 0;
1390
1391
3.25M
    for (i = 1; i < 512; ++i) cpi->fixed_divide[i] = 0x80000 / i;
1392
6.35k
  }
1393
6.35k
#endif
1394
6.35k
}
1395
1396
0
void vp8_update_layer_contexts(VP8_COMP *cpi) {
1397
0
  VP8_CONFIG *oxcf = &cpi->oxcf;
1398
1399
  /* Update snapshots of the layer contexts to reflect new parameters */
1400
0
  if (oxcf->number_of_layers > 1) {
1401
0
    unsigned int i;
1402
0
    double prev_layer_framerate = 0;
1403
1404
0
    assert(oxcf->number_of_layers <= VPX_TS_MAX_LAYERS);
1405
0
    for (i = 0; i < oxcf->number_of_layers && i < VPX_TS_MAX_LAYERS; ++i) {
1406
0
      LAYER_CONTEXT *lc = &cpi->layer_context[i];
1407
1408
0
      lc->framerate = cpi->ref_framerate / oxcf->rate_decimator[i];
1409
0
      if (oxcf->target_bitrate[i] > INT_MAX / 1000)
1410
0
        lc->target_bandwidth = INT_MAX;
1411
0
      else
1412
0
        lc->target_bandwidth = oxcf->target_bitrate[i] * 1000;
1413
1414
0
      lc->starting_buffer_level = rescale(
1415
0
          (int)oxcf->starting_buffer_level_in_ms, lc->target_bandwidth, 1000);
1416
1417
0
      if (oxcf->optimal_buffer_level == 0) {
1418
0
        lc->optimal_buffer_level = lc->target_bandwidth / 8;
1419
0
      } else {
1420
0
        lc->optimal_buffer_level = rescale(
1421
0
            (int)oxcf->optimal_buffer_level_in_ms, lc->target_bandwidth, 1000);
1422
0
      }
1423
1424
0
      if (oxcf->maximum_buffer_size == 0) {
1425
0
        lc->maximum_buffer_size = lc->target_bandwidth / 8;
1426
0
      } else {
1427
0
        lc->maximum_buffer_size = rescale((int)oxcf->maximum_buffer_size_in_ms,
1428
0
                                          lc->target_bandwidth, 1000);
1429
0
      }
1430
1431
      /* Work out the average size of a frame within this layer */
1432
0
      if (i > 0) {
1433
0
        lc->avg_frame_size_for_layer =
1434
0
            (int)round((oxcf->target_bitrate[i] - oxcf->target_bitrate[i - 1]) *
1435
0
                       1000 / (lc->framerate - prev_layer_framerate));
1436
0
      }
1437
1438
0
      prev_layer_framerate = lc->framerate;
1439
0
    }
1440
0
  }
1441
0
}
1442
1443
56.9k
void vp8_change_config(VP8_COMP *cpi, const VP8_CONFIG *oxcf) {
1444
56.9k
  VP8_COMMON *cm = &cpi->common;
1445
56.9k
  int last_w, last_h;
1446
56.9k
  unsigned int prev_number_of_layers;
1447
56.9k
  double raw_target_rate;
1448
1449
56.9k
  if (!cpi) return;
1450
1451
56.9k
  if (!oxcf) return;
1452
1453
56.9k
  if (cm->version != oxcf->Version) {
1454
0
    cm->version = oxcf->Version;
1455
0
    vp8_setup_version(cm);
1456
0
  }
1457
1458
56.9k
  last_w = cpi->oxcf.Width;
1459
56.9k
  last_h = cpi->oxcf.Height;
1460
56.9k
  prev_number_of_layers = cpi->oxcf.number_of_layers;
1461
1462
56.9k
  cpi->oxcf = *oxcf;
1463
1464
56.9k
  switch (cpi->oxcf.Mode) {
1465
2.69k
    case MODE_REALTIME:
1466
2.69k
      cpi->pass = 0;
1467
2.69k
      cpi->compressor_speed = 2;
1468
1469
2.69k
      if (cpi->oxcf.cpu_used < -16) {
1470
0
        cpi->oxcf.cpu_used = -16;
1471
0
      }
1472
1473
2.69k
      if (cpi->oxcf.cpu_used > 16) cpi->oxcf.cpu_used = 16;
1474
1475
2.69k
      break;
1476
1477
3.46k
    case MODE_GOODQUALITY:
1478
3.46k
      cpi->pass = 0;
1479
3.46k
      cpi->compressor_speed = 1;
1480
1481
3.46k
      if (cpi->oxcf.cpu_used < -5) {
1482
0
        cpi->oxcf.cpu_used = -5;
1483
0
      }
1484
1485
3.46k
      if (cpi->oxcf.cpu_used > 5) cpi->oxcf.cpu_used = 5;
1486
1487
3.46k
      break;
1488
1489
50.8k
    case MODE_BESTQUALITY:
1490
50.8k
      cpi->pass = 0;
1491
50.8k
      cpi->compressor_speed = 0;
1492
50.8k
      break;
1493
1494
0
    case MODE_FIRSTPASS:
1495
0
      cpi->pass = 1;
1496
0
      cpi->compressor_speed = 1;
1497
0
      break;
1498
0
    case MODE_SECONDPASS:
1499
0
      cpi->pass = 2;
1500
0
      cpi->compressor_speed = 1;
1501
1502
0
      if (cpi->oxcf.cpu_used < -5) {
1503
0
        cpi->oxcf.cpu_used = -5;
1504
0
      }
1505
1506
0
      if (cpi->oxcf.cpu_used > 5) cpi->oxcf.cpu_used = 5;
1507
1508
0
      break;
1509
0
    case MODE_SECONDPASS_BEST:
1510
0
      cpi->pass = 2;
1511
0
      cpi->compressor_speed = 0;
1512
0
      break;
1513
56.9k
  }
1514
1515
56.9k
  if (cpi->pass == 0) cpi->auto_worst_q = 1;
1516
1517
56.9k
  cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1518
56.9k
  cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1519
56.9k
  cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1520
1521
56.9k
  if (oxcf->fixed_q >= 0) {
1522
0
    if (oxcf->worst_allowed_q < 0) {
1523
0
      cpi->oxcf.fixed_q = q_trans[0];
1524
0
    } else {
1525
0
      cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
1526
0
    }
1527
1528
0
    if (oxcf->alt_q < 0) {
1529
0
      cpi->oxcf.alt_q = q_trans[0];
1530
0
    } else {
1531
0
      cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
1532
0
    }
1533
1534
0
    if (oxcf->key_q < 0) {
1535
0
      cpi->oxcf.key_q = q_trans[0];
1536
0
    } else {
1537
0
      cpi->oxcf.key_q = q_trans[oxcf->key_q];
1538
0
    }
1539
1540
0
    if (oxcf->gold_q < 0) {
1541
0
      cpi->oxcf.gold_q = q_trans[0];
1542
0
    } else {
1543
0
      cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
1544
0
    }
1545
0
  }
1546
1547
56.9k
  cpi->ext_refresh_frame_flags_pending = 0;
1548
1549
56.9k
  cpi->baseline_gf_interval =
1550
56.9k
      cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
1551
1552
  // GF behavior for 1 pass CBR, used when error_resilience is off.
1553
56.9k
  if (!cpi->oxcf.error_resilient_mode &&
1554
56.9k
      cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
1555
0
      cpi->oxcf.Mode == MODE_REALTIME)
1556
0
    cpi->baseline_gf_interval = cpi->gf_interval_onepass_cbr;
1557
1558
#if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1559
  cpi->oxcf.token_partitions = 3;
1560
#endif
1561
1562
56.9k
  if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3) {
1563
56.9k
    cm->multi_token_partition = (TOKEN_PARTITION)cpi->oxcf.token_partitions;
1564
56.9k
  }
1565
1566
56.9k
  setup_features(cpi);
1567
1568
56.9k
  if (!cpi->use_roi_static_threshold) {
1569
56.9k
    int i;
1570
284k
    for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
1571
227k
      cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1572
227k
    }
1573
56.9k
  }
1574
1575
  /* At the moment the first order values may not be > MAXQ */
1576
56.9k
  if (cpi->oxcf.fixed_q > MAXQ) cpi->oxcf.fixed_q = MAXQ;
1577
1578
  /* local file playback mode == really big buffer */
1579
56.9k
  if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1580
53.5k
    cpi->oxcf.starting_buffer_level = 60000;
1581
53.5k
    cpi->oxcf.optimal_buffer_level = 60000;
1582
53.5k
    cpi->oxcf.maximum_buffer_size = 240000;
1583
53.5k
    cpi->oxcf.starting_buffer_level_in_ms = 60000;
1584
53.5k
    cpi->oxcf.optimal_buffer_level_in_ms = 60000;
1585
53.5k
    cpi->oxcf.maximum_buffer_size_in_ms = 240000;
1586
53.5k
  }
1587
1588
56.9k
  raw_target_rate = ((int64_t)cpi->oxcf.Width * cpi->oxcf.Height * 8 * 3 *
1589
56.9k
                     cpi->framerate / 1000.0);
1590
56.9k
  if (cpi->oxcf.target_bandwidth > raw_target_rate)
1591
47.5k
    cpi->oxcf.target_bandwidth = (unsigned int)raw_target_rate;
1592
  /* Convert target bandwidth from Kbit/s to Bit/s */
1593
56.9k
  cpi->oxcf.target_bandwidth *= 1000;
1594
1595
56.9k
  cpi->oxcf.starting_buffer_level = rescale(
1596
56.9k
      (int)cpi->oxcf.starting_buffer_level, cpi->oxcf.target_bandwidth, 1000);
1597
1598
  /* Set or reset optimal and maximum buffer levels. */
1599
56.9k
  if (cpi->oxcf.optimal_buffer_level == 0) {
1600
0
    cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1601
56.9k
  } else {
1602
56.9k
    cpi->oxcf.optimal_buffer_level = rescale(
1603
56.9k
        (int)cpi->oxcf.optimal_buffer_level, cpi->oxcf.target_bandwidth, 1000);
1604
56.9k
  }
1605
1606
56.9k
  if (cpi->oxcf.maximum_buffer_size == 0) {
1607
0
    cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1608
56.9k
  } else {
1609
56.9k
    cpi->oxcf.maximum_buffer_size = rescale((int)cpi->oxcf.maximum_buffer_size,
1610
56.9k
                                            cpi->oxcf.target_bandwidth, 1000);
1611
56.9k
  }
1612
  // Under a configuration change, where maximum_buffer_size may change,
1613
  // keep buffer level clipped to the maximum allowed buffer size.
1614
56.9k
  if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
1615
0
    cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
1616
0
    cpi->buffer_level = cpi->bits_off_target;
1617
0
  }
1618
1619
  /* Set up frame rate and related parameters rate control values. */
1620
56.9k
  vp8_new_framerate(cpi, cpi->framerate);
1621
1622
  /* Set absolute upper and lower quality limits */
1623
56.9k
  cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1624
56.9k
  cpi->best_quality = cpi->oxcf.best_allowed_q;
1625
1626
  /* active values should only be modified if out of new range */
1627
56.9k
  if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q) {
1628
0
    cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1629
0
  }
1630
  /* less likely */
1631
56.9k
  else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q) {
1632
6.35k
    cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
1633
6.35k
  }
1634
56.9k
  if (cpi->active_best_quality < cpi->oxcf.best_allowed_q) {
1635
6.35k
    cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1636
6.35k
  }
1637
  /* less likely */
1638
50.6k
  else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q) {
1639
0
    cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
1640
0
  }
1641
1642
56.9k
  cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1643
1644
56.9k
  cpi->cq_target_quality = cpi->oxcf.cq_level;
1645
1646
  /* Only allow dropped frames in buffered mode */
1647
56.9k
  cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
1648
1649
56.9k
  cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1650
1651
  // Check if the number of temporal layers has changed, and if so reset the
1652
  // pattern counter and set/initialize the temporal layer context for the
1653
  // new layer configuration.
1654
56.9k
  if (cpi->oxcf.number_of_layers != prev_number_of_layers) {
1655
    // If the number of temporal layers are changed we must start at the
1656
    // base of the pattern cycle, so set the layer id to 0 and reset
1657
    // the temporal pattern counter.
1658
0
    if (cpi->temporal_layer_id > 0) {
1659
0
      cpi->temporal_layer_id = 0;
1660
0
    }
1661
0
    cpi->temporal_pattern_counter = 0;
1662
0
    vp8_reset_temporal_layer_change(cpi, oxcf, prev_number_of_layers);
1663
0
  }
1664
1665
56.9k
  if (!cpi->initial_width) {
1666
6.35k
    cpi->initial_width = cpi->oxcf.Width;
1667
6.35k
    cpi->initial_height = cpi->oxcf.Height;
1668
6.35k
  }
1669
1670
56.9k
  cm->Width = cpi->oxcf.Width;
1671
56.9k
  cm->Height = cpi->oxcf.Height;
1672
56.9k
  assert(cm->Width <= cpi->initial_width);
1673
56.9k
  assert(cm->Height <= cpi->initial_height);
1674
1675
  /* TODO(jkoleszar): if an internal spatial resampling is active,
1676
   * and we downsize the input image, maybe we should clear the
1677
   * internal scale immediately rather than waiting for it to
1678
   * correct.
1679
   */
1680
1681
  /* VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs) */
1682
56.9k
  if (cpi->oxcf.Sharpness > 7) cpi->oxcf.Sharpness = 7;
1683
1684
56.9k
  cm->sharpness_level = cpi->oxcf.Sharpness;
1685
1686
56.9k
  if (cm->horiz_scale != VP8E_NORMAL || cm->vert_scale != VP8E_NORMAL) {
1687
0
    int hr, hs, vr, vs;
1688
1689
0
    Scale2Ratio(cm->horiz_scale, &hr, &hs);
1690
0
    Scale2Ratio(cm->vert_scale, &vr, &vs);
1691
1692
    /* always go to the next whole number */
1693
0
    cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
1694
0
    cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
1695
0
  }
1696
1697
56.9k
  if (last_w != cpi->oxcf.Width || last_h != cpi->oxcf.Height) {
1698
0
    cpi->force_next_frame_intra = 1;
1699
0
  }
1700
1701
56.9k
  if (((cm->Width + 15) & ~15) != cm->yv12_fb[cm->lst_fb_idx].y_width ||
1702
50.6k
      ((cm->Height + 15) & ~15) != cm->yv12_fb[cm->lst_fb_idx].y_height ||
1703
50.6k
      cm->yv12_fb[cm->lst_fb_idx].y_width == 0) {
1704
6.35k
    dealloc_raw_frame_buffers(cpi);
1705
6.35k
    alloc_raw_frame_buffers(cpi);
1706
6.35k
    vp8_alloc_compressor_data(cpi);
1707
6.35k
  }
1708
1709
56.9k
  if (cpi->oxcf.fixed_q >= 0) {
1710
0
    cpi->last_q[0] = cpi->oxcf.fixed_q;
1711
0
    cpi->last_q[1] = cpi->oxcf.fixed_q;
1712
0
  }
1713
1714
56.9k
  cpi->Speed = cpi->oxcf.cpu_used;
1715
1716
  /* force to allowlag to 0 if lag_in_frames is 0; */
1717
56.9k
  if (cpi->oxcf.lag_in_frames == 0) {
1718
56.9k
    cpi->oxcf.allow_lag = 0;
1719
56.9k
  }
1720
  /* Limit on lag buffers as these are not currently dynamically allocated */
1721
0
  else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1722
0
    cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1723
0
  }
1724
1725
  /* YX Temp */
1726
56.9k
  cpi->alt_ref_source = NULL;
1727
56.9k
  cpi->is_src_frame_alt_ref = 0;
1728
1729
56.9k
#if CONFIG_TEMPORAL_DENOISING
1730
56.9k
  if (cpi->oxcf.noise_sensitivity) {
1731
0
    if (!cpi->denoiser.yv12_mc_running_avg.buffer_alloc) {
1732
0
      int width = (cpi->oxcf.Width + 15) & ~15;
1733
0
      int height = (cpi->oxcf.Height + 15) & ~15;
1734
0
      if (vp8_denoiser_allocate(&cpi->denoiser, width, height, cm->mb_rows,
1735
0
                                cm->mb_cols, cpi->oxcf.noise_sensitivity)) {
1736
0
        vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1737
0
                           "Failed to allocate denoiser");
1738
0
      }
1739
0
    }
1740
0
  }
1741
56.9k
#endif
1742
1743
#if 0
1744
    /* Experimental RD Code */
1745
    cpi->frame_distortion = 0;
1746
    cpi->last_frame_distortion = 0;
1747
#endif
1748
56.9k
}
1749
1750
#ifndef M_LOG2_E
1751
1.62M
#define M_LOG2_E 0.693147180559945309417
1752
#endif
1753
1.62M
#define log2f(x) (log(x) / (float)M_LOG2_E)
1754
1755
6.35k
static void cal_mvsadcosts(int *mvsadcost[2]) {
1756
6.35k
  int i = 1;
1757
1758
6.35k
  mvsadcost[0][0] = 300;
1759
6.35k
  mvsadcost[1][0] = 300;
1760
1761
1.62M
  do {
1762
1.62M
    double z = 256 * (2 * (log2f(8 * i) + .6));
1763
1.62M
    mvsadcost[0][i] = (int)z;
1764
1.62M
    mvsadcost[1][i] = (int)z;
1765
1.62M
    mvsadcost[0][-i] = (int)z;
1766
1.62M
    mvsadcost[1][-i] = (int)z;
1767
1.62M
  } while (++i <= mvfp_max);
1768
6.35k
}
1769
1770
6.35k
struct VP8_COMP *vp8_create_compressor(const VP8_CONFIG *oxcf) {
1771
6.35k
  int i;
1772
1773
6.35k
  VP8_COMP *cpi;
1774
6.35k
  VP8_COMMON *cm;
1775
1776
6.35k
  cpi = vpx_memalign(32, sizeof(VP8_COMP));
1777
  /* Check that the CPI instance is valid */
1778
6.35k
  if (!cpi) return 0;
1779
1780
6.35k
  cm = &cpi->common;
1781
1782
6.35k
  memset(cpi, 0, sizeof(VP8_COMP));
1783
1784
6.35k
  if (setjmp(cm->error.jmp)) {
1785
0
    cpi->common.error.setjmp = 0;
1786
0
    vp8_remove_compressor(&cpi);
1787
0
    return 0;
1788
0
  }
1789
1790
6.35k
  cpi->common.error.setjmp = 1;
1791
1792
6.35k
  CHECK_MEM_ERROR(
1793
6.35k
      &cpi->common.error, cpi->mb.ss,
1794
6.35k
      vpx_calloc(sizeof(search_site), (MAX_MVSEARCH_STEPS * 8) + 1));
1795
1796
6.35k
  vp8_create_common(&cpi->common);
1797
1798
6.35k
  init_config(cpi, oxcf);
1799
1800
6.35k
  memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob,
1801
6.35k
         sizeof(vp8cx_base_skip_false_prob));
1802
6.35k
  cpi->common.current_video_frame = 0;
1803
6.35k
  cpi->temporal_pattern_counter = 0;
1804
6.35k
  cpi->temporal_layer_id = -1;
1805
6.35k
  cpi->kf_overspend_bits = 0;
1806
6.35k
  cpi->kf_bitrate_adjustment = 0;
1807
6.35k
  cpi->frames_till_gf_update_due = 0;
1808
6.35k
  cpi->gf_overspend_bits = 0;
1809
6.35k
  cpi->non_gf_bitrate_adjustment = 0;
1810
6.35k
  cpi->prob_last_coded = 128;
1811
6.35k
  cpi->prob_gf_coded = 128;
1812
6.35k
  cpi->prob_intra_coded = 63;
1813
1814
  /* Prime the recent reference frame usage counters.
1815
   * Hereafter they will be maintained as a sort of moving average
1816
   */
1817
6.35k
  cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
1818
6.35k
  cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
1819
6.35k
  cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
1820
6.35k
  cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
1821
1822
  /* Set reference frame sign bias for ALTREF frame to 1 (for now) */
1823
6.35k
  cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
1824
1825
6.35k
  cpi->twopass.gf_decay_rate = 0;
1826
6.35k
  cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1827
1828
6.35k
  cpi->gold_is_last = 0;
1829
6.35k
  cpi->alt_is_last = 0;
1830
6.35k
  cpi->gold_is_alt = 0;
1831
1832
6.35k
  cpi->active_map_enabled = 0;
1833
1834
6.35k
  cpi->use_roi_static_threshold = 0;
1835
1836
#if 0
1837
    /* Experimental code for lagged and one pass */
1838
    /* Initialise one_pass GF frames stats */
1839
    /* Update stats used for GF selection */
1840
    if (cpi->pass == 0)
1841
    {
1842
        cpi->one_pass_frame_index = 0;
1843
1844
        for (i = 0; i < MAX_LAG_BUFFERS; ++i)
1845
        {
1846
            cpi->one_pass_frame_stats[i].frames_so_far = 0;
1847
            cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
1848
            cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
1849
            cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
1850
            cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
1851
            cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
1852
            cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
1853
            cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
1854
            cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
1855
        }
1856
    }
1857
#endif
1858
1859
6.35k
  cpi->mse_source_denoised = 0;
1860
1861
  /* Should we use the cyclic refresh method.
1862
   * Currently there is no external control for this.
1863
   * Enable it for error_resilient_mode, or for 1 pass CBR mode.
1864
   */
1865
6.35k
  cpi->cyclic_refresh_mode_enabled =
1866
6.35k
      (cpi->oxcf.error_resilient_mode ||
1867
6.35k
       (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
1868
0
        cpi->oxcf.Mode <= 2));
1869
6.35k
  cpi->cyclic_refresh_mode_max_mbs_perframe =
1870
6.35k
      (cpi->common.mb_rows * cpi->common.mb_cols) / 7;
1871
6.35k
  if (cpi->oxcf.number_of_layers == 1) {
1872
6.35k
    cpi->cyclic_refresh_mode_max_mbs_perframe =
1873
6.35k
        (cpi->common.mb_rows * cpi->common.mb_cols) / 20;
1874
6.35k
  } else if (cpi->oxcf.number_of_layers == 2) {
1875
0
    cpi->cyclic_refresh_mode_max_mbs_perframe =
1876
0
        (cpi->common.mb_rows * cpi->common.mb_cols) / 10;
1877
0
  }
1878
6.35k
  cpi->cyclic_refresh_mode_index = 0;
1879
6.35k
  cpi->cyclic_refresh_q = 32;
1880
1881
  // GF behavior for 1 pass CBR, used when error_resilience is off.
1882
6.35k
  cpi->gf_update_onepass_cbr = 0;
1883
6.35k
  cpi->gf_noboost_onepass_cbr = 0;
1884
6.35k
  if (!cpi->oxcf.error_resilient_mode &&
1885
6.35k
      cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER && cpi->oxcf.Mode <= 2) {
1886
0
    cpi->gf_update_onepass_cbr = 1;
1887
0
    cpi->gf_noboost_onepass_cbr = 1;
1888
0
    cpi->gf_interval_onepass_cbr =
1889
0
        cpi->cyclic_refresh_mode_max_mbs_perframe > 0
1890
0
            ? (2 * (cpi->common.mb_rows * cpi->common.mb_cols) /
1891
0
               cpi->cyclic_refresh_mode_max_mbs_perframe)
1892
0
            : 10;
1893
0
    cpi->gf_interval_onepass_cbr = clamp(cpi->gf_interval_onepass_cbr, 6, 40);
1894
0
    cpi->baseline_gf_interval = cpi->gf_interval_onepass_cbr;
1895
0
  }
1896
1897
6.35k
  if (cpi->cyclic_refresh_mode_enabled) {
1898
0
    CHECK_MEM_ERROR(&cpi->common.error, cpi->cyclic_refresh_map,
1899
0
                    vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1900
6.35k
  } else {
1901
6.35k
    cpi->cyclic_refresh_map = (signed char *)NULL;
1902
6.35k
  }
1903
1904
6.35k
  CHECK_MEM_ERROR(
1905
6.35k
      &cpi->common.error, cpi->skin_map,
1906
6.35k
      vpx_calloc(cm->mb_rows * cm->mb_cols, sizeof(cpi->skin_map[0])));
1907
1908
6.35k
  CHECK_MEM_ERROR(&cpi->common.error, cpi->consec_zero_last,
1909
6.35k
                  vpx_calloc(cm->mb_rows * cm->mb_cols, 1));
1910
6.35k
  CHECK_MEM_ERROR(&cpi->common.error, cpi->consec_zero_last_mvbias,
1911
6.35k
                  vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
1912
1913
  /*Initialize the feed-forward activity masking.*/
1914
6.35k
  cpi->activity_avg = 90 << 12;
1915
1916
  /* Give a sensible default for the first frame. */
1917
6.35k
  cpi->frames_since_key = 8;
1918
6.35k
  cpi->key_frame_frequency = cpi->oxcf.key_freq;
1919
6.35k
  cpi->this_key_frame_forced = 0;
1920
6.35k
  cpi->next_key_frame_forced = 0;
1921
1922
6.35k
  cpi->source_alt_ref_pending = 0;
1923
6.35k
  cpi->source_alt_ref_active = 0;
1924
6.35k
  cpi->common.refresh_alt_ref_frame = 0;
1925
1926
6.35k
  cpi->force_maxqp = 0;
1927
6.35k
  cpi->frames_since_last_drop_overshoot = 0;
1928
6.35k
  cpi->rt_always_update_correction_factor = 0;
1929
6.35k
  cpi->rt_drop_recode_on_overshoot = 1;
1930
1931
6.35k
  cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1932
#if CONFIG_INTERNAL_STATS
1933
  cpi->b_calculate_ssimg = 0;
1934
1935
  cpi->count = 0;
1936
  cpi->bytes = 0;
1937
1938
  if (cpi->b_calculate_psnr) {
1939
    cpi->total_sq_error = 0.0;
1940
    cpi->total_sq_error2 = 0.0;
1941
    cpi->total_y = 0.0;
1942
    cpi->total_u = 0.0;
1943
    cpi->total_v = 0.0;
1944
    cpi->total = 0.0;
1945
    cpi->totalp_y = 0.0;
1946
    cpi->totalp_u = 0.0;
1947
    cpi->totalp_v = 0.0;
1948
    cpi->totalp = 0.0;
1949
    cpi->tot_recode_hits = 0;
1950
    cpi->summed_quality = 0;
1951
    cpi->summed_weights = 0;
1952
  }
1953
1954
#endif
1955
1956
6.35k
  cpi->first_time_stamp_ever = 0x7FFFFFFF;
1957
1958
6.35k
  cpi->frames_till_gf_update_due = 0;
1959
6.35k
  cpi->key_frame_count = 1;
1960
1961
6.35k
  cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1962
6.35k
  cpi->ni_tot_qi = 0;
1963
6.35k
  cpi->ni_frames = 0;
1964
6.35k
  cpi->total_byte_count = 0;
1965
1966
6.35k
  cpi->drop_frame = 0;
1967
1968
6.35k
  cpi->rate_correction_factor = 1.0;
1969
6.35k
  cpi->key_frame_rate_correction_factor = 1.0;
1970
6.35k
  cpi->gf_rate_correction_factor = 1.0;
1971
6.35k
  cpi->twopass.est_max_qcorrection_factor = 1.0;
1972
1973
38.1k
  for (i = 0; i < KEY_FRAME_CONTEXT; ++i) {
1974
31.7k
    cpi->prior_key_frame_distance[i] = (int)cpi->output_framerate;
1975
31.7k
  }
1976
1977
#ifdef OUTPUT_YUV_SRC
1978
  yuv_file = fopen("bd.yuv", "ab");
1979
#endif
1980
#ifdef OUTPUT_YUV_DENOISED
1981
  yuv_denoised_file = fopen("denoised.yuv", "ab");
1982
#endif
1983
#ifdef OUTPUT_YUV_SKINMAP
1984
  yuv_skinmap_file = fopen("skinmap.yuv", "wb");
1985
#endif
1986
1987
#if 0
1988
    framepsnr = fopen("framepsnr.stt", "a");
1989
    kf_list = fopen("kf_list.stt", "w");
1990
#endif
1991
1992
6.35k
  cpi->output_pkt_list = oxcf->output_pkt_list;
1993
1994
6.35k
#if !CONFIG_REALTIME_ONLY
1995
1996
6.35k
  if (cpi->pass == 1) {
1997
0
    vp8_init_first_pass(cpi);
1998
6.35k
  } else if (cpi->pass == 2) {
1999
0
    size_t packet_sz = sizeof(FIRSTPASS_STATS);
2000
0
    int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
2001
2002
0
    cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
2003
0
    cpi->twopass.stats_in = cpi->twopass.stats_in_start;
2004
0
    cpi->twopass.stats_in_end =
2005
0
        (void *)((char *)cpi->twopass.stats_in + (packets - 1) * packet_sz);
2006
0
    vp8_init_second_pass(cpi);
2007
0
  }
2008
2009
6.35k
#endif
2010
2011
6.35k
  if (cpi->compressor_speed == 2) {
2012
0
    cpi->avg_encode_time = 0;
2013
0
    cpi->avg_pick_mode_time = 0;
2014
0
  }
2015
2016
6.35k
  vp8_set_speed_features(cpi);
2017
2018
  /* Set starting values of RD threshold multipliers (128 = *1) */
2019
133k
  for (i = 0; i < MAX_MODES; ++i) {
2020
127k
    cpi->mb.rd_thresh_mult[i] = 128;
2021
127k
  }
2022
2023
6.35k
#if CONFIG_MULTITHREAD
2024
6.35k
  if (vp8cx_create_encoder_threads(cpi)) {
2025
0
    cpi->common.error.setjmp = 0;
2026
0
    vp8_remove_compressor(&cpi);
2027
0
    return 0;
2028
0
  }
2029
6.35k
#endif
2030
2031
6.35k
  cpi->fn_ptr[BLOCK_16X16].sdf = vpx_sad16x16;
2032
6.35k
  cpi->fn_ptr[BLOCK_16X16].vf = vpx_variance16x16;
2033
6.35k
  cpi->fn_ptr[BLOCK_16X16].svf = vpx_sub_pixel_variance16x16;
2034
6.35k
  cpi->fn_ptr[BLOCK_16X16].sdx4df = vpx_sad16x16x4d;
2035
2036
6.35k
  cpi->fn_ptr[BLOCK_16X8].sdf = vpx_sad16x8;
2037
6.35k
  cpi->fn_ptr[BLOCK_16X8].vf = vpx_variance16x8;
2038
6.35k
  cpi->fn_ptr[BLOCK_16X8].svf = vpx_sub_pixel_variance16x8;
2039
6.35k
  cpi->fn_ptr[BLOCK_16X8].sdx4df = vpx_sad16x8x4d;
2040
2041
6.35k
  cpi->fn_ptr[BLOCK_8X16].sdf = vpx_sad8x16;
2042
6.35k
  cpi->fn_ptr[BLOCK_8X16].vf = vpx_variance8x16;
2043
6.35k
  cpi->fn_ptr[BLOCK_8X16].svf = vpx_sub_pixel_variance8x16;
2044
6.35k
  cpi->fn_ptr[BLOCK_8X16].sdx4df = vpx_sad8x16x4d;
2045
2046
6.35k
  cpi->fn_ptr[BLOCK_8X8].sdf = vpx_sad8x8;
2047
6.35k
  cpi->fn_ptr[BLOCK_8X8].vf = vpx_variance8x8;
2048
6.35k
  cpi->fn_ptr[BLOCK_8X8].svf = vpx_sub_pixel_variance8x8;
2049
6.35k
  cpi->fn_ptr[BLOCK_8X8].sdx4df = vpx_sad8x8x4d;
2050
2051
6.35k
  cpi->fn_ptr[BLOCK_4X4].sdf = vpx_sad4x4;
2052
6.35k
  cpi->fn_ptr[BLOCK_4X4].vf = vpx_variance4x4;
2053
6.35k
  cpi->fn_ptr[BLOCK_4X4].svf = vpx_sub_pixel_variance4x4;
2054
6.35k
  cpi->fn_ptr[BLOCK_4X4].sdx4df = vpx_sad4x4x4d;
2055
2056
6.35k
#if VPX_ARCH_X86 || VPX_ARCH_X86_64
2057
6.35k
  cpi->fn_ptr[BLOCK_16X16].copymem = vp8_copy32xn;
2058
6.35k
  cpi->fn_ptr[BLOCK_16X8].copymem = vp8_copy32xn;
2059
6.35k
  cpi->fn_ptr[BLOCK_8X16].copymem = vp8_copy32xn;
2060
6.35k
  cpi->fn_ptr[BLOCK_8X8].copymem = vp8_copy32xn;
2061
6.35k
  cpi->fn_ptr[BLOCK_4X4].copymem = vp8_copy32xn;
2062
6.35k
#endif
2063
2064
6.35k
  cpi->diamond_search_sad = vp8_diamond_search_sad;
2065
6.35k
  cpi->refining_search_sad = vp8_refining_search_sad;
2066
2067
  /* make sure frame 1 is okay */
2068
6.35k
  cpi->mb.error_bins[0] = cpi->common.MBs;
2069
2070
  /* vp8cx_init_quantizer() is first called here. Add check in
2071
   * vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only
2072
   * called later when needed. This will avoid unnecessary calls of
2073
   * vp8cx_init_quantizer() for every frame.
2074
   */
2075
6.35k
  vp8cx_init_quantizer(cpi);
2076
2077
6.35k
  vp8_loop_filter_init(cm);
2078
2079
#if CONFIG_MULTI_RES_ENCODING
2080
2081
  /* Calculate # of MBs in a row in lower-resolution level image. */
2082
  if (cpi->oxcf.mr_encoder_id > 0) vp8_cal_low_res_mb_cols(cpi);
2083
2084
#endif
2085
2086
  /* setup RD costs to MACROBLOCK struct */
2087
2088
6.35k
  cpi->mb.mvcost[0] = &cpi->rd_costs.mvcosts[0][mv_max + 1];
2089
6.35k
  cpi->mb.mvcost[1] = &cpi->rd_costs.mvcosts[1][mv_max + 1];
2090
6.35k
  cpi->mb.mvsadcost[0] = &cpi->rd_costs.mvsadcosts[0][mvfp_max + 1];
2091
6.35k
  cpi->mb.mvsadcost[1] = &cpi->rd_costs.mvsadcosts[1][mvfp_max + 1];
2092
2093
6.35k
  cal_mvsadcosts(cpi->mb.mvsadcost);
2094
2095
6.35k
  cpi->mb.mbmode_cost = cpi->rd_costs.mbmode_cost;
2096
6.35k
  cpi->mb.intra_uv_mode_cost = cpi->rd_costs.intra_uv_mode_cost;
2097
6.35k
  cpi->mb.bmode_costs = cpi->rd_costs.bmode_costs;
2098
6.35k
  cpi->mb.inter_bmode_costs = cpi->rd_costs.inter_bmode_costs;
2099
6.35k
  cpi->mb.token_costs = cpi->rd_costs.token_costs;
2100
2101
  /* setup block ptrs & offsets */
2102
6.35k
  vp8_setup_block_ptrs(&cpi->mb);
2103
6.35k
  vp8_setup_block_dptrs(&cpi->mb.e_mbd);
2104
2105
6.35k
  cpi->common.error.setjmp = 0;
2106
2107
6.35k
  return cpi;
2108
6.35k
}
2109
2110
6.41k
void vp8_remove_compressor(VP8_COMP **comp) {
2111
6.41k
  VP8_COMP *cpi = *comp;
2112
2113
6.41k
  if (!cpi) return;
2114
2115
6.35k
  if (cpi && (cpi->common.current_video_frame > 0)) {
2116
6.06k
#if !CONFIG_REALTIME_ONLY
2117
2118
6.06k
    if (cpi->pass == 2) {
2119
0
      vp8_end_second_pass(cpi);
2120
0
    }
2121
2122
6.06k
#endif
2123
2124
#if CONFIG_INTERNAL_STATS
2125
2126
    if (cpi->pass != 1) {
2127
      FILE *f = fopen("opsnr.stt", "a");
2128
      double time_encoded =
2129
          (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
2130
          10000000.000;
2131
2132
      if (cpi->b_calculate_psnr) {
2133
        if (cpi->oxcf.number_of_layers > 1) {
2134
          int i;
2135
2136
          fprintf(f,
2137
                  "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2138
                  "GLPsnrP\tVPXSSIM\n");
2139
          for (i = 0; i < (int)cpi->oxcf.number_of_layers; ++i) {
2140
            double dr =
2141
                (double)cpi->bytes_in_layer[i] * 8.0 / 1000.0 / time_encoded;
2142
            double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
2143
                             cpi->common.Width * cpi->common.Height;
2144
            double total_psnr =
2145
                vpx_sse_to_psnr(samples, 255.0, cpi->total_error2[i]);
2146
            double total_psnr2 =
2147
                vpx_sse_to_psnr(samples, 255.0, cpi->total_error2_p[i]);
2148
            double total_ssim =
2149
                100 * pow(cpi->sum_ssim[i] / cpi->sum_weights[i], 8.0);
2150
2151
            fprintf(f,
2152
                    "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2153
                    "%7.3f\t%7.3f\n",
2154
                    i, dr, cpi->sum_psnr[i] / cpi->frames_in_layer[i],
2155
                    total_psnr, cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
2156
                    total_psnr2, total_ssim);
2157
          }
2158
        } else {
2159
          double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
2160
          double samples =
2161
              3.0 / 2 * cpi->count * cpi->common.Width * cpi->common.Height;
2162
          double total_psnr =
2163
              vpx_sse_to_psnr(samples, 255.0, cpi->total_sq_error);
2164
          double total_psnr2 =
2165
              vpx_sse_to_psnr(samples, 255.0, cpi->total_sq_error2);
2166
          double total_ssim =
2167
              100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
2168
2169
          fprintf(f,
2170
                  "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
2171
                  "GLPsnrP\tVPXSSIM\n");
2172
          fprintf(f,
2173
                  "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2174
                  "%7.3f\n",
2175
                  dr, cpi->total / cpi->count, total_psnr,
2176
                  cpi->totalp / cpi->count, total_psnr2, total_ssim);
2177
        }
2178
      }
2179
      fclose(f);
2180
#if 0
2181
            f = fopen("qskip.stt", "a");
2182
            fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
2183
            fclose(f);
2184
#endif
2185
    }
2186
2187
#endif
2188
2189
#ifdef SPEEDSTATS
2190
2191
    if (cpi->compressor_speed == 2) {
2192
      int i;
2193
      FILE *f = fopen("cxspeed.stt", "a");
2194
      cnt_pm /= cpi->common.MBs;
2195
2196
      for (i = 0; i < 16; ++i) fprintf(f, "%5d", frames_at_speed[i]);
2197
2198
      fprintf(f, "\n");
2199
      fclose(f);
2200
    }
2201
2202
#endif
2203
2204
#ifdef MODE_STATS
2205
    {
2206
      extern int count_mb_seg[4];
2207
      FILE *f = fopen("modes.stt", "a");
2208
      double dr = cpi->framerate * (double)bytes * (double)8 / (double)count /
2209
                  (double)1000;
2210
      fprintf(f, "intra_mode in Intra Frames:\n");
2211
      fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1],
2212
              y_modes[2], y_modes[3], y_modes[4]);
2213
      fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1],
2214
              uv_modes[2], uv_modes[3]);
2215
      fprintf(f, "B: ");
2216
      {
2217
        int i;
2218
2219
        for (i = 0; i < 10; ++i) fprintf(f, "%8d, ", b_modes[i]);
2220
2221
        fprintf(f, "\n");
2222
      }
2223
2224
      fprintf(f, "Modes in Inter Frames:\n");
2225
      fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
2226
              inter_y_modes[0], inter_y_modes[1], inter_y_modes[2],
2227
              inter_y_modes[3], inter_y_modes[4], inter_y_modes[5],
2228
              inter_y_modes[6], inter_y_modes[7], inter_y_modes[8],
2229
              inter_y_modes[9]);
2230
      fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0],
2231
              inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
2232
      fprintf(f, "B: ");
2233
      {
2234
        int i;
2235
2236
        for (i = 0; i < 15; ++i) fprintf(f, "%8d, ", inter_b_modes[i]);
2237
2238
        fprintf(f, "\n");
2239
      }
2240
      fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1],
2241
              count_mb_seg[2], count_mb_seg[3]);
2242
      fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4],
2243
              inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4],
2244
              inter_b_modes[NEW4X4]);
2245
2246
      fclose(f);
2247
    }
2248
#endif
2249
2250
#if defined(SECTIONBITS_OUTPUT)
2251
2252
    if (0) {
2253
      int i;
2254
      FILE *f = fopen("tokenbits.stt", "a");
2255
2256
      for (i = 0; i < 28; ++i) fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
2257
2258
      fprintf(f, "\n");
2259
      fclose(f);
2260
    }
2261
2262
#endif
2263
2264
#if 0
2265
        {
2266
            printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2267
            printf("\n_frames receive_data encod_mb_row compress_frame  Total\n");
2268
            printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame, cpi->time_receive_data / 1000, cpi->time_encode_mb_row / 1000, cpi->time_compress_data / 1000, (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2269
        }
2270
#endif
2271
6.06k
  }
2272
2273
6.35k
#if CONFIG_MULTITHREAD
2274
6.35k
  vp8cx_remove_encoder_threads(cpi);
2275
6.35k
#endif
2276
2277
6.35k
#if CONFIG_TEMPORAL_DENOISING
2278
6.35k
  vp8_denoiser_free(&cpi->denoiser);
2279
6.35k
#endif
2280
6.35k
  dealloc_compressor_data(cpi);
2281
6.35k
  vpx_free(cpi->mb.ss);
2282
6.35k
  vpx_free(cpi->tok);
2283
6.35k
  vpx_free(cpi->skin_map);
2284
6.35k
  vpx_free(cpi->cyclic_refresh_map);
2285
6.35k
  vpx_free(cpi->consec_zero_last);
2286
6.35k
  vpx_free(cpi->consec_zero_last_mvbias);
2287
2288
6.35k
  vp8_remove_common(&cpi->common);
2289
6.35k
  vpx_free(cpi);
2290
6.35k
  *comp = 0;
2291
2292
#ifdef OUTPUT_YUV_SRC
2293
  fclose(yuv_file);
2294
#endif
2295
#ifdef OUTPUT_YUV_DENOISED
2296
  fclose(yuv_denoised_file);
2297
#endif
2298
#ifdef OUTPUT_YUV_SKINMAP
2299
  fclose(yuv_skinmap_file);
2300
#endif
2301
2302
#if 0
2303
2304
    if (keyfile)
2305
        fclose(keyfile);
2306
2307
    if (framepsnr)
2308
        fclose(framepsnr);
2309
2310
    if (kf_list)
2311
        fclose(kf_list);
2312
2313
#endif
2314
6.35k
}
2315
2316
static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
2317
                                 unsigned char *recon, int recon_stride,
2318
0
                                 unsigned int cols, unsigned int rows) {
2319
0
  unsigned int row, col;
2320
0
  uint64_t total_sse = 0;
2321
0
  int diff;
2322
2323
0
  for (row = 0; row + 16 <= rows; row += 16) {
2324
0
    for (col = 0; col + 16 <= cols; col += 16) {
2325
0
      unsigned int sse;
2326
2327
0
      vpx_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
2328
0
      total_sse += sse;
2329
0
    }
2330
2331
    /* Handle odd-sized width */
2332
0
    if (col < cols) {
2333
0
      unsigned int border_row, border_col;
2334
0
      unsigned char *border_orig = orig;
2335
0
      unsigned char *border_recon = recon;
2336
2337
0
      for (border_row = 0; border_row < 16; ++border_row) {
2338
0
        for (border_col = col; border_col < cols; ++border_col) {
2339
0
          diff = border_orig[border_col] - border_recon[border_col];
2340
0
          total_sse += diff * diff;
2341
0
        }
2342
2343
0
        border_orig += orig_stride;
2344
0
        border_recon += recon_stride;
2345
0
      }
2346
0
    }
2347
2348
0
    orig += orig_stride * 16;
2349
0
    recon += recon_stride * 16;
2350
0
  }
2351
2352
  /* Handle odd-sized height */
2353
0
  for (; row < rows; ++row) {
2354
0
    for (col = 0; col < cols; ++col) {
2355
0
      diff = orig[col] - recon[col];
2356
0
      total_sse += diff * diff;
2357
0
    }
2358
2359
0
    orig += orig_stride;
2360
0
    recon += recon_stride;
2361
0
  }
2362
2363
0
  vpx_clear_system_state();
2364
0
  return total_sse;
2365
0
}
2366
2367
0
static void generate_psnr_packet(VP8_COMP *cpi) {
2368
0
  YV12_BUFFER_CONFIG *orig = cpi->Source;
2369
0
  YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2370
0
  struct vpx_codec_cx_pkt pkt;
2371
0
  uint64_t sse;
2372
0
  int i;
2373
0
  unsigned int width = cpi->common.Width;
2374
0
  unsigned int height = cpi->common.Height;
2375
2376
0
  pkt.kind = VPX_CODEC_PSNR_PKT;
2377
0
  sse = calc_plane_error(orig->y_buffer, orig->y_stride, recon->y_buffer,
2378
0
                         recon->y_stride, width, height);
2379
0
  pkt.data.psnr.sse[0] = sse;
2380
0
  pkt.data.psnr.sse[1] = sse;
2381
0
  pkt.data.psnr.samples[0] = width * height;
2382
0
  pkt.data.psnr.samples[1] = width * height;
2383
2384
0
  width = (width + 1) / 2;
2385
0
  height = (height + 1) / 2;
2386
2387
0
  sse = calc_plane_error(orig->u_buffer, orig->uv_stride, recon->u_buffer,
2388
0
                         recon->uv_stride, width, height);
2389
0
  pkt.data.psnr.sse[0] += sse;
2390
0
  pkt.data.psnr.sse[2] = sse;
2391
0
  pkt.data.psnr.samples[0] += width * height;
2392
0
  pkt.data.psnr.samples[2] = width * height;
2393
2394
0
  sse = calc_plane_error(orig->v_buffer, orig->uv_stride, recon->v_buffer,
2395
0
                         recon->uv_stride, width, height);
2396
0
  pkt.data.psnr.sse[0] += sse;
2397
0
  pkt.data.psnr.sse[3] = sse;
2398
0
  pkt.data.psnr.samples[0] += width * height;
2399
0
  pkt.data.psnr.samples[3] = width * height;
2400
2401
0
  for (i = 0; i < 4; ++i) {
2402
0
    pkt.data.psnr.psnr[i] = vpx_sse_to_psnr(pkt.data.psnr.samples[i], 255.0,
2403
0
                                            (double)(pkt.data.psnr.sse[i]));
2404
0
  }
2405
2406
0
  vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2407
0
}
2408
2409
0
int vp8_use_as_reference(VP8_COMP *cpi, int ref_frame_flags) {
2410
0
  if (ref_frame_flags > 7) return -1;
2411
2412
0
  cpi->ref_frame_flags = ref_frame_flags;
2413
0
  return 0;
2414
0
}
2415
0
int vp8_update_reference(VP8_COMP *cpi, int ref_frame_flags) {
2416
0
  if (ref_frame_flags > 7) return -1;
2417
2418
0
  cpi->common.refresh_golden_frame = 0;
2419
0
  cpi->common.refresh_alt_ref_frame = 0;
2420
0
  cpi->common.refresh_last_frame = 0;
2421
2422
0
  if (ref_frame_flags & VP8_LAST_FRAME) cpi->common.refresh_last_frame = 1;
2423
2424
0
  if (ref_frame_flags & VP8_GOLD_FRAME) cpi->common.refresh_golden_frame = 1;
2425
2426
0
  if (ref_frame_flags & VP8_ALTR_FRAME) cpi->common.refresh_alt_ref_frame = 1;
2427
2428
0
  cpi->ext_refresh_frame_flags_pending = 1;
2429
0
  return 0;
2430
0
}
2431
2432
int vp8_get_reference(VP8_COMP *cpi, enum vpx_ref_frame_type ref_frame_flag,
2433
0
                      YV12_BUFFER_CONFIG *sd) {
2434
0
  VP8_COMMON *cm = &cpi->common;
2435
0
  int ref_fb_idx;
2436
2437
0
  if (ref_frame_flag == VP8_LAST_FRAME) {
2438
0
    ref_fb_idx = cm->lst_fb_idx;
2439
0
  } else if (ref_frame_flag == VP8_GOLD_FRAME) {
2440
0
    ref_fb_idx = cm->gld_fb_idx;
2441
0
  } else if (ref_frame_flag == VP8_ALTR_FRAME) {
2442
0
    ref_fb_idx = cm->alt_fb_idx;
2443
0
  } else {
2444
0
    return -1;
2445
0
  }
2446
2447
0
  if (cm->yv12_fb[ref_fb_idx].y_width != sd->y_width ||
2448
0
      cm->yv12_fb[ref_fb_idx].y_height != sd->y_height) {
2449
0
    return -1;
2450
0
  }
2451
2452
0
  vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
2453
2454
0
  return 0;
2455
0
}
2456
int vp8_set_reference(VP8_COMP *cpi, enum vpx_ref_frame_type ref_frame_flag,
2457
0
                      YV12_BUFFER_CONFIG *sd) {
2458
0
  VP8_COMMON *cm = &cpi->common;
2459
2460
0
  int ref_fb_idx;
2461
2462
0
  if (ref_frame_flag == VP8_LAST_FRAME) {
2463
0
    ref_fb_idx = cm->lst_fb_idx;
2464
0
  } else if (ref_frame_flag == VP8_GOLD_FRAME) {
2465
0
    ref_fb_idx = cm->gld_fb_idx;
2466
0
  } else if (ref_frame_flag == VP8_ALTR_FRAME) {
2467
0
    ref_fb_idx = cm->alt_fb_idx;
2468
0
  } else {
2469
0
    return -1;
2470
0
  }
2471
2472
0
  if (cm->yv12_fb[ref_fb_idx].y_width != sd->y_width ||
2473
0
      cm->yv12_fb[ref_fb_idx].y_height != sd->y_height) {
2474
0
    return -1;
2475
0
  }
2476
2477
0
  vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
2478
2479
0
  return 0;
2480
0
}
2481
0
int vp8_update_entropy(VP8_COMP *cpi, int update) {
2482
0
  VP8_COMMON *cm = &cpi->common;
2483
0
  cm->refresh_entropy_probs = update;
2484
2485
0
  return 0;
2486
0
}
2487
2488
117k
static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi) {
2489
117k
  VP8_COMMON *cm = &cpi->common;
2490
2491
  /* are we resizing the image */
2492
117k
  if (cm->horiz_scale != 0 || cm->vert_scale != 0) {
2493
0
#if CONFIG_SPATIAL_RESAMPLING
2494
0
    int hr, hs, vr, vs;
2495
0
    int tmp_height;
2496
2497
0
    if (cm->vert_scale == 3) {
2498
0
      tmp_height = 9;
2499
0
    } else {
2500
0
      tmp_height = 11;
2501
0
    }
2502
2503
0
    Scale2Ratio(cm->horiz_scale, &hr, &hs);
2504
0
    Scale2Ratio(cm->vert_scale, &vr, &vs);
2505
2506
0
    vpx_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
2507
0
                    tmp_height, hs, hr, vs, vr, 0);
2508
2509
0
    vp8_yv12_extend_frame_borders(&cpi->scaled_source);
2510
0
    cpi->Source = &cpi->scaled_source;
2511
0
#endif
2512
117k
  } else {
2513
117k
    cpi->Source = sd;
2514
117k
  }
2515
117k
}
2516
2517
34.8k
static int resize_key_frame(VP8_COMP *cpi) {
2518
34.8k
#if CONFIG_SPATIAL_RESAMPLING
2519
34.8k
  VP8_COMMON *cm = &cpi->common;
2520
2521
  /* Do we need to apply resampling for one pass cbr.
2522
   * In one pass this is more limited than in two pass cbr.
2523
   * The test and any change is only made once per key frame sequence.
2524
   */
2525
34.8k
  if (cpi->oxcf.allow_spatial_resampling &&
2526
0
      (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) {
2527
0
    int hr, hs, vr, vs;
2528
0
    int new_width, new_height;
2529
2530
    /* If we are below the resample DOWN watermark then scale down a
2531
     * notch.
2532
     */
2533
0
    if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark *
2534
0
                             cpi->oxcf.optimal_buffer_level / 100)) {
2535
0
      cm->horiz_scale =
2536
0
          (cm->horiz_scale < VP8E_ONETWO) ? cm->horiz_scale + 1 : VP8E_ONETWO;
2537
0
      cm->vert_scale =
2538
0
          (cm->vert_scale < VP8E_ONETWO) ? cm->vert_scale + 1 : VP8E_ONETWO;
2539
0
    }
2540
    /* Should we now start scaling back up */
2541
0
    else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark *
2542
0
                                  cpi->oxcf.optimal_buffer_level / 100)) {
2543
0
      cm->horiz_scale =
2544
0
          (cm->horiz_scale > VP8E_NORMAL) ? cm->horiz_scale - 1 : VP8E_NORMAL;
2545
0
      cm->vert_scale =
2546
0
          (cm->vert_scale > VP8E_NORMAL) ? cm->vert_scale - 1 : VP8E_NORMAL;
2547
0
    }
2548
2549
    /* Get the new height and width */
2550
0
    Scale2Ratio(cm->horiz_scale, &hr, &hs);
2551
0
    Scale2Ratio(cm->vert_scale, &vr, &vs);
2552
0
    new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
2553
0
    new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
2554
2555
    /* If the image size has changed we need to reallocate the buffers
2556
     * and resample the source image
2557
     */
2558
0
    if ((cm->Width != new_width) || (cm->Height != new_height)) {
2559
0
      cm->Width = new_width;
2560
0
      cm->Height = new_height;
2561
0
      vp8_alloc_compressor_data(cpi);
2562
0
      scale_and_extend_source(cpi->un_scaled_source, cpi);
2563
0
      return 1;
2564
0
    }
2565
0
  }
2566
2567
34.8k
#endif
2568
34.8k
  return 0;
2569
34.8k
}
2570
2571
0
static void update_alt_ref_frame_stats(VP8_COMP *cpi) {
2572
0
  VP8_COMMON *cm = &cpi->common;
2573
2574
  /* Select an interval before next GF or altref */
2575
0
  if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
2576
2577
0
  if ((cpi->pass != 2) && cpi->frames_till_gf_update_due) {
2578
0
    cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2579
2580
    /* Set the bits per frame that we should try and recover in
2581
     * subsequent inter frames to account for the extra GF spend...
2582
     * note that his does not apply for GF updates that occur
2583
     * coincident with a key frame as the extra cost of key frames is
2584
     * dealt with elsewhere.
2585
     */
2586
0
    cpi->gf_overspend_bits += cpi->projected_frame_size;
2587
0
    cpi->non_gf_bitrate_adjustment =
2588
0
        cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2589
0
  }
2590
2591
  /* Update data structure that monitors level of reference to last GF */
2592
0
  memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2593
0
  cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2594
2595
  /* this frame refreshes means next frames don't unless specified by user */
2596
0
  cpi->frames_since_golden = 0;
2597
2598
  /* Clear the alternate reference update pending flag. */
2599
0
  cpi->source_alt_ref_pending = 0;
2600
2601
  /* Set the alternate reference frame active flag */
2602
0
  cpi->source_alt_ref_active = 1;
2603
0
}
2604
117k
static void update_golden_frame_stats(VP8_COMP *cpi) {
2605
117k
  VP8_COMMON *cm = &cpi->common;
2606
2607
  /* Update the Golden frame usage counts. */
2608
117k
  if (cm->refresh_golden_frame) {
2609
    /* Select an interval before next GF */
2610
29.5k
    if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
2611
2612
29.5k
    if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0)) {
2613
29.5k
      cpi->current_gf_interval = cpi->frames_till_gf_update_due;
2614
2615
      /* Set the bits per frame that we should try and recover in
2616
       * subsequent inter frames to account for the extra GF spend...
2617
       * note that his does not apply for GF updates that occur
2618
       * coincident with a key frame as the extra cost of key frames
2619
       * is dealt with elsewhere.
2620
       */
2621
29.5k
      if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active) {
2622
        /* Calcluate GF bits to be recovered
2623
         * Projected size - av frame bits available for inter
2624
         * frames for clip as a whole
2625
         */
2626
8.70k
        cpi->gf_overspend_bits +=
2627
8.70k
            (cpi->projected_frame_size - cpi->inter_frame_target);
2628
8.70k
      }
2629
2630
29.5k
      cpi->non_gf_bitrate_adjustment =
2631
29.5k
          cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
2632
29.5k
    }
2633
2634
    /* Update data structure that monitors level of reference to last GF */
2635
29.5k
    memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
2636
29.5k
    cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
2637
2638
    /* this frame refreshes means next frames don't unless specified by
2639
     * user
2640
     */
2641
29.5k
    cm->refresh_golden_frame = 0;
2642
29.5k
    cpi->frames_since_golden = 0;
2643
2644
29.5k
    cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
2645
29.5k
    cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
2646
29.5k
    cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
2647
29.5k
    cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
2648
2649
    /* ******** Fixed Q test code only ************ */
2650
    /* If we are going to use the ALT reference for the next group of
2651
     * frames set a flag to say so.
2652
     */
2653
29.5k
    if (cpi->oxcf.fixed_q >= 0 && cpi->oxcf.play_alternate &&
2654
0
        !cpi->common.refresh_alt_ref_frame) {
2655
0
      cpi->source_alt_ref_pending = 1;
2656
0
      cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2657
0
    }
2658
2659
29.5k
    if (!cpi->source_alt_ref_pending) cpi->source_alt_ref_active = 0;
2660
2661
    /* Decrement count down till next gf */
2662
29.5k
    if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
2663
2664
87.9k
  } else if (!cpi->common.refresh_alt_ref_frame) {
2665
    /* Decrement count down till next gf */
2666
87.9k
    if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
2667
2668
87.9k
    if (cpi->frames_till_alt_ref_frame) cpi->frames_till_alt_ref_frame--;
2669
2670
87.9k
    cpi->frames_since_golden++;
2671
2672
87.9k
    if (cpi->frames_since_golden > 1) {
2673
70.5k
      cpi->recent_ref_frame_usage[INTRA_FRAME] +=
2674
70.5k
          cpi->mb.count_mb_ref_frame_usage[INTRA_FRAME];
2675
70.5k
      cpi->recent_ref_frame_usage[LAST_FRAME] +=
2676
70.5k
          cpi->mb.count_mb_ref_frame_usage[LAST_FRAME];
2677
70.5k
      cpi->recent_ref_frame_usage[GOLDEN_FRAME] +=
2678
70.5k
          cpi->mb.count_mb_ref_frame_usage[GOLDEN_FRAME];
2679
70.5k
      cpi->recent_ref_frame_usage[ALTREF_FRAME] +=
2680
70.5k
          cpi->mb.count_mb_ref_frame_usage[ALTREF_FRAME];
2681
70.5k
    }
2682
87.9k
  }
2683
117k
}
2684
2685
/* This function updates the reference frame probability estimates that
2686
 * will be used during mode selection
2687
 */
2688
117k
static void update_rd_ref_frame_probs(VP8_COMP *cpi) {
2689
117k
  VP8_COMMON *cm = &cpi->common;
2690
2691
117k
  const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
2692
117k
  const int rf_intra = rfct[INTRA_FRAME];
2693
117k
  const int rf_inter =
2694
117k
      rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
2695
2696
117k
  if (cm->frame_type == KEY_FRAME) {
2697
17.4k
    cpi->prob_intra_coded = 255;
2698
17.4k
    cpi->prob_last_coded = 128;
2699
17.4k
    cpi->prob_gf_coded = 128;
2700
100k
  } else if (!(rf_intra + rf_inter)) {
2701
9.17k
    cpi->prob_intra_coded = 63;
2702
9.17k
    cpi->prob_last_coded = 128;
2703
9.17k
    cpi->prob_gf_coded = 128;
2704
9.17k
  }
2705
2706
  /* update reference frame costs since we can do better than what we got
2707
   * last frame.
2708
   */
2709
117k
  if (cpi->oxcf.number_of_layers == 1) {
2710
117k
    if (cpi->common.refresh_alt_ref_frame) {
2711
0
      cpi->prob_intra_coded += 40;
2712
0
      if (cpi->prob_intra_coded > 255) cpi->prob_intra_coded = 255;
2713
0
      cpi->prob_last_coded = 200;
2714
0
      cpi->prob_gf_coded = 1;
2715
117k
    } else if (cpi->frames_since_golden == 0) {
2716
33.8k
      cpi->prob_last_coded = 214;
2717
83.7k
    } else if (cpi->frames_since_golden == 1) {
2718
15.2k
      cpi->prob_last_coded = 192;
2719
15.2k
      cpi->prob_gf_coded = 220;
2720
68.4k
    } else if (cpi->source_alt_ref_active) {
2721
0
      cpi->prob_gf_coded -= 20;
2722
2723
0
      if (cpi->prob_gf_coded < 10) cpi->prob_gf_coded = 10;
2724
0
    }
2725
117k
    if (!cpi->source_alt_ref_active) cpi->prob_gf_coded = 255;
2726
117k
  }
2727
117k
}
2728
2729
#if !CONFIG_REALTIME_ONLY
2730
/* 1 = key, 0 = inter */
2731
63.4k
static int decide_key_frame(VP8_COMP *cpi) {
2732
63.4k
  VP8_COMMON *cm = &cpi->common;
2733
2734
63.4k
  int code_key_frame = 0;
2735
2736
63.4k
  cpi->kf_boost = 0;
2737
2738
63.4k
  if (cpi->Speed > 11) return 0;
2739
2740
  /* Clear down mmx registers */
2741
63.4k
  vpx_clear_system_state();
2742
2743
63.4k
  if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0)) {
2744
0
    double change = 1.0 *
2745
0
                    abs((int)(cpi->mb.intra_error - cpi->last_intra_error)) /
2746
0
                    (1 + cpi->last_intra_error);
2747
0
    double change2 =
2748
0
        1.0 *
2749
0
        abs((int)(cpi->mb.prediction_error - cpi->last_prediction_error)) /
2750
0
        (1 + cpi->last_prediction_error);
2751
0
    double minerror = cm->MBs * 256;
2752
2753
0
    cpi->last_intra_error = cpi->mb.intra_error;
2754
0
    cpi->last_prediction_error = cpi->mb.prediction_error;
2755
2756
0
    if (10 * cpi->mb.intra_error / (1 + cpi->mb.prediction_error) < 15 &&
2757
0
        cpi->mb.prediction_error > minerror &&
2758
0
        (change > .25 || change2 > .25)) {
2759
      /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra >
2760
       * cpi->last_frame_percent_intra + 3*/
2761
0
      return 1;
2762
0
    }
2763
2764
0
    return 0;
2765
0
  }
2766
2767
  /* If the following are true we might as well code a key frame */
2768
63.4k
  if (((cpi->this_frame_percent_intra == 100) &&
2769
10.8k
       (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
2770
60.7k
      ((cpi->this_frame_percent_intra > 95) &&
2771
8.52k
       (cpi->this_frame_percent_intra >=
2772
8.52k
        (cpi->last_frame_percent_intra + 5)))) {
2773
2.73k
    code_key_frame = 1;
2774
2.73k
  }
2775
  /* in addition if the following are true and this is not a golden frame
2776
   * then code a key frame Note that on golden frames there often seems
2777
   * to be a pop in intra usage anyway hence this restriction is
2778
   * designed to prevent spurious key frames. The Intra pop needs to be
2779
   * investigated.
2780
   */
2781
60.7k
  else if (((cpi->this_frame_percent_intra > 60) &&
2782
16.4k
            (cpi->this_frame_percent_intra >
2783
16.4k
             (cpi->last_frame_percent_intra * 2))) ||
2784
59.9k
           ((cpi->this_frame_percent_intra > 75) &&
2785
9.96k
            (cpi->this_frame_percent_intra >
2786
9.96k
             (cpi->last_frame_percent_intra * 3 / 2))) ||
2787
59.8k
           ((cpi->this_frame_percent_intra > 90) &&
2788
9.11k
            (cpi->this_frame_percent_intra >
2789
9.11k
             (cpi->last_frame_percent_intra + 10)))) {
2790
980
    if (!cm->refresh_golden_frame) code_key_frame = 1;
2791
980
  }
2792
2793
63.4k
  return code_key_frame;
2794
63.4k
}
2795
2796
0
static void Pass1Encode(VP8_COMP *cpi) {
2797
0
  vp8_set_quantizer(cpi, 26);
2798
0
  vp8_first_pass(cpi);
2799
0
}
2800
#endif
2801
2802
#if 0
2803
void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
2804
{
2805
2806
    /* write the frame */
2807
    FILE *yframe;
2808
    int i;
2809
    char filename[255];
2810
2811
    sprintf(filename, "cx\\y%04d.raw", this_frame);
2812
    yframe = fopen(filename, "wb");
2813
2814
    for (i = 0; i < frame->y_height; ++i)
2815
        fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
2816
2817
    fclose(yframe);
2818
    sprintf(filename, "cx\\u%04d.raw", this_frame);
2819
    yframe = fopen(filename, "wb");
2820
2821
    for (i = 0; i < frame->uv_height; ++i)
2822
        fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2823
2824
    fclose(yframe);
2825
    sprintf(filename, "cx\\v%04d.raw", this_frame);
2826
    yframe = fopen(filename, "wb");
2827
2828
    for (i = 0; i < frame->uv_height; ++i)
2829
        fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
2830
2831
    fclose(yframe);
2832
}
2833
#endif
2834
2835
#if !CONFIG_REALTIME_ONLY
2836
/* Function to test for conditions that indeicate we should loop
2837
 * back and recode a frame.
2838
 */
2839
static int recode_loop_test(VP8_COMP *cpi, int high_limit, int low_limit, int q,
2840
148k
                            int maxq, int minq) {
2841
148k
  int force_recode = 0;
2842
148k
  VP8_COMMON *cm = &cpi->common;
2843
2844
  /* Is frame recode allowed at all
2845
   * Yes if either recode mode 1 is selected or mode two is selcted
2846
   * and the frame is a key frame. golden frame or alt_ref_frame
2847
   */
2848
148k
  if ((cpi->sf.recode_loop == 1) ||
2849
60.3k
      ((cpi->sf.recode_loop == 2) &&
2850
0
       ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
2851
88.1k
        cm->refresh_alt_ref_frame))) {
2852
    /* General over and under shoot tests */
2853
88.1k
    if (((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2854
69.4k
        ((cpi->projected_frame_size < low_limit) && (q > minq))) {
2855
29.7k
      force_recode = 1;
2856
29.7k
    }
2857
    /* Special Constrained quality tests */
2858
58.4k
    else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2859
      /* Undershoot and below auto cq level */
2860
13.8k
      if ((q > cpi->cq_target_quality) &&
2861
7.28k
          (cpi->projected_frame_size < ((cpi->this_frame_target * 7) >> 3))) {
2862
2.90k
        force_recode = 1;
2863
2.90k
      }
2864
      /* Severe undershoot and between auto and user cq level */
2865
10.9k
      else if ((q > cpi->oxcf.cq_level) &&
2866
4.37k
               (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
2867
0
               (cpi->active_best_quality > cpi->oxcf.cq_level)) {
2868
0
        force_recode = 1;
2869
0
        cpi->active_best_quality = cpi->oxcf.cq_level;
2870
0
      }
2871
13.8k
    }
2872
88.1k
  }
2873
2874
148k
  return force_recode;
2875
148k
}
2876
#endif  // !CONFIG_REALTIME_ONLY
2877
2878
117k
static void update_reference_frames(VP8_COMP *cpi) {
2879
117k
  VP8_COMMON *cm = &cpi->common;
2880
117k
  YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
2881
2882
  /* At this point the new frame has been encoded.
2883
   * If any buffer copy / swapping is signaled it should be done here.
2884
   */
2885
2886
117k
  if (cm->frame_type == KEY_FRAME) {
2887
20.8k
    yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FRAME | VP8_ALTR_FRAME;
2888
2889
20.8k
    yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2890
20.8k
    yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2891
2892
20.8k
    cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
2893
2894
20.8k
    cpi->current_ref_frames[GOLDEN_FRAME] = cm->current_video_frame;
2895
20.8k
    cpi->current_ref_frames[ALTREF_FRAME] = cm->current_video_frame;
2896
96.6k
  } else {
2897
96.6k
    if (cm->refresh_alt_ref_frame) {
2898
0
      assert(!cm->copy_buffer_to_arf);
2899
2900
0
      cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALTR_FRAME;
2901
0
      cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2902
0
      cm->alt_fb_idx = cm->new_fb_idx;
2903
2904
0
      cpi->current_ref_frames[ALTREF_FRAME] = cm->current_video_frame;
2905
96.6k
    } else if (cm->copy_buffer_to_arf) {
2906
8.70k
      assert(!(cm->copy_buffer_to_arf & ~0x3));
2907
2908
8.70k
      if (cm->copy_buffer_to_arf == 1) {
2909
0
        if (cm->alt_fb_idx != cm->lst_fb_idx) {
2910
0
          yv12_fb[cm->lst_fb_idx].flags |= VP8_ALTR_FRAME;
2911
0
          yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2912
0
          cm->alt_fb_idx = cm->lst_fb_idx;
2913
2914
0
          cpi->current_ref_frames[ALTREF_FRAME] =
2915
0
              cpi->current_ref_frames[LAST_FRAME];
2916
0
        }
2917
8.70k
      } else {
2918
8.70k
        if (cm->alt_fb_idx != cm->gld_fb_idx) {
2919
6.86k
          yv12_fb[cm->gld_fb_idx].flags |= VP8_ALTR_FRAME;
2920
6.86k
          yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
2921
6.86k
          cm->alt_fb_idx = cm->gld_fb_idx;
2922
2923
6.86k
          cpi->current_ref_frames[ALTREF_FRAME] =
2924
6.86k
              cpi->current_ref_frames[GOLDEN_FRAME];
2925
6.86k
        }
2926
8.70k
      }
2927
8.70k
    }
2928
2929
96.6k
    if (cm->refresh_golden_frame) {
2930
8.70k
      assert(!cm->copy_buffer_to_gf);
2931
2932
8.70k
      cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FRAME;
2933
8.70k
      cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2934
8.70k
      cm->gld_fb_idx = cm->new_fb_idx;
2935
2936
8.70k
      cpi->current_ref_frames[GOLDEN_FRAME] = cm->current_video_frame;
2937
87.9k
    } else if (cm->copy_buffer_to_gf) {
2938
0
      assert(!(cm->copy_buffer_to_arf & ~0x3));
2939
2940
0
      if (cm->copy_buffer_to_gf == 1) {
2941
0
        if (cm->gld_fb_idx != cm->lst_fb_idx) {
2942
0
          yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FRAME;
2943
0
          yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2944
0
          cm->gld_fb_idx = cm->lst_fb_idx;
2945
2946
0
          cpi->current_ref_frames[GOLDEN_FRAME] =
2947
0
              cpi->current_ref_frames[LAST_FRAME];
2948
0
        }
2949
0
      } else {
2950
0
        if (cm->alt_fb_idx != cm->gld_fb_idx) {
2951
0
          yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FRAME;
2952
0
          yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
2953
0
          cm->gld_fb_idx = cm->alt_fb_idx;
2954
2955
0
          cpi->current_ref_frames[GOLDEN_FRAME] =
2956
0
              cpi->current_ref_frames[ALTREF_FRAME];
2957
0
        }
2958
0
      }
2959
0
    }
2960
96.6k
  }
2961
2962
117k
  if (cm->refresh_last_frame) {
2963
117k
    cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FRAME;
2964
117k
    cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FRAME;
2965
117k
    cm->lst_fb_idx = cm->new_fb_idx;
2966
2967
117k
    cpi->current_ref_frames[LAST_FRAME] = cm->current_video_frame;
2968
117k
  }
2969
2970
117k
#if CONFIG_TEMPORAL_DENOISING
2971
117k
  if (cpi->oxcf.noise_sensitivity) {
2972
    /* we shouldn't have to keep multiple copies as we know in advance which
2973
     * buffer we should start - for now to get something up and running
2974
     * I've chosen to copy the buffers
2975
     */
2976
0
    if (cm->frame_type == KEY_FRAME) {
2977
0
      int i;
2978
0
      for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i)
2979
0
        vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_running_avg[i]);
2980
0
    } else {
2981
0
      vp8_yv12_extend_frame_borders(
2982
0
          &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
2983
2984
0
      if (cm->refresh_alt_ref_frame || cm->copy_buffer_to_arf) {
2985
0
        vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
2986
0
                            &cpi->denoiser.yv12_running_avg[ALTREF_FRAME]);
2987
0
      }
2988
0
      if (cm->refresh_golden_frame || cm->copy_buffer_to_gf) {
2989
0
        vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
2990
0
                            &cpi->denoiser.yv12_running_avg[GOLDEN_FRAME]);
2991
0
      }
2992
0
      if (cm->refresh_last_frame) {
2993
0
        if (cpi->denoiser.denoiser_mode == kDenoiserOnYOnly) {
2994
0
          vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
2995
0
                              &cpi->denoiser.yv12_running_avg[LAST_FRAME]);
2996
0
        } else {
2997
0
          YV12_BUFFER_CONFIG tmp = cpi->denoiser.yv12_running_avg[INTRA_FRAME];
2998
0
          cpi->denoiser.yv12_running_avg[INTRA_FRAME] =
2999
0
              cpi->denoiser.yv12_running_avg[LAST_FRAME];
3000
0
          cpi->denoiser.yv12_running_avg[LAST_FRAME] = tmp;
3001
0
        }
3002
0
      }
3003
0
    }
3004
0
    if (cpi->oxcf.noise_sensitivity == 4)
3005
0
      vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_last_source);
3006
0
  }
3007
117k
#endif
3008
117k
}
3009
3010
static int measure_square_diff_partial(YV12_BUFFER_CONFIG *source,
3011
                                       YV12_BUFFER_CONFIG *dest,
3012
0
                                       VP8_COMP *cpi) {
3013
0
  int i, j;
3014
0
  int Total = 0;
3015
0
  int num_blocks = 0;
3016
0
  int skip = 2;
3017
0
  int min_consec_zero_last = 10;
3018
0
  int tot_num_blocks = (source->y_height * source->y_width) >> 8;
3019
0
  unsigned char *src = source->y_buffer;
3020
0
  unsigned char *dst = dest->y_buffer;
3021
3022
  /* Loop through the Y plane, every |skip| blocks along rows and colmumns,
3023
   * summing the square differences, and only for blocks that have been
3024
   * zero_last mode at least |x| frames in a row.
3025
   */
3026
0
  for (i = 0; i < source->y_height; i += 16 * skip) {
3027
0
    int block_index_row = (i >> 4) * cpi->common.mb_cols;
3028
0
    for (j = 0; j < source->y_width; j += 16 * skip) {
3029
0
      int index = block_index_row + (j >> 4);
3030
0
      if (cpi->consec_zero_last[index] >= min_consec_zero_last) {
3031
0
        unsigned int sse;
3032
0
        Total += vpx_mse16x16(src + j, source->y_stride, dst + j,
3033
0
                              dest->y_stride, &sse);
3034
0
        num_blocks++;
3035
0
      }
3036
0
    }
3037
0
    src += 16 * skip * source->y_stride;
3038
0
    dst += 16 * skip * dest->y_stride;
3039
0
  }
3040
  // Only return non-zero if we have at least ~1/16 samples for estimate.
3041
0
  if (num_blocks > (tot_num_blocks >> 4)) {
3042
0
    assert(num_blocks != 0);
3043
0
    return (Total / num_blocks);
3044
0
  } else {
3045
0
    return 0;
3046
0
  }
3047
0
}
3048
3049
#if CONFIG_TEMPORAL_DENOISING
3050
0
static void process_denoiser_mode_change(VP8_COMP *cpi) {
3051
0
  const VP8_COMMON *const cm = &cpi->common;
3052
0
  int i, j;
3053
0
  int total = 0;
3054
0
  int num_blocks = 0;
3055
  // Number of blocks skipped along row/column in computing the
3056
  // nmse (normalized mean square error) of source.
3057
0
  int skip = 2;
3058
  // Only select blocks for computing nmse that have been encoded
3059
  // as ZERO LAST min_consec_zero_last frames in a row.
3060
  // Scale with number of temporal layers.
3061
0
  int min_consec_zero_last = 12 / cpi->oxcf.number_of_layers;
3062
  // Decision is tested for changing the denoising mode every
3063
  // num_mode_change times this function is called. Note that this
3064
  // function called every 8 frames, so (8 * num_mode_change) is number
3065
  // of frames where denoising mode change is tested for switch.
3066
0
  int num_mode_change = 20;
3067
  // Framerate factor, to compensate for larger mse at lower framerates.
3068
  // Use ref_framerate, which is full source framerate for temporal layers.
3069
  // TODO(marpan): Adjust this factor.
3070
0
  int fac_framerate = cpi->ref_framerate < 25.0f ? 80 : 100;
3071
0
  int tot_num_blocks = cm->mb_rows * cm->mb_cols;
3072
0
  int ystride = cpi->Source->y_stride;
3073
0
  unsigned char *src = cpi->Source->y_buffer;
3074
0
  unsigned char *dst = cpi->denoiser.yv12_last_source.y_buffer;
3075
0
  static const unsigned char const_source[16] = { 128, 128, 128, 128, 128, 128,
3076
0
                                                  128, 128, 128, 128, 128, 128,
3077
0
                                                  128, 128, 128, 128 };
3078
0
  int bandwidth = (int)(cpi->target_bandwidth);
3079
  // For temporal layers, use full bandwidth (top layer).
3080
0
  if (cpi->oxcf.number_of_layers > 1) {
3081
0
    LAYER_CONTEXT *lc = &cpi->layer_context[cpi->oxcf.number_of_layers - 1];
3082
0
    bandwidth = (int)(lc->target_bandwidth);
3083
0
  }
3084
  // Loop through the Y plane, every skip blocks along rows and columns,
3085
  // summing the normalized mean square error, only for blocks that have
3086
  // been encoded as ZEROMV LAST at least min_consec_zero_last least frames in
3087
  // a row and have small sum difference between current and previous frame.
3088
  // Normalization here is by the contrast of the current frame block.
3089
0
  for (i = 0; i < cm->Height; i += 16 * skip) {
3090
0
    int block_index_row = (i >> 4) * cm->mb_cols;
3091
0
    for (j = 0; j < cm->Width; j += 16 * skip) {
3092
0
      int index = block_index_row + (j >> 4);
3093
0
      if (cpi->consec_zero_last[index] >= min_consec_zero_last) {
3094
0
        unsigned int sse;
3095
0
        const unsigned int var =
3096
0
            vpx_variance16x16(src + j, ystride, dst + j, ystride, &sse);
3097
        // Only consider this block as valid for noise measurement
3098
        // if the sum_diff average of the current and previous frame
3099
        // is small (to avoid effects from lighting change).
3100
0
        if ((sse - var) < 128) {
3101
0
          unsigned int sse2;
3102
0
          const unsigned int act =
3103
0
              vpx_variance16x16(src + j, ystride, const_source, 0, &sse2);
3104
0
          if (act > 0) total += sse / act;
3105
0
          num_blocks++;
3106
0
        }
3107
0
      }
3108
0
    }
3109
0
    src += 16 * skip * ystride;
3110
0
    dst += 16 * skip * ystride;
3111
0
  }
3112
0
  total = total * fac_framerate / 100;
3113
3114
  // Only consider this frame as valid sample if we have computed nmse over
3115
  // at least ~1/16 blocks, and Total > 0 (Total == 0 can happen if the
3116
  // application inputs duplicate frames, or contrast is all zero).
3117
0
  if (total > 0 && (num_blocks > (tot_num_blocks >> 4))) {
3118
    // Update the recursive mean square source_diff.
3119
0
    total = (total << 8) / num_blocks;
3120
0
    if (cpi->denoiser.nmse_source_diff_count == 0) {
3121
      // First sample in new interval.
3122
0
      cpi->denoiser.nmse_source_diff = total;
3123
0
      cpi->denoiser.qp_avg = cm->base_qindex;
3124
0
    } else {
3125
      // For subsequent samples, use average with weight ~1/4 for new sample.
3126
0
      cpi->denoiser.nmse_source_diff =
3127
0
          (int)((total + 3 * cpi->denoiser.nmse_source_diff) >> 2);
3128
0
      cpi->denoiser.qp_avg =
3129
0
          (int)((cm->base_qindex + 3 * cpi->denoiser.qp_avg) >> 2);
3130
0
    }
3131
0
    cpi->denoiser.nmse_source_diff_count++;
3132
0
  }
3133
  // Check for changing the denoiser mode, when we have obtained #samples =
3134
  // num_mode_change. Condition the change also on the bitrate and QP.
3135
0
  if (cpi->denoiser.nmse_source_diff_count == num_mode_change) {
3136
    // Check for going up: from normal to aggressive mode.
3137
0
    if ((cpi->denoiser.denoiser_mode == kDenoiserOnYUV) &&
3138
0
        (cpi->denoiser.nmse_source_diff >
3139
0
         cpi->denoiser.threshold_aggressive_mode) &&
3140
0
        (cpi->denoiser.qp_avg < cpi->denoiser.qp_threshold_up &&
3141
0
         bandwidth > cpi->denoiser.bitrate_threshold)) {
3142
0
      vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUVAggressive);
3143
0
    } else {
3144
      // Check for going down: from aggressive to normal mode.
3145
0
      if (((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
3146
0
           (cpi->denoiser.nmse_source_diff <
3147
0
            cpi->denoiser.threshold_aggressive_mode)) ||
3148
0
          ((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
3149
0
           (cpi->denoiser.qp_avg > cpi->denoiser.qp_threshold_down ||
3150
0
            bandwidth < cpi->denoiser.bitrate_threshold))) {
3151
0
        vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
3152
0
      }
3153
0
    }
3154
    // Reset metric and counter for next interval.
3155
0
    cpi->denoiser.nmse_source_diff = 0;
3156
0
    cpi->denoiser.qp_avg = 0;
3157
0
    cpi->denoiser.nmse_source_diff_count = 0;
3158
0
  }
3159
0
}
3160
#endif
3161
3162
117k
void vp8_loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm) {
3163
117k
  const FRAME_TYPE frame_type = cm->frame_type;
3164
3165
117k
  int update_any_ref_buffers = 1;
3166
117k
  if (cpi->common.refresh_last_frame == 0 &&
3167
0
      cpi->common.refresh_golden_frame == 0 &&
3168
0
      cpi->common.refresh_alt_ref_frame == 0) {
3169
0
    update_any_ref_buffers = 0;
3170
0
  }
3171
3172
117k
  if (cm->no_lpf) {
3173
0
    cm->filter_level = 0;
3174
117k
  } else {
3175
#if CONFIG_INTERNAL_STATS
3176
    struct vpx_usec_timer timer;
3177
#endif
3178
3179
117k
    vpx_clear_system_state();
3180
3181
#if CONFIG_INTERNAL_STATS
3182
    vpx_usec_timer_start(&timer);
3183
#endif
3184
117k
    if (cpi->sf.auto_filter == 0) {
3185
11
#if CONFIG_TEMPORAL_DENOISING
3186
11
      if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) {
3187
        // Use the denoised buffer for selecting base loop filter level.
3188
        // Denoised signal for current frame is stored in INTRA_FRAME.
3189
        // No denoising on key frames.
3190
0
        vp8cx_pick_filter_level_fast(
3191
0
            &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi);
3192
11
      } else {
3193
11
        vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3194
11
      }
3195
#else
3196
      vp8cx_pick_filter_level_fast(cpi->Source, cpi);
3197
#endif
3198
117k
    } else {
3199
117k
#if CONFIG_TEMPORAL_DENOISING
3200
117k
      if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) {
3201
        // Use the denoised buffer for selecting base loop filter level.
3202
        // Denoised signal for current frame is stored in INTRA_FRAME.
3203
        // No denoising on key frames.
3204
0
        vp8cx_pick_filter_level(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
3205
0
                                cpi);
3206
117k
      } else {
3207
117k
        vp8cx_pick_filter_level(cpi->Source, cpi);
3208
117k
      }
3209
#else
3210
      vp8cx_pick_filter_level(cpi->Source, cpi);
3211
#endif
3212
117k
    }
3213
3214
117k
    if (cm->filter_level > 0) {
3215
104k
      vp8cx_set_alt_lf_level(cpi, cm->filter_level);
3216
104k
    }
3217
3218
#if CONFIG_INTERNAL_STATS
3219
    vpx_usec_timer_mark(&timer);
3220
    cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
3221
#endif
3222
117k
  }
3223
3224
117k
#if CONFIG_MULTITHREAD
3225
117k
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
3226
    /* signal that we have set filter_level */
3227
0
    vp8_sem_post(&cpi->h_event_end_lpf);
3228
0
  }
3229
117k
#endif
3230
3231
  // No need to apply loop-filter if the encoded frame does not update
3232
  // any reference buffers.
3233
117k
  if (cm->filter_level > 0 && update_any_ref_buffers) {
3234
104k
    vp8_loop_filter_frame(cm, &cpi->mb.e_mbd, frame_type);
3235
104k
  }
3236
3237
117k
  vp8_yv12_extend_frame_borders(cm->frame_to_show);
3238
117k
}
3239
// Return 1 if frame is to be dropped. Update frame drop decimation
3240
// counters.
3241
117k
int vp8_check_drop_buffer(VP8_COMP *cpi) {
3242
117k
  VP8_COMMON *cm = &cpi->common;
3243
117k
  int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
3244
117k
                        cpi->oxcf.optimal_buffer_level / 100);
3245
117k
  int drop_mark75 = drop_mark * 2 / 3;
3246
117k
  int drop_mark50 = drop_mark / 4;
3247
117k
  int drop_mark25 = drop_mark / 8;
3248
117k
  if (cpi->drop_frames_allowed) {
3249
    /* The reset to decimation 0 is only done here for one pass.
3250
     * Once it is set two pass leaves decimation on till the next kf.
3251
     */
3252
0
    if (cpi->buffer_level > drop_mark && cpi->decimation_factor > 0) {
3253
0
      cpi->decimation_factor--;
3254
0
    }
3255
3256
0
    if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0) {
3257
0
      cpi->decimation_factor = 1;
3258
3259
0
    } else if (cpi->buffer_level < drop_mark25 &&
3260
0
               (cpi->decimation_factor == 2 || cpi->decimation_factor == 3)) {
3261
0
      cpi->decimation_factor = 3;
3262
0
    } else if (cpi->buffer_level < drop_mark50 &&
3263
0
               (cpi->decimation_factor == 1 || cpi->decimation_factor == 2)) {
3264
0
      cpi->decimation_factor = 2;
3265
0
    } else if (cpi->buffer_level < drop_mark75 &&
3266
0
               (cpi->decimation_factor == 0 || cpi->decimation_factor == 1)) {
3267
0
      cpi->decimation_factor = 1;
3268
0
    }
3269
0
  }
3270
3271
  /* The following decimates the frame rate according to a regular
3272
   * pattern (i.e. to 1/2 or 2/3 frame rate) This can be used to help
3273
   * prevent buffer under-run in CBR mode. Alternatively it might be
3274
   * desirable in some situations to drop frame rate but throw more bits
3275
   * at each frame.
3276
   *
3277
   * Note that dropping a key frame can be problematic if spatial
3278
   * resampling is also active
3279
   */
3280
117k
  if (cpi->decimation_factor > 0 && cpi->drop_frames_allowed) {
3281
0
    switch (cpi->decimation_factor) {
3282
0
      case 1:
3283
0
        cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
3284
0
        break;
3285
0
      case 2:
3286
0
        cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3287
0
        break;
3288
0
      case 3:
3289
0
        cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
3290
0
        break;
3291
0
    }
3292
3293
    /* Note that we should not throw out a key frame (especially when
3294
     * spatial resampling is enabled).
3295
     */
3296
0
    if (cm->frame_type == KEY_FRAME) {
3297
0
      cpi->decimation_count = cpi->decimation_factor;
3298
0
    } else if (cpi->decimation_count > 0) {
3299
0
      cpi->decimation_count--;
3300
3301
0
      cpi->bits_off_target += cpi->av_per_frame_bandwidth;
3302
0
      if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
3303
0
        cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3304
0
      }
3305
3306
#if CONFIG_MULTI_RES_ENCODING
3307
      vp8_store_drop_frame_info(cpi);
3308
#endif
3309
3310
0
      cm->current_video_frame++;
3311
0
      cpi->frames_since_key++;
3312
0
      cpi->ext_refresh_frame_flags_pending = 0;
3313
      // We advance the temporal pattern for dropped frames.
3314
0
      cpi->temporal_pattern_counter++;
3315
3316
#if CONFIG_INTERNAL_STATS
3317
      cpi->count++;
3318
#endif
3319
3320
0
      cpi->buffer_level = cpi->bits_off_target;
3321
3322
0
      if (cpi->oxcf.number_of_layers > 1) {
3323
0
        unsigned int i;
3324
3325
        /* Propagate bits saved by dropping the frame to higher
3326
         * layers
3327
         */
3328
0
        for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
3329
0
          LAYER_CONTEXT *lc = &cpi->layer_context[i];
3330
0
          lc->bits_off_target += (int)(lc->target_bandwidth / lc->framerate);
3331
0
          if (lc->bits_off_target > lc->maximum_buffer_size) {
3332
0
            lc->bits_off_target = lc->maximum_buffer_size;
3333
0
          }
3334
0
          lc->buffer_level = lc->bits_off_target;
3335
0
        }
3336
0
      }
3337
0
      return 1;
3338
0
    } else {
3339
0
      cpi->decimation_count = cpi->decimation_factor;
3340
0
    }
3341
117k
  } else {
3342
117k
    cpi->decimation_count = 0;
3343
117k
  }
3344
117k
  return 0;
3345
117k
}
3346
3347
static void encode_frame_to_data_rate(VP8_COMP *cpi, size_t *size,
3348
                                      unsigned char *dest,
3349
                                      unsigned char *dest_end,
3350
117k
                                      unsigned int *frame_flags) {
3351
117k
  int Q;
3352
117k
  int frame_over_shoot_limit;
3353
117k
  int frame_under_shoot_limit;
3354
3355
117k
  int Loop = 0;
3356
3357
117k
  VP8_COMMON *cm = &cpi->common;
3358
117k
  int active_worst_qchanged = 0;
3359
3360
117k
#if !CONFIG_REALTIME_ONLY
3361
117k
  int q_low;
3362
117k
  int q_high;
3363
117k
  int zbin_oq_high;
3364
117k
  int zbin_oq_low = 0;
3365
117k
  int top_index;
3366
117k
  int bottom_index;
3367
117k
  int overshoot_seen = 0;
3368
117k
  int undershoot_seen = 0;
3369
117k
#endif
3370
3371
  /* Clear down mmx registers to allow floating point in what follows */
3372
117k
  vpx_clear_system_state();
3373
3374
117k
  if (cpi->force_next_frame_intra) {
3375
0
    cm->frame_type = KEY_FRAME; /* delayed intra frame */
3376
0
    cpi->force_next_frame_intra = 0;
3377
0
  }
3378
3379
  /* For an alt ref frame in 2 pass we skip the call to the second pass
3380
   * function that sets the target bandwidth
3381
   */
3382
117k
  switch (cpi->pass) {
3383
0
#if !CONFIG_REALTIME_ONLY
3384
0
    case 2:
3385
0
      if (cpi->common.refresh_alt_ref_frame) {
3386
        /* Per frame bit target for the alt ref frame */
3387
0
        cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
3388
        /* per second target bitrate */
3389
0
        cpi->target_bandwidth =
3390
0
            (int)(cpi->twopass.gf_bits * cpi->output_framerate);
3391
0
      }
3392
0
      break;
3393
0
#endif  // !CONFIG_REALTIME_ONLY
3394
117k
    default: {
3395
117k
      const double per_frame_bandwidth =
3396
117k
          round(cpi->target_bandwidth / cpi->output_framerate);
3397
117k
      cpi->per_frame_bandwidth = (int)VPXMIN(per_frame_bandwidth, INT_MAX);
3398
117k
      break;
3399
0
    }
3400
117k
  }
3401
3402
  /* Default turn off buffer to buffer copying */
3403
117k
  cm->copy_buffer_to_gf = 0;
3404
117k
  cm->copy_buffer_to_arf = 0;
3405
3406
  /* Clear zbin over-quant value and mode boost values. */
3407
117k
  cpi->mb.zbin_over_quant = 0;
3408
117k
  cpi->mb.zbin_mode_boost = 0;
3409
3410
  /* Enable or disable mode based tweaking of the zbin
3411
   * For 2 Pass Only used where GF/ARF prediction quality
3412
   * is above a threshold
3413
   */
3414
117k
  cpi->mb.zbin_mode_boost_enabled = 1;
3415
117k
  if (cpi->pass == 2) {
3416
0
    if (cpi->gfu_boost <= 400) {
3417
0
      cpi->mb.zbin_mode_boost_enabled = 0;
3418
0
    }
3419
0
  }
3420
3421
  /* Current default encoder behaviour for the altref sign bias */
3422
117k
  if (cpi->source_alt_ref_active) {
3423
0
    cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
3424
117k
  } else {
3425
117k
    cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
3426
117k
  }
3427
3428
  /* Check to see if a key frame is signaled
3429
   * For two pass with auto key frame enabled cm->frame_type may already
3430
   * be set, but not for one pass.
3431
   */
3432
117k
  if ((cm->current_video_frame == 0) || (cm->frame_flags & FRAMEFLAGS_KEY) ||
3433
104k
      (cpi->oxcf.auto_key &&
3434
104k
       (cpi->frames_since_key % cpi->key_frame_frequency == 0))) {
3435
    /* Key frame from VFW/auto-keyframe/first frame */
3436
17.4k
    cm->frame_type = KEY_FRAME;
3437
17.4k
#if CONFIG_TEMPORAL_DENOISING
3438
17.4k
    if (cpi->oxcf.noise_sensitivity == 4) {
3439
      // For adaptive mode, reset denoiser to normal mode on key frame.
3440
0
      vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
3441
0
    }
3442
17.4k
#endif
3443
17.4k
  }
3444
3445
#if CONFIG_MULTI_RES_ENCODING
3446
  if (cpi->oxcf.mr_total_resolutions > 1) {
3447
    LOWER_RES_FRAME_INFO *low_res_frame_info =
3448
        (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
3449
3450
    if (cpi->oxcf.mr_encoder_id) {
3451
      // Check if lower resolution is available for motion vector reuse.
3452
      if (cm->frame_type != KEY_FRAME) {
3453
        cpi->mr_low_res_mv_avail = 1;
3454
        cpi->mr_low_res_mv_avail &= !(low_res_frame_info->is_frame_dropped);
3455
3456
        if (cpi->ref_frame_flags & VP8_LAST_FRAME)
3457
          cpi->mr_low_res_mv_avail &=
3458
              (cpi->current_ref_frames[LAST_FRAME] ==
3459
               low_res_frame_info->low_res_ref_frames[LAST_FRAME]);
3460
3461
        if (cpi->ref_frame_flags & VP8_GOLD_FRAME)
3462
          cpi->mr_low_res_mv_avail &=
3463
              (cpi->current_ref_frames[GOLDEN_FRAME] ==
3464
               low_res_frame_info->low_res_ref_frames[GOLDEN_FRAME]);
3465
3466
        // Don't use altref to determine whether low res is available.
3467
        // TODO (marpan): Should we make this type of condition on a
3468
        // per-reference frame basis?
3469
        /*
3470
        if (cpi->ref_frame_flags & VP8_ALTR_FRAME)
3471
            cpi->mr_low_res_mv_avail &= (cpi->current_ref_frames[ALTREF_FRAME]
3472
                     == low_res_frame_info->low_res_ref_frames[ALTREF_FRAME]);
3473
        */
3474
      }
3475
      // Disable motion vector reuse (i.e., disable any usage of the low_res)
3476
      // if the previous lower stream is skipped/disabled.
3477
      if (low_res_frame_info->skip_encoding_prev_stream) {
3478
        cpi->mr_low_res_mv_avail = 0;
3479
      }
3480
    }
3481
    // This stream is not skipped (i.e., it's being encoded), so set this skip
3482
    // flag to 0. This is needed for the next stream (i.e., which is the next
3483
    // frame to be encoded).
3484
    low_res_frame_info->skip_encoding_prev_stream = 0;
3485
3486
    // On a key frame: For the lowest resolution, keep track of the key frame
3487
    // counter value. For the higher resolutions, reset the current video
3488
    // frame counter to that of the lowest resolution.
3489
    // This is done to the handle the case where we may stop/start encoding
3490
    // higher layer(s). The restart-encoding of higher layer is only signaled
3491
    // by a key frame for now.
3492
    // TODO (marpan): Add flag to indicate restart-encoding of higher layer.
3493
    if (cm->frame_type == KEY_FRAME) {
3494
      if (cpi->oxcf.mr_encoder_id) {
3495
        // If the initial starting value of the buffer level is zero (this can
3496
        // happen because we may have not started encoding this higher stream),
3497
        // then reset it to non-zero value based on |starting_buffer_level|.
3498
        if (cpi->common.current_video_frame == 0 && cpi->buffer_level == 0) {
3499
          unsigned int i;
3500
          cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
3501
          cpi->buffer_level = cpi->oxcf.starting_buffer_level;
3502
          for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
3503
            LAYER_CONTEXT *lc = &cpi->layer_context[i];
3504
            lc->bits_off_target = lc->starting_buffer_level;
3505
            lc->buffer_level = lc->starting_buffer_level;
3506
          }
3507
        }
3508
        cpi->common.current_video_frame =
3509
            low_res_frame_info->key_frame_counter_value;
3510
      } else {
3511
        low_res_frame_info->key_frame_counter_value =
3512
            cpi->common.current_video_frame;
3513
      }
3514
    }
3515
  }
3516
#endif
3517
3518
  // Find the reference frame closest to the current frame.
3519
117k
  cpi->closest_reference_frame = LAST_FRAME;
3520
117k
  if (cm->frame_type != KEY_FRAME) {
3521
100k
    int i;
3522
100k
    MV_REFERENCE_FRAME closest_ref = INTRA_FRAME;
3523
100k
    if (cpi->ref_frame_flags & VP8_LAST_FRAME) {
3524
100k
      closest_ref = LAST_FRAME;
3525
100k
    } else if (cpi->ref_frame_flags & VP8_GOLD_FRAME) {
3526
0
      closest_ref = GOLDEN_FRAME;
3527
0
    } else if (cpi->ref_frame_flags & VP8_ALTR_FRAME) {
3528
0
      closest_ref = ALTREF_FRAME;
3529
0
    }
3530
400k
    for (i = 1; i <= 3; ++i) {
3531
300k
      vpx_ref_frame_type_t ref_frame_type =
3532
300k
          (vpx_ref_frame_type_t)((i == 3) ? 4 : i);
3533
300k
      if (cpi->ref_frame_flags & ref_frame_type) {
3534
248k
        if ((cm->current_video_frame - cpi->current_ref_frames[i]) <
3535
248k
            (cm->current_video_frame - cpi->current_ref_frames[closest_ref])) {
3536
0
          closest_ref = i;
3537
0
        }
3538
248k
      }
3539
300k
    }
3540
100k
    cpi->closest_reference_frame = closest_ref;
3541
100k
  }
3542
3543
  /* Set various flags etc to special state if it is a key frame */
3544
117k
  if (cm->frame_type == KEY_FRAME) {
3545
17.4k
    int i;
3546
3547
    // Set the loop filter deltas and segmentation map update
3548
17.4k
    setup_features(cpi);
3549
3550
    /* The alternate reference frame cannot be active for a key frame */
3551
17.4k
    cpi->source_alt_ref_active = 0;
3552
3553
    /* Reset the RD threshold multipliers to default of * 1 (128) */
3554
366k
    for (i = 0; i < MAX_MODES; ++i) {
3555
349k
      cpi->mb.rd_thresh_mult[i] = 128;
3556
349k
    }
3557
3558
    // Reset the zero_last counter to 0 on key frame.
3559
17.4k
    memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
3560
17.4k
    memset(cpi->consec_zero_last_mvbias, 0,
3561
17.4k
           (cpi->common.mb_rows * cpi->common.mb_cols));
3562
17.4k
  }
3563
3564
#if 0
3565
    /* Experimental code for lagged compress and one pass
3566
     * Initialise one_pass GF frames stats
3567
     * Update stats used for GF selection
3568
     */
3569
    {
3570
        cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
3571
3572
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
3573
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
3574
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
3575
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
3576
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
3577
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
3578
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
3579
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
3580
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
3581
    }
3582
#endif
3583
3584
117k
  update_rd_ref_frame_probs(cpi);
3585
3586
117k
  if (vp8_check_drop_buffer(cpi)) {
3587
0
    return;
3588
0
  }
3589
3590
  /* Decide how big to make the frame */
3591
117k
  if (!vp8_pick_frame_size(cpi)) {
3592
/*TODO: 2 drop_frame and return code could be put together. */
3593
#if CONFIG_MULTI_RES_ENCODING
3594
    vp8_store_drop_frame_info(cpi);
3595
#endif
3596
0
    cm->current_video_frame++;
3597
0
    cpi->frames_since_key++;
3598
0
    cpi->ext_refresh_frame_flags_pending = 0;
3599
    // We advance the temporal pattern for dropped frames.
3600
0
    cpi->temporal_pattern_counter++;
3601
0
    return;
3602
0
  }
3603
3604
  /* Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
3605
   * This has a knock on effect on active best quality as well.
3606
   * For CBR if the buffer reaches its maximum level then we can no longer
3607
   * save up bits for later frames so we might as well use them up
3608
   * on the current frame.
3609
   */
3610
117k
  if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
3611
0
      (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) &&
3612
0
      cpi->buffered_mode) {
3613
    /* Max adjustment is 1/4 */
3614
0
    int Adjustment = cpi->active_worst_quality / 4;
3615
3616
0
    if (Adjustment) {
3617
0
      int buff_lvl_step;
3618
3619
0
      if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size) {
3620
0
        buff_lvl_step = (int)((cpi->oxcf.maximum_buffer_size -
3621
0
                               cpi->oxcf.optimal_buffer_level) /
3622
0
                              Adjustment);
3623
3624
0
        if (buff_lvl_step) {
3625
0
          Adjustment =
3626
0
              (int)((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) /
3627
0
                    buff_lvl_step);
3628
0
        } else {
3629
0
          Adjustment = 0;
3630
0
        }
3631
0
      }
3632
3633
0
      cpi->active_worst_quality -= Adjustment;
3634
3635
0
      if (cpi->active_worst_quality < cpi->active_best_quality) {
3636
0
        cpi->active_worst_quality = cpi->active_best_quality;
3637
0
      }
3638
0
    }
3639
0
  }
3640
3641
  /* Set an active best quality and if necessary active worst quality
3642
   * There is some odd behavior for one pass here that needs attention.
3643
   */
3644
117k
  if ((cpi->pass == 2) || (cpi->ni_frames > 150)) {
3645
11.2k
    vpx_clear_system_state();
3646
3647
11.2k
    Q = cpi->active_worst_quality;
3648
3649
11.2k
    if (cm->frame_type == KEY_FRAME) {
3650
240
      if (cpi->pass == 2) {
3651
0
        if (cpi->gfu_boost > 600) {
3652
0
          cpi->active_best_quality = kf_low_motion_minq[Q];
3653
0
        } else {
3654
0
          cpi->active_best_quality = kf_high_motion_minq[Q];
3655
0
        }
3656
3657
        /* Special case for key frames forced because we have reached
3658
         * the maximum key frame interval. Here force the Q to a range
3659
         * based on the ambient Q to reduce the risk of popping
3660
         */
3661
0
        if (cpi->this_key_frame_forced) {
3662
0
          if (cpi->active_best_quality > cpi->avg_frame_qindex * 7 / 8) {
3663
0
            cpi->active_best_quality = cpi->avg_frame_qindex * 7 / 8;
3664
0
          } else if (cpi->active_best_quality < (cpi->avg_frame_qindex >> 2)) {
3665
0
            cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
3666
0
          }
3667
0
        }
3668
0
      }
3669
      /* One pass more conservative */
3670
240
      else {
3671
240
        cpi->active_best_quality = kf_high_motion_minq[Q];
3672
240
      }
3673
240
    }
3674
3675
10.9k
    else if (cpi->oxcf.number_of_layers == 1 &&
3676
10.9k
             (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)) {
3677
      /* Use the lower of cpi->active_worst_quality and recent
3678
       * average Q as basis for GF/ARF Q limit unless last frame was
3679
       * a key frame.
3680
       */
3681
1.11k
      if ((cpi->frames_since_key > 1) &&
3682
1.11k
          (cpi->avg_frame_qindex < cpi->active_worst_quality)) {
3683
768
        Q = cpi->avg_frame_qindex;
3684
768
      }
3685
3686
      /* For constrained quality don't allow Q less than the cq level */
3687
1.11k
      if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3688
315
          (Q < cpi->cq_target_quality)) {
3689
118
        Q = cpi->cq_target_quality;
3690
118
      }
3691
3692
1.11k
      if (cpi->pass == 2) {
3693
0
        if (cpi->gfu_boost > 1000) {
3694
0
          cpi->active_best_quality = gf_low_motion_minq[Q];
3695
0
        } else if (cpi->gfu_boost < 400) {
3696
0
          cpi->active_best_quality = gf_high_motion_minq[Q];
3697
0
        } else {
3698
0
          cpi->active_best_quality = gf_mid_motion_minq[Q];
3699
0
        }
3700
3701
        /* Constrained quality use slightly lower active best. */
3702
0
        if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
3703
0
          cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
3704
0
        }
3705
0
      }
3706
      /* One pass more conservative */
3707
1.11k
      else {
3708
1.11k
        cpi->active_best_quality = gf_high_motion_minq[Q];
3709
1.11k
      }
3710
9.86k
    } else {
3711
9.86k
      cpi->active_best_quality = inter_minq[Q];
3712
3713
      /* For the constant/constrained quality mode we don't want
3714
       * q to fall below the cq level.
3715
       */
3716
9.86k
      if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
3717
3.10k
          (cpi->active_best_quality < cpi->cq_target_quality)) {
3718
        /* If we are strongly undershooting the target rate in the last
3719
         * frames then use the user passed in cq value not the auto
3720
         * cq value.
3721
         */
3722
1.57k
        if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth) {
3723
0
          cpi->active_best_quality = cpi->oxcf.cq_level;
3724
1.57k
        } else {
3725
1.57k
          cpi->active_best_quality = cpi->cq_target_quality;
3726
1.57k
        }
3727
1.57k
      }
3728
9.86k
    }
3729
3730
    /* If CBR and the buffer is as full then it is reasonable to allow
3731
     * higher quality on the frames to prevent bits just going to waste.
3732
     */
3733
11.2k
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
3734
      /* Note that the use of >= here elliminates the risk of a divide
3735
       * by 0 error in the else if clause
3736
       */
3737
0
      if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size) {
3738
0
        cpi->active_best_quality = cpi->best_quality;
3739
3740
0
      } else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level) {
3741
0
        int Fraction =
3742
0
            (int)(((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) /
3743
0
                  (cpi->oxcf.maximum_buffer_size -
3744
0
                   cpi->oxcf.optimal_buffer_level));
3745
0
        int min_qadjustment =
3746
0
            ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
3747
3748
0
        cpi->active_best_quality -= min_qadjustment;
3749
0
      }
3750
0
    }
3751
11.2k
  }
3752
  /* Make sure constrained quality mode limits are adhered to for the first
3753
   * few frames of one pass encodes
3754
   */
3755
106k
  else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
3756
17.7k
    if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
3757
14.3k
        cpi->common.refresh_alt_ref_frame) {
3758
3.40k
      cpi->active_best_quality = cpi->best_quality;
3759
14.3k
    } else if (cpi->active_best_quality < cpi->cq_target_quality) {
3760
13.1k
      cpi->active_best_quality = cpi->cq_target_quality;
3761
13.1k
    }
3762
17.7k
  }
3763
3764
  /* Clip the active best and worst quality values to limits */
3765
117k
  if (cpi->active_worst_quality > cpi->worst_quality) {
3766
0
    cpi->active_worst_quality = cpi->worst_quality;
3767
0
  }
3768
3769
117k
  if (cpi->active_best_quality < cpi->best_quality) {
3770
2.65k
    cpi->active_best_quality = cpi->best_quality;
3771
2.65k
  }
3772
3773
117k
  if (cpi->active_worst_quality < cpi->active_best_quality) {
3774
0
    cpi->active_worst_quality = cpi->active_best_quality;
3775
0
  }
3776
3777
  /* Determine initial Q to try */
3778
117k
  Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3779
3780
117k
#if !CONFIG_REALTIME_ONLY
3781
3782
  /* Set highest allowed value for Zbin over quant */
3783
117k
  if (cm->frame_type == KEY_FRAME) {
3784
17.4k
    zbin_oq_high = 0;
3785
100k
  } else if ((cpi->oxcf.number_of_layers == 1) &&
3786
100k
             ((cm->refresh_alt_ref_frame ||
3787
100k
               (cm->refresh_golden_frame && !cpi->source_alt_ref_active)))) {
3788
9.02k
    zbin_oq_high = 16;
3789
91.0k
  } else {
3790
91.0k
    zbin_oq_high = ZBIN_OQ_MAX;
3791
91.0k
  }
3792
117k
#endif
3793
3794
117k
  compute_skin_map(cpi);
3795
3796
  /* Setup background Q adjustment for error resilient mode.
3797
   * For multi-layer encodes only enable this for the base layer.
3798
   */
3799
117k
  if (cpi->cyclic_refresh_mode_enabled) {
3800
    // Special case for screen_content_mode with golden frame updates.
3801
0
    int disable_cr_gf =
3802
0
        (cpi->oxcf.screen_content_mode == 2 && cm->refresh_golden_frame);
3803
0
    if (cpi->current_layer == 0 && cpi->force_maxqp == 0 && !disable_cr_gf) {
3804
0
      cyclic_background_refresh(cpi, Q, 0);
3805
0
    } else {
3806
0
      disable_segmentation(cpi);
3807
0
    }
3808
0
  }
3809
3810
117k
  vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
3811
117k
                                &frame_over_shoot_limit);
3812
3813
117k
#if !CONFIG_REALTIME_ONLY
3814
  /* Limit Q range for the adaptive loop. */
3815
117k
  bottom_index = cpi->active_best_quality;
3816
117k
  top_index = cpi->active_worst_quality;
3817
117k
  q_low = cpi->active_best_quality;
3818
117k
  q_high = cpi->active_worst_quality;
3819
117k
#endif
3820
3821
117k
  vp8_save_coding_context(cpi);
3822
3823
117k
  scale_and_extend_source(cpi->un_scaled_source, cpi);
3824
3825
117k
#if CONFIG_TEMPORAL_DENOISING && CONFIG_POSTPROC
3826
  // Option to apply spatial blur under the aggressive or adaptive
3827
  // (temporal denoising) mode.
3828
117k
  if (cpi->oxcf.noise_sensitivity >= 3) {
3829
0
    if (cpi->denoiser.denoise_pars.spatial_blur != 0) {
3830
0
      vp8_de_noise(cm, cpi->Source, cpi->denoiser.denoise_pars.spatial_blur, 1);
3831
0
    }
3832
0
  }
3833
117k
#endif
3834
3835
#if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC && !(CONFIG_TEMPORAL_DENOISING)
3836
3837
  if (cpi->oxcf.noise_sensitivity > 0) {
3838
    unsigned char *src;
3839
    int l = 0;
3840
3841
    switch (cpi->oxcf.noise_sensitivity) {
3842
      case 1: l = 20; break;
3843
      case 2: l = 40; break;
3844
      case 3: l = 60; break;
3845
      case 4: l = 80; break;
3846
      case 5: l = 100; break;
3847
      case 6: l = 150; break;
3848
    }
3849
3850
    if (cm->frame_type == KEY_FRAME) {
3851
      vp8_de_noise(cm, cpi->Source, l, 1);
3852
    } else {
3853
      vp8_de_noise(cm, cpi->Source, l, 1);
3854
3855
      src = cpi->Source->y_buffer;
3856
3857
      if (cpi->Source->y_stride < 0) {
3858
        src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
3859
      }
3860
    }
3861
  }
3862
3863
#endif
3864
3865
#ifdef OUTPUT_YUV_SRC
3866
  vpx_write_yuv_frame(yuv_file, cpi->Source);
3867
#endif
3868
3869
151k
  do {
3870
151k
    vpx_clear_system_state();
3871
3872
151k
    vp8_set_quantizer(cpi, Q);
3873
3874
    /* setup skip prob for costing in mode/mv decision */
3875
151k
    if (cpi->common.mb_no_coeff_skip) {
3876
151k
      cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
3877
3878
151k
      if (cm->frame_type != KEY_FRAME) {
3879
117k
        if (cpi->common.refresh_alt_ref_frame) {
3880
0
          if (cpi->last_skip_false_probs[2] != 0) {
3881
0
            cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3882
0
          }
3883
3884
          /*
3885
                              if(cpi->last_skip_false_probs[2]!=0 && abs(Q-
3886
             cpi->last_skip_probs_q[2])<=16 )
3887
             cpi->prob_skip_false = cpi->last_skip_false_probs[2];
3888
                              else if (cpi->last_skip_false_probs[2]!=0)
3889
             cpi->prob_skip_false = (cpi->last_skip_false_probs[2]  +
3890
             cpi->prob_skip_false ) / 2;
3891
             */
3892
117k
        } else if (cpi->common.refresh_golden_frame) {
3893
11.5k
          if (cpi->last_skip_false_probs[1] != 0) {
3894
8.97k
            cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3895
8.97k
          }
3896
3897
          /*
3898
                              if(cpi->last_skip_false_probs[1]!=0 && abs(Q-
3899
             cpi->last_skip_probs_q[1])<=16 )
3900
             cpi->prob_skip_false = cpi->last_skip_false_probs[1];
3901
                              else if (cpi->last_skip_false_probs[1]!=0)
3902
             cpi->prob_skip_false = (cpi->last_skip_false_probs[1]  +
3903
             cpi->prob_skip_false ) / 2;
3904
             */
3905
105k
        } else {
3906
105k
          if (cpi->last_skip_false_probs[0] != 0) {
3907
95.6k
            cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3908
95.6k
          }
3909
3910
          /*
3911
          if(cpi->last_skip_false_probs[0]!=0 && abs(Q-
3912
          cpi->last_skip_probs_q[0])<=16 )
3913
              cpi->prob_skip_false = cpi->last_skip_false_probs[0];
3914
          else if(cpi->last_skip_false_probs[0]!=0)
3915
              cpi->prob_skip_false = (cpi->last_skip_false_probs[0]  +
3916
          cpi->prob_skip_false ) / 2;
3917
              */
3918
105k
        }
3919
3920
        /* as this is for cost estimate, let's make sure it does not
3921
         * go extreme eitehr way
3922
         */
3923
117k
        if (cpi->prob_skip_false < 5) cpi->prob_skip_false = 5;
3924
3925
117k
        if (cpi->prob_skip_false > 250) cpi->prob_skip_false = 250;
3926
3927
117k
        if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref) {
3928
0
          cpi->prob_skip_false = 1;
3929
0
        }
3930
117k
      }
3931
3932
#if 0
3933
3934
            if (cpi->pass != 1)
3935
            {
3936
                FILE *f = fopen("skip.stt", "a");
3937
                fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
3938
                fclose(f);
3939
            }
3940
3941
#endif
3942
151k
    }
3943
3944
151k
    if (cm->frame_type == KEY_FRAME) {
3945
34.8k
      if (resize_key_frame(cpi)) {
3946
        /* If the frame size has changed, need to reset Q, quantizer,
3947
         * and background refresh.
3948
         */
3949
0
        Q = vp8_regulate_q(cpi, cpi->this_frame_target);
3950
0
        if (cpi->cyclic_refresh_mode_enabled) {
3951
0
          if (cpi->current_layer == 0) {
3952
0
            cyclic_background_refresh(cpi, Q, 0);
3953
0
          } else {
3954
0
            disable_segmentation(cpi);
3955
0
          }
3956
0
        }
3957
        // Reset the zero_last counter to 0 on key frame.
3958
0
        memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
3959
0
        memset(cpi->consec_zero_last_mvbias, 0,
3960
0
               (cpi->common.mb_rows * cpi->common.mb_cols));
3961
0
        vp8_set_quantizer(cpi, Q);
3962
0
      }
3963
3964
34.8k
      vp8_setup_key_frame(cpi);
3965
34.8k
    }
3966
3967
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
3968
    {
3969
      if (cpi->oxcf.error_resilient_mode) cm->refresh_entropy_probs = 0;
3970
3971
      if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
3972
        if (cm->frame_type == KEY_FRAME) cm->refresh_entropy_probs = 1;
3973
      }
3974
3975
      if (cm->refresh_entropy_probs == 0) {
3976
        /* save a copy for later refresh */
3977
        cm->lfc = cm->fc;
3978
      }
3979
3980
      vp8_update_coef_context(cpi);
3981
3982
      vp8_update_coef_probs(cpi);
3983
3984
      /* transform / motion compensation build reconstruction frame
3985
       * +pack coef partitions
3986
       */
3987
      vp8_encode_frame(cpi);
3988
3989
      /* cpi->projected_frame_size is not needed for RT mode */
3990
    }
3991
#else
3992
    /* transform / motion compensation build reconstruction frame */
3993
151k
    vp8_encode_frame(cpi);
3994
3995
151k
    if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
3996
0
        cpi->rt_drop_recode_on_overshoot == 1) {
3997
0
      if (vp8_drop_encodedframe_overshoot(cpi, Q)) {
3998
0
        vpx_clear_system_state();
3999
0
        return;
4000
0
      }
4001
0
      if (cm->frame_type != KEY_FRAME)
4002
0
        cpi->last_pred_err_mb =
4003
0
            (int)(cpi->mb.prediction_error / cpi->common.MBs);
4004
0
    }
4005
4006
151k
    cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
4007
151k
    cpi->projected_frame_size =
4008
151k
        (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
4009
151k
#endif
4010
151k
    vpx_clear_system_state();
4011
4012
    /* Test to see if the stats generated for this frame indicate that
4013
     * we should have coded a key frame (assuming that we didn't)!
4014
     */
4015
4016
151k
    if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME &&
4017
117k
        cpi->compressor_speed != 2) {
4018
63.4k
#if !CONFIG_REALTIME_ONLY
4019
63.4k
      if (decide_key_frame(cpi)) {
4020
        /* Reset all our sizing numbers and recode */
4021
3.39k
        cm->frame_type = KEY_FRAME;
4022
4023
3.39k
        vp8_pick_frame_size(cpi);
4024
4025
        /* Clear the Alt reference frame active flag when we have
4026
         * a key frame
4027
         */
4028
3.39k
        cpi->source_alt_ref_active = 0;
4029
4030
        // Set the loop filter deltas and segmentation map update
4031
3.39k
        setup_features(cpi);
4032
4033
3.39k
        vp8_restore_coding_context(cpi);
4034
4035
3.39k
        Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4036
4037
3.39k
        vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
4038
3.39k
                                      &frame_over_shoot_limit);
4039
4040
        /* Limit Q range for the adaptive loop. */
4041
3.39k
        bottom_index = cpi->active_best_quality;
4042
3.39k
        top_index = cpi->active_worst_quality;
4043
3.39k
        q_low = cpi->active_best_quality;
4044
3.39k
        q_high = cpi->active_worst_quality;
4045
4046
3.39k
        Loop = 1;
4047
4048
3.39k
        continue;
4049
3.39k
      }
4050
63.4k
#endif
4051
63.4k
    }
4052
4053
148k
    vpx_clear_system_state();
4054
4055
148k
    if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
4056
4057
    /* Are we are overshooting and up against the limit of active max Q. */
4058
148k
    if (!cpi->rt_always_update_correction_factor &&
4059
148k
        ((cpi->pass != 2) ||
4060
0
         (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
4061
148k
        (Q == cpi->active_worst_quality) &&
4062
35.0k
        (cpi->active_worst_quality < cpi->worst_quality) &&
4063
2.77k
        (cpi->projected_frame_size > frame_over_shoot_limit)) {
4064
679
      int over_size_percent =
4065
679
          ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) /
4066
679
          frame_over_shoot_limit;
4067
4068
      /* If so is there any scope for relaxing it */
4069
30.6k
      while ((cpi->active_worst_quality < cpi->worst_quality) &&
4070
30.4k
             (over_size_percent > 0)) {
4071
29.9k
        cpi->active_worst_quality++;
4072
        /* Assume 1 qstep = about 4% on frame size. */
4073
29.9k
        over_size_percent = (int)(over_size_percent * 0.96);
4074
29.9k
      }
4075
679
#if !CONFIG_REALTIME_ONLY
4076
679
      top_index = cpi->active_worst_quality;
4077
679
#endif  // !CONFIG_REALTIME_ONLY
4078
      /* If we have updated the active max Q do not call
4079
       * vp8_update_rate_correction_factors() this loop.
4080
       */
4081
679
      active_worst_qchanged = 1;
4082
147k
    } else {
4083
147k
      active_worst_qchanged = 0;
4084
147k
    }
4085
4086
#if CONFIG_REALTIME_ONLY
4087
    Loop = 0;
4088
#else
4089
    /* Special case handling for forced key frames */
4090
148k
    if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
4091
0
      int last_q = Q;
4092
0
      int kf_err = vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
4093
4094
      /* The key frame is not good enough */
4095
0
      if (kf_err > ((cpi->ambient_err * 7) >> 3)) {
4096
        /* Lower q_high */
4097
0
        q_high = (Q > q_low) ? (Q - 1) : q_low;
4098
4099
        /* Adjust Q */
4100
0
        Q = (q_high + q_low) >> 1;
4101
0
      }
4102
      /* The key frame is much better than the previous frame */
4103
0
      else if (kf_err < (cpi->ambient_err >> 1)) {
4104
        /* Raise q_low */
4105
0
        q_low = (Q < q_high) ? (Q + 1) : q_high;
4106
4107
        /* Adjust Q */
4108
0
        Q = (q_high + q_low + 1) >> 1;
4109
0
      }
4110
4111
      /* Clamp Q to upper and lower limits: */
4112
0
      if (Q > q_high) {
4113
0
        Q = q_high;
4114
0
      } else if (Q < q_low) {
4115
0
        Q = q_low;
4116
0
      }
4117
4118
0
      Loop = Q != last_q;
4119
0
    }
4120
4121
    /* Is the projected frame size out of range and are we allowed
4122
     * to attempt to recode.
4123
     */
4124
148k
    else if (recode_loop_test(cpi, frame_over_shoot_limit,
4125
148k
                              frame_under_shoot_limit, Q, top_index,
4126
148k
                              bottom_index)) {
4127
32.6k
      int last_q = Q;
4128
32.6k
      int Retries = 0;
4129
4130
      /* Frame size out of permitted range. Update correction factor
4131
       * & compute new Q to try...
4132
       */
4133
4134
      /* Frame is too large */
4135
32.6k
      if (cpi->projected_frame_size > cpi->this_frame_target) {
4136
        /* Raise Qlow as to at least the current value */
4137
18.6k
        q_low = (Q < q_high) ? (Q + 1) : q_high;
4138
4139
        /* If we are using over quant do the same for zbin_oq_low */
4140
18.6k
        if (cpi->mb.zbin_over_quant > 0) {
4141
1
          zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
4142
1
                            ? (cpi->mb.zbin_over_quant + 1)
4143
1
                            : zbin_oq_high;
4144
1
        }
4145
4146
18.6k
        if (undershoot_seen) {
4147
          /* Update rate_correction_factor unless
4148
           * cpi->active_worst_quality has changed.
4149
           */
4150
1.39k
          if (!active_worst_qchanged) {
4151
1.39k
            vp8_update_rate_correction_factors(cpi, 1);
4152
1.39k
          }
4153
4154
1.39k
          Q = (q_high + q_low + 1) / 2;
4155
4156
          /* Adjust cpi->zbin_over_quant (only allowed when Q
4157
           * is max)
4158
           */
4159
1.39k
          if (Q < MAXQ) {
4160
1.38k
            cpi->mb.zbin_over_quant = 0;
4161
1.38k
          } else {
4162
3
            zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
4163
3
                              ? (cpi->mb.zbin_over_quant + 1)
4164
3
                              : zbin_oq_high;
4165
3
            cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4166
3
          }
4167
17.2k
        } else {
4168
          /* Update rate_correction_factor unless
4169
           * cpi->active_worst_quality has changed.
4170
           */
4171
17.2k
          if (!active_worst_qchanged) {
4172
16.6k
            vp8_update_rate_correction_factors(cpi, 0);
4173
16.6k
          }
4174
4175
17.2k
          Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4176
4177
17.3k
          while (((Q < q_low) || (cpi->mb.zbin_over_quant < zbin_oq_low)) &&
4178
42
                 (Retries < 10)) {
4179
42
            vp8_update_rate_correction_factors(cpi, 0);
4180
42
            Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4181
42
            Retries++;
4182
42
          }
4183
17.2k
        }
4184
4185
18.6k
        overshoot_seen = 1;
4186
18.6k
      }
4187
      /* Frame is too small */
4188
13.9k
      else {
4189
13.9k
        if (cpi->mb.zbin_over_quant == 0) {
4190
          /* Lower q_high if not using over quant */
4191
12.8k
          q_high = (Q > q_low) ? (Q - 1) : q_low;
4192
12.8k
        } else {
4193
          /* else lower zbin_oq_high */
4194
1.05k
          zbin_oq_high = (cpi->mb.zbin_over_quant > zbin_oq_low)
4195
1.05k
                             ? (cpi->mb.zbin_over_quant - 1)
4196
1.05k
                             : zbin_oq_low;
4197
1.05k
        }
4198
4199
13.9k
        if (overshoot_seen) {
4200
          /* Update rate_correction_factor unless
4201
           * cpi->active_worst_quality has changed.
4202
           */
4203
913
          if (!active_worst_qchanged) {
4204
913
            vp8_update_rate_correction_factors(cpi, 1);
4205
913
          }
4206
4207
913
          Q = (q_high + q_low) / 2;
4208
4209
          /* Adjust cpi->zbin_over_quant (only allowed when Q
4210
           * is max)
4211
           */
4212
913
          if (Q < MAXQ) {
4213
912
            cpi->mb.zbin_over_quant = 0;
4214
912
          } else {
4215
1
            cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
4216
1
          }
4217
13.0k
        } else {
4218
          /* Update rate_correction_factor unless
4219
           * cpi->active_worst_quality has changed.
4220
           */
4221
13.0k
          if (!active_worst_qchanged) {
4222
13.0k
            vp8_update_rate_correction_factors(cpi, 0);
4223
13.0k
          }
4224
4225
13.0k
          Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4226
4227
          /* Special case reset for qlow for constrained quality.
4228
           * This should only trigger where there is very substantial
4229
           * undershoot on a frame and the auto cq level is above
4230
           * the user passsed in value.
4231
           */
4232
13.0k
          if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
4233
2.89k
              (Q < q_low)) {
4234
0
            q_low = Q;
4235
0
          }
4236
4237
17.0k
          while (((Q > q_high) || (cpi->mb.zbin_over_quant > zbin_oq_high)) &&
4238
4.41k
                 (Retries < 10)) {
4239
4.05k
            vp8_update_rate_correction_factors(cpi, 0);
4240
4.05k
            Q = vp8_regulate_q(cpi, cpi->this_frame_target);
4241
4.05k
            Retries++;
4242
4.05k
          }
4243
13.0k
        }
4244
4245
13.9k
        undershoot_seen = 1;
4246
13.9k
      }
4247
4248
      /* Clamp Q to upper and lower limits: */
4249
32.6k
      if (Q > q_high) {
4250
689
        Q = q_high;
4251
31.9k
      } else if (Q < q_low) {
4252
0
        Q = q_low;
4253
0
      }
4254
4255
      /* Clamp cpi->zbin_over_quant */
4256
32.6k
      cpi->mb.zbin_over_quant =
4257
32.6k
          (cpi->mb.zbin_over_quant < zbin_oq_low)    ? zbin_oq_low
4258
32.6k
          : (cpi->mb.zbin_over_quant > zbin_oq_high) ? zbin_oq_high
4259
32.6k
                                                     : cpi->mb.zbin_over_quant;
4260
4261
32.6k
      Loop = Q != last_q;
4262
115k
    } else {
4263
115k
      Loop = 0;
4264
115k
    }
4265
148k
#endif  // CONFIG_REALTIME_ONLY
4266
4267
148k
    if (cpi->is_src_frame_alt_ref) Loop = 0;
4268
4269
148k
    if (Loop == 1) {
4270
30.9k
      vp8_restore_coding_context(cpi);
4271
#if CONFIG_INTERNAL_STATS
4272
      cpi->tot_recode_hits++;
4273
#endif
4274
30.9k
    }
4275
151k
  } while (Loop == 1);
4276
4277
#if defined(DROP_UNCODED_FRAMES)
4278
  /* if there are no coded macroblocks at all drop this frame */
4279
  if (cpi->common.MBs == cpi->mb.skip_true_count &&
4280
      (cpi->drop_frame_count & 7) != 7 && cm->frame_type != KEY_FRAME) {
4281
    cpi->common.current_video_frame++;
4282
    cpi->frames_since_key++;
4283
    cpi->drop_frame_count++;
4284
    cpi->ext_refresh_frame_flags_pending = 0;
4285
    // We advance the temporal pattern for dropped frames.
4286
    cpi->temporal_pattern_counter++;
4287
    return;
4288
  }
4289
  cpi->drop_frame_count = 0;
4290
#endif
4291
4292
#if 0
4293
    /* Experimental code for lagged and one pass
4294
     * Update stats used for one pass GF selection
4295
     */
4296
    {
4297
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
4298
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
4299
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
4300
    }
4301
#endif
4302
4303
  /* Special case code to reduce pulsing when key frames are forced at a
4304
   * fixed interval. Note the reconstruction error if it is the frame before
4305
   * the force key frame
4306
   */
4307
117k
  if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
4308
0
    cpi->ambient_err =
4309
0
        vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
4310
0
  }
4311
4312
/* This frame's MVs are saved and will be used in next frame's MV predictor.
4313
 * Last frame has one more line(add to bottom) and one more column(add to
4314
 * right) than cm->mip. The edge elements are initialized to 0.
4315
 */
4316
#if CONFIG_MULTI_RES_ENCODING
4317
  if (!cpi->oxcf.mr_encoder_id && cm->show_frame)
4318
#else
4319
117k
  if (cm->show_frame) /* do not save for altref frame */
4320
117k
#endif
4321
117k
  {
4322
117k
    int mb_row;
4323
117k
    int mb_col;
4324
    /* Point to beginning of allocated MODE_INFO arrays. */
4325
117k
    MODE_INFO *tmp = cm->mip;
4326
4327
117k
    if (cm->frame_type != KEY_FRAME) {
4328
433k
      for (mb_row = 0; mb_row < cm->mb_rows + 1; ++mb_row) {
4329
2.22M
        for (mb_col = 0; mb_col < cm->mb_cols + 1; ++mb_col) {
4330
1.88M
          if (tmp->mbmi.ref_frame != INTRA_FRAME) {
4331
568k
            cpi->lfmv[mb_col + mb_row * (cm->mode_info_stride + 1)].as_int =
4332
568k
                tmp->mbmi.mv.as_int;
4333
568k
          }
4334
4335
1.88M
          cpi->lf_ref_frame_sign_bias[mb_col +
4336
1.88M
                                      mb_row * (cm->mode_info_stride + 1)] =
4337
1.88M
              cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
4338
1.88M
          cpi->lf_ref_frame[mb_col + mb_row * (cm->mode_info_stride + 1)] =
4339
1.88M
              tmp->mbmi.ref_frame;
4340
1.88M
          tmp++;
4341
1.88M
        }
4342
337k
      }
4343
96.6k
    }
4344
117k
  }
4345
4346
  /* Count last ref frame 0,0 usage on current encoded frame. */
4347
117k
  {
4348
117k
    int mb_row;
4349
117k
    int mb_col;
4350
    /* Point to beginning of MODE_INFO arrays. */
4351
117k
    MODE_INFO *tmp = cm->mi;
4352
4353
117k
    cpi->zeromv_count = 0;
4354
4355
117k
    if (cm->frame_type != KEY_FRAME) {
4356
337k
      for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
4357
1.43M
        for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
4358
1.19M
          if (tmp->mbmi.mode == ZEROMV && tmp->mbmi.ref_frame == LAST_FRAME) {
4359
134k
            cpi->zeromv_count++;
4360
134k
          }
4361
1.19M
          tmp++;
4362
1.19M
        }
4363
240k
        tmp++;
4364
240k
      }
4365
96.6k
    }
4366
117k
  }
4367
4368
#if CONFIG_MULTI_RES_ENCODING
4369
  vp8_cal_dissimilarity(cpi);
4370
#endif
4371
4372
  /* Update the GF usage maps.
4373
   * This is done after completing the compression of a frame when all
4374
   * modes etc. are finalized but before loop filter
4375
   */
4376
117k
  if (cpi->oxcf.number_of_layers == 1) {
4377
117k
    vp8_update_gf_usage_maps(cpi, cm, &cpi->mb);
4378
117k
  }
4379
4380
117k
  if (cm->frame_type == KEY_FRAME) cm->refresh_last_frame = 1;
4381
4382
#if 0
4383
    {
4384
        FILE *f = fopen("gfactive.stt", "a");
4385
        fprintf(f, "%8d %8d %8d %8d %8d\n", cm->current_video_frame, (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols), cpi->this_iiratio, cpi->next_iiratio, cm->refresh_golden_frame);
4386
        fclose(f);
4387
    }
4388
#endif
4389
4390
  /* For inter frames the current default behavior is that when
4391
   * cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
4392
   * This is purely an encoder decision at present.
4393
   * Avoid this behavior when refresh flags are set by the user.
4394
   */
4395
117k
  if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame &&
4396
29.5k
      !cpi->ext_refresh_frame_flags_pending) {
4397
29.5k
    cm->copy_buffer_to_arf = 2;
4398
87.9k
  } else {
4399
87.9k
    cm->copy_buffer_to_arf = 0;
4400
87.9k
  }
4401
4402
117k
  cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
4403
4404
117k
#if CONFIG_TEMPORAL_DENOISING
4405
  // Get some measure of the amount of noise, by measuring the (partial) mse
4406
  // between source and denoised buffer, for y channel. Partial refers to
4407
  // computing the sse for a sub-sample of the frame (i.e., skip x blocks along
4408
  // row/column),
4409
  // and only for blocks in that set that are consecutive ZEROMV_LAST mode.
4410
  // Do this every ~8 frames, to further reduce complexity.
4411
  // TODO(marpan): Keep this for now for the case cpi->oxcf.noise_sensitivity <
4412
  // 4,
4413
  // should be removed in favor of the process_denoiser_mode_change() function
4414
  // below.
4415
117k
  if (cpi->oxcf.noise_sensitivity > 0 && cpi->oxcf.noise_sensitivity < 4 &&
4416
0
      !cpi->oxcf.screen_content_mode && cpi->frames_since_key % 8 == 0 &&
4417
0
      cm->frame_type != KEY_FRAME) {
4418
0
    cpi->mse_source_denoised = measure_square_diff_partial(
4419
0
        &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi->Source, cpi);
4420
0
  }
4421
4422
  // For the adaptive denoising mode (noise_sensitivity == 4), sample the mse
4423
  // of source diff (between current and previous frame), and determine if we
4424
  // should switch the denoiser mode. Sampling refers to computing the mse for
4425
  // a sub-sample of the frame (i.e., skip x blocks along row/column), and
4426
  // only for blocks in that set that have used ZEROMV LAST, along with some
4427
  // constraint on the sum diff between blocks. This process is called every
4428
  // ~8 frames, to further reduce complexity.
4429
117k
  if (cpi->oxcf.noise_sensitivity == 4 && !cpi->oxcf.screen_content_mode &&
4430
0
      cpi->frames_since_key % 8 == 0 && cm->frame_type != KEY_FRAME) {
4431
0
    process_denoiser_mode_change(cpi);
4432
0
  }
4433
117k
#endif
4434
4435
#ifdef OUTPUT_YUV_SKINMAP
4436
  if (cpi->common.current_video_frame > 1) {
4437
    vp8_compute_skin_map(cpi, yuv_skinmap_file);
4438
  }
4439
#endif
4440
4441
117k
#if CONFIG_MULTITHREAD
4442
117k
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
4443
    /* start loopfilter in separate thread */
4444
0
    vp8_sem_post(&cpi->h_event_start_lpf);
4445
0
    cpi->b_lpf_running = 1;
4446
    /* wait for the filter_level to be picked so that we can continue with
4447
     * stream packing */
4448
0
    vp8_sem_wait(&cpi->h_event_end_lpf);
4449
0
  } else
4450
117k
#endif
4451
117k
  {
4452
117k
    vp8_loopfilter_frame(cpi, cm);
4453
117k
  }
4454
4455
117k
  update_reference_frames(cpi);
4456
4457
#ifdef OUTPUT_YUV_DENOISED
4458
  vpx_write_yuv_frame(yuv_denoised_file,
4459
                      &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
4460
#endif
4461
4462
117k
#if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
4463
117k
  if (cpi->oxcf.error_resilient_mode) {
4464
0
    cm->refresh_entropy_probs = 0;
4465
0
  }
4466
117k
#endif
4467
4468
  /* build the bitstream */
4469
117k
  vp8_pack_bitstream(cpi, dest, dest_end, size);
4470
4471
  /* Move storing frame_type out of the above loop since it is also
4472
   * needed in motion search besides loopfilter */
4473
117k
  cm->last_frame_type = cm->frame_type;
4474
4475
  /* Update rate control heuristics */
4476
117k
  cpi->total_byte_count += (*size);
4477
117k
  cpi->projected_frame_size = (int)(*size) << 3;
4478
4479
117k
  if (cpi->oxcf.number_of_layers > 1) {
4480
0
    unsigned int i;
4481
0
    for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
4482
0
      cpi->layer_context[i].total_byte_count += (*size);
4483
0
    }
4484
0
  }
4485
4486
117k
  if (!active_worst_qchanged) vp8_update_rate_correction_factors(cpi, 2);
4487
4488
117k
  cpi->last_q[cm->frame_type] = cm->base_qindex;
4489
4490
117k
  if (cm->frame_type == KEY_FRAME) {
4491
20.8k
    vp8_adjust_key_frame_context(cpi);
4492
20.8k
  }
4493
4494
  /* Keep a record of ambient average Q. */
4495
117k
  if (cm->frame_type != KEY_FRAME) {
4496
96.6k
    cpi->avg_frame_qindex =
4497
96.6k
        (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
4498
96.6k
  }
4499
4500
  /* Keep a record from which we can calculate the average Q excluding
4501
   * GF updates and key frames
4502
   */
4503
117k
  if ((cm->frame_type != KEY_FRAME) &&
4504
96.6k
      ((cpi->oxcf.number_of_layers > 1) ||
4505
96.6k
       (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame))) {
4506
87.9k
    cpi->ni_frames++;
4507
4508
    /* Calculate the average Q for normal inter frames (not key or GFU
4509
     * frames).
4510
     */
4511
87.9k
    if (cpi->pass == 2) {
4512
0
      cpi->ni_tot_qi += Q;
4513
0
      cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4514
87.9k
    } else {
4515
      /* Damp value for first few frames */
4516
87.9k
      if (cpi->ni_frames > 150) {
4517
9.79k
        cpi->ni_tot_qi += Q;
4518
9.79k
        cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
4519
9.79k
      }
4520
      /* For one pass, early in the clip ... average the current frame Q
4521
       * value with the worstq entered by the user as a dampening measure
4522
       */
4523
78.1k
      else {
4524
78.1k
        cpi->ni_tot_qi += Q;
4525
78.1k
        cpi->ni_av_qi =
4526
78.1k
            ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
4527
78.1k
      }
4528
4529
      /* If the average Q is higher than what was used in the last
4530
       * frame (after going through the recode loop to keep the frame
4531
       * size within range) then use the last frame value - 1. The -1
4532
       * is designed to stop Q and hence the data rate, from
4533
       * progressively falling away during difficult sections, but at
4534
       * the same time reduce the number of iterations around the
4535
       * recode loop.
4536
       */
4537
87.9k
      if (Q > cpi->ni_av_qi) cpi->ni_av_qi = Q - 1;
4538
87.9k
    }
4539
87.9k
  }
4540
4541
  /* Update the buffer level variable. */
4542
  /* Non-viewable frames are a special case and are treated as pure overhead. */
4543
117k
  if (!cm->show_frame) {
4544
0
    cpi->bits_off_target -= cpi->projected_frame_size;
4545
117k
  } else {
4546
117k
    cpi->bits_off_target +=
4547
117k
        cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
4548
117k
  }
4549
4550
  /* Clip the buffer level to the maximum specified buffer size */
4551
117k
  if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
4552
8.81k
    cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
4553
8.81k
  }
4554
4555
  // Don't let the buffer level go below some threshold, given here
4556
  // by -|maximum_buffer_size|. For now we only do this for
4557
  // screen content input.
4558
117k
  if (cpi->oxcf.screen_content_mode &&
4559
0
      cpi->bits_off_target < -cpi->oxcf.maximum_buffer_size) {
4560
0
    cpi->bits_off_target = -cpi->oxcf.maximum_buffer_size;
4561
0
  }
4562
4563
  /* Rolling monitors of whether we are over or underspending used to
4564
   * help regulate min and Max Q in two pass.
4565
   */
4566
117k
  cpi->rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
4567
117k
      (int64_t)cpi->rolling_target_bits * 3 + cpi->this_frame_target, 2);
4568
117k
  cpi->rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
4569
117k
      (int64_t)cpi->rolling_actual_bits * 3 + cpi->projected_frame_size, 2);
4570
117k
  cpi->long_rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
4571
117k
      (int64_t)cpi->long_rolling_target_bits * 31 + cpi->this_frame_target, 5);
4572
117k
  cpi->long_rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
4573
117k
      (int64_t)cpi->long_rolling_actual_bits * 31 + cpi->projected_frame_size,
4574
117k
      5);
4575
4576
  /* Actual bits spent */
4577
117k
  cpi->total_actual_bits += cpi->projected_frame_size;
4578
4579
#if 0 && CONFIG_INTERNAL_STATS
4580
  /* Debug stats */
4581
  cpi->total_target_vs_actual +=
4582
      (cpi->this_frame_target - cpi->projected_frame_size);
4583
#endif
4584
4585
117k
  cpi->buffer_level = cpi->bits_off_target;
4586
4587
  /* Propagate values to higher temporal layers */
4588
117k
  if (cpi->oxcf.number_of_layers > 1) {
4589
0
    unsigned int i;
4590
4591
0
    for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
4592
0
      LAYER_CONTEXT *lc = &cpi->layer_context[i];
4593
0
      int bits_off_for_this_layer = (int)round(
4594
0
          lc->target_bandwidth / lc->framerate - cpi->projected_frame_size);
4595
4596
0
      lc->bits_off_target += bits_off_for_this_layer;
4597
4598
      /* Clip buffer level to maximum buffer size for the layer */
4599
0
      if (lc->bits_off_target > lc->maximum_buffer_size) {
4600
0
        lc->bits_off_target = lc->maximum_buffer_size;
4601
0
      }
4602
4603
0
      lc->total_actual_bits += cpi->projected_frame_size;
4604
0
      lc->total_target_vs_actual += bits_off_for_this_layer;
4605
0
      lc->buffer_level = lc->bits_off_target;
4606
0
    }
4607
0
  }
4608
4609
  /* Update bits left to the kf and gf groups to account for overshoot
4610
   * or undershoot on these frames
4611
   */
4612
117k
  if (cm->frame_type == KEY_FRAME) {
4613
20.8k
    cpi->twopass.kf_group_bits +=
4614
20.8k
        cpi->this_frame_target - cpi->projected_frame_size;
4615
4616
20.8k
    if (cpi->twopass.kf_group_bits < 0) cpi->twopass.kf_group_bits = 0;
4617
96.6k
  } else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame) {
4618
8.70k
    cpi->twopass.gf_group_bits +=
4619
8.70k
        cpi->this_frame_target - cpi->projected_frame_size;
4620
4621
8.70k
    if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
4622
8.70k
  }
4623
4624
117k
  if (cm->frame_type != KEY_FRAME) {
4625
96.6k
    if (cpi->common.refresh_alt_ref_frame) {
4626
0
      cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
4627
0
      cpi->last_skip_probs_q[2] = cm->base_qindex;
4628
96.6k
    } else if (cpi->common.refresh_golden_frame) {
4629
8.70k
      cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
4630
8.70k
      cpi->last_skip_probs_q[1] = cm->base_qindex;
4631
87.9k
    } else {
4632
87.9k
      cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
4633
87.9k
      cpi->last_skip_probs_q[0] = cm->base_qindex;
4634
4635
      /* update the baseline */
4636
87.9k
      cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
4637
87.9k
    }
4638
96.6k
  }
4639
4640
#if 0 && CONFIG_INTERNAL_STATS
4641
    {
4642
        FILE *f = fopen("tmp.stt", "a");
4643
4644
        vpx_clear_system_state();
4645
4646
        if (cpi->twopass.total_left_stats.coded_error != 0.0)
4647
            fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
4648
                       "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
4649
                       "%8.2lf %"PRId64" %10.3lf %10"PRId64" %8d\n",
4650
                       cpi->common.current_video_frame, cpi->this_frame_target,
4651
                       cpi->projected_frame_size,
4652
                       (cpi->projected_frame_size - cpi->this_frame_target),
4653
                       cpi->total_target_vs_actual,
4654
                       cpi->buffer_level,
4655
                       (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4656
                       cpi->total_actual_bits, cm->base_qindex,
4657
                       cpi->active_best_quality, cpi->active_worst_quality,
4658
                       cpi->ni_av_qi, cpi->cq_target_quality,
4659
                       cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4660
                       cm->frame_type, cpi->gfu_boost,
4661
                       cpi->twopass.est_max_qcorrection_factor,
4662
                       cpi->twopass.bits_left,
4663
                       cpi->twopass.total_left_stats.coded_error,
4664
                       (double)cpi->twopass.bits_left /
4665
                           cpi->twopass.total_left_stats.coded_error,
4666
                       cpi->tot_recode_hits);
4667
        else
4668
            fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
4669
                       "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
4670
                       "%8.2lf %"PRId64" %10.3lf %8d\n",
4671
                       cpi->common.current_video_frame, cpi->this_frame_target,
4672
                       cpi->projected_frame_size,
4673
                       (cpi->projected_frame_size - cpi->this_frame_target),
4674
                       cpi->total_target_vs_actual,
4675
                       cpi->buffer_level,
4676
                       (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
4677
                       cpi->total_actual_bits, cm->base_qindex,
4678
                       cpi->active_best_quality, cpi->active_worst_quality,
4679
                       cpi->ni_av_qi, cpi->cq_target_quality,
4680
                       cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
4681
                       cm->frame_type, cpi->gfu_boost,
4682
                       cpi->twopass.est_max_qcorrection_factor,
4683
                       cpi->twopass.bits_left,
4684
                       cpi->twopass.total_left_stats.coded_error,
4685
                       cpi->tot_recode_hits);
4686
4687
        fclose(f);
4688
4689
        {
4690
            FILE *fmodes = fopen("Modes.stt", "a");
4691
4692
            fprintf(fmodes, "%6d:%1d:%1d:%1d ",
4693
                        cpi->common.current_video_frame,
4694
                        cm->frame_type, cm->refresh_golden_frame,
4695
                        cm->refresh_alt_ref_frame);
4696
4697
            fprintf(fmodes, "\n");
4698
4699
            fclose(fmodes);
4700
        }
4701
    }
4702
4703
#endif
4704
4705
117k
  cpi->ext_refresh_frame_flags_pending = 0;
4706
4707
117k
  if (cm->refresh_golden_frame == 1) {
4708
29.5k
    cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
4709
87.9k
  } else {
4710
87.9k
    cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_GOLDEN;
4711
87.9k
  }
4712
4713
117k
  if (cm->refresh_alt_ref_frame == 1) {
4714
20.8k
    cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
4715
96.6k
  } else {
4716
96.6k
    cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_ALTREF;
4717
96.6k
  }
4718
4719
117k
  if (cm->refresh_last_frame & cm->refresh_golden_frame) { /* both refreshed */
4720
29.5k
    cpi->gold_is_last = 1;
4721
87.9k
  } else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) {
4722
    /* 1 refreshed but not the other */
4723
87.9k
    cpi->gold_is_last = 0;
4724
87.9k
  }
4725
4726
117k
  if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) { /* both refreshed */
4727
20.8k
    cpi->alt_is_last = 1;
4728
96.6k
  } else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) {
4729
    /* 1 refreshed but not the other */
4730
96.6k
    cpi->alt_is_last = 0;
4731
96.6k
  }
4732
4733
117k
  if (cm->refresh_alt_ref_frame &
4734
117k
      cm->refresh_golden_frame) { /* both refreshed */
4735
20.8k
    cpi->gold_is_alt = 1;
4736
96.6k
  } else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) {
4737
    /* 1 refreshed but not the other */
4738
8.70k
    cpi->gold_is_alt = 0;
4739
8.70k
  }
4740
4741
117k
  cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;
4742
4743
117k
  if (cpi->gold_is_last) cpi->ref_frame_flags &= ~VP8_GOLD_FRAME;
4744
4745
117k
  if (cpi->alt_is_last) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;
4746
4747
117k
  if (cpi->gold_is_alt) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;
4748
4749
117k
  if (!cpi->oxcf.error_resilient_mode) {
4750
117k
    if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame &&
4751
0
        (cm->frame_type != KEY_FRAME)) {
4752
      /* Update the alternate reference frame stats as appropriate. */
4753
0
      update_alt_ref_frame_stats(cpi);
4754
117k
    } else {
4755
      /* Update the Golden frame stats as appropriate. */
4756
117k
      update_golden_frame_stats(cpi);
4757
117k
    }
4758
117k
  }
4759
4760
117k
  if (cm->frame_type == KEY_FRAME) {
4761
    /* Tell the caller that the frame was coded as a key frame */
4762
20.8k
    *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
4763
4764
    /* As this frame is a key frame  the next defaults to an inter frame. */
4765
20.8k
    cm->frame_type = INTER_FRAME;
4766
4767
20.8k
    cpi->last_frame_percent_intra = 100;
4768
96.6k
  } else {
4769
96.6k
    *frame_flags = cm->frame_flags & ~FRAMEFLAGS_KEY;
4770
4771
96.6k
    cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
4772
96.6k
  }
4773
4774
  /* Clear the one shot update flags for segmentation map and mode/ref
4775
   * loop filter deltas.
4776
   */
4777
117k
  cpi->mb.e_mbd.update_mb_segmentation_map = 0;
4778
117k
  cpi->mb.e_mbd.update_mb_segmentation_data = 0;
4779
117k
  cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
4780
4781
  /* Don't increment frame counters if this was an altref buffer update
4782
   * not a real frame
4783
   */
4784
117k
  if (cm->show_frame) {
4785
117k
    cm->current_video_frame++;
4786
117k
    cpi->frames_since_key++;
4787
117k
    cpi->temporal_pattern_counter++;
4788
117k
  }
4789
4790
#if 0
4791
    {
4792
        char filename[512];
4793
        FILE *recon_file;
4794
        sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
4795
        recon_file = fopen(filename, "wb");
4796
        fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
4797
               cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
4798
        fclose(recon_file);
4799
    }
4800
#endif
4801
4802
  /* DEBUG */
4803
  /* vpx_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show); */
4804
117k
}
4805
#if !CONFIG_REALTIME_ONLY
4806
static void Pass2Encode(VP8_COMP *cpi, size_t *size, unsigned char *dest,
4807
0
                        unsigned char *dest_end, unsigned int *frame_flags) {
4808
0
  if (!cpi->common.refresh_alt_ref_frame) vp8_second_pass(cpi);
4809
4810
0
  encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
4811
0
  cpi->twopass.bits_left -= 8 * (int)(*size);
4812
4813
0
  if (!cpi->common.refresh_alt_ref_frame) {
4814
0
    double two_pass_min_rate =
4815
0
        (double)(cpi->oxcf.target_bandwidth *
4816
0
                 cpi->oxcf.two_pass_vbrmin_section / 100);
4817
0
    cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->framerate);
4818
0
  }
4819
0
}
4820
#endif
4821
4822
int vp8_receive_raw_frame(VP8_COMP *cpi, unsigned int frame_flags,
4823
                          YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4824
117k
                          int64_t end_time) {
4825
#if CONFIG_INTERNAL_STATS
4826
  struct vpx_usec_timer timer;
4827
#endif
4828
117k
  int res = 0;
4829
4830
#if CONFIG_INTERNAL_STATS
4831
  vpx_usec_timer_start(&timer);
4832
#endif
4833
4834
  /* Reinit the lookahead buffer if the frame size changes */
4835
117k
  if (sd->y_width != cpi->oxcf.Width || sd->y_height != cpi->oxcf.Height) {
4836
0
    assert(cpi->oxcf.lag_in_frames < 2);
4837
0
    dealloc_raw_frame_buffers(cpi);
4838
0
    alloc_raw_frame_buffers(cpi);
4839
0
  }
4840
4841
117k
  if (vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
4842
117k
                         cpi->active_map_enabled ? cpi->active_map : NULL)) {
4843
0
    res = -1;
4844
0
  }
4845
#if CONFIG_INTERNAL_STATS
4846
  vpx_usec_timer_mark(&timer);
4847
  cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4848
#endif
4849
4850
117k
  return res;
4851
117k
}
4852
4853
117k
static int frame_is_reference(const VP8_COMP *cpi) {
4854
117k
  const VP8_COMMON *cm = &cpi->common;
4855
117k
  const MACROBLOCKD *xd = &cpi->mb.e_mbd;
4856
4857
117k
  return cm->frame_type == KEY_FRAME || cm->refresh_last_frame ||
4858
0
         cm->refresh_golden_frame || cm->refresh_alt_ref_frame ||
4859
0
         cm->copy_buffer_to_gf || cm->copy_buffer_to_arf ||
4860
0
         cm->refresh_entropy_probs || xd->mode_ref_lf_delta_update ||
4861
0
         xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
4862
117k
}
4863
4864
int vp8_get_compressed_data(VP8_COMP *cpi, unsigned int *frame_flags,
4865
                            size_t *size, unsigned char *dest,
4866
                            unsigned char *dest_end, int64_t *time_stamp,
4867
241k
                            int64_t *time_end, int flush) {
4868
241k
  VP8_COMMON *cm;
4869
241k
  struct vpx_usec_timer ticktimer;
4870
#if CONFIG_INTERNAL_STATS
4871
  struct vpx_usec_timer cmptimer;
4872
#endif
4873
241k
  YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4874
4875
241k
  if (!cpi) return -1;
4876
4877
241k
  cm = &cpi->common;
4878
4879
#if CONFIG_INTERNAL_STATS
4880
  vpx_usec_timer_start(&cmptimer);
4881
#endif
4882
4883
241k
  cpi->source = NULL;
4884
4885
241k
#if !CONFIG_REALTIME_ONLY
4886
  /* Should we code an alternate reference frame */
4887
241k
  if (cpi->oxcf.error_resilient_mode == 0 && cpi->oxcf.play_alternate &&
4888
0
      cpi->source_alt_ref_pending) {
4889
0
    if ((cpi->source = vp8_lookahead_peek(
4890
0
             cpi->lookahead, cpi->frames_till_gf_update_due, PEEK_FORWARD))) {
4891
0
      cpi->alt_ref_source = cpi->source;
4892
0
      if (cpi->oxcf.arnr_max_frames > 0) {
4893
0
        vp8_temporal_filter_prepare_c(cpi, cpi->frames_till_gf_update_due);
4894
0
        force_src_buffer = &cpi->alt_ref_buffer;
4895
0
      }
4896
0
      cpi->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
4897
0
      cm->refresh_alt_ref_frame = 1;
4898
0
      cm->refresh_golden_frame = 0;
4899
0
      cm->refresh_last_frame = 0;
4900
0
      cm->show_frame = 0;
4901
      /* Clear Pending alt Ref flag. */
4902
0
      cpi->source_alt_ref_pending = 0;
4903
0
      cpi->is_src_frame_alt_ref = 0;
4904
0
    }
4905
0
  }
4906
241k
#endif
4907
4908
241k
  if (!cpi->source) {
4909
    /* Read last frame source if we are encoding first pass. */
4910
241k
    if (cpi->pass == 1 && cm->current_video_frame > 0) {
4911
0
      if ((cpi->last_source =
4912
0
               vp8_lookahead_peek(cpi->lookahead, 1, PEEK_BACKWARD)) == NULL) {
4913
0
        return -1;
4914
0
      }
4915
0
    }
4916
4917
241k
    if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush))) {
4918
117k
      cm->show_frame = 1;
4919
4920
117k
      cpi->is_src_frame_alt_ref =
4921
117k
          cpi->alt_ref_source && (cpi->source == cpi->alt_ref_source);
4922
4923
117k
      if (cpi->is_src_frame_alt_ref) cpi->alt_ref_source = NULL;
4924
117k
    }
4925
241k
  }
4926
4927
241k
  if (cpi->source) {
4928
117k
    cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
4929
117k
    cpi->un_scaled_source = cpi->Source;
4930
117k
    *time_stamp = cpi->source->ts_start;
4931
117k
    *time_end = cpi->source->ts_end;
4932
117k
    *frame_flags = cpi->source->flags;
4933
4934
117k
    if (cpi->pass == 1 && cm->current_video_frame > 0) {
4935
0
      cpi->last_frame_unscaled_source = &cpi->last_source->img;
4936
0
    }
4937
123k
  } else {
4938
123k
    *size = 0;
4939
123k
#if !CONFIG_REALTIME_ONLY
4940
4941
123k
    if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
4942
0
      vp8_end_first_pass(cpi); /* get last stats packet */
4943
0
      cpi->twopass.first_pass_done = 1;
4944
0
    }
4945
4946
123k
#endif
4947
4948
123k
    return -1;
4949
123k
  }
4950
4951
117k
  if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
4952
6.06k
    cpi->first_time_stamp_ever = cpi->source->ts_start;
4953
6.06k
    cpi->last_end_time_stamp_seen = cpi->source->ts_start;
4954
6.06k
  }
4955
4956
  /* adjust frame rates based on timestamps given */
4957
117k
  if (cm->show_frame) {
4958
117k
    int64_t this_duration;
4959
117k
    int step = 0;
4960
4961
117k
    if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
4962
117k
      this_duration = cpi->source->ts_end - cpi->source->ts_start;
4963
117k
      step = 1;
4964
117k
    } else {
4965
0
      int64_t last_duration;
4966
4967
0
      this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
4968
0
      last_duration = cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
4969
      // Cap this to avoid overflow of (this_duration - last_duration) * 10
4970
0
      this_duration = VPXMIN(this_duration, INT64_MAX / 10);
4971
      /* do a step update if the duration changes by 10% */
4972
0
      if (last_duration) {
4973
0
        step = (int)(((this_duration - last_duration) * 10 / last_duration));
4974
0
      }
4975
0
    }
4976
4977
117k
    if (this_duration) {
4978
117k
      if (step) {
4979
117k
        cpi->ref_framerate = 10000000.0 / this_duration;
4980
117k
      } else {
4981
0
        double avg_duration, interval;
4982
4983
        /* Average this frame's rate into the last second's average
4984
         * frame rate. If we haven't seen 1 second yet, then average
4985
         * over the whole interval seen.
4986
         */
4987
0
        interval = (double)(cpi->source->ts_end - cpi->first_time_stamp_ever);
4988
0
        if (interval > 10000000.0) interval = 10000000;
4989
4990
0
        avg_duration = 10000000.0 / cpi->ref_framerate;
4991
0
        avg_duration *= (interval - avg_duration + this_duration);
4992
0
        avg_duration /= interval;
4993
4994
0
        cpi->ref_framerate = 10000000.0 / avg_duration;
4995
0
      }
4996
#if CONFIG_MULTI_RES_ENCODING
4997
      if (cpi->oxcf.mr_total_resolutions > 1) {
4998
        LOWER_RES_FRAME_INFO *low_res_frame_info =
4999
            (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
5000
        // Frame rate should be the same for all spatial layers in
5001
        // multi-res-encoding (simulcast), so we constrain the frame for
5002
        // higher layers to be that of lowest resolution. This is needed
5003
        // as he application may decide to skip encoding a high layer and
5004
        // then start again, in which case a big jump in time-stamps will
5005
        // be received for that high layer, which will yield an incorrect
5006
        // frame rate (from time-stamp adjustment in above calculation).
5007
        if (cpi->oxcf.mr_encoder_id) {
5008
          if (!low_res_frame_info->skip_encoding_base_stream)
5009
            cpi->ref_framerate = low_res_frame_info->low_res_framerate;
5010
        } else {
5011
          // Keep track of frame rate for lowest resolution.
5012
          low_res_frame_info->low_res_framerate = cpi->ref_framerate;
5013
          // The base stream is being encoded so set skip flag to 0.
5014
          low_res_frame_info->skip_encoding_base_stream = 0;
5015
        }
5016
      }
5017
#endif
5018
117k
      cpi->ref_framerate = clamp_framerate(cpi->ref_framerate);
5019
117k
      if (cpi->oxcf.number_of_layers > 1) {
5020
0
        unsigned int i;
5021
5022
        /* Update frame rates for each layer */
5023
0
        assert(cpi->oxcf.number_of_layers <= VPX_TS_MAX_LAYERS);
5024
0
        for (i = 0; i < cpi->oxcf.number_of_layers && i < VPX_TS_MAX_LAYERS;
5025
0
             ++i) {
5026
0
          LAYER_CONTEXT *lc = &cpi->layer_context[i];
5027
0
          lc->framerate = cpi->ref_framerate / cpi->oxcf.rate_decimator[i];
5028
0
        }
5029
117k
      } else {
5030
117k
        vp8_new_framerate(cpi, cpi->ref_framerate);
5031
117k
      }
5032
117k
    }
5033
5034
117k
    cpi->last_time_stamp_seen = cpi->source->ts_start;
5035
117k
    cpi->last_end_time_stamp_seen = cpi->source->ts_end;
5036
117k
  }
5037
5038
117k
  if (cpi->oxcf.number_of_layers > 1) {
5039
0
    int layer;
5040
5041
0
    vp8_update_layer_contexts(cpi);
5042
5043
    /* Restore layer specific context & set frame rate */
5044
0
    if (cpi->temporal_layer_id >= 0) {
5045
0
      layer = cpi->temporal_layer_id;
5046
0
    } else {
5047
0
      layer =
5048
0
          cpi->oxcf
5049
0
              .layer_id[cpi->temporal_pattern_counter % cpi->oxcf.periodicity];
5050
0
    }
5051
0
    vp8_restore_layer_context(cpi, layer);
5052
0
    vp8_new_framerate(cpi, cpi->layer_context[layer].framerate);
5053
0
  }
5054
5055
117k
  if (cpi->compressor_speed == 2) {
5056
60.3k
    vpx_usec_timer_start(&ticktimer);
5057
60.3k
  }
5058
5059
117k
  cpi->lf_zeromv_pct = (cpi->zeromv_count * 100) / cm->MBs;
5060
5061
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
5062
  {
5063
    int i;
5064
    const int num_part = (1 << cm->multi_token_partition);
5065
    /* the available bytes in dest */
5066
    const unsigned long dest_size = dest_end - dest;
5067
    const int tok_part_buff_size = (dest_size * 9) / (10 * num_part);
5068
5069
    unsigned char *dp = dest;
5070
5071
    cpi->partition_d[0] = dp;
5072
    dp += dest_size / 10; /* reserve 1/10 for control partition */
5073
    cpi->partition_d_end[0] = dp;
5074
5075
    for (i = 0; i < num_part; ++i) {
5076
      cpi->partition_d[i + 1] = dp;
5077
      dp += tok_part_buff_size;
5078
      cpi->partition_d_end[i + 1] = dp;
5079
    }
5080
  }
5081
#endif
5082
5083
  /* start with a 0 size frame */
5084
117k
  *size = 0;
5085
5086
  /* Clear down mmx registers */
5087
117k
  vpx_clear_system_state();
5088
5089
117k
  cm->frame_type = INTER_FRAME;
5090
117k
  cm->frame_flags = *frame_flags;
5091
5092
#if 0
5093
5094
    if (cm->refresh_alt_ref_frame)
5095
    {
5096
        cm->refresh_golden_frame = 0;
5097
        cm->refresh_last_frame = 0;
5098
    }
5099
    else
5100
    {
5101
        cm->refresh_golden_frame = 0;
5102
        cm->refresh_last_frame = 1;
5103
    }
5104
5105
#endif
5106
  /* find a free buffer for the new frame */
5107
117k
  {
5108
117k
    int i = 0;
5109
277k
    for (; i < NUM_YV12_BUFFERS; ++i) {
5110
277k
      if (!cm->yv12_fb[i].flags) {
5111
117k
        cm->new_fb_idx = i;
5112
117k
        break;
5113
117k
      }
5114
277k
    }
5115
5116
117k
    assert(i < NUM_YV12_BUFFERS);
5117
117k
  }
5118
117k
  switch (cpi->pass) {
5119
0
#if !CONFIG_REALTIME_ONLY
5120
0
    case 1: Pass1Encode(cpi); break;
5121
0
    case 2: Pass2Encode(cpi, size, dest, dest_end, frame_flags); break;
5122
0
#endif  // !CONFIG_REALTIME_ONLY
5123
117k
    default:
5124
117k
      encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
5125
117k
      break;
5126
117k
  }
5127
5128
117k
  if (cpi->compressor_speed == 2) {
5129
60.3k
    unsigned int duration, duration2;
5130
60.3k
    vpx_usec_timer_mark(&ticktimer);
5131
5132
60.3k
    duration = (int)(vpx_usec_timer_elapsed(&ticktimer));
5133
60.3k
    duration2 = (unsigned int)((double)duration / 2);
5134
5135
60.3k
    if (cm->frame_type != KEY_FRAME) {
5136
60.3k
      if (cpi->avg_encode_time == 0) {
5137
59.8k
        cpi->avg_encode_time = duration;
5138
59.8k
      } else {
5139
459
        cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
5140
459
      }
5141
60.3k
    }
5142
5143
60.3k
    if (duration2) {
5144
60.3k
      {
5145
60.3k
        if (cpi->avg_pick_mode_time == 0) {
5146
59.8k
          cpi->avg_pick_mode_time = duration2;
5147
59.8k
        } else {
5148
459
          cpi->avg_pick_mode_time =
5149
459
              (7 * cpi->avg_pick_mode_time + duration2) >> 3;
5150
459
        }
5151
60.3k
      }
5152
60.3k
    }
5153
60.3k
  }
5154
5155
117k
  if (cm->refresh_entropy_probs == 0) {
5156
0
    cm->fc = cm->lfc;
5157
0
  }
5158
5159
  /* Save the contexts separately for alt ref, gold and last. */
5160
  /* (TODO jbb -> Optimize this with pointers to avoid extra copies. ) */
5161
117k
  if (cm->refresh_alt_ref_frame) cpi->lfc_a = cm->fc;
5162
5163
117k
  if (cm->refresh_golden_frame) cpi->lfc_g = cm->fc;
5164
5165
117k
  if (cm->refresh_last_frame) cpi->lfc_n = cm->fc;
5166
5167
  /* if it's a dropped frame honor the requests on subsequent frames */
5168
117k
  if (*size > 0) {
5169
117k
    cpi->droppable = !frame_is_reference(cpi);
5170
5171
    /* return to normal state */
5172
117k
    cm->refresh_entropy_probs = 1;
5173
117k
    cm->refresh_alt_ref_frame = 0;
5174
117k
    cm->refresh_golden_frame = 0;
5175
117k
    cm->refresh_last_frame = 1;
5176
117k
    cm->frame_type = INTER_FRAME;
5177
117k
  }
5178
5179
  /* Save layer specific state */
5180
117k
  if (cpi->oxcf.number_of_layers > 1) vp8_save_layer_context(cpi);
5181
5182
#if CONFIG_INTERNAL_STATS
5183
  vpx_usec_timer_mark(&cmptimer);
5184
  cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
5185
#endif
5186
5187
117k
#if CONFIG_MULTITHREAD
5188
  /* wait for the lpf thread done */
5189
117k
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded) && cpi->b_lpf_running) {
5190
0
    vp8_sem_wait(&cpi->h_event_end_lpf);
5191
0
    cpi->b_lpf_running = 0;
5192
0
  }
5193
117k
#endif
5194
5195
117k
  if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame) {
5196
0
    generate_psnr_packet(cpi);
5197
0
  }
5198
5199
#if CONFIG_INTERNAL_STATS
5200
5201
  if (cpi->pass != 1) {
5202
    cpi->bytes += *size;
5203
5204
    if (cm->show_frame) {
5205
      cpi->common.show_frame_mi = cpi->common.mi;
5206
      cpi->count++;
5207
5208
      if (cpi->b_calculate_psnr) {
5209
        uint64_t ye, ue, ve;
5210
        double frame_psnr;
5211
        YV12_BUFFER_CONFIG *orig = cpi->Source;
5212
        YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
5213
        unsigned int y_width = cpi->common.Width;
5214
        unsigned int y_height = cpi->common.Height;
5215
        unsigned int uv_width = (y_width + 1) / 2;
5216
        unsigned int uv_height = (y_height + 1) / 2;
5217
        int y_samples = y_height * y_width;
5218
        int uv_samples = uv_height * uv_width;
5219
        int t_samples = y_samples + 2 * uv_samples;
5220
        double sq_error;
5221
5222
        ye = calc_plane_error(orig->y_buffer, orig->y_stride, recon->y_buffer,
5223
                              recon->y_stride, y_width, y_height);
5224
5225
        ue = calc_plane_error(orig->u_buffer, orig->uv_stride, recon->u_buffer,
5226
                              recon->uv_stride, uv_width, uv_height);
5227
5228
        ve = calc_plane_error(orig->v_buffer, orig->uv_stride, recon->v_buffer,
5229
                              recon->uv_stride, uv_width, uv_height);
5230
5231
        sq_error = (double)(ye + ue + ve);
5232
5233
        frame_psnr = vpx_sse_to_psnr(t_samples, 255.0, sq_error);
5234
5235
        cpi->total_y += vpx_sse_to_psnr(y_samples, 255.0, (double)ye);
5236
        cpi->total_u += vpx_sse_to_psnr(uv_samples, 255.0, (double)ue);
5237
        cpi->total_v += vpx_sse_to_psnr(uv_samples, 255.0, (double)ve);
5238
        cpi->total_sq_error += sq_error;
5239
        cpi->total += frame_psnr;
5240
#if CONFIG_POSTPROC
5241
        {
5242
          YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
5243
          double sq_error2;
5244
          double frame_psnr2, frame_ssim2 = 0;
5245
          double weight = 0;
5246
5247
          vp8_deblock(cm, cm->frame_to_show, &cm->post_proc_buffer,
5248
                      cm->filter_level * 10 / 6);
5249
          vpx_clear_system_state();
5250
5251
          ye = calc_plane_error(orig->y_buffer, orig->y_stride, pp->y_buffer,
5252
                                pp->y_stride, y_width, y_height);
5253
5254
          ue = calc_plane_error(orig->u_buffer, orig->uv_stride, pp->u_buffer,
5255
                                pp->uv_stride, uv_width, uv_height);
5256
5257
          ve = calc_plane_error(orig->v_buffer, orig->uv_stride, pp->v_buffer,
5258
                                pp->uv_stride, uv_width, uv_height);
5259
5260
          sq_error2 = (double)(ye + ue + ve);
5261
5262
          frame_psnr2 = vpx_sse_to_psnr(t_samples, 255.0, sq_error2);
5263
5264
          cpi->totalp_y += vpx_sse_to_psnr(y_samples, 255.0, (double)ye);
5265
          cpi->totalp_u += vpx_sse_to_psnr(uv_samples, 255.0, (double)ue);
5266
          cpi->totalp_v += vpx_sse_to_psnr(uv_samples, 255.0, (double)ve);
5267
          cpi->total_sq_error2 += sq_error2;
5268
          cpi->totalp += frame_psnr2;
5269
5270
          frame_ssim2 =
5271
              vpx_calc_ssim(cpi->Source, &cm->post_proc_buffer, &weight);
5272
5273
          cpi->summed_quality += frame_ssim2 * weight;
5274
          cpi->summed_weights += weight;
5275
5276
          if (cpi->oxcf.number_of_layers > 1) {
5277
            unsigned int i;
5278
5279
            for (i = cpi->current_layer; i < cpi->oxcf.number_of_layers; ++i) {
5280
              cpi->frames_in_layer[i]++;
5281
5282
              cpi->bytes_in_layer[i] += *size;
5283
              cpi->sum_psnr[i] += frame_psnr;
5284
              cpi->sum_psnr_p[i] += frame_psnr2;
5285
              cpi->total_error2[i] += sq_error;
5286
              cpi->total_error2_p[i] += sq_error2;
5287
              cpi->sum_ssim[i] += frame_ssim2 * weight;
5288
              cpi->sum_weights[i] += weight;
5289
            }
5290
          }
5291
        }
5292
#endif
5293
      }
5294
    }
5295
  }
5296
5297
#if 0
5298
5299
    if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
5300
    {
5301
        skiptruecount += cpi->skip_true_count;
5302
        skipfalsecount += cpi->skip_false_count;
5303
    }
5304
5305
#endif
5306
#if 0
5307
5308
    if (cpi->pass != 1)
5309
    {
5310
        FILE *f = fopen("skip.stt", "a");
5311
        fprintf(f, "frame:%4d flags:%4x Q:%4d P:%4d Size:%5d\n", cpi->common.current_video_frame, *frame_flags, cpi->common.base_qindex, cpi->prob_skip_false, *size);
5312
5313
        if (cpi->is_src_frame_alt_ref == 1)
5314
            fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
5315
5316
        fclose(f);
5317
    }
5318
5319
#endif
5320
#endif
5321
5322
117k
  return 0;
5323
117k
}
5324
5325
int vp8_get_preview_raw_frame(VP8_COMP *cpi, YV12_BUFFER_CONFIG *dest,
5326
0
                              vp8_ppflags_t *flags) {
5327
0
  if (cpi->common.refresh_alt_ref_frame) {
5328
0
    return -1;
5329
0
  } else {
5330
0
    int ret;
5331
5332
0
#if CONFIG_POSTPROC
5333
0
    cpi->common.show_frame_mi = cpi->common.mi;
5334
0
    ret = vp8_post_proc_frame(&cpi->common, dest, flags);
5335
#else
5336
    (void)flags;
5337
5338
    if (cpi->common.frame_to_show) {
5339
      *dest = *cpi->common.frame_to_show;
5340
      dest->y_width = cpi->common.Width;
5341
      dest->y_height = cpi->common.Height;
5342
      dest->uv_height = cpi->common.Height / 2;
5343
      ret = 0;
5344
    } else {
5345
      ret = -1;
5346
    }
5347
5348
#endif
5349
0
    vpx_clear_system_state();
5350
0
    return ret;
5351
0
  }
5352
0
}
5353
5354
int vp8_set_roimap(VP8_COMP *cpi, unsigned char *map, unsigned int rows,
5355
                   unsigned int cols, int delta_q[4], int delta_lf[4],
5356
0
                   unsigned int threshold[4]) {
5357
0
  signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
5358
0
  int internal_delta_q[MAX_MB_SEGMENTS];
5359
0
  const int range = 63;
5360
0
  int i;
5361
5362
  // Check number of rows and columns match
5363
0
  if (cpi->common.mb_rows != (int)rows || cpi->common.mb_cols != (int)cols) {
5364
0
    return -1;
5365
0
  }
5366
5367
0
  for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
5368
    // Note abs() alone can't be used as the behavior of abs(INT_MIN) is
5369
    // undefined.
5370
0
    if (delta_q[i] > range || delta_q[i] < -range || delta_lf[i] > range ||
5371
0
        delta_lf[i] < -range) {
5372
0
      return -1;
5373
0
    }
5374
0
  }
5375
5376
  // Also disable segmentation if no deltas are specified.
5377
0
  if (!map || (delta_q[0] == 0 && delta_q[1] == 0 && delta_q[2] == 0 &&
5378
0
               delta_q[3] == 0 && delta_lf[0] == 0 && delta_lf[1] == 0 &&
5379
0
               delta_lf[2] == 0 && delta_lf[3] == 0 && threshold[0] == 0 &&
5380
0
               threshold[1] == 0 && threshold[2] == 0 && threshold[3] == 0)) {
5381
0
    disable_segmentation(cpi);
5382
0
    return 0;
5383
0
  }
5384
5385
  // Translate the external delta q values to internal values.
5386
0
  for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
5387
0
    internal_delta_q[i] =
5388
0
        (delta_q[i] >= 0) ? q_trans[delta_q[i]] : -q_trans[-delta_q[i]];
5389
0
  }
5390
5391
  /* Set the segmentation Map */
5392
0
  set_segmentation_map(cpi, map);
5393
5394
  /* Activate segmentation. */
5395
0
  enable_segmentation(cpi);
5396
5397
  /* Set up the quant segment data */
5398
0
  feature_data[MB_LVL_ALT_Q][0] = internal_delta_q[0];
5399
0
  feature_data[MB_LVL_ALT_Q][1] = internal_delta_q[1];
5400
0
  feature_data[MB_LVL_ALT_Q][2] = internal_delta_q[2];
5401
0
  feature_data[MB_LVL_ALT_Q][3] = internal_delta_q[3];
5402
5403
  /* Set up the loop segment data s */
5404
0
  feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
5405
0
  feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
5406
0
  feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
5407
0
  feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
5408
5409
0
  cpi->segment_encode_breakout[0] = threshold[0];
5410
0
  cpi->segment_encode_breakout[1] = threshold[1];
5411
0
  cpi->segment_encode_breakout[2] = threshold[2];
5412
0
  cpi->segment_encode_breakout[3] = threshold[3];
5413
5414
  /* Initialise the feature data structure */
5415
0
  set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
5416
5417
0
  if (threshold[0] != 0 || threshold[1] != 0 || threshold[2] != 0 ||
5418
0
      threshold[3] != 0)
5419
0
    cpi->use_roi_static_threshold = 1;
5420
0
  cpi->cyclic_refresh_mode_enabled = 0;
5421
5422
0
  return 0;
5423
0
}
5424
5425
int vp8_set_active_map(VP8_COMP *cpi, unsigned char *map, unsigned int rows,
5426
0
                       unsigned int cols) {
5427
0
  if ((int)rows == cpi->common.mb_rows && (int)cols == cpi->common.mb_cols) {
5428
0
    if (map) {
5429
0
      memcpy(cpi->active_map, map, rows * cols);
5430
0
      cpi->active_map_enabled = 1;
5431
0
    } else {
5432
0
      cpi->active_map_enabled = 0;
5433
0
    }
5434
5435
0
    return 0;
5436
0
  } else {
5437
0
    return -1;
5438
0
  }
5439
0
}
5440
5441
int vp8_set_internal_size(VP8_COMP *cpi, VPX_SCALING_MODE horiz_mode,
5442
0
                          VPX_SCALING_MODE vert_mode) {
5443
0
  if (horiz_mode <= VP8E_ONETWO) {
5444
0
    cpi->common.horiz_scale = horiz_mode;
5445
0
  } else {
5446
0
    return -1;
5447
0
  }
5448
5449
0
  if (vert_mode <= VP8E_ONETWO) {
5450
0
    cpi->common.vert_scale = vert_mode;
5451
0
  } else {
5452
0
    return -1;
5453
0
  }
5454
5455
0
  return 0;
5456
0
}
5457
5458
780k
int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
5459
780k
  int i, j;
5460
780k
  int Total = 0;
5461
5462
780k
  unsigned char *src = source->y_buffer;
5463
780k
  unsigned char *dst = dest->y_buffer;
5464
5465
  /* Loop through the Y plane raw and reconstruction data summing
5466
   * (square differences)
5467
   */
5468
2.88M
  for (i = 0; i < source->y_height; i += 16) {
5469
13.1M
    for (j = 0; j < source->y_width; j += 16) {
5470
11.0M
      unsigned int sse;
5471
11.0M
      Total += vpx_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
5472
11.0M
                            &sse);
5473
11.0M
    }
5474
5475
2.10M
    src += 16 * source->y_stride;
5476
2.10M
    dst += 16 * dest->y_stride;
5477
2.10M
  }
5478
5479
780k
  return Total;
5480
780k
}
5481
5482
117k
int vp8_get_quantizer(VP8_COMP *cpi) { return cpi->common.base_qindex; }