blob: 7510f096144c072b3847888c323ab7df34e50297 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "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>
sprangc5d62e22017-04-02 23:53:04 -070019#include <string>
20#include <utility>
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000021
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#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"
Niels Möller7dc26b72017-12-06 10:27:48 +010026#include "rtc_base/numerics/exp_filter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/timeutils.h"
28#include "system_wrappers/include/field_trial.h"
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000029
pbosa1025072016-05-14 03:04:19 -070030#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080031#include <mach/mach.h>
pbosa1025072016-05-14 03:04:19 -070032#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080033
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000034namespace webrtc {
35
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000036namespace {
perkjd52063f2016-09-07 06:32:18 -070037const int64_t kCheckForOveruseIntervalMs = 5000;
38const int64_t kTimeToFirstCheckForOveruseMs = 100;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000039
pbos@webrtc.orga9575702013-08-30 17:16:32 +000040// Delay between consecutive rampups. (Used for quick recovery.)
41const int kQuickRampUpDelayMs = 10 * 1000;
42// Delay between rampup attempts. Initially uses standard, scales up to max.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000043const int kStandardRampUpDelayMs = 40 * 1000;
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +000044const int kMaxRampUpDelayMs = 240 * 1000;
pbos@webrtc.orga9575702013-08-30 17:16:32 +000045// Expontential back-off factor, to prevent annoying up-down behaviour.
46const double kRampUpBackoffFactor = 2.0;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000047
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +000048// Max number of overuses detected before always applying the rampup delay.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000049const int kMaxOverusesBeforeApplyRampupDelay = 4;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000050
Niels Möller7dc26b72017-12-06 10:27:48 +010051// The maximum exponent to use in VCMExpFilter.
52const float kMaxExp = 7.0f;
53// Default value used before first reconfiguration.
54const int kDefaultFrameRate = 30;
55// Default sample diff, default frame rate.
56const 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.
61const 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.
64const int kMinFramerate = 7;
65const int kMaxFramerate = 30;
66
sprangb1ca0732017-02-01 08:38:12 -080067const auto kScaleReasonCpu = AdaptationObserverInterface::AdaptReason::kCpu;
torbjorng448468d2016-02-10 08:11:57 -080068
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +000069// Class for calculating the processing usage on the send-side (the average
70// processing time of a frame divided by the average time difference between
71// captured frames).
Niels Möller904f8692017-12-07 11:22:39 +010072class SendProcessingUsage : public OveruseFrameDetector::ProcessingUsage {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000073 public:
Peter Boström4b91bd02015-06-26 06:58:16 +020074 explicit SendProcessingUsage(const CpuOveruseOptions& options)
Niels Möller7dc26b72017-12-06 10:27:48 +010075 : kWeightFactorFrameDiff(0.998f),
76 kWeightFactorProcessing(0.995f),
77 kInitialSampleDiffMs(40.0f),
78 count_(0),
79 options_(options),
80 max_sample_diff_ms_(kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor),
81 filtered_processing_ms_(new rtc::ExpFilter(kWeightFactorProcessing)),
82 filtered_frame_diff_ms_(new rtc::ExpFilter(kWeightFactorFrameDiff)) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +000083 Reset();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000084 }
sprangc5d62e22017-04-02 23:53:04 -070085 virtual ~SendProcessingUsage() {}
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000086
Niels Möller904f8692017-12-07 11:22:39 +010087 void Reset() override {
Niels Möller7dc26b72017-12-06 10:27:48 +010088 count_ = 0;
89 max_sample_diff_ms_ = kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor;
90 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
91 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
92 filtered_processing_ms_->Reset(kWeightFactorProcessing);
93 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +000094 }
95
Niels Möller904f8692017-12-07 11:22:39 +010096 void SetMaxSampleDiffMs(float diff_ms) override {
97 max_sample_diff_ms_ = diff_ms;
98 }
sprangfda496a2017-06-15 04:21:07 -070099
Niels Möller904f8692017-12-07 11:22:39 +0100100 void AddCaptureSample(float sample_ms) override {
Niels Möller7dc26b72017-12-06 10:27:48 +0100101 float exp = sample_ms / kDefaultSampleDiffMs;
102 exp = std::min(exp, kMaxExp);
103 filtered_frame_diff_ms_->Apply(exp, sample_ms);
104 }
105
Niels Möller904f8692017-12-07 11:22:39 +0100106 void AddSample(float processing_ms, int64_t diff_last_sample_ms) override {
Niels Möller7dc26b72017-12-06 10:27:48 +0100107 ++count_;
108 float exp = diff_last_sample_ms / kDefaultSampleDiffMs;
109 exp = std::min(exp, kMaxExp);
110 filtered_processing_ms_->Apply(exp, processing_ms);
111 }
112
Niels Möller904f8692017-12-07 11:22:39 +0100113 int Value() override {
Niels Möller7dc26b72017-12-06 10:27:48 +0100114 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
115 return static_cast<int>(InitialUsageInPercent() + 0.5f);
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000116 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100117 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
118 frame_diff_ms = std::min(frame_diff_ms, max_sample_diff_ms_);
119 float encode_usage_percent =
120 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
121 return static_cast<int>(encode_usage_percent + 0.5);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000122 }
123
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000124 private:
Niels Möller7dc26b72017-12-06 10:27:48 +0100125 float InitialUsageInPercent() const {
126 // Start in between the underuse and overuse threshold.
127 return (options_.low_encode_usage_threshold_percent +
128 options_.high_encode_usage_threshold_percent) / 2.0f;
129 }
130
131 float InitialProcessingMs() const {
132 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
133 }
134
135 const float kWeightFactorFrameDiff;
136 const float kWeightFactorProcessing;
137 const float kInitialSampleDiffMs;
138 uint64_t count_;
Peter Boström4b91bd02015-06-26 06:58:16 +0200139 const CpuOveruseOptions options_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100140 float max_sample_diff_ms_;
141 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
142 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000143};
144
sprangc5d62e22017-04-02 23:53:04 -0700145// Class used for manual testing of overuse, enabled via field trial flag.
Niels Möller904f8692017-12-07 11:22:39 +0100146class OverdoseInjector : public SendProcessingUsage {
sprangc5d62e22017-04-02 23:53:04 -0700147 public:
148 OverdoseInjector(const CpuOveruseOptions& options,
149 int64_t normal_period_ms,
150 int64_t overuse_period_ms,
151 int64_t underuse_period_ms)
Niels Möller904f8692017-12-07 11:22:39 +0100152 : SendProcessingUsage(options),
sprangc5d62e22017-04-02 23:53:04 -0700153 normal_period_ms_(normal_period_ms),
154 overuse_period_ms_(overuse_period_ms),
155 underuse_period_ms_(underuse_period_ms),
156 state_(State::kNormal),
157 last_toggling_ms_(-1) {
158 RTC_DCHECK_GT(overuse_period_ms, 0);
159 RTC_DCHECK_GT(normal_period_ms, 0);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100160 RTC_LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
161 << "ms normal mode, " << overuse_period_ms
162 << "ms overuse mode.";
sprangc5d62e22017-04-02 23:53:04 -0700163 }
164
165 ~OverdoseInjector() override {}
166
167 int Value() override {
168 int64_t now_ms = rtc::TimeMillis();
169 if (last_toggling_ms_ == -1) {
170 last_toggling_ms_ = now_ms;
171 } else {
172 switch (state_) {
173 case State::kNormal:
174 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
175 state_ = State::kOveruse;
176 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100177 RTC_LOG(LS_INFO) << "Simulating CPU overuse.";
sprangc5d62e22017-04-02 23:53:04 -0700178 }
179 break;
180 case State::kOveruse:
181 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
182 state_ = State::kUnderuse;
183 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100184 RTC_LOG(LS_INFO) << "Simulating CPU underuse.";
sprangc5d62e22017-04-02 23:53:04 -0700185 }
186 break;
187 case State::kUnderuse:
188 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
189 state_ = State::kNormal;
190 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100191 RTC_LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
sprangc5d62e22017-04-02 23:53:04 -0700192 }
193 break;
194 }
195 }
196
197 rtc::Optional<int> overried_usage_value;
198 switch (state_) {
199 case State::kNormal:
200 break;
201 case State::kOveruse:
202 overried_usage_value.emplace(250);
203 break;
204 case State::kUnderuse:
205 overried_usage_value.emplace(5);
206 break;
207 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100208
sprangc5d62e22017-04-02 23:53:04 -0700209 return overried_usage_value.value_or(SendProcessingUsage::Value());
210 }
211
212 private:
213 const int64_t normal_period_ms_;
214 const int64_t overuse_period_ms_;
215 const int64_t underuse_period_ms_;
216 enum class State { kNormal, kOveruse, kUnderuse } state_;
217 int64_t last_toggling_ms_;
218};
219
Niels Möller904f8692017-12-07 11:22:39 +0100220} // namespace
221
222CpuOveruseOptions::CpuOveruseOptions()
223 : high_encode_usage_threshold_percent(85),
224 frame_timeout_interval_ms(1500),
225 min_frame_samples(120),
226 min_process_count(3),
227 high_threshold_consecutive_count(2) {
228#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
229 // This is proof-of-concept code for letting the physical core count affect
230 // the interval into which we attempt to scale. For now, the code is Mac OS
231 // specific, since that's the platform were we saw most problems.
232 // TODO(torbjorng): Enhance SystemInfo to return this metric.
233
234 mach_port_t mach_host = mach_host_self();
235 host_basic_info hbi = {};
236 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
237 kern_return_t kr =
238 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
239 &info_count);
240 mach_port_deallocate(mach_task_self(), mach_host);
241
242 int n_physical_cores;
243 if (kr != KERN_SUCCESS) {
244 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
245 n_physical_cores = 1;
246 RTC_LOG(LS_ERROR)
247 << "Failed to determine number of physical cores, assuming 1";
248 } else {
249 n_physical_cores = hbi.physical_cpu;
250 RTC_LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
251 }
252
253 // Change init list default for few core systems. The assumption here is that
254 // encoding, which we measure here, takes about 1/4 of the processing of a
255 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
256 // hardware encoding. Since we don't affect the incoming stream here, we only
257 // control about 1/2 of the total processing needs, but this is not taken into
258 // account.
259 if (n_physical_cores == 1)
260 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
261 else if (n_physical_cores == 2)
262 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
263#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
264
265 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
266 // are close to that (when squared). This wide interval makes sure that
267 // scaling up or down does not jump all the way across the interval.
268 low_encode_usage_threshold_percent =
269 (high_encode_usage_threshold_percent - 1) / 2;
270}
271
272std::unique_ptr<OveruseFrameDetector::ProcessingUsage>
273OveruseFrameDetector::CreateProcessingUsage(const CpuOveruseOptions& options) {
274 std::unique_ptr<ProcessingUsage> instance;
sprangc5d62e22017-04-02 23:53:04 -0700275 std::string toggling_interval =
276 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
277 if (!toggling_interval.empty()) {
278 int normal_period_ms = 0;
279 int overuse_period_ms = 0;
280 int underuse_period_ms = 0;
281 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
282 &overuse_period_ms, &underuse_period_ms) == 3) {
283 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
284 underuse_period_ms > 0) {
285 instance.reset(new OverdoseInjector(
286 options, normal_period_ms, overuse_period_ms, underuse_period_ms));
287 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100288 RTC_LOG(LS_WARNING)
sprangc5d62e22017-04-02 23:53:04 -0700289 << "Invalid (non-positive) normal/overuse/underuse periods: "
290 << normal_period_ms << " / " << overuse_period_ms << " / "
291 << underuse_period_ms;
292 }
293 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100294 RTC_LOG(LS_WARNING) << "Malformed toggling interval: "
295 << toggling_interval;
sprangc5d62e22017-04-02 23:53:04 -0700296 }
297 }
298
299 if (!instance) {
300 // No valid overuse simulation parameters set, use normal usage class.
301 instance.reset(new SendProcessingUsage(options));
302 }
303
304 return instance;
305}
306
perkjd52063f2016-09-07 06:32:18 -0700307class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
308 public:
309 explicit CheckOveruseTask(OveruseFrameDetector* overuse_detector)
310 : overuse_detector_(overuse_detector) {
311 rtc::TaskQueue::Current()->PostDelayedTask(
312 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
313 }
314
315 void Stop() {
316 RTC_CHECK(task_checker_.CalledSequentially());
317 overuse_detector_ = nullptr;
318 }
319
320 private:
321 bool Run() override {
322 RTC_CHECK(task_checker_.CalledSequentially());
323 if (!overuse_detector_)
324 return true; // This will make the task queue delete this task.
325 overuse_detector_->CheckForOveruse();
326
327 rtc::TaskQueue::Current()->PostDelayedTask(
328 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
329 // Return false to prevent this task from being deleted. Ownership has been
330 // transferred to the task queue when PostDelayedTask was called.
331 return false;
332 }
333 rtc::SequencedTaskChecker task_checker_;
334 OveruseFrameDetector* overuse_detector_;
335};
336
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000337OveruseFrameDetector::OveruseFrameDetector(
Peter Boström4b91bd02015-06-26 06:58:16 +0200338 const CpuOveruseOptions& options,
sprangb1ca0732017-02-01 08:38:12 -0800339 AdaptationObserverInterface* observer,
Peter Boströme4499152016-02-05 11:13:28 +0100340 EncodedFrameObserver* encoder_timing,
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000341 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700342 : check_overuse_task_(nullptr),
343 options_(options),
Peter Boström4b91bd02015-06-26 06:58:16 +0200344 observer_(observer),
Peter Boströme4499152016-02-05 11:13:28 +0100345 encoder_timing_(encoder_timing),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000346 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000347 num_process_times_(0),
nissee0e3bdf2017-01-18 02:16:20 -0800348 // TODO(nisse): Use rtc::Optional
349 last_capture_time_us_(-1),
350 last_processed_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700351 num_pixels_(0),
Niels Möller7dc26b72017-12-06 10:27:48 +0100352 max_framerate_(kDefaultFrameRate),
Peter Boströme4499152016-02-05 11:13:28 +0100353 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000354 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000355 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100356 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000357 in_quick_rampup_(false),
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000358 current_rampup_delay_ms_(kStandardRampUpDelayMs),
Niels Möller904f8692017-12-07 11:22:39 +0100359 usage_(CreateProcessingUsage(options)) {
perkjd52063f2016-09-07 06:32:18 -0700360 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000361}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000362
363OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700364 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
365}
366
367void OveruseFrameDetector::StartCheckForOveruse() {
368 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
369 RTC_DCHECK(!check_overuse_task_);
370 check_overuse_task_ = new CheckOveruseTask(this);
371}
372void OveruseFrameDetector::StopCheckForOveruse() {
373 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
374 check_overuse_task_->Stop();
375 check_overuse_task_ = nullptr;
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000376}
377
Peter Boströme4499152016-02-05 11:13:28 +0100378void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700379 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100380 if (!metrics_)
381 metrics_ = rtc::Optional<CpuOveruseMetrics>(CpuOveruseMetrics());
382 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000383
Peter Boströme4499152016-02-05 11:13:28 +0100384 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000385}
386
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000387bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700388 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000389 if (num_pixels != num_pixels_) {
390 return true;
391 }
392 return false;
393}
394
nissee0e3bdf2017-01-18 02:16:20 -0800395bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700396 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800397 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000398 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800399 return (now_us - last_capture_time_us_) >
400 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000401}
402
Niels Möller7dc26b72017-12-06 10:27:48 +0100403void OveruseFrameDetector::ResetAll(int num_pixels) {
404 // Reset state, as a result resolution being changed. Do not however change
405 // the current frame rate back to the default.
perkjd52063f2016-09-07 06:32:18 -0700406 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100407 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000408 usage_->Reset();
Niels Möller7dc26b72017-12-06 10:27:48 +0100409 frame_timing_.clear();
nissee0e3bdf2017-01-18 02:16:20 -0800410 last_capture_time_us_ = -1;
411 last_processed_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000412 num_process_times_ = 0;
Peter Boströme4499152016-02-05 11:13:28 +0100413 metrics_ = rtc::Optional<CpuOveruseMetrics>();
Niels Möller7dc26b72017-12-06 10:27:48 +0100414 OnTargetFramerateUpdated(max_framerate_);
sprangfda496a2017-06-15 04:21:07 -0700415}
416
Niels Möller7dc26b72017-12-06 10:27:48 +0100417void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
perkjd52063f2016-09-07 06:32:18 -0700418 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100419 RTC_DCHECK_GE(framerate_fps, 0);
420 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
421 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
422 kMaxSampleDiffMarginFactor);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000423}
424
Niels Möller7dc26b72017-12-06 10:27:48 +0100425void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
426 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700427 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möllereee7ced2017-12-01 11:25:01 +0100428
Niels Möller7dc26b72017-12-06 10:27:48 +0100429 if (FrameSizeChanged(frame.width() * frame.height()) ||
430 FrameTimeoutDetected(time_when_first_seen_us)) {
431 ResetAll(frame.width() * frame.height());
432 }
433
434 if (last_capture_time_us_ != -1)
435 usage_->AddCaptureSample(
436 1e-3 * (time_when_first_seen_us - last_capture_time_us_));
437
438 last_capture_time_us_ = time_when_first_seen_us;
439
440 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
441 time_when_first_seen_us));
442}
443
444void OveruseFrameDetector::FrameSent(uint32_t timestamp,
445 int64_t time_sent_in_us) {
446 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
447 // Delay before reporting actual encoding time, used to have the ability to
448 // detect total encoding time when encoding more than one layer. Encoding is
449 // here assumed to finish within a second (or that we get enough long-time
450 // samples before one second to trigger an overuse even when this is not the
451 // case).
452 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
453 for (auto& it : frame_timing_) {
454 if (it.timestamp == timestamp) {
455 it.last_send_us = time_sent_in_us;
456 break;
457 }
458 }
459 // TODO(pbos): Handle the case/log errors when not finding the corresponding
460 // frame (either very slow encoding or incorrect wrong timestamps returned
461 // from the encoder).
462 // This is currently the case for all frames on ChromeOS, so logging them
463 // would be spammy, and triggering overuse would be wrong.
464 // https://crbug.com/350106
465 while (!frame_timing_.empty()) {
466 FrameTiming timing = frame_timing_.front();
467 if (time_sent_in_us - timing.capture_us <
468 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec) {
469 break;
470 }
471 if (timing.last_send_us != -1) {
472 int encode_duration_us =
473 static_cast<int>(timing.last_send_us - timing.capture_us);
474 if (encoder_timing_) {
475 // TODO(nisse): Update encoder_timing_ to also use us units.
476 encoder_timing_->OnEncodeTiming(timing.capture_time_us /
477 rtc::kNumMicrosecsPerMillisec,
478 encode_duration_us /
479 rtc::kNumMicrosecsPerMillisec);
480 }
481 if (last_processed_capture_time_us_ != -1) {
482 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
483 usage_->AddSample(1e-3 * encode_duration_us, 1e-3 * diff_us);
484 }
485 last_processed_capture_time_us_ = timing.capture_us;
486 EncodedFrameTimeMeasured(encode_duration_us /
487 rtc::kNumMicrosecsPerMillisec);
488 }
489 frame_timing_.pop_front();
Peter Boströme4499152016-02-05 11:13:28 +0100490 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000491}
492
perkjd52063f2016-09-07 06:32:18 -0700493void OveruseFrameDetector::CheckForOveruse() {
494 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
495 ++num_process_times_;
496 if (num_process_times_ <= options_.min_process_count || !metrics_)
497 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000498
nissee0e3bdf2017-01-18 02:16:20 -0800499 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000500
perkjd52063f2016-09-07 06:32:18 -0700501 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000502 // If the last thing we did was going up, and now have to back down, we need
503 // to check if this peak was short. If so we should back off to avoid going
504 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100505 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000506 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800507 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000508 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000509 // Going up was not ok for very long, back off.
510 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
511 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
512 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
513 } else {
514 // Not currently backing off, reset rampup delay.
515 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
516 }
517 }
518
nissee0e3bdf2017-01-18 02:16:20 -0800519 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000520 in_quick_rampup_ = false;
521 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000522 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000523
Peter Boström74f6e9e2016-04-04 17:56:10 +0200524 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800525 observer_->AdaptDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800526 } else if (IsUnderusing(*metrics_, now_ms)) {
527 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000528 in_quick_rampup_ = true;
529
Peter Boström74f6e9e2016-04-04 17:56:10 +0200530 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800531 observer_->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000532 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000533
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000534 int rampup_delay =
535 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700536
Mirko Bonadei675513b2017-11-09 11:09:25 +0100537 RTC_LOG(LS_VERBOSE) << " Frame stats: "
538 << " encode usage " << metrics_->encode_usage_percent
539 << " overuse detections " << num_overuse_detections_
540 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000541}
542
asapersson74d85e12015-09-24 00:53:32 -0700543bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700544 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700545
Peter Boström01f364e2016-01-07 16:38:25 +0100546 if (metrics.encode_usage_percent >=
547 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000548 ++checks_above_threshold_;
549 } else {
550 checks_above_threshold_ = 0;
551 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000552 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000553}
554
asapersson74d85e12015-09-24 00:53:32 -0700555bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
556 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700557 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000558 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100559 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000560 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000561
Peter Boström01f364e2016-01-07 16:38:25 +0100562 return metrics.encode_usage_percent <
563 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000564}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000565} // namespace webrtc