blob: b2cd7337cae77d3130cb46c6826540f88c9c6c8a [file] [log] [blame]
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +00001/*
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
Peter Boström7623ce42015-12-09 12:13:30 +010011#include "webrtc/video/overuse_frame_detector.h"
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000012
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000013#include <assert.h>
pbos@webrtc.orga9575702013-08-30 17:16:32 +000014#include <math.h>
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000015
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000016#include <algorithm>
17#include <list>
asapersson@webrtc.org734a5322014-06-10 06:35:22 +000018#include <map>
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000019
nisseaf916892017-01-10 07:44:26 -080020#include "webrtc/api/video/video_frame.h"
tommi@webrtc.org7a57f8f2015-02-08 18:27:46 +000021#include "webrtc/base/checks.h"
Peter Boström415d2cd2015-10-26 11:35:17 +010022#include "webrtc/base/logging.h"
tereliusbc5d9212017-01-13 09:14:33 -080023#include "webrtc/base/numerics/exp_filter.h"
pbosa96b60b2016-04-18 21:12:48 -070024#include "webrtc/common_video/include/frame_callback.h"
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000025
pbosa1025072016-05-14 03:04:19 -070026#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080027#include <mach/mach.h>
pbosa1025072016-05-14 03:04:19 -070028#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080029
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000030namespace webrtc {
31
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000032namespace {
perkjd52063f2016-09-07 06:32:18 -070033const int64_t kCheckForOveruseIntervalMs = 5000;
34const int64_t kTimeToFirstCheckForOveruseMs = 100;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000035
pbos@webrtc.orga9575702013-08-30 17:16:32 +000036// Delay between consecutive rampups. (Used for quick recovery.)
37const int kQuickRampUpDelayMs = 10 * 1000;
38// Delay between rampup attempts. Initially uses standard, scales up to max.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000039const int kStandardRampUpDelayMs = 40 * 1000;
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +000040const int kMaxRampUpDelayMs = 240 * 1000;
pbos@webrtc.orga9575702013-08-30 17:16:32 +000041// Expontential back-off factor, to prevent annoying up-down behaviour.
42const double kRampUpBackoffFactor = 2.0;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000043
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +000044// Max number of overuses detected before always applying the rampup delay.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000045const int kMaxOverusesBeforeApplyRampupDelay = 4;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000046
47// The maximum exponent to use in VCMExpFilter.
48const float kSampleDiffMs = 33.0f;
49const float kMaxExp = 7.0f;
50
kthelgason876222f2016-11-29 01:44:11 -080051const auto kScaleReasonCpu = ScalingObserverInterface::ScaleReason::kCpu;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000052} // namespace
53
torbjorng448468d2016-02-10 08:11:57 -080054CpuOveruseOptions::CpuOveruseOptions()
55 : high_encode_usage_threshold_percent(85),
56 frame_timeout_interval_ms(1500),
57 min_frame_samples(120),
58 min_process_count(3),
59 high_threshold_consecutive_count(2) {
pbosa1025072016-05-14 03:04:19 -070060#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080061 // This is proof-of-concept code for letting the physical core count affect
62 // the interval into which we attempt to scale. For now, the code is Mac OS
63 // specific, since that's the platform were we saw most problems.
64 // TODO(torbjorng): Enhance SystemInfo to return this metric.
65
66 mach_port_t mach_host = mach_host_self();
67 host_basic_info hbi = {};
68 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
69 kern_return_t kr =
70 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
71 &info_count);
72 mach_port_deallocate(mach_task_self(), mach_host);
73
74 int n_physical_cores;
75 if (kr != KERN_SUCCESS) {
76 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
77 n_physical_cores = 1;
78 LOG(LS_ERROR) << "Failed to determine number of physical cores, assuming 1";
79 } else {
80 n_physical_cores = hbi.physical_cpu;
81 LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
82 }
83
84 // Change init list default for few core systems. The assumption here is that
85 // encoding, which we measure here, takes about 1/4 of the processing of a
86 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
87 // hardware encoding. Since we don't affect the incoming stream here, we only
88 // control about 1/2 of the total processing needs, but this is not taken into
89 // account.
90 if (n_physical_cores == 1)
91 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
92 else if (n_physical_cores == 2)
93 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
pbosa1025072016-05-14 03:04:19 -070094#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080095
torbjorng448468d2016-02-10 08:11:57 -080096 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
97 // are close to that (when squared). This wide interval makes sure that
98 // scaling up or down does not jump all the way across the interval.
99 low_encode_usage_threshold_percent =
100 (high_encode_usage_threshold_percent - 1) / 2;
101}
102
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000103// Class for calculating the processing usage on the send-side (the average
104// processing time of a frame divided by the average time difference between
105// captured frames).
106class OveruseFrameDetector::SendProcessingUsage {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000107 public:
Peter Boström4b91bd02015-06-26 06:58:16 +0200108 explicit SendProcessingUsage(const CpuOveruseOptions& options)
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000109 : kWeightFactorFrameDiff(0.998f),
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000110 kWeightFactorProcessing(0.995f),
asapersson@webrtc.orge41dbee2014-05-13 13:45:13 +0000111 kInitialSampleDiffMs(40.0f),
112 kMaxSampleDiffMs(45.0f),
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000113 count_(0),
Peter Boström4b91bd02015-06-26 06:58:16 +0200114 options_(options),
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000115 filtered_processing_ms_(new rtc::ExpFilter(kWeightFactorProcessing)),
minyue@webrtc.org74aaf292014-07-16 21:28:26 +0000116 filtered_frame_diff_ms_(new rtc::ExpFilter(kWeightFactorFrameDiff)) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000117 Reset();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000118 }
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000119 ~SendProcessingUsage() {}
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000120
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000121 void Reset() {
122 count_ = 0;
123 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
124 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000125 filtered_processing_ms_->Reset(kWeightFactorProcessing);
126 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000127 }
128
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000129 void AddCaptureSample(float sample_ms) {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000130 float exp = sample_ms / kSampleDiffMs;
131 exp = std::min(exp, kMaxExp);
132 filtered_frame_diff_ms_->Apply(exp, sample_ms);
133 }
134
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000135 void AddSample(float processing_ms, int64_t diff_last_sample_ms) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000136 ++count_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000137 float exp = diff_last_sample_ms / kSampleDiffMs;
138 exp = std::min(exp, kMaxExp);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000139 filtered_processing_ms_->Apply(exp, processing_ms);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000140 }
141
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000142 int Value() const {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000143 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
144 return static_cast<int>(InitialUsageInPercent() + 0.5f);
145 }
minyue@webrtc.org74aaf292014-07-16 21:28:26 +0000146 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000147 frame_diff_ms = std::min(frame_diff_ms, kMaxSampleDiffMs);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000148 float encode_usage_percent =
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000149 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000150 return static_cast<int>(encode_usage_percent + 0.5);
151 }
152
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000153 private:
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000154 float InitialUsageInPercent() const {
155 // Start in between the underuse and overuse threshold.
156 return (options_.low_encode_usage_threshold_percent +
157 options_.high_encode_usage_threshold_percent) / 2.0f;
158 }
159
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000160 float InitialProcessingMs() const {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000161 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
162 }
163
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000164 const float kWeightFactorFrameDiff;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000165 const float kWeightFactorProcessing;
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000166 const float kInitialSampleDiffMs;
167 const float kMaxSampleDiffMs;
168 uint64_t count_;
Peter Boström4b91bd02015-06-26 06:58:16 +0200169 const CpuOveruseOptions options_;
kwiberg27f982b2016-03-01 11:52:33 -0800170 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
171 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000172};
173
perkjd52063f2016-09-07 06:32:18 -0700174class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
175 public:
176 explicit CheckOveruseTask(OveruseFrameDetector* overuse_detector)
177 : overuse_detector_(overuse_detector) {
178 rtc::TaskQueue::Current()->PostDelayedTask(
179 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
180 }
181
182 void Stop() {
183 RTC_CHECK(task_checker_.CalledSequentially());
184 overuse_detector_ = nullptr;
185 }
186
187 private:
188 bool Run() override {
189 RTC_CHECK(task_checker_.CalledSequentially());
190 if (!overuse_detector_)
191 return true; // This will make the task queue delete this task.
192 overuse_detector_->CheckForOveruse();
193
194 rtc::TaskQueue::Current()->PostDelayedTask(
195 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
196 // Return false to prevent this task from being deleted. Ownership has been
197 // transferred to the task queue when PostDelayedTask was called.
198 return false;
199 }
200 rtc::SequencedTaskChecker task_checker_;
201 OveruseFrameDetector* overuse_detector_;
202};
203
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000204OveruseFrameDetector::OveruseFrameDetector(
Peter Boström4b91bd02015-06-26 06:58:16 +0200205 const CpuOveruseOptions& options,
kthelgason876222f2016-11-29 01:44:11 -0800206 ScalingObserverInterface* observer,
Peter Boströme4499152016-02-05 11:13:28 +0100207 EncodedFrameObserver* encoder_timing,
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000208 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700209 : check_overuse_task_(nullptr),
210 options_(options),
Peter Boström4b91bd02015-06-26 06:58:16 +0200211 observer_(observer),
Peter Boströme4499152016-02-05 11:13:28 +0100212 encoder_timing_(encoder_timing),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000213 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000214 num_process_times_(0),
nissee0e3bdf2017-01-18 02:16:20 -0800215 // TODO(nisse): Use rtc::Optional
216 last_capture_time_us_(-1),
217 last_processed_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700218 num_pixels_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100219 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000220 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000221 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100222 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000223 in_quick_rampup_(false),
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000224 current_rampup_delay_ms_(kStandardRampUpDelayMs),
Peter Boströme4499152016-02-05 11:13:28 +0100225 usage_(new SendProcessingUsage(options)) {
perkjd52063f2016-09-07 06:32:18 -0700226 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000227}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000228
229OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700230 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
231}
232
233void OveruseFrameDetector::StartCheckForOveruse() {
234 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
235 RTC_DCHECK(!check_overuse_task_);
236 check_overuse_task_ = new CheckOveruseTask(this);
237}
238void OveruseFrameDetector::StopCheckForOveruse() {
239 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
240 check_overuse_task_->Stop();
241 check_overuse_task_ = nullptr;
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000242}
243
Peter Boströme4499152016-02-05 11:13:28 +0100244void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700245 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100246 if (!metrics_)
247 metrics_ = rtc::Optional<CpuOveruseMetrics>(CpuOveruseMetrics());
248 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000249
Peter Boströme4499152016-02-05 11:13:28 +0100250 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000251}
252
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000253bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700254 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000255 if (num_pixels != num_pixels_) {
256 return true;
257 }
258 return false;
259}
260
nissee0e3bdf2017-01-18 02:16:20 -0800261bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700262 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800263 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000264 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800265 return (now_us - last_capture_time_us_) >
266 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000267}
268
269void OveruseFrameDetector::ResetAll(int num_pixels) {
perkjd52063f2016-09-07 06:32:18 -0700270 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000271 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000272 usage_->Reset();
Peter Boströme4499152016-02-05 11:13:28 +0100273 frame_timing_.clear();
nissee0e3bdf2017-01-18 02:16:20 -0800274 last_capture_time_us_ = -1;
275 last_processed_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000276 num_process_times_ = 0;
Peter Boströme4499152016-02-05 11:13:28 +0100277 metrics_ = rtc::Optional<CpuOveruseMetrics>();
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000278}
279
perkjd52063f2016-09-07 06:32:18 -0700280void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
nissee0e3bdf2017-01-18 02:16:20 -0800281 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700282 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000283
Peter Boströme4499152016-02-05 11:13:28 +0100284 if (FrameSizeChanged(frame.width() * frame.height()) ||
nissee0e3bdf2017-01-18 02:16:20 -0800285 FrameTimeoutDetected(time_when_first_seen_us)) {
Peter Boströme4499152016-02-05 11:13:28 +0100286 ResetAll(frame.width() * frame.height());
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000287 }
288
nissee0e3bdf2017-01-18 02:16:20 -0800289 if (last_capture_time_us_ != -1)
290 usage_->AddCaptureSample(
291 1e-3 * (time_when_first_seen_us - last_capture_time_us_));
Åsa Persson746210f2015-09-08 10:52:42 +0200292
nissee0e3bdf2017-01-18 02:16:20 -0800293 last_capture_time_us_ = time_when_first_seen_us;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000294
nissee0e3bdf2017-01-18 02:16:20 -0800295 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
296 time_when_first_seen_us));
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000297}
298
perkjd52063f2016-09-07 06:32:18 -0700299void OveruseFrameDetector::FrameSent(uint32_t timestamp,
nissee0e3bdf2017-01-18 02:16:20 -0800300 int64_t time_sent_in_us) {
perkjd52063f2016-09-07 06:32:18 -0700301 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100302 // Delay before reporting actual encoding time, used to have the ability to
303 // detect total encoding time when encoding more than one layer. Encoding is
304 // here assumed to finish within a second (or that we get enough long-time
305 // samples before one second to trigger an overuse even when this is not the
306 // case).
307 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
Peter Boströme4499152016-02-05 11:13:28 +0100308 for (auto& it : frame_timing_) {
309 if (it.timestamp == timestamp) {
nissee0e3bdf2017-01-18 02:16:20 -0800310 it.last_send_us = time_sent_in_us;
Peter Boströme4499152016-02-05 11:13:28 +0100311 break;
312 }
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000313 }
Peter Boströme4499152016-02-05 11:13:28 +0100314 // TODO(pbos): Handle the case/log errors when not finding the corresponding
315 // frame (either very slow encoding or incorrect wrong timestamps returned
316 // from the encoder).
317 // This is currently the case for all frames on ChromeOS, so logging them
318 // would be spammy, and triggering overuse would be wrong.
319 // https://crbug.com/350106
320 while (!frame_timing_.empty()) {
321 FrameTiming timing = frame_timing_.front();
nissee0e3bdf2017-01-18 02:16:20 -0800322 if (time_sent_in_us - timing.capture_us <
323 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec)
Peter Boströme4499152016-02-05 11:13:28 +0100324 break;
nissee0e3bdf2017-01-18 02:16:20 -0800325 if (timing.last_send_us != -1) {
326 int encode_duration_us =
327 static_cast<int>(timing.last_send_us - timing.capture_us);
Peter Boströme4499152016-02-05 11:13:28 +0100328 if (encoder_timing_) {
nissee0e3bdf2017-01-18 02:16:20 -0800329 // TODO(nisse): Update encoder_timing_ to also use us units.
330 encoder_timing_->OnEncodeTiming(timing.capture_time_us /
331 rtc::kNumMicrosecsPerMillisec,
332 encode_duration_us /
333 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100334 }
nissee0e3bdf2017-01-18 02:16:20 -0800335 if (last_processed_capture_time_us_ != -1) {
336 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
337 usage_->AddSample(1e-3 * encode_duration_us, 1e-3 * diff_us);
Peter Boströme4499152016-02-05 11:13:28 +0100338 }
nissee0e3bdf2017-01-18 02:16:20 -0800339 last_processed_capture_time_us_ = timing.capture_us;
340 EncodedFrameTimeMeasured(encode_duration_us /
341 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100342 }
343 frame_timing_.pop_front();
344 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000345}
346
perkjd52063f2016-09-07 06:32:18 -0700347void OveruseFrameDetector::CheckForOveruse() {
348 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
349 ++num_process_times_;
350 if (num_process_times_ <= options_.min_process_count || !metrics_)
351 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000352
nissee0e3bdf2017-01-18 02:16:20 -0800353 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000354
perkjd52063f2016-09-07 06:32:18 -0700355 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000356 // If the last thing we did was going up, and now have to back down, we need
357 // to check if this peak was short. If so we should back off to avoid going
358 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100359 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000360 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800361 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000362 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000363 // Going up was not ok for very long, back off.
364 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
365 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
366 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
367 } else {
368 // Not currently backing off, reset rampup delay.
369 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
370 }
371 }
372
nissee0e3bdf2017-01-18 02:16:20 -0800373 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000374 in_quick_rampup_ = false;
375 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000376 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000377
Peter Boström74f6e9e2016-04-04 17:56:10 +0200378 if (observer_)
kthelgason876222f2016-11-29 01:44:11 -0800379 observer_->ScaleDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800380 } else if (IsUnderusing(*metrics_, now_ms)) {
381 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000382 in_quick_rampup_ = true;
383
Peter Boström74f6e9e2016-04-04 17:56:10 +0200384 if (observer_)
kthelgason876222f2016-11-29 01:44:11 -0800385 observer_->ScaleUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000386 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000387
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000388 int rampup_delay =
389 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700390
391 LOG(LS_VERBOSE) << " Frame stats: "
perkjd52063f2016-09-07 06:32:18 -0700392 << " encode usage " << metrics_->encode_usage_percent
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000393 << " overuse detections " << num_overuse_detections_
394 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000395}
396
asapersson74d85e12015-09-24 00:53:32 -0700397bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700398 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boström01f364e2016-01-07 16:38:25 +0100399 if (metrics.encode_usage_percent >=
400 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000401 ++checks_above_threshold_;
402 } else {
403 checks_above_threshold_ = 0;
404 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000405 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000406}
407
asapersson74d85e12015-09-24 00:53:32 -0700408bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
409 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700410 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000411 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100412 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000413 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000414
Peter Boström01f364e2016-01-07 16:38:25 +0100415 return metrics.encode_usage_percent <
416 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000417}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000418} // namespace webrtc