1 /*
2 * Copyright (c) 2013 The WebRTC 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 "video/overuse_frame_detector.h"
12
13 #include <assert.h>
14 #include <math.h>
15
16 #include <algorithm>
17 #include <list>
18 #include <map>
19 #include <string>
20 #include <utility>
21
22 #include "api/video/video_frame.h"
23 #include "common_video/include/frame_callback.h"
24 #include "rtc_base/checks.h"
25 #include "rtc_base/logging.h"
26 #include "rtc_base/numerics/exp_filter.h"
27 #include "rtc_base/timeutils.h"
28 #include "system_wrappers/include/field_trial.h"
29
30 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
31 #include <mach/mach.h>
32 #endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
33
34 namespace webrtc {
35
36 namespace {
37 const int64_t kCheckForOveruseIntervalMs = 5000;
38 const int64_t kTimeToFirstCheckForOveruseMs = 100;
39
40 // Delay between consecutive rampups. (Used for quick recovery.)
41 const int kQuickRampUpDelayMs = 10 * 1000;
42 // Delay between rampup attempts. Initially uses standard, scales up to max.
43 const int kStandardRampUpDelayMs = 40 * 1000;
44 const int kMaxRampUpDelayMs = 240 * 1000;
45 // Expontential back-off factor, to prevent annoying up-down behaviour.
46 const double kRampUpBackoffFactor = 2.0;
47
48 // Max number of overuses detected before always applying the rampup delay.
49 const int kMaxOverusesBeforeApplyRampupDelay = 4;
50
51 // The maximum exponent to use in VCMExpFilter.
52 const float kMaxExp = 7.0f;
53 // Default value used before first reconfiguration.
54 const int kDefaultFrameRate = 30;
55 // Default sample diff, default frame rate.
56 const float kDefaultSampleDiffMs = 1000.0f / kDefaultFrameRate;
57 // A factor applied to the sample diff on OnTargetFramerateUpdated to determine
58 // a max limit for the sample diff. For instance, with a framerate of 30fps,
59 // the sample diff is capped to (1000 / 30) * 1.35 = 45ms. This prevents
60 // triggering too soon if there are individual very large outliers.
61 const float kMaxSampleDiffMarginFactor = 1.35f;
62 // Minimum framerate allowed for usage calculation. This prevents crazy long
63 // encode times from being accepted if the frame rate happens to be low.
64 const int kMinFramerate = 7;
65 const int kMaxFramerate = 30;
66
67 const auto kScaleReasonCpu = AdaptationObserverInterface::AdaptReason::kCpu;
68 } // namespace
69
CpuOveruseOptions()70 CpuOveruseOptions::CpuOveruseOptions()
71 : high_encode_usage_threshold_percent(85),
72 frame_timeout_interval_ms(1500),
73 min_frame_samples(120),
74 min_process_count(3),
75 high_threshold_consecutive_count(2) {
76 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
77 // This is proof-of-concept code for letting the physical core count affect
78 // the interval into which we attempt to scale. For now, the code is Mac OS
79 // specific, since that's the platform were we saw most problems.
80 // TODO(torbjorng): Enhance SystemInfo to return this metric.
81
82 mach_port_t mach_host = mach_host_self();
83 host_basic_info hbi = {};
84 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
85 kern_return_t kr =
86 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
87 &info_count);
88 mach_port_deallocate(mach_task_self(), mach_host);
89
90 int n_physical_cores;
91 if (kr != KERN_SUCCESS) {
92 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
93 n_physical_cores = 1;
94 RTC_LOG(LS_ERROR)
95 << "Failed to determine number of physical cores, assuming 1";
96 } else {
97 n_physical_cores = hbi.physical_cpu;
98 RTC_LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
99 }
100
101 // Change init list default for few core systems. The assumption here is that
102 // encoding, which we measure here, takes about 1/4 of the processing of a
103 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
104 // hardware encoding. Since we don't affect the incoming stream here, we only
105 // control about 1/2 of the total processing needs, but this is not taken into
106 // account.
107 if (n_physical_cores == 1)
108 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
109 else if (n_physical_cores == 2)
110 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
111 #endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
112
113 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
114 // are close to that (when squared). This wide interval makes sure that
115 // scaling up or down does not jump all the way across the interval.
116 low_encode_usage_threshold_percent =
117 (high_encode_usage_threshold_percent - 1) / 2;
118 }
119
120 // Class for calculating the processing usage on the send-side (the average
121 // processing time of a frame divided by the average time difference between
122 // captured frames).
123 class OveruseFrameDetector::SendProcessingUsage {
124 public:
SendProcessingUsage(const CpuOveruseOptions & options)125 explicit SendProcessingUsage(const CpuOveruseOptions& options)
126 : kWeightFactorFrameDiff(0.998f),
127 kWeightFactorProcessing(0.995f),
128 kInitialSampleDiffMs(40.0f),
129 count_(0),
130 options_(options),
131 max_sample_diff_ms_(kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor),
132 filtered_processing_ms_(new rtc::ExpFilter(kWeightFactorProcessing)),
133 filtered_frame_diff_ms_(new rtc::ExpFilter(kWeightFactorFrameDiff)) {
134 Reset();
135 }
~SendProcessingUsage()136 virtual ~SendProcessingUsage() {}
137
Reset()138 void Reset() {
139 count_ = 0;
140 max_sample_diff_ms_ = kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor;
141 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
142 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
143 filtered_processing_ms_->Reset(kWeightFactorProcessing);
144 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
145 }
146
SetMaxSampleDiffMs(float diff_ms)147 void SetMaxSampleDiffMs(float diff_ms) { max_sample_diff_ms_ = diff_ms; }
148
AddCaptureSample(float sample_ms)149 void AddCaptureSample(float sample_ms) {
150 float exp = sample_ms / kDefaultSampleDiffMs;
151 exp = std::min(exp, kMaxExp);
152 filtered_frame_diff_ms_->Apply(exp, sample_ms);
153 }
154
AddSample(float processing_ms,int64_t diff_last_sample_ms)155 void AddSample(float processing_ms, int64_t diff_last_sample_ms) {
156 ++count_;
157 float exp = diff_last_sample_ms / kDefaultSampleDiffMs;
158 exp = std::min(exp, kMaxExp);
159 filtered_processing_ms_->Apply(exp, processing_ms);
160 }
161
Value()162 virtual int Value() {
163 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
164 return static_cast<int>(InitialUsageInPercent() + 0.5f);
165 }
166 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
167 frame_diff_ms = std::min(frame_diff_ms, max_sample_diff_ms_);
168 float encode_usage_percent =
169 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
170 return static_cast<int>(encode_usage_percent + 0.5);
171 }
172
173 private:
InitialUsageInPercent() const174 float InitialUsageInPercent() const {
175 // Start in between the underuse and overuse threshold.
176 return (options_.low_encode_usage_threshold_percent +
177 options_.high_encode_usage_threshold_percent) / 2.0f;
178 }
179
InitialProcessingMs() const180 float InitialProcessingMs() const {
181 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
182 }
183
184 const float kWeightFactorFrameDiff;
185 const float kWeightFactorProcessing;
186 const float kInitialSampleDiffMs;
187 uint64_t count_;
188 const CpuOveruseOptions options_;
189 float max_sample_diff_ms_;
190 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
191 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
192 };
193
194 // Class used for manual testing of overuse, enabled via field trial flag.
195 class OveruseFrameDetector::OverdoseInjector
196 : public OveruseFrameDetector::SendProcessingUsage {
197 public:
OverdoseInjector(const CpuOveruseOptions & options,int64_t normal_period_ms,int64_t overuse_period_ms,int64_t underuse_period_ms)198 OverdoseInjector(const CpuOveruseOptions& options,
199 int64_t normal_period_ms,
200 int64_t overuse_period_ms,
201 int64_t underuse_period_ms)
202 : OveruseFrameDetector::SendProcessingUsage(options),
203 normal_period_ms_(normal_period_ms),
204 overuse_period_ms_(overuse_period_ms),
205 underuse_period_ms_(underuse_period_ms),
206 state_(State::kNormal),
207 last_toggling_ms_(-1) {
208 RTC_DCHECK_GT(overuse_period_ms, 0);
209 RTC_DCHECK_GT(normal_period_ms, 0);
210 RTC_LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
211 << "ms normal mode, " << overuse_period_ms
212 << "ms overuse mode.";
213 }
214
~OverdoseInjector()215 ~OverdoseInjector() override {}
216
Value()217 int Value() override {
218 int64_t now_ms = rtc::TimeMillis();
219 if (last_toggling_ms_ == -1) {
220 last_toggling_ms_ = now_ms;
221 } else {
222 switch (state_) {
223 case State::kNormal:
224 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
225 state_ = State::kOveruse;
226 last_toggling_ms_ = now_ms;
227 RTC_LOG(LS_INFO) << "Simulating CPU overuse.";
228 }
229 break;
230 case State::kOveruse:
231 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
232 state_ = State::kUnderuse;
233 last_toggling_ms_ = now_ms;
234 RTC_LOG(LS_INFO) << "Simulating CPU underuse.";
235 }
236 break;
237 case State::kUnderuse:
238 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
239 state_ = State::kNormal;
240 last_toggling_ms_ = now_ms;
241 RTC_LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
242 }
243 break;
244 }
245 }
246
247 rtc::Optional<int> overried_usage_value;
248 switch (state_) {
249 case State::kNormal:
250 break;
251 case State::kOveruse:
252 overried_usage_value.emplace(250);
253 break;
254 case State::kUnderuse:
255 overried_usage_value.emplace(5);
256 break;
257 }
258
259 return overried_usage_value.value_or(SendProcessingUsage::Value());
260 }
261
262 private:
263 const int64_t normal_period_ms_;
264 const int64_t overuse_period_ms_;
265 const int64_t underuse_period_ms_;
266 enum class State { kNormal, kOveruse, kUnderuse } state_;
267 int64_t last_toggling_ms_;
268 };
269
270 std::unique_ptr<OveruseFrameDetector::SendProcessingUsage>
CreateSendProcessingUsage(const CpuOveruseOptions & options)271 OveruseFrameDetector::CreateSendProcessingUsage(
272 const CpuOveruseOptions& options) {
273 std::unique_ptr<SendProcessingUsage> instance;
274 std::string toggling_interval =
275 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
276 if (!toggling_interval.empty()) {
277 int normal_period_ms = 0;
278 int overuse_period_ms = 0;
279 int underuse_period_ms = 0;
280 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
281 &overuse_period_ms, &underuse_period_ms) == 3) {
282 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
283 underuse_period_ms > 0) {
284 instance.reset(new OverdoseInjector(
285 options, normal_period_ms, overuse_period_ms, underuse_period_ms));
286 } else {
287 RTC_LOG(LS_WARNING)
288 << "Invalid (non-positive) normal/overuse/underuse periods: "
289 << normal_period_ms << " / " << overuse_period_ms << " / "
290 << underuse_period_ms;
291 }
292 } else {
293 RTC_LOG(LS_WARNING) << "Malformed toggling interval: "
294 << toggling_interval;
295 }
296 }
297
298 if (!instance) {
299 // No valid overuse simulation parameters set, use normal usage class.
300 instance.reset(new SendProcessingUsage(options));
301 }
302
303 return instance;
304 }
305
306 class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
307 public:
CheckOveruseTask(OveruseFrameDetector * overuse_detector)308 explicit CheckOveruseTask(OveruseFrameDetector* overuse_detector)
309 : overuse_detector_(overuse_detector) {
310 rtc::TaskQueue::Current()->PostDelayedTask(
311 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
312 }
313
Stop()314 void Stop() {
315 RTC_CHECK(task_checker_.CalledSequentially());
316 overuse_detector_ = nullptr;
317 }
318
319 private:
Run()320 bool Run() override {
321 RTC_CHECK(task_checker_.CalledSequentially());
322 if (!overuse_detector_)
323 return true; // This will make the task queue delete this task.
324 overuse_detector_->CheckForOveruse();
325
326 rtc::TaskQueue::Current()->PostDelayedTask(
327 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
328 // Return false to prevent this task from being deleted. Ownership has been
329 // transferred to the task queue when PostDelayedTask was called.
330 return false;
331 }
332 rtc::SequencedTaskChecker task_checker_;
333 OveruseFrameDetector* overuse_detector_;
334 };
335
OveruseFrameDetector(const CpuOveruseOptions & options,AdaptationObserverInterface * observer,EncodedFrameObserver * encoder_timing,CpuOveruseMetricsObserver * metrics_observer)336 OveruseFrameDetector::OveruseFrameDetector(
337 const CpuOveruseOptions& options,
338 AdaptationObserverInterface* observer,
339 EncodedFrameObserver* encoder_timing,
340 CpuOveruseMetricsObserver* metrics_observer)
341 : check_overuse_task_(nullptr),
342 options_(options),
343 observer_(observer),
344 encoder_timing_(encoder_timing),
345 metrics_observer_(metrics_observer),
346 num_process_times_(0),
347 // TODO(nisse): Use rtc::Optional
348 last_capture_time_us_(-1),
349 last_processed_capture_time_us_(-1),
350 num_pixels_(0),
351 max_framerate_(kDefaultFrameRate),
352 last_overuse_time_ms_(-1),
353 checks_above_threshold_(0),
354 num_overuse_detections_(0),
355 last_rampup_time_ms_(-1),
356 in_quick_rampup_(false),
357 current_rampup_delay_ms_(kStandardRampUpDelayMs),
358 usage_(CreateSendProcessingUsage(options)) {
359 task_checker_.Detach();
360 }
361
~OveruseFrameDetector()362 OveruseFrameDetector::~OveruseFrameDetector() {
363 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
364 }
365
StartCheckForOveruse()366 void OveruseFrameDetector::StartCheckForOveruse() {
367 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
368 RTC_DCHECK(!check_overuse_task_);
369 check_overuse_task_ = new CheckOveruseTask(this);
370 }
StopCheckForOveruse()371 void OveruseFrameDetector::StopCheckForOveruse() {
372 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
373 check_overuse_task_->Stop();
374 check_overuse_task_ = nullptr;
375 }
376
EncodedFrameTimeMeasured(int encode_duration_ms)377 void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
378 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
379 if (!metrics_)
380 metrics_ = rtc::Optional<CpuOveruseMetrics>(CpuOveruseMetrics());
381 metrics_->encode_usage_percent = usage_->Value();
382
383 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
384 }
385
FrameSizeChanged(int num_pixels) const386 bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
387 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
388 if (num_pixels != num_pixels_) {
389 return true;
390 }
391 return false;
392 }
393
FrameTimeoutDetected(int64_t now_us) const394 bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
395 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
396 if (last_capture_time_us_ == -1)
397 return false;
398 return (now_us - last_capture_time_us_) >
399 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
400 }
401
ResetAll(int num_pixels)402 void OveruseFrameDetector::ResetAll(int num_pixels) {
403 // Reset state, as a result resolution being changed. Do not however change
404 // the current frame rate back to the default.
405 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
406 num_pixels_ = num_pixels;
407 usage_->Reset();
408 frame_timing_.clear();
409 last_capture_time_us_ = -1;
410 last_processed_capture_time_us_ = -1;
411 num_process_times_ = 0;
412 metrics_ = rtc::Optional<CpuOveruseMetrics>();
413 OnTargetFramerateUpdated(max_framerate_);
414 }
415
OnTargetFramerateUpdated(int framerate_fps)416 void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
417 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
418 RTC_DCHECK_GE(framerate_fps, 0);
419 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
420 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
421 kMaxSampleDiffMarginFactor);
422 }
423
FrameCaptured(const VideoFrame & frame,int64_t time_when_first_seen_us)424 void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
425 int64_t time_when_first_seen_us) {
426 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
427
428 if (FrameSizeChanged(frame.width() * frame.height()) ||
429 FrameTimeoutDetected(time_when_first_seen_us)) {
430 ResetAll(frame.width() * frame.height());
431 }
432
433 if (last_capture_time_us_ != -1)
434 usage_->AddCaptureSample(
435 1e-3 * (time_when_first_seen_us - last_capture_time_us_));
436
437 last_capture_time_us_ = time_when_first_seen_us;
438
439 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
440 time_when_first_seen_us));
441 }
442
FrameSent(uint32_t timestamp,int64_t time_sent_in_us)443 void OveruseFrameDetector::FrameSent(uint32_t timestamp,
444 int64_t time_sent_in_us) {
445 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
446 // Delay before reporting actual encoding time, used to have the ability to
447 // detect total encoding time when encoding more than one layer. Encoding is
448 // here assumed to finish within a second (or that we get enough long-time
449 // samples before one second to trigger an overuse even when this is not the
450 // case).
451 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
452 for (auto& it : frame_timing_) {
453 if (it.timestamp == timestamp) {
454 it.last_send_us = time_sent_in_us;
455 break;
456 }
457 }
458 // TODO(pbos): Handle the case/log errors when not finding the corresponding
459 // frame (either very slow encoding or incorrect wrong timestamps returned
460 // from the encoder).
461 // This is currently the case for all frames on ChromeOS, so logging them
462 // would be spammy, and triggering overuse would be wrong.
463 // https://crbug.com/350106
464 while (!frame_timing_.empty()) {
465 FrameTiming timing = frame_timing_.front();
466 if (time_sent_in_us - timing.capture_us <
467 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec) {
468 break;
469 }
470 if (timing.last_send_us != -1) {
471 int encode_duration_us =
472 static_cast<int>(timing.last_send_us - timing.capture_us);
473 if (encoder_timing_) {
474 // TODO(nisse): Update encoder_timing_ to also use us units.
475 encoder_timing_->OnEncodeTiming(timing.capture_time_us /
476 rtc::kNumMicrosecsPerMillisec,
477 encode_duration_us /
478 rtc::kNumMicrosecsPerMillisec);
479 }
480 if (last_processed_capture_time_us_ != -1) {
481 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
482 usage_->AddSample(1e-3 * encode_duration_us, 1e-3 * diff_us);
483 }
484 last_processed_capture_time_us_ = timing.capture_us;
485 EncodedFrameTimeMeasured(encode_duration_us /
486 rtc::kNumMicrosecsPerMillisec);
487 }
488 frame_timing_.pop_front();
489 }
490 }
491
CheckForOveruse()492 void OveruseFrameDetector::CheckForOveruse() {
493 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
494 ++num_process_times_;
495 if (num_process_times_ <= options_.min_process_count || !metrics_)
496 return;
497
498 int64_t now_ms = rtc::TimeMillis();
499
500 if (IsOverusing(*metrics_)) {
501 // If the last thing we did was going up, and now have to back down, we need
502 // to check if this peak was short. If so we should back off to avoid going
503 // back and forth between this load, the system doesn't seem to handle it.
504 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
505 if (check_for_backoff) {
506 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
507 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
508 // Going up was not ok for very long, back off.
509 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
510 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
511 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
512 } else {
513 // Not currently backing off, reset rampup delay.
514 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
515 }
516 }
517
518 last_overuse_time_ms_ = now_ms;
519 in_quick_rampup_ = false;
520 checks_above_threshold_ = 0;
521 ++num_overuse_detections_;
522
523 if (observer_)
524 observer_->AdaptDown(kScaleReasonCpu);
525 } else if (IsUnderusing(*metrics_, now_ms)) {
526 last_rampup_time_ms_ = now_ms;
527 in_quick_rampup_ = true;
528
529 if (observer_)
530 observer_->AdaptUp(kScaleReasonCpu);
531 }
532
533 int rampup_delay =
534 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
535
536 RTC_LOG(LS_VERBOSE) << " Frame stats: "
537 << " encode usage " << metrics_->encode_usage_percent
538 << " overuse detections " << num_overuse_detections_
539 << " rampup delay " << rampup_delay;
540 }
541
IsOverusing(const CpuOveruseMetrics & metrics)542 bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
543 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
544
545 if (metrics.encode_usage_percent >=
546 options_.high_encode_usage_threshold_percent) {
547 ++checks_above_threshold_;
548 } else {
549 checks_above_threshold_ = 0;
550 }
551 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
552 }
553
IsUnderusing(const CpuOveruseMetrics & metrics,int64_t time_now)554 bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
555 int64_t time_now) {
556 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
557 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
558 if (time_now < last_rampup_time_ms_ + delay)
559 return false;
560
561 return metrics.encode_usage_percent <
562 options_.low_encode_usage_threshold_percent;
563 }
564 } // namespace webrtc
565