blob: 71e3bd68cd2a607b0fa9e33bef70955a58c827c2 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/checks.h"
24#include "rtc_base/logging.h"
Niels Möller7dc26b72017-12-06 10:27:48 +010025#include "rtc_base/numerics/exp_filter.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/timeutils.h"
27#include "system_wrappers/include/field_trial.h"
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000028
pbosa1025072016-05-14 03:04:19 -070029#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080030#include <mach/mach.h>
pbosa1025072016-05-14 03:04:19 -070031#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080032
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000033namespace webrtc {
34
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000035namespace {
perkjd52063f2016-09-07 06:32:18 -070036const int64_t kCheckForOveruseIntervalMs = 5000;
37const int64_t kTimeToFirstCheckForOveruseMs = 100;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000038
pbos@webrtc.orga9575702013-08-30 17:16:32 +000039// Delay between consecutive rampups. (Used for quick recovery.)
40const int kQuickRampUpDelayMs = 10 * 1000;
41// Delay between rampup attempts. Initially uses standard, scales up to max.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000042const int kStandardRampUpDelayMs = 40 * 1000;
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +000043const int kMaxRampUpDelayMs = 240 * 1000;
pbos@webrtc.orga9575702013-08-30 17:16:32 +000044// Expontential back-off factor, to prevent annoying up-down behaviour.
45const double kRampUpBackoffFactor = 2.0;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000046
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +000047// Max number of overuses detected before always applying the rampup delay.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000048const int kMaxOverusesBeforeApplyRampupDelay = 4;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000049
Niels Möller7dc26b72017-12-06 10:27:48 +010050// The maximum exponent to use in VCMExpFilter.
51const float kMaxExp = 7.0f;
52// Default value used before first reconfiguration.
53const int kDefaultFrameRate = 30;
54// Default sample diff, default frame rate.
55const float kDefaultSampleDiffMs = 1000.0f / kDefaultFrameRate;
56// A factor applied to the sample diff on OnTargetFramerateUpdated to determine
57// a max limit for the sample diff. For instance, with a framerate of 30fps,
58// the sample diff is capped to (1000 / 30) * 1.35 = 45ms. This prevents
59// triggering too soon if there are individual very large outliers.
60const float kMaxSampleDiffMarginFactor = 1.35f;
61// Minimum framerate allowed for usage calculation. This prevents crazy long
62// encode times from being accepted if the frame rate happens to be low.
63const int kMinFramerate = 7;
64const int kMaxFramerate = 30;
65
sprangb1ca0732017-02-01 08:38:12 -080066const auto kScaleReasonCpu = AdaptationObserverInterface::AdaptReason::kCpu;
torbjorng448468d2016-02-10 08:11:57 -080067
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +000068// Class for calculating the processing usage on the send-side (the average
69// processing time of a frame divided by the average time difference between
70// captured frames).
Niels Möller83dbeac2017-12-14 16:39:44 +010071class SendProcessingUsage1 : public OveruseFrameDetector::ProcessingUsage {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000072 public:
Niels Möller83dbeac2017-12-14 16:39:44 +010073 explicit SendProcessingUsage1(const CpuOveruseOptions& options)
Niels Möller7dc26b72017-12-06 10:27:48 +010074 : kWeightFactorFrameDiff(0.998f),
75 kWeightFactorProcessing(0.995f),
76 kInitialSampleDiffMs(40.0f),
Niels Möller7dc26b72017-12-06 10:27:48 +010077 options_(options),
Niels Möllere08cf3a2017-12-07 15:23:58 +010078 count_(0),
79 last_processed_capture_time_us_(-1),
Niels Möller7dc26b72017-12-06 10:27:48 +010080 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 }
Niels Möller83dbeac2017-12-14 16:39:44 +010085 virtual ~SendProcessingUsage1() {}
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000086
Niels Möller904f8692017-12-07 11:22:39 +010087 void Reset() override {
Niels Möllere08cf3a2017-12-07 15:23:58 +010088 frame_timing_.clear();
Niels Möller7dc26b72017-12-06 10:27:48 +010089 count_ = 0;
Niels Möllere08cf3a2017-12-07 15:23:58 +010090 last_processed_capture_time_us_ = -1;
Niels Möller7dc26b72017-12-06 10:27:48 +010091 max_sample_diff_ms_ = kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor;
92 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
93 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
94 filtered_processing_ms_->Reset(kWeightFactorProcessing);
95 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +000096 }
97
Niels Möller904f8692017-12-07 11:22:39 +010098 void SetMaxSampleDiffMs(float diff_ms) override {
99 max_sample_diff_ms_ = diff_ms;
100 }
sprangfda496a2017-06-15 04:21:07 -0700101
Niels Möllere08cf3a2017-12-07 15:23:58 +0100102 void FrameCaptured(const VideoFrame& frame,
103 int64_t time_when_first_seen_us,
104 int64_t last_capture_time_us) override {
105 if (last_capture_time_us != -1)
106 AddCaptureSample(1e-3 * (time_when_first_seen_us - last_capture_time_us));
107
108 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
109 time_when_first_seen_us));
Niels Möller7dc26b72017-12-06 10:27:48 +0100110 }
111
Niels Möller83dbeac2017-12-14 16:39:44 +0100112 rtc::Optional<int> FrameSent(
113 uint32_t timestamp,
114 int64_t time_sent_in_us,
115 int64_t /* capture_time_us */,
116 rtc::Optional<int> /* encode_duration_us */) override {
Niels Möllere08cf3a2017-12-07 15:23:58 +0100117 rtc::Optional<int> encode_duration_us;
118 // Delay before reporting actual encoding time, used to have the ability to
119 // detect total encoding time when encoding more than one layer. Encoding is
120 // here assumed to finish within a second (or that we get enough long-time
121 // samples before one second to trigger an overuse even when this is not the
122 // case).
123 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
124 for (auto& it : frame_timing_) {
125 if (it.timestamp == timestamp) {
126 it.last_send_us = time_sent_in_us;
127 break;
128 }
129 }
130 // TODO(pbos): Handle the case/log errors when not finding the corresponding
131 // frame (either very slow encoding or incorrect wrong timestamps returned
132 // from the encoder).
133 // This is currently the case for all frames on ChromeOS, so logging them
134 // would be spammy, and triggering overuse would be wrong.
135 // https://crbug.com/350106
136 while (!frame_timing_.empty()) {
137 FrameTiming timing = frame_timing_.front();
138 if (time_sent_in_us - timing.capture_us <
139 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec) {
140 break;
141 }
142 if (timing.last_send_us != -1) {
143 encode_duration_us.emplace(
144 static_cast<int>(timing.last_send_us - timing.capture_us));
Niels Möller6b642f72017-12-08 14:11:14 +0100145
Niels Möllere08cf3a2017-12-07 15:23:58 +0100146 if (last_processed_capture_time_us_ != -1) {
147 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
148 AddSample(1e-3 * (*encode_duration_us), 1e-3 * diff_us);
149 }
150 last_processed_capture_time_us_ = timing.capture_us;
151 }
152 frame_timing_.pop_front();
153 }
154 return encode_duration_us;
Niels Möller7dc26b72017-12-06 10:27:48 +0100155 }
156
Niels Möller904f8692017-12-07 11:22:39 +0100157 int Value() override {
Niels Möller7dc26b72017-12-06 10:27:48 +0100158 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
159 return static_cast<int>(InitialUsageInPercent() + 0.5f);
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000160 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100161 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
162 frame_diff_ms = std::min(frame_diff_ms, max_sample_diff_ms_);
163 float encode_usage_percent =
164 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
165 return static_cast<int>(encode_usage_percent + 0.5);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000166 }
167
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000168 private:
Niels Möllere08cf3a2017-12-07 15:23:58 +0100169 struct FrameTiming {
170 FrameTiming(int64_t capture_time_us, uint32_t timestamp, int64_t now)
171 : capture_time_us(capture_time_us),
172 timestamp(timestamp),
173 capture_us(now),
174 last_send_us(-1) {}
175 int64_t capture_time_us;
176 uint32_t timestamp;
177 int64_t capture_us;
178 int64_t last_send_us;
179 };
180
181 void AddCaptureSample(float sample_ms) {
182 float exp = sample_ms / kDefaultSampleDiffMs;
183 exp = std::min(exp, kMaxExp);
184 filtered_frame_diff_ms_->Apply(exp, sample_ms);
185 }
186
187 void AddSample(float processing_ms, int64_t diff_last_sample_ms) {
188 ++count_;
189 float exp = diff_last_sample_ms / kDefaultSampleDiffMs;
190 exp = std::min(exp, kMaxExp);
191 filtered_processing_ms_->Apply(exp, processing_ms);
192 }
193
Niels Möller7dc26b72017-12-06 10:27:48 +0100194 float InitialUsageInPercent() const {
195 // Start in between the underuse and overuse threshold.
196 return (options_.low_encode_usage_threshold_percent +
197 options_.high_encode_usage_threshold_percent) / 2.0f;
198 }
199
200 float InitialProcessingMs() const {
201 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
202 }
203
204 const float kWeightFactorFrameDiff;
205 const float kWeightFactorProcessing;
206 const float kInitialSampleDiffMs;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100207
Peter Boström4b91bd02015-06-26 06:58:16 +0200208 const CpuOveruseOptions options_;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100209 std::list<FrameTiming> frame_timing_;
210 uint64_t count_;
211 int64_t last_processed_capture_time_us_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100212 float max_sample_diff_ms_;
213 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
214 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000215};
216
Niels Möller83dbeac2017-12-14 16:39:44 +0100217// New cpu load estimator.
218// TODO(bugs.webrtc.org/8504): For some period of time, we need to
219// switch between the two versions of the estimator for experiments.
220// When problems are sorted out, the old estimator should be deleted.
221class SendProcessingUsage2 : public OveruseFrameDetector::ProcessingUsage {
sprangc5d62e22017-04-02 23:53:04 -0700222 public:
Niels Möller83dbeac2017-12-14 16:39:44 +0100223 explicit SendProcessingUsage2(const CpuOveruseOptions& options)
224 : options_(options) {
225 Reset();
226 }
227 virtual ~SendProcessingUsage2() = default;
228
229 void Reset() override {
230 prev_time_us_ = -1;
231 // Start in between the underuse and overuse threshold.
232 load_estimate_ = (options_.low_encode_usage_threshold_percent +
233 options_.high_encode_usage_threshold_percent) /
234 200.0;
235 }
236
237 void SetMaxSampleDiffMs(float /* diff_ms */) override {}
238
239 void FrameCaptured(const VideoFrame& frame,
240 int64_t time_when_first_seen_us,
241 int64_t last_capture_time_us) override {}
242
243 rtc::Optional<int> FrameSent(uint32_t timestamp,
244 int64_t time_sent_in_us,
245 int64_t capture_time_us,
246 rtc::Optional<int> encode_duration_us) override {
247 if (encode_duration_us) {
248 if (prev_time_us_ != -1) {
249 AddSample(1e-6 * (*encode_duration_us),
250 1e-6 * (capture_time_us - prev_time_us_));
251 }
252 }
253 prev_time_us_ = capture_time_us;
254
255 return encode_duration_us;
256 }
257
258 private:
259 void AddSample(double encode_time, double diff_time) {
260 RTC_CHECK_GE(diff_time, 0.0);
261
262 // Use the filter update
263 //
264 // load <-- x/d (1-exp (-d/T)) + exp (-d/T) load
265 //
266 // where we must take care for small d, using the proper limit
267 // (1 - exp(-d/tau)) / d = 1/tau - d/2tau^2 + O(d^2)
268 double tau = (1e-3 * options_.filter_time_ms);
269 double e = diff_time / tau;
270 double c;
271 if (e < 0.0001) {
272 c = (1 - e / 2) / tau;
273 } else {
274 c = -expm1(-e) / diff_time;
275 }
276 load_estimate_ = c * encode_time + exp(-e) * load_estimate_;
277 }
278
279 int Value() override {
280 return static_cast<int>(100.0 * load_estimate_ + 0.5);
281 }
282
283 private:
284 const CpuOveruseOptions options_;
285 int64_t prev_time_us_ = -1;
286 double load_estimate_;
287};
288
289// Class used for manual testing of overuse, enabled via field trial flag.
290class OverdoseInjector : public OveruseFrameDetector::ProcessingUsage {
291 public:
292 OverdoseInjector(std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage,
sprangc5d62e22017-04-02 23:53:04 -0700293 int64_t normal_period_ms,
294 int64_t overuse_period_ms,
295 int64_t underuse_period_ms)
Niels Möller83dbeac2017-12-14 16:39:44 +0100296 : usage_(std::move(usage)),
sprangc5d62e22017-04-02 23:53:04 -0700297 normal_period_ms_(normal_period_ms),
298 overuse_period_ms_(overuse_period_ms),
299 underuse_period_ms_(underuse_period_ms),
300 state_(State::kNormal),
301 last_toggling_ms_(-1) {
302 RTC_DCHECK_GT(overuse_period_ms, 0);
303 RTC_DCHECK_GT(normal_period_ms, 0);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100304 RTC_LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
305 << "ms normal mode, " << overuse_period_ms
306 << "ms overuse mode.";
sprangc5d62e22017-04-02 23:53:04 -0700307 }
308
309 ~OverdoseInjector() override {}
310
Niels Möller83dbeac2017-12-14 16:39:44 +0100311 void Reset() override { usage_->Reset(); }
312
313 void SetMaxSampleDiffMs(float diff_ms) override {
314 usage_->SetMaxSampleDiffMs(diff_ms);
315 }
316
317 void FrameCaptured(const VideoFrame& frame,
318 int64_t time_when_first_seen_us,
319 int64_t last_capture_time_us) override {
320 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us);
321 }
322
323 rtc::Optional<int> FrameSent(
324 // These two argument used by old estimator.
325 uint32_t timestamp,
326 int64_t time_sent_in_us,
327 // And these two by the new estimator.
328 int64_t capture_time_us,
329 rtc::Optional<int> encode_duration_us) override {
330 return usage_->FrameSent(timestamp, time_sent_in_us, capture_time_us,
331 encode_duration_us);
332 }
333
sprangc5d62e22017-04-02 23:53:04 -0700334 int Value() override {
335 int64_t now_ms = rtc::TimeMillis();
336 if (last_toggling_ms_ == -1) {
337 last_toggling_ms_ = now_ms;
338 } else {
339 switch (state_) {
340 case State::kNormal:
341 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
342 state_ = State::kOveruse;
343 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100344 RTC_LOG(LS_INFO) << "Simulating CPU overuse.";
sprangc5d62e22017-04-02 23:53:04 -0700345 }
346 break;
347 case State::kOveruse:
348 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
349 state_ = State::kUnderuse;
350 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100351 RTC_LOG(LS_INFO) << "Simulating CPU underuse.";
sprangc5d62e22017-04-02 23:53:04 -0700352 }
353 break;
354 case State::kUnderuse:
355 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
356 state_ = State::kNormal;
357 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100358 RTC_LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
sprangc5d62e22017-04-02 23:53:04 -0700359 }
360 break;
361 }
362 }
363
364 rtc::Optional<int> overried_usage_value;
365 switch (state_) {
366 case State::kNormal:
367 break;
368 case State::kOveruse:
369 overried_usage_value.emplace(250);
370 break;
371 case State::kUnderuse:
372 overried_usage_value.emplace(5);
373 break;
374 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100375
Niels Möller83dbeac2017-12-14 16:39:44 +0100376 return overried_usage_value.value_or(usage_->Value());
sprangc5d62e22017-04-02 23:53:04 -0700377 }
378
379 private:
Niels Möller83dbeac2017-12-14 16:39:44 +0100380 const std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage_;
sprangc5d62e22017-04-02 23:53:04 -0700381 const int64_t normal_period_ms_;
382 const int64_t overuse_period_ms_;
383 const int64_t underuse_period_ms_;
384 enum class State { kNormal, kOveruse, kUnderuse } state_;
385 int64_t last_toggling_ms_;
386};
387
Niels Möller904f8692017-12-07 11:22:39 +0100388} // namespace
389
390CpuOveruseOptions::CpuOveruseOptions()
391 : high_encode_usage_threshold_percent(85),
392 frame_timeout_interval_ms(1500),
393 min_frame_samples(120),
394 min_process_count(3),
Niels Möller83dbeac2017-12-14 16:39:44 +0100395 high_threshold_consecutive_count(2),
396 // Disabled by default.
397 filter_time_ms(0) {
Niels Möller904f8692017-12-07 11:22:39 +0100398#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
399 // This is proof-of-concept code for letting the physical core count affect
400 // the interval into which we attempt to scale. For now, the code is Mac OS
401 // specific, since that's the platform were we saw most problems.
402 // TODO(torbjorng): Enhance SystemInfo to return this metric.
403
404 mach_port_t mach_host = mach_host_self();
405 host_basic_info hbi = {};
406 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
407 kern_return_t kr =
408 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
409 &info_count);
410 mach_port_deallocate(mach_task_self(), mach_host);
411
412 int n_physical_cores;
413 if (kr != KERN_SUCCESS) {
414 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
415 n_physical_cores = 1;
416 RTC_LOG(LS_ERROR)
417 << "Failed to determine number of physical cores, assuming 1";
418 } else {
419 n_physical_cores = hbi.physical_cpu;
420 RTC_LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
421 }
422
423 // Change init list default for few core systems. The assumption here is that
424 // encoding, which we measure here, takes about 1/4 of the processing of a
425 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
426 // hardware encoding. Since we don't affect the incoming stream here, we only
427 // control about 1/2 of the total processing needs, but this is not taken into
428 // account.
429 if (n_physical_cores == 1)
430 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
431 else if (n_physical_cores == 2)
432 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
433#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
434
435 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
436 // are close to that (when squared). This wide interval makes sure that
437 // scaling up or down does not jump all the way across the interval.
438 low_encode_usage_threshold_percent =
439 (high_encode_usage_threshold_percent - 1) / 2;
440}
441
442std::unique_ptr<OveruseFrameDetector::ProcessingUsage>
Niels Möllere08cf3a2017-12-07 15:23:58 +0100443OveruseFrameDetector::CreateProcessingUsage(
Niels Möller6b642f72017-12-08 14:11:14 +0100444 const CpuOveruseOptions& options) {
Niels Möller904f8692017-12-07 11:22:39 +0100445 std::unique_ptr<ProcessingUsage> instance;
Niels Möller83dbeac2017-12-14 16:39:44 +0100446 if (options.filter_time_ms > 0) {
447 instance = rtc::MakeUnique<SendProcessingUsage2>(options);
448 } else {
449 instance = rtc::MakeUnique<SendProcessingUsage1>(options);
450 }
sprangc5d62e22017-04-02 23:53:04 -0700451 std::string toggling_interval =
452 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
453 if (!toggling_interval.empty()) {
454 int normal_period_ms = 0;
455 int overuse_period_ms = 0;
456 int underuse_period_ms = 0;
457 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
458 &overuse_period_ms, &underuse_period_ms) == 3) {
459 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
460 underuse_period_ms > 0) {
Niels Möllere08cf3a2017-12-07 15:23:58 +0100461 instance = rtc::MakeUnique<OverdoseInjector>(
Niels Möller83dbeac2017-12-14 16:39:44 +0100462 std::move(instance), normal_period_ms,
463 overuse_period_ms, underuse_period_ms);
sprangc5d62e22017-04-02 23:53:04 -0700464 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
sprangc5d62e22017-04-02 23:53:04 -0700466 << "Invalid (non-positive) normal/overuse/underuse periods: "
467 << normal_period_ms << " / " << overuse_period_ms << " / "
468 << underuse_period_ms;
469 }
470 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100471 RTC_LOG(LS_WARNING) << "Malformed toggling interval: "
472 << toggling_interval;
sprangc5d62e22017-04-02 23:53:04 -0700473 }
474 }
sprangc5d62e22017-04-02 23:53:04 -0700475 return instance;
476}
477
perkjd52063f2016-09-07 06:32:18 -0700478class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
479 public:
480 explicit CheckOveruseTask(OveruseFrameDetector* overuse_detector)
481 : overuse_detector_(overuse_detector) {
482 rtc::TaskQueue::Current()->PostDelayedTask(
483 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
484 }
485
486 void Stop() {
487 RTC_CHECK(task_checker_.CalledSequentially());
488 overuse_detector_ = nullptr;
489 }
490
491 private:
492 bool Run() override {
493 RTC_CHECK(task_checker_.CalledSequentially());
494 if (!overuse_detector_)
495 return true; // This will make the task queue delete this task.
496 overuse_detector_->CheckForOveruse();
497
498 rtc::TaskQueue::Current()->PostDelayedTask(
499 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
500 // Return false to prevent this task from being deleted. Ownership has been
501 // transferred to the task queue when PostDelayedTask was called.
502 return false;
503 }
504 rtc::SequencedTaskChecker task_checker_;
505 OveruseFrameDetector* overuse_detector_;
506};
507
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000508OveruseFrameDetector::OveruseFrameDetector(
Peter Boström4b91bd02015-06-26 06:58:16 +0200509 const CpuOveruseOptions& options,
sprangb1ca0732017-02-01 08:38:12 -0800510 AdaptationObserverInterface* observer,
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000511 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700512 : check_overuse_task_(nullptr),
513 options_(options),
Peter Boström4b91bd02015-06-26 06:58:16 +0200514 observer_(observer),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000515 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000516 num_process_times_(0),
nissee0e3bdf2017-01-18 02:16:20 -0800517 // TODO(nisse): Use rtc::Optional
518 last_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700519 num_pixels_(0),
Niels Möller7dc26b72017-12-06 10:27:48 +0100520 max_framerate_(kDefaultFrameRate),
Peter Boströme4499152016-02-05 11:13:28 +0100521 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000522 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000523 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100524 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000525 in_quick_rampup_(false),
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000526 current_rampup_delay_ms_(kStandardRampUpDelayMs),
Niels Möller6b642f72017-12-08 14:11:14 +0100527 usage_(CreateProcessingUsage(options)) {
perkjd52063f2016-09-07 06:32:18 -0700528 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000529}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000530
531OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700532 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
533}
534
535void OveruseFrameDetector::StartCheckForOveruse() {
536 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
537 RTC_DCHECK(!check_overuse_task_);
538 check_overuse_task_ = new CheckOveruseTask(this);
539}
540void OveruseFrameDetector::StopCheckForOveruse() {
541 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
542 check_overuse_task_->Stop();
543 check_overuse_task_ = nullptr;
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000544}
545
Peter Boströme4499152016-02-05 11:13:28 +0100546void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700547 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100548 if (!metrics_)
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100549 metrics_ = CpuOveruseMetrics();
Peter Boströme4499152016-02-05 11:13:28 +0100550 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000551
Peter Boströme4499152016-02-05 11:13:28 +0100552 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000553}
554
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000555bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700556 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000557 if (num_pixels != num_pixels_) {
558 return true;
559 }
560 return false;
561}
562
nissee0e3bdf2017-01-18 02:16:20 -0800563bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700564 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800565 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000566 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800567 return (now_us - last_capture_time_us_) >
568 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000569}
570
Niels Möller7dc26b72017-12-06 10:27:48 +0100571void OveruseFrameDetector::ResetAll(int num_pixels) {
572 // Reset state, as a result resolution being changed. Do not however change
573 // the current frame rate back to the default.
perkjd52063f2016-09-07 06:32:18 -0700574 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100575 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000576 usage_->Reset();
nissee0e3bdf2017-01-18 02:16:20 -0800577 last_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000578 num_process_times_ = 0;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100579 metrics_ = rtc::nullopt;
Niels Möller7dc26b72017-12-06 10:27:48 +0100580 OnTargetFramerateUpdated(max_framerate_);
sprangfda496a2017-06-15 04:21:07 -0700581}
582
Niels Möller7dc26b72017-12-06 10:27:48 +0100583void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
perkjd52063f2016-09-07 06:32:18 -0700584 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100585 RTC_DCHECK_GE(framerate_fps, 0);
586 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
587 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
588 kMaxSampleDiffMarginFactor);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000589}
590
Niels Möller7dc26b72017-12-06 10:27:48 +0100591void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
592 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700593 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möllereee7ced2017-12-01 11:25:01 +0100594
Niels Möller7dc26b72017-12-06 10:27:48 +0100595 if (FrameSizeChanged(frame.width() * frame.height()) ||
596 FrameTimeoutDetected(time_when_first_seen_us)) {
597 ResetAll(frame.width() * frame.height());
598 }
599
Niels Möllere08cf3a2017-12-07 15:23:58 +0100600 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100601 last_capture_time_us_ = time_when_first_seen_us;
Niels Möller7dc26b72017-12-06 10:27:48 +0100602}
603
604void OveruseFrameDetector::FrameSent(uint32_t timestamp,
Niels Möller83dbeac2017-12-14 16:39:44 +0100605 int64_t time_sent_in_us,
606 int64_t capture_time_us,
607 rtc::Optional<int> encode_duration_us) {
Niels Möller7dc26b72017-12-06 10:27:48 +0100608 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller83dbeac2017-12-14 16:39:44 +0100609 encode_duration_us = usage_->FrameSent(timestamp, time_sent_in_us,
610 capture_time_us, encode_duration_us);
Niels Möllere08cf3a2017-12-07 15:23:58 +0100611
612 if (encode_duration_us) {
613 EncodedFrameTimeMeasured(*encode_duration_us /
614 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100615 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000616}
617
perkjd52063f2016-09-07 06:32:18 -0700618void OveruseFrameDetector::CheckForOveruse() {
619 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
620 ++num_process_times_;
621 if (num_process_times_ <= options_.min_process_count || !metrics_)
622 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000623
nissee0e3bdf2017-01-18 02:16:20 -0800624 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000625
perkjd52063f2016-09-07 06:32:18 -0700626 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000627 // If the last thing we did was going up, and now have to back down, we need
628 // to check if this peak was short. If so we should back off to avoid going
629 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100630 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000631 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800632 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000633 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000634 // Going up was not ok for very long, back off.
635 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
636 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
637 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
638 } else {
639 // Not currently backing off, reset rampup delay.
640 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
641 }
642 }
643
nissee0e3bdf2017-01-18 02:16:20 -0800644 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000645 in_quick_rampup_ = false;
646 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000647 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000648
Peter Boström74f6e9e2016-04-04 17:56:10 +0200649 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800650 observer_->AdaptDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800651 } else if (IsUnderusing(*metrics_, now_ms)) {
652 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000653 in_quick_rampup_ = true;
654
Peter Boström74f6e9e2016-04-04 17:56:10 +0200655 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800656 observer_->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000657 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000658
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000659 int rampup_delay =
660 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700661
Mirko Bonadei675513b2017-11-09 11:09:25 +0100662 RTC_LOG(LS_VERBOSE) << " Frame stats: "
663 << " encode usage " << metrics_->encode_usage_percent
664 << " overuse detections " << num_overuse_detections_
665 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000666}
667
asapersson74d85e12015-09-24 00:53:32 -0700668bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700669 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700670
Peter Boström01f364e2016-01-07 16:38:25 +0100671 if (metrics.encode_usage_percent >=
672 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000673 ++checks_above_threshold_;
674 } else {
675 checks_above_threshold_ = 0;
676 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000677 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000678}
679
asapersson74d85e12015-09-24 00:53:32 -0700680bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
681 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700682 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000683 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100684 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000685 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000686
Peter Boström01f364e2016-01-07 16:38:25 +0100687 return metrics.encode_usage_percent <
688 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000689}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000690} // namespace webrtc