Coverage Report

Created: 2026-04-01 07:42

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