blob: 4bccdf3cbd6a708a8f0c36072ec458cefd9b7182 [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>
Piotr Tworek5e4833c2017-12-12 12:09:31 +010015#include <stdio.h>
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000016
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000017#include <algorithm>
18#include <list>
asapersson@webrtc.org734a5322014-06-10 06:35:22 +000019#include <map>
sprangc5d62e22017-04-02 23:53:04 -070020#include <string>
21#include <utility>
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000022
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/video/video_frame.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#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öller83dbeac2017-12-14 16:39:44 +010072class SendProcessingUsage1 : public OveruseFrameDetector::ProcessingUsage {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000073 public:
Niels Möller83dbeac2017-12-14 16:39:44 +010074 explicit SendProcessingUsage1(const CpuOveruseOptions& options)
Niels Möller7dc26b72017-12-06 10:27:48 +010075 : kWeightFactorFrameDiff(0.998f),
76 kWeightFactorProcessing(0.995f),
77 kInitialSampleDiffMs(40.0f),
Niels Möller7dc26b72017-12-06 10:27:48 +010078 options_(options),
Niels Möllere08cf3a2017-12-07 15:23:58 +010079 count_(0),
80 last_processed_capture_time_us_(-1),
Niels Möller7dc26b72017-12-06 10:27:48 +010081 max_sample_diff_ms_(kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor),
82 filtered_processing_ms_(new rtc::ExpFilter(kWeightFactorProcessing)),
83 filtered_frame_diff_ms_(new rtc::ExpFilter(kWeightFactorFrameDiff)) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +000084 Reset();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000085 }
Niels Möller83dbeac2017-12-14 16:39:44 +010086 virtual ~SendProcessingUsage1() {}
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000087
Niels Möller904f8692017-12-07 11:22:39 +010088 void Reset() override {
Niels Möllere08cf3a2017-12-07 15:23:58 +010089 frame_timing_.clear();
Niels Möller7dc26b72017-12-06 10:27:48 +010090 count_ = 0;
Niels Möllere08cf3a2017-12-07 15:23:58 +010091 last_processed_capture_time_us_ = -1;
Niels Möller7dc26b72017-12-06 10:27:48 +010092 max_sample_diff_ms_ = kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor;
93 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
94 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
95 filtered_processing_ms_->Reset(kWeightFactorProcessing);
96 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +000097 }
98
Niels Möller904f8692017-12-07 11:22:39 +010099 void SetMaxSampleDiffMs(float diff_ms) override {
100 max_sample_diff_ms_ = diff_ms;
101 }
sprangfda496a2017-06-15 04:21:07 -0700102
Niels Möllere08cf3a2017-12-07 15:23:58 +0100103 void FrameCaptured(const VideoFrame& frame,
104 int64_t time_when_first_seen_us,
105 int64_t last_capture_time_us) override {
106 if (last_capture_time_us != -1)
107 AddCaptureSample(1e-3 * (time_when_first_seen_us - last_capture_time_us));
108
109 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
110 time_when_first_seen_us));
Niels Möller7dc26b72017-12-06 10:27:48 +0100111 }
112
Niels Möller83dbeac2017-12-14 16:39:44 +0100113 rtc::Optional<int> FrameSent(
114 uint32_t timestamp,
115 int64_t time_sent_in_us,
116 int64_t /* capture_time_us */,
117 rtc::Optional<int> /* encode_duration_us */) override {
Niels Möllere08cf3a2017-12-07 15:23:58 +0100118 rtc::Optional<int> encode_duration_us;
119 // Delay before reporting actual encoding time, used to have the ability to
120 // detect total encoding time when encoding more than one layer. Encoding is
121 // here assumed to finish within a second (or that we get enough long-time
122 // samples before one second to trigger an overuse even when this is not the
123 // case).
124 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
125 for (auto& it : frame_timing_) {
126 if (it.timestamp == timestamp) {
127 it.last_send_us = time_sent_in_us;
128 break;
129 }
130 }
131 // TODO(pbos): Handle the case/log errors when not finding the corresponding
132 // frame (either very slow encoding or incorrect wrong timestamps returned
133 // from the encoder).
134 // This is currently the case for all frames on ChromeOS, so logging them
135 // would be spammy, and triggering overuse would be wrong.
136 // https://crbug.com/350106
137 while (!frame_timing_.empty()) {
138 FrameTiming timing = frame_timing_.front();
139 if (time_sent_in_us - timing.capture_us <
140 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec) {
141 break;
142 }
143 if (timing.last_send_us != -1) {
144 encode_duration_us.emplace(
145 static_cast<int>(timing.last_send_us - timing.capture_us));
Niels Möller6b642f72017-12-08 14:11:14 +0100146
Niels Möllere08cf3a2017-12-07 15:23:58 +0100147 if (last_processed_capture_time_us_ != -1) {
148 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
149 AddSample(1e-3 * (*encode_duration_us), 1e-3 * diff_us);
150 }
151 last_processed_capture_time_us_ = timing.capture_us;
152 }
153 frame_timing_.pop_front();
154 }
155 return encode_duration_us;
Niels Möller7dc26b72017-12-06 10:27:48 +0100156 }
157
Niels Möller904f8692017-12-07 11:22:39 +0100158 int Value() override {
Niels Möller7dc26b72017-12-06 10:27:48 +0100159 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
160 return static_cast<int>(InitialUsageInPercent() + 0.5f);
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000161 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100162 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
163 frame_diff_ms = std::min(frame_diff_ms, max_sample_diff_ms_);
164 float encode_usage_percent =
165 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
166 return static_cast<int>(encode_usage_percent + 0.5);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000167 }
168
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000169 private:
Niels Möllere08cf3a2017-12-07 15:23:58 +0100170 struct FrameTiming {
171 FrameTiming(int64_t capture_time_us, uint32_t timestamp, int64_t now)
172 : capture_time_us(capture_time_us),
173 timestamp(timestamp),
174 capture_us(now),
175 last_send_us(-1) {}
176 int64_t capture_time_us;
177 uint32_t timestamp;
178 int64_t capture_us;
179 int64_t last_send_us;
180 };
181
182 void AddCaptureSample(float sample_ms) {
183 float exp = sample_ms / kDefaultSampleDiffMs;
184 exp = std::min(exp, kMaxExp);
185 filtered_frame_diff_ms_->Apply(exp, sample_ms);
186 }
187
188 void AddSample(float processing_ms, int64_t diff_last_sample_ms) {
189 ++count_;
190 float exp = diff_last_sample_ms / kDefaultSampleDiffMs;
191 exp = std::min(exp, kMaxExp);
192 filtered_processing_ms_->Apply(exp, processing_ms);
193 }
194
Niels Möller7dc26b72017-12-06 10:27:48 +0100195 float InitialUsageInPercent() const {
196 // Start in between the underuse and overuse threshold.
197 return (options_.low_encode_usage_threshold_percent +
198 options_.high_encode_usage_threshold_percent) / 2.0f;
199 }
200
201 float InitialProcessingMs() const {
202 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
203 }
204
205 const float kWeightFactorFrameDiff;
206 const float kWeightFactorProcessing;
207 const float kInitialSampleDiffMs;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100208
Peter Boström4b91bd02015-06-26 06:58:16 +0200209 const CpuOveruseOptions options_;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100210 std::list<FrameTiming> frame_timing_;
211 uint64_t count_;
212 int64_t last_processed_capture_time_us_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100213 float max_sample_diff_ms_;
214 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
215 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000216};
217
Niels Möller83dbeac2017-12-14 16:39:44 +0100218// New cpu load estimator.
219// TODO(bugs.webrtc.org/8504): For some period of time, we need to
220// switch between the two versions of the estimator for experiments.
221// When problems are sorted out, the old estimator should be deleted.
222class SendProcessingUsage2 : public OveruseFrameDetector::ProcessingUsage {
sprangc5d62e22017-04-02 23:53:04 -0700223 public:
Niels Möller83dbeac2017-12-14 16:39:44 +0100224 explicit SendProcessingUsage2(const CpuOveruseOptions& options)
225 : options_(options) {
226 Reset();
227 }
228 virtual ~SendProcessingUsage2() = default;
229
230 void Reset() override {
231 prev_time_us_ = -1;
232 // Start in between the underuse and overuse threshold.
233 load_estimate_ = (options_.low_encode_usage_threshold_percent +
234 options_.high_encode_usage_threshold_percent) /
235 200.0;
236 }
237
238 void SetMaxSampleDiffMs(float /* diff_ms */) override {}
239
240 void FrameCaptured(const VideoFrame& frame,
241 int64_t time_when_first_seen_us,
242 int64_t last_capture_time_us) override {}
243
244 rtc::Optional<int> FrameSent(uint32_t timestamp,
245 int64_t time_sent_in_us,
246 int64_t capture_time_us,
247 rtc::Optional<int> encode_duration_us) override {
248 if (encode_duration_us) {
249 if (prev_time_us_ != -1) {
250 AddSample(1e-6 * (*encode_duration_us),
251 1e-6 * (capture_time_us - prev_time_us_));
252 }
253 }
254 prev_time_us_ = capture_time_us;
255
256 return encode_duration_us;
257 }
258
259 private:
260 void AddSample(double encode_time, double diff_time) {
261 RTC_CHECK_GE(diff_time, 0.0);
262
263 // Use the filter update
264 //
265 // load <-- x/d (1-exp (-d/T)) + exp (-d/T) load
266 //
267 // where we must take care for small d, using the proper limit
268 // (1 - exp(-d/tau)) / d = 1/tau - d/2tau^2 + O(d^2)
269 double tau = (1e-3 * options_.filter_time_ms);
270 double e = diff_time / tau;
271 double c;
272 if (e < 0.0001) {
273 c = (1 - e / 2) / tau;
274 } else {
275 c = -expm1(-e) / diff_time;
276 }
277 load_estimate_ = c * encode_time + exp(-e) * load_estimate_;
278 }
279
280 int Value() override {
281 return static_cast<int>(100.0 * load_estimate_ + 0.5);
282 }
283
284 private:
285 const CpuOveruseOptions options_;
286 int64_t prev_time_us_ = -1;
287 double load_estimate_;
288};
289
290// Class used for manual testing of overuse, enabled via field trial flag.
291class OverdoseInjector : public OveruseFrameDetector::ProcessingUsage {
292 public:
293 OverdoseInjector(std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage,
sprangc5d62e22017-04-02 23:53:04 -0700294 int64_t normal_period_ms,
295 int64_t overuse_period_ms,
296 int64_t underuse_period_ms)
Niels Möller83dbeac2017-12-14 16:39:44 +0100297 : usage_(std::move(usage)),
sprangc5d62e22017-04-02 23:53:04 -0700298 normal_period_ms_(normal_period_ms),
299 overuse_period_ms_(overuse_period_ms),
300 underuse_period_ms_(underuse_period_ms),
301 state_(State::kNormal),
302 last_toggling_ms_(-1) {
303 RTC_DCHECK_GT(overuse_period_ms, 0);
304 RTC_DCHECK_GT(normal_period_ms, 0);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100305 RTC_LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
306 << "ms normal mode, " << overuse_period_ms
307 << "ms overuse mode.";
sprangc5d62e22017-04-02 23:53:04 -0700308 }
309
310 ~OverdoseInjector() override {}
311
Niels Möller83dbeac2017-12-14 16:39:44 +0100312 void Reset() override { usage_->Reset(); }
313
314 void SetMaxSampleDiffMs(float diff_ms) override {
315 usage_->SetMaxSampleDiffMs(diff_ms);
316 }
317
318 void FrameCaptured(const VideoFrame& frame,
319 int64_t time_when_first_seen_us,
320 int64_t last_capture_time_us) override {
321 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us);
322 }
323
324 rtc::Optional<int> FrameSent(
325 // These two argument used by old estimator.
326 uint32_t timestamp,
327 int64_t time_sent_in_us,
328 // And these two by the new estimator.
329 int64_t capture_time_us,
330 rtc::Optional<int> encode_duration_us) override {
331 return usage_->FrameSent(timestamp, time_sent_in_us, capture_time_us,
332 encode_duration_us);
333 }
334
sprangc5d62e22017-04-02 23:53:04 -0700335 int Value() override {
336 int64_t now_ms = rtc::TimeMillis();
337 if (last_toggling_ms_ == -1) {
338 last_toggling_ms_ = now_ms;
339 } else {
340 switch (state_) {
341 case State::kNormal:
342 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
343 state_ = State::kOveruse;
344 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100345 RTC_LOG(LS_INFO) << "Simulating CPU overuse.";
sprangc5d62e22017-04-02 23:53:04 -0700346 }
347 break;
348 case State::kOveruse:
349 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
350 state_ = State::kUnderuse;
351 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100352 RTC_LOG(LS_INFO) << "Simulating CPU underuse.";
sprangc5d62e22017-04-02 23:53:04 -0700353 }
354 break;
355 case State::kUnderuse:
356 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
357 state_ = State::kNormal;
358 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100359 RTC_LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
sprangc5d62e22017-04-02 23:53:04 -0700360 }
361 break;
362 }
363 }
364
365 rtc::Optional<int> overried_usage_value;
366 switch (state_) {
367 case State::kNormal:
368 break;
369 case State::kOveruse:
370 overried_usage_value.emplace(250);
371 break;
372 case State::kUnderuse:
373 overried_usage_value.emplace(5);
374 break;
375 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100376
Niels Möller83dbeac2017-12-14 16:39:44 +0100377 return overried_usage_value.value_or(usage_->Value());
sprangc5d62e22017-04-02 23:53:04 -0700378 }
379
380 private:
Niels Möller83dbeac2017-12-14 16:39:44 +0100381 const std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage_;
sprangc5d62e22017-04-02 23:53:04 -0700382 const int64_t normal_period_ms_;
383 const int64_t overuse_period_ms_;
384 const int64_t underuse_period_ms_;
385 enum class State { kNormal, kOveruse, kUnderuse } state_;
386 int64_t last_toggling_ms_;
387};
388
Niels Möller904f8692017-12-07 11:22:39 +0100389} // namespace
390
391CpuOveruseOptions::CpuOveruseOptions()
392 : high_encode_usage_threshold_percent(85),
393 frame_timeout_interval_ms(1500),
394 min_frame_samples(120),
395 min_process_count(3),
Niels Möller83dbeac2017-12-14 16:39:44 +0100396 high_threshold_consecutive_count(2),
397 // Disabled by default.
398 filter_time_ms(0) {
Niels Möller904f8692017-12-07 11:22:39 +0100399#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
400 // This is proof-of-concept code for letting the physical core count affect
401 // the interval into which we attempt to scale. For now, the code is Mac OS
402 // specific, since that's the platform were we saw most problems.
403 // TODO(torbjorng): Enhance SystemInfo to return this metric.
404
405 mach_port_t mach_host = mach_host_self();
406 host_basic_info hbi = {};
407 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
408 kern_return_t kr =
409 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
410 &info_count);
411 mach_port_deallocate(mach_task_self(), mach_host);
412
413 int n_physical_cores;
414 if (kr != KERN_SUCCESS) {
415 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
416 n_physical_cores = 1;
417 RTC_LOG(LS_ERROR)
418 << "Failed to determine number of physical cores, assuming 1";
419 } else {
420 n_physical_cores = hbi.physical_cpu;
421 RTC_LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
422 }
423
424 // Change init list default for few core systems. The assumption here is that
425 // encoding, which we measure here, takes about 1/4 of the processing of a
426 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
427 // hardware encoding. Since we don't affect the incoming stream here, we only
428 // control about 1/2 of the total processing needs, but this is not taken into
429 // account.
430 if (n_physical_cores == 1)
431 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
432 else if (n_physical_cores == 2)
433 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
434#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
435
436 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
437 // are close to that (when squared). This wide interval makes sure that
438 // scaling up or down does not jump all the way across the interval.
439 low_encode_usage_threshold_percent =
440 (high_encode_usage_threshold_percent - 1) / 2;
441}
442
443std::unique_ptr<OveruseFrameDetector::ProcessingUsage>
Niels Möllere08cf3a2017-12-07 15:23:58 +0100444OveruseFrameDetector::CreateProcessingUsage(
Niels Möller6b642f72017-12-08 14:11:14 +0100445 const CpuOveruseOptions& options) {
Niels Möller904f8692017-12-07 11:22:39 +0100446 std::unique_ptr<ProcessingUsage> instance;
Niels Möller83dbeac2017-12-14 16:39:44 +0100447 if (options.filter_time_ms > 0) {
448 instance = rtc::MakeUnique<SendProcessingUsage2>(options);
449 } else {
450 instance = rtc::MakeUnique<SendProcessingUsage1>(options);
451 }
sprangc5d62e22017-04-02 23:53:04 -0700452 std::string toggling_interval =
453 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
454 if (!toggling_interval.empty()) {
455 int normal_period_ms = 0;
456 int overuse_period_ms = 0;
457 int underuse_period_ms = 0;
458 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
459 &overuse_period_ms, &underuse_period_ms) == 3) {
460 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
461 underuse_period_ms > 0) {
Niels Möllere08cf3a2017-12-07 15:23:58 +0100462 instance = rtc::MakeUnique<OverdoseInjector>(
Niels Möller83dbeac2017-12-14 16:39:44 +0100463 std::move(instance), normal_period_ms,
464 overuse_period_ms, underuse_period_ms);
sprangc5d62e22017-04-02 23:53:04 -0700465 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100466 RTC_LOG(LS_WARNING)
sprangc5d62e22017-04-02 23:53:04 -0700467 << "Invalid (non-positive) normal/overuse/underuse periods: "
468 << normal_period_ms << " / " << overuse_period_ms << " / "
469 << underuse_period_ms;
470 }
471 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100472 RTC_LOG(LS_WARNING) << "Malformed toggling interval: "
473 << toggling_interval;
sprangc5d62e22017-04-02 23:53:04 -0700474 }
475 }
sprangc5d62e22017-04-02 23:53:04 -0700476 return instance;
477}
478
perkjd52063f2016-09-07 06:32:18 -0700479class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
480 public:
Niels Möller73f29cb2018-01-31 16:09:31 +0100481 CheckOveruseTask(OveruseFrameDetector* overuse_detector,
482 AdaptationObserverInterface* observer)
483 : overuse_detector_(overuse_detector), observer_(observer) {
perkjd52063f2016-09-07 06:32:18 -0700484 rtc::TaskQueue::Current()->PostDelayedTask(
485 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
486 }
487
488 void Stop() {
489 RTC_CHECK(task_checker_.CalledSequentially());
490 overuse_detector_ = nullptr;
491 }
492
493 private:
494 bool Run() override {
495 RTC_CHECK(task_checker_.CalledSequentially());
496 if (!overuse_detector_)
497 return true; // This will make the task queue delete this task.
Niels Möller73f29cb2018-01-31 16:09:31 +0100498 overuse_detector_->CheckForOveruse(observer_);
perkjd52063f2016-09-07 06:32:18 -0700499
500 rtc::TaskQueue::Current()->PostDelayedTask(
501 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
502 // Return false to prevent this task from being deleted. Ownership has been
503 // transferred to the task queue when PostDelayedTask was called.
504 return false;
505 }
506 rtc::SequencedTaskChecker task_checker_;
507 OveruseFrameDetector* overuse_detector_;
Niels Möller73f29cb2018-01-31 16:09:31 +0100508 // Observer getting overuse reports.
509 AdaptationObserverInterface* observer_;
perkjd52063f2016-09-07 06:32:18 -0700510};
511
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000512OveruseFrameDetector::OveruseFrameDetector(
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000513 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700514 : check_overuse_task_(nullptr),
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),
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200526 current_rampup_delay_ms_(kStandardRampUpDelayMs) {
perkjd52063f2016-09-07 06:32:18 -0700527 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000528}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000529
530OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700531 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
532}
533
Niels Möller73f29cb2018-01-31 16:09:31 +0100534void OveruseFrameDetector::StartCheckForOveruse(
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200535 const CpuOveruseOptions& options,
Niels Möller73f29cb2018-01-31 16:09:31 +0100536 AdaptationObserverInterface* overuse_observer) {
perkjd52063f2016-09-07 06:32:18 -0700537 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
538 RTC_DCHECK(!check_overuse_task_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100539 RTC_DCHECK(overuse_observer != nullptr);
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200540
541 SetOptions(options);
Niels Möller73f29cb2018-01-31 16:09:31 +0100542 check_overuse_task_ = new CheckOveruseTask(this, overuse_observer);
perkjd52063f2016-09-07 06:32:18 -0700543}
544void OveruseFrameDetector::StopCheckForOveruse() {
545 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller4db138e2018-04-19 09:04:13 +0200546 if (check_overuse_task_) {
547 check_overuse_task_->Stop();
548 check_overuse_task_ = nullptr;
549 }
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000550}
551
Peter Boströme4499152016-02-05 11:13:28 +0100552void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700553 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100554 if (!metrics_)
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100555 metrics_ = CpuOveruseMetrics();
Peter Boströme4499152016-02-05 11:13:28 +0100556 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000557
Peter Boströme4499152016-02-05 11:13:28 +0100558 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000559}
560
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000561bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700562 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000563 if (num_pixels != num_pixels_) {
564 return true;
565 }
566 return false;
567}
568
nissee0e3bdf2017-01-18 02:16:20 -0800569bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700570 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800571 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000572 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800573 return (now_us - last_capture_time_us_) >
574 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000575}
576
Niels Möller7dc26b72017-12-06 10:27:48 +0100577void OveruseFrameDetector::ResetAll(int num_pixels) {
578 // Reset state, as a result resolution being changed. Do not however change
579 // the current frame rate back to the default.
perkjd52063f2016-09-07 06:32:18 -0700580 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100581 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000582 usage_->Reset();
nissee0e3bdf2017-01-18 02:16:20 -0800583 last_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000584 num_process_times_ = 0;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100585 metrics_ = rtc::nullopt;
Niels Möller7dc26b72017-12-06 10:27:48 +0100586 OnTargetFramerateUpdated(max_framerate_);
sprangfda496a2017-06-15 04:21:07 -0700587}
588
Niels Möller7dc26b72017-12-06 10:27:48 +0100589void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
perkjd52063f2016-09-07 06:32:18 -0700590 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100591 RTC_DCHECK_GE(framerate_fps, 0);
592 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
593 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
594 kMaxSampleDiffMarginFactor);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000595}
596
Niels Möller7dc26b72017-12-06 10:27:48 +0100597void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
598 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700599 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möllereee7ced2017-12-01 11:25:01 +0100600
Niels Möller7dc26b72017-12-06 10:27:48 +0100601 if (FrameSizeChanged(frame.width() * frame.height()) ||
602 FrameTimeoutDetected(time_when_first_seen_us)) {
603 ResetAll(frame.width() * frame.height());
604 }
605
Niels Möllere08cf3a2017-12-07 15:23:58 +0100606 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100607 last_capture_time_us_ = time_when_first_seen_us;
Niels Möller7dc26b72017-12-06 10:27:48 +0100608}
609
610void OveruseFrameDetector::FrameSent(uint32_t timestamp,
Niels Möller83dbeac2017-12-14 16:39:44 +0100611 int64_t time_sent_in_us,
612 int64_t capture_time_us,
613 rtc::Optional<int> encode_duration_us) {
Niels Möller7dc26b72017-12-06 10:27:48 +0100614 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller83dbeac2017-12-14 16:39:44 +0100615 encode_duration_us = usage_->FrameSent(timestamp, time_sent_in_us,
616 capture_time_us, encode_duration_us);
Niels Möllere08cf3a2017-12-07 15:23:58 +0100617
618 if (encode_duration_us) {
619 EncodedFrameTimeMeasured(*encode_duration_us /
620 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100621 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000622}
623
Niels Möller73f29cb2018-01-31 16:09:31 +0100624void OveruseFrameDetector::CheckForOveruse(
625 AdaptationObserverInterface* observer) {
perkjd52063f2016-09-07 06:32:18 -0700626 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100627 RTC_DCHECK(observer);
perkjd52063f2016-09-07 06:32:18 -0700628 ++num_process_times_;
629 if (num_process_times_ <= options_.min_process_count || !metrics_)
630 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000631
nissee0e3bdf2017-01-18 02:16:20 -0800632 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000633
perkjd52063f2016-09-07 06:32:18 -0700634 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000635 // If the last thing we did was going up, and now have to back down, we need
636 // to check if this peak was short. If so we should back off to avoid going
637 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100638 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000639 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800640 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000641 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000642 // Going up was not ok for very long, back off.
643 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
644 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
645 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
646 } else {
647 // Not currently backing off, reset rampup delay.
648 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
649 }
650 }
651
nissee0e3bdf2017-01-18 02:16:20 -0800652 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000653 in_quick_rampup_ = false;
654 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000655 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000656
Niels Möller73f29cb2018-01-31 16:09:31 +0100657 observer->AdaptDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800658 } else if (IsUnderusing(*metrics_, now_ms)) {
659 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000660 in_quick_rampup_ = true;
661
Niels Möller73f29cb2018-01-31 16:09:31 +0100662 observer->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000663 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000664
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000665 int rampup_delay =
666 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700667
Mirko Bonadei675513b2017-11-09 11:09:25 +0100668 RTC_LOG(LS_VERBOSE) << " Frame stats: "
669 << " encode usage " << metrics_->encode_usage_percent
670 << " overuse detections " << num_overuse_detections_
671 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000672}
673
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200674void OveruseFrameDetector::SetOptions(const CpuOveruseOptions& options) {
675 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
676 options_ = options;
677 // Force reset with next frame.
678 num_pixels_ = 0;
679 usage_ = CreateProcessingUsage(options);
680}
681
asapersson74d85e12015-09-24 00:53:32 -0700682bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700683 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700684
Peter Boström01f364e2016-01-07 16:38:25 +0100685 if (metrics.encode_usage_percent >=
686 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000687 ++checks_above_threshold_;
688 } else {
689 checks_above_threshold_ = 0;
690 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000691 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000692}
693
asapersson74d85e12015-09-24 00:53:32 -0700694bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
695 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700696 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000697 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100698 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000699 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000700
Peter Boström01f364e2016-01-07 16:38:25 +0100701 return metrics.encode_usage_percent <
702 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000703}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000704} // namespace webrtc