2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/video_engine/overuse_frame_detector.h"
19 #include "webrtc/modules/video_coding/utility/include/exp_filter.h"
20 #include "webrtc/system_wrappers/interface/clock.h"
21 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
22 #include "webrtc/system_wrappers/interface/logging.h"
26 // TODO(mflodman) Test different values for all of these to trigger correctly,
27 // avoid fluctuations etc.
29 const int64_t kProcessIntervalMs = 5000;
31 // Weight factor to apply to the standard deviation.
32 const float kWeightFactor = 0.997f;
33 // Weight factor to apply to the average.
34 const float kWeightFactorMean = 0.98f;
36 // Delay between consecutive rampups. (Used for quick recovery.)
37 const int kQuickRampUpDelayMs = 10 * 1000;
38 // Delay between rampup attempts. Initially uses standard, scales up to max.
39 const int kStandardRampUpDelayMs = 30 * 1000;
40 const int kMaxRampUpDelayMs = 120 * 1000;
41 // Expontential back-off factor, to prevent annoying up-down behaviour.
42 const double kRampUpBackoffFactor = 2.0;
44 // The initial average encode time (set to a fairly small value).
45 const float kInitialAvgEncodeTimeMs = 5.0f;
47 // The maximum exponent to use in VCMExpFilter.
48 const float kSampleDiffMs = 33.0f;
49 const float kMaxExp = 7.0f;
53 Statistics::Statistics() :
56 filtered_samples_(new VCMExpFilter(kWeightFactorMean)),
57 filtered_variance_(new VCMExpFilter(kWeightFactor)) {
61 void Statistics::SetOptions(const CpuOveruseOptions& options) {
65 void Statistics::Reset() {
68 filtered_variance_->Reset(kWeightFactor);
69 filtered_variance_->Apply(1.0f, InitialVariance());
72 void Statistics::AddSample(float sample_ms) {
76 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
77 // Initialize filtered samples.
78 filtered_samples_->Reset(kWeightFactorMean);
79 filtered_samples_->Apply(1.0f, InitialMean());
83 float exp = sample_ms / kSampleDiffMs;
84 exp = std::min(exp, kMaxExp);
85 filtered_samples_->Apply(exp, sample_ms);
86 filtered_variance_->Apply(exp, (sample_ms - filtered_samples_->Value()) *
87 (sample_ms - filtered_samples_->Value()));
90 float Statistics::InitialMean() const {
96 float Statistics::InitialVariance() const {
97 // Start in between the underuse and overuse threshold.
98 float average_stddev = (options_.low_capture_jitter_threshold_ms +
99 options_.high_capture_jitter_threshold_ms) / 2.0f;
100 return average_stddev * average_stddev;
103 float Statistics::Mean() const { return filtered_samples_->Value(); }
105 float Statistics::StdDev() const {
106 return sqrt(std::max(filtered_variance_->Value(), 0.0f));
109 uint64_t Statistics::Count() const { return count_; }
112 // Class for calculating the average encode time.
113 class OveruseFrameDetector::EncodeTimeAvg {
116 : kWeightFactor(0.5f),
117 filtered_encode_time_ms_(new VCMExpFilter(kWeightFactor)) {
118 filtered_encode_time_ms_->Apply(1.0f, kInitialAvgEncodeTimeMs);
122 void AddEncodeSample(float encode_time_ms, int64_t diff_last_sample_ms) {
123 float exp = diff_last_sample_ms / kSampleDiffMs;
124 exp = std::min(exp, kMaxExp);
125 filtered_encode_time_ms_->Apply(exp, encode_time_ms);
128 int filtered_encode_time_ms() const {
129 return static_cast<int>(filtered_encode_time_ms_->Value() + 0.5);
133 const float kWeightFactor;
134 scoped_ptr<VCMExpFilter> filtered_encode_time_ms_;
137 // Class for calculating the encode usage.
138 class OveruseFrameDetector::EncodeUsage {
141 : kWeightFactorFrameDiff(0.998f),
142 kWeightFactorEncodeTime(0.995f),
143 kInitialSampleDiffMs(50.0f),
144 kMaxSampleDiffMs(66.0f),
146 filtered_encode_time_ms_(new VCMExpFilter(kWeightFactorEncodeTime)),
147 filtered_frame_diff_ms_(new VCMExpFilter(kWeightFactorFrameDiff)) {
152 void SetOptions(const CpuOveruseOptions& options) {
158 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
159 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
160 filtered_encode_time_ms_->Reset(kWeightFactorEncodeTime);
161 filtered_encode_time_ms_->Apply(1.0f, InitialEncodeTimeMs());
164 void AddSample(float sample_ms) {
165 float exp = sample_ms / kSampleDiffMs;
166 exp = std::min(exp, kMaxExp);
167 filtered_frame_diff_ms_->Apply(exp, sample_ms);
170 void AddEncodeSample(float encode_time_ms, int64_t diff_last_sample_ms) {
172 float exp = diff_last_sample_ms / kSampleDiffMs;
173 exp = std::min(exp, kMaxExp);
174 filtered_encode_time_ms_->Apply(exp, encode_time_ms);
177 int UsageInPercent() const {
178 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
179 return static_cast<int>(InitialUsageInPercent() + 0.5f);
181 float frame_diff_ms = std::max(filtered_frame_diff_ms_->Value(), 1.0f);
182 frame_diff_ms = std::min(frame_diff_ms, kMaxSampleDiffMs);
183 float encode_usage_percent =
184 100.0f * filtered_encode_time_ms_->Value() / frame_diff_ms;
185 return static_cast<int>(encode_usage_percent + 0.5);
188 float InitialUsageInPercent() const {
189 // Start in between the underuse and overuse threshold.
190 return (options_.low_encode_usage_threshold_percent +
191 options_.high_encode_usage_threshold_percent) / 2.0f;
194 float InitialEncodeTimeMs() const {
195 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
199 const float kWeightFactorFrameDiff;
200 const float kWeightFactorEncodeTime;
201 const float kInitialSampleDiffMs;
202 const float kMaxSampleDiffMs;
204 CpuOveruseOptions options_;
205 scoped_ptr<VCMExpFilter> filtered_encode_time_ms_;
206 scoped_ptr<VCMExpFilter> filtered_frame_diff_ms_;
209 // Class for calculating the capture queue delay change.
210 class OveruseFrameDetector::CaptureQueueDelay {
213 : kWeightFactor(0.5f),
215 filtered_delay_ms_per_s_(new VCMExpFilter(kWeightFactor)) {
216 filtered_delay_ms_per_s_->Apply(1.0f, 0.0f);
218 ~CaptureQueueDelay() {}
220 void FrameCaptured(int64_t now) {
221 const size_t kMaxSize = 200;
222 if (frames_.size() > kMaxSize) {
225 frames_.push_back(now);
228 void FrameProcessingStarted(int64_t now) {
229 if (frames_.empty()) {
232 delay_ms_ = now - frames_.front();
236 void CalculateDelayChange(int64_t diff_last_sample_ms) {
237 if (diff_last_sample_ms <= 0) {
240 float exp = static_cast<float>(diff_last_sample_ms) / kProcessIntervalMs;
241 exp = std::min(exp, kMaxExp);
242 filtered_delay_ms_per_s_->Apply(exp,
243 delay_ms_ * 1000.0f / diff_last_sample_ms);
251 int delay_ms() const {
255 int filtered_delay_ms_per_s() const {
256 return static_cast<int>(filtered_delay_ms_per_s_->Value() + 0.5);
260 const float kWeightFactor;
261 std::list<int64_t> frames_;
263 scoped_ptr<VCMExpFilter> filtered_delay_ms_per_s_;
266 OveruseFrameDetector::OveruseFrameDetector(Clock* clock)
267 : crit_(CriticalSectionWrapper::CreateCriticalSection()),
270 next_process_time_(clock_->TimeInMilliseconds()),
271 num_process_times_(0),
272 last_capture_time_(0),
273 last_overuse_time_(0),
274 checks_above_threshold_(0),
275 last_rampup_time_(0),
276 in_quick_rampup_(false),
277 current_rampup_delay_ms_(kStandardRampUpDelayMs),
279 last_encode_sample_ms_(0),
280 encode_time_(new EncodeTimeAvg()),
281 encode_usage_(new EncodeUsage()),
282 capture_queue_delay_(new CaptureQueueDelay()) {
285 OveruseFrameDetector::~OveruseFrameDetector() {
288 void OveruseFrameDetector::SetObserver(CpuOveruseObserver* observer) {
289 CriticalSectionScoped cs(crit_.get());
290 observer_ = observer;
293 void OveruseFrameDetector::SetOptions(const CpuOveruseOptions& options) {
294 assert(options.min_frame_samples > 0);
295 CriticalSectionScoped cs(crit_.get());
296 if (options_.Equals(options)) {
300 capture_deltas_.SetOptions(options);
301 encode_usage_->SetOptions(options);
302 ResetAll(num_pixels_);
305 int OveruseFrameDetector::CaptureJitterMs() const {
306 CriticalSectionScoped cs(crit_.get());
307 return static_cast<int>(capture_deltas_.StdDev() + 0.5);
310 int OveruseFrameDetector::AvgEncodeTimeMs() const {
311 CriticalSectionScoped cs(crit_.get());
312 return encode_time_->filtered_encode_time_ms();
315 int OveruseFrameDetector::EncodeUsagePercent() const {
316 CriticalSectionScoped cs(crit_.get());
317 return encode_usage_->UsageInPercent();
320 int OveruseFrameDetector::AvgCaptureQueueDelayMsPerS() const {
321 CriticalSectionScoped cs(crit_.get());
322 return capture_queue_delay_->filtered_delay_ms_per_s();
325 int OveruseFrameDetector::CaptureQueueDelayMsPerS() const {
326 CriticalSectionScoped cs(crit_.get());
327 return capture_queue_delay_->delay_ms();
330 int32_t OveruseFrameDetector::TimeUntilNextProcess() {
331 CriticalSectionScoped cs(crit_.get());
332 return next_process_time_ - clock_->TimeInMilliseconds();
335 bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
336 if (num_pixels != num_pixels_) {
342 bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now) const {
343 if (last_capture_time_ == 0) {
346 return (now - last_capture_time_) > options_.frame_timeout_interval_ms;
349 void OveruseFrameDetector::ResetAll(int num_pixels) {
350 num_pixels_ = num_pixels;
351 capture_deltas_.Reset();
352 encode_usage_->Reset();
353 capture_queue_delay_->ClearFrames();
354 last_capture_time_ = 0;
355 num_process_times_ = 0;
358 void OveruseFrameDetector::FrameCaptured(int width, int height) {
359 CriticalSectionScoped cs(crit_.get());
361 int64_t now = clock_->TimeInMilliseconds();
362 if (FrameSizeChanged(width * height) || FrameTimeoutDetected(now)) {
363 ResetAll(width * height);
366 if (last_capture_time_ != 0) {
367 capture_deltas_.AddSample(now - last_capture_time_);
368 encode_usage_->AddSample(now - last_capture_time_);
370 last_capture_time_ = now;
372 capture_queue_delay_->FrameCaptured(now);
375 void OveruseFrameDetector::FrameProcessingStarted() {
376 CriticalSectionScoped cs(crit_.get());
377 capture_queue_delay_->FrameProcessingStarted(clock_->TimeInMilliseconds());
380 void OveruseFrameDetector::FrameEncoded(int encode_time_ms) {
381 CriticalSectionScoped cs(crit_.get());
382 int64_t time = clock_->TimeInMilliseconds();
383 if (last_encode_sample_ms_ != 0) {
384 int64_t diff_ms = time - last_encode_sample_ms_;
385 encode_time_->AddEncodeSample(encode_time_ms, diff_ms);
386 encode_usage_->AddEncodeSample(encode_time_ms, diff_ms);
388 last_encode_sample_ms_ = time;
391 int32_t OveruseFrameDetector::Process() {
392 CriticalSectionScoped cs(crit_.get());
394 int64_t now = clock_->TimeInMilliseconds();
396 // Used to protect against Process() being called too often.
397 if (now < next_process_time_)
400 int64_t diff_ms = now - next_process_time_ + kProcessIntervalMs;
401 next_process_time_ = now + kProcessIntervalMs;
402 ++num_process_times_;
404 capture_queue_delay_->CalculateDelayChange(diff_ms);
406 if (num_process_times_ <= options_.min_process_count) {
411 // If the last thing we did was going up, and now have to back down, we need
412 // to check if this peak was short. If so we should back off to avoid going
413 // back and forth between this load, the system doesn't seem to handle it.
414 bool check_for_backoff = last_rampup_time_ > last_overuse_time_;
415 if (check_for_backoff) {
416 if (now - last_rampup_time_ < kStandardRampUpDelayMs) {
417 // Going up was not ok for very long, back off.
418 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
419 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
420 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
422 // Not currently backing off, reset rampup delay.
423 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
427 last_overuse_time_ = now;
428 in_quick_rampup_ = false;
429 checks_above_threshold_ = 0;
431 if (observer_ != NULL)
432 observer_->OveruseDetected();
433 } else if (IsUnderusing(now)) {
434 last_rampup_time_ = now;
435 in_quick_rampup_ = true;
437 if (observer_ != NULL)
438 observer_->NormalUsage();
442 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
443 LOG(LS_VERBOSE) << "Capture input stats: avg: " << capture_deltas_.Mean()
444 << " std_dev " << capture_deltas_.StdDev()
445 << " rampup delay " << rampup_delay
446 << " overuse >= " << options_.high_capture_jitter_threshold_ms
447 << " underuse < " << options_.low_capture_jitter_threshold_ms;
451 bool OveruseFrameDetector::IsOverusing() {
452 bool overusing = false;
453 if (options_.enable_capture_jitter_method) {
454 overusing = capture_deltas_.StdDev() >=
455 options_.high_capture_jitter_threshold_ms;
456 } else if (options_.enable_encode_usage_method) {
457 overusing = encode_usage_->UsageInPercent() >=
458 options_.high_encode_usage_threshold_percent;
462 ++checks_above_threshold_;
464 checks_above_threshold_ = 0;
466 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
469 bool OveruseFrameDetector::IsUnderusing(int64_t time_now) {
470 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
471 if (time_now < last_rampup_time_ + delay)
474 bool underusing = false;
475 if (options_.enable_capture_jitter_method) {
476 underusing = capture_deltas_.StdDev() <
477 options_.low_capture_jitter_threshold_ms;
478 } else if (options_.enable_encode_usage_method) {
479 underusing = encode_usage_->UsageInPercent() <
480 options_.low_encode_usage_threshold_percent;
484 } // namespace webrtc