blob: 95aaf59f173c977bddc14e215442d7fb39e66430 [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
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200113 absl::optional<int> FrameSent(
Niels Möller83dbeac2017-12-14 16:39:44 +0100114 uint32_t timestamp,
115 int64_t time_sent_in_us,
116 int64_t /* capture_time_us */,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200117 absl::optional<int> /* encode_duration_us */) override {
118 absl::optional<int> encode_duration_us;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100119 // 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 +
Yves Gerey665174f2018-06-19 15:03:05 +0200198 options_.high_encode_usage_threshold_percent) /
199 2.0f;
Niels Möller7dc26b72017-12-06 10:27:48 +0100200 }
201
202 float InitialProcessingMs() const {
203 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
204 }
205
206 const float kWeightFactorFrameDiff;
207 const float kWeightFactorProcessing;
208 const float kInitialSampleDiffMs;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100209
Peter Boström4b91bd02015-06-26 06:58:16 +0200210 const CpuOveruseOptions options_;
Niels Möllere08cf3a2017-12-07 15:23:58 +0100211 std::list<FrameTiming> frame_timing_;
212 uint64_t count_;
213 int64_t last_processed_capture_time_us_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100214 float max_sample_diff_ms_;
215 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
216 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000217};
218
Niels Möller83dbeac2017-12-14 16:39:44 +0100219// New cpu load estimator.
220// TODO(bugs.webrtc.org/8504): For some period of time, we need to
221// switch between the two versions of the estimator for experiments.
222// When problems are sorted out, the old estimator should be deleted.
223class SendProcessingUsage2 : public OveruseFrameDetector::ProcessingUsage {
sprangc5d62e22017-04-02 23:53:04 -0700224 public:
Niels Möller83dbeac2017-12-14 16:39:44 +0100225 explicit SendProcessingUsage2(const CpuOveruseOptions& options)
226 : options_(options) {
227 Reset();
228 }
229 virtual ~SendProcessingUsage2() = default;
230
231 void Reset() override {
232 prev_time_us_ = -1;
233 // Start in between the underuse and overuse threshold.
234 load_estimate_ = (options_.low_encode_usage_threshold_percent +
235 options_.high_encode_usage_threshold_percent) /
236 200.0;
237 }
238
239 void SetMaxSampleDiffMs(float /* diff_ms */) override {}
240
241 void FrameCaptured(const VideoFrame& frame,
242 int64_t time_when_first_seen_us,
243 int64_t last_capture_time_us) override {}
244
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200245 absl::optional<int> FrameSent(
246 uint32_t timestamp,
247 int64_t time_sent_in_us,
248 int64_t capture_time_us,
249 absl::optional<int> encode_duration_us) override {
Niels Möller83dbeac2017-12-14 16:39:44 +0100250 if (encode_duration_us) {
251 if (prev_time_us_ != -1) {
Niels Möller58d2a5e2018-08-07 16:37:18 +0200252 if (capture_time_us < prev_time_us_) {
253 // The weighting in AddSample assumes that samples are processed with
254 // non-decreasing measurement timestamps. We could implement
255 // appropriate weights for samples arriving late, but since it is a
256 // rare case, keep things simple, by just pushing those measurements a
257 // bit forward in time.
258 capture_time_us = prev_time_us_;
259 }
Niels Möller83dbeac2017-12-14 16:39:44 +0100260 AddSample(1e-6 * (*encode_duration_us),
261 1e-6 * (capture_time_us - prev_time_us_));
262 }
263 }
264 prev_time_us_ = capture_time_us;
265
266 return encode_duration_us;
267 }
268
269 private:
270 void AddSample(double encode_time, double diff_time) {
271 RTC_CHECK_GE(diff_time, 0.0);
272
273 // Use the filter update
274 //
275 // load <-- x/d (1-exp (-d/T)) + exp (-d/T) load
276 //
277 // where we must take care for small d, using the proper limit
278 // (1 - exp(-d/tau)) / d = 1/tau - d/2tau^2 + O(d^2)
279 double tau = (1e-3 * options_.filter_time_ms);
280 double e = diff_time / tau;
281 double c;
282 if (e < 0.0001) {
283 c = (1 - e / 2) / tau;
284 } else {
285 c = -expm1(-e) / diff_time;
286 }
287 load_estimate_ = c * encode_time + exp(-e) * load_estimate_;
288 }
289
290 int Value() override {
291 return static_cast<int>(100.0 * load_estimate_ + 0.5);
292 }
293
294 private:
295 const CpuOveruseOptions options_;
296 int64_t prev_time_us_ = -1;
297 double load_estimate_;
298};
299
300// Class used for manual testing of overuse, enabled via field trial flag.
301class OverdoseInjector : public OveruseFrameDetector::ProcessingUsage {
302 public:
303 OverdoseInjector(std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage,
sprangc5d62e22017-04-02 23:53:04 -0700304 int64_t normal_period_ms,
305 int64_t overuse_period_ms,
306 int64_t underuse_period_ms)
Niels Möller83dbeac2017-12-14 16:39:44 +0100307 : usage_(std::move(usage)),
sprangc5d62e22017-04-02 23:53:04 -0700308 normal_period_ms_(normal_period_ms),
309 overuse_period_ms_(overuse_period_ms),
310 underuse_period_ms_(underuse_period_ms),
311 state_(State::kNormal),
312 last_toggling_ms_(-1) {
313 RTC_DCHECK_GT(overuse_period_ms, 0);
314 RTC_DCHECK_GT(normal_period_ms, 0);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100315 RTC_LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
316 << "ms normal mode, " << overuse_period_ms
317 << "ms overuse mode.";
sprangc5d62e22017-04-02 23:53:04 -0700318 }
319
320 ~OverdoseInjector() override {}
321
Niels Möller83dbeac2017-12-14 16:39:44 +0100322 void Reset() override { usage_->Reset(); }
323
324 void SetMaxSampleDiffMs(float diff_ms) override {
325 usage_->SetMaxSampleDiffMs(diff_ms);
326 }
327
328 void FrameCaptured(const VideoFrame& frame,
329 int64_t time_when_first_seen_us,
330 int64_t last_capture_time_us) override {
331 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us);
332 }
333
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200334 absl::optional<int> FrameSent(
Niels Möller83dbeac2017-12-14 16:39:44 +0100335 // These two argument used by old estimator.
336 uint32_t timestamp,
337 int64_t time_sent_in_us,
338 // And these two by the new estimator.
339 int64_t capture_time_us,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200340 absl::optional<int> encode_duration_us) override {
Niels Möller83dbeac2017-12-14 16:39:44 +0100341 return usage_->FrameSent(timestamp, time_sent_in_us, capture_time_us,
342 encode_duration_us);
343 }
344
sprangc5d62e22017-04-02 23:53:04 -0700345 int Value() override {
346 int64_t now_ms = rtc::TimeMillis();
347 if (last_toggling_ms_ == -1) {
348 last_toggling_ms_ = now_ms;
349 } else {
350 switch (state_) {
351 case State::kNormal:
352 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
353 state_ = State::kOveruse;
354 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100355 RTC_LOG(LS_INFO) << "Simulating CPU overuse.";
sprangc5d62e22017-04-02 23:53:04 -0700356 }
357 break;
358 case State::kOveruse:
359 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
360 state_ = State::kUnderuse;
361 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100362 RTC_LOG(LS_INFO) << "Simulating CPU underuse.";
sprangc5d62e22017-04-02 23:53:04 -0700363 }
364 break;
365 case State::kUnderuse:
366 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
367 state_ = State::kNormal;
368 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100369 RTC_LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
sprangc5d62e22017-04-02 23:53:04 -0700370 }
371 break;
372 }
373 }
374
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200375 absl::optional<int> overried_usage_value;
sprangc5d62e22017-04-02 23:53:04 -0700376 switch (state_) {
377 case State::kNormal:
378 break;
379 case State::kOveruse:
380 overried_usage_value.emplace(250);
381 break;
382 case State::kUnderuse:
383 overried_usage_value.emplace(5);
384 break;
385 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100386
Niels Möller83dbeac2017-12-14 16:39:44 +0100387 return overried_usage_value.value_or(usage_->Value());
sprangc5d62e22017-04-02 23:53:04 -0700388 }
389
390 private:
Niels Möller83dbeac2017-12-14 16:39:44 +0100391 const std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage_;
sprangc5d62e22017-04-02 23:53:04 -0700392 const int64_t normal_period_ms_;
393 const int64_t overuse_period_ms_;
394 const int64_t underuse_period_ms_;
395 enum class State { kNormal, kOveruse, kUnderuse } state_;
396 int64_t last_toggling_ms_;
397};
398
Niels Möller904f8692017-12-07 11:22:39 +0100399} // namespace
400
401CpuOveruseOptions::CpuOveruseOptions()
402 : high_encode_usage_threshold_percent(85),
403 frame_timeout_interval_ms(1500),
404 min_frame_samples(120),
405 min_process_count(3),
Niels Möller83dbeac2017-12-14 16:39:44 +0100406 high_threshold_consecutive_count(2),
407 // Disabled by default.
408 filter_time_ms(0) {
Niels Möller904f8692017-12-07 11:22:39 +0100409#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
410 // This is proof-of-concept code for letting the physical core count affect
411 // the interval into which we attempt to scale. For now, the code is Mac OS
412 // specific, since that's the platform were we saw most problems.
413 // TODO(torbjorng): Enhance SystemInfo to return this metric.
414
415 mach_port_t mach_host = mach_host_self();
416 host_basic_info hbi = {};
417 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
418 kern_return_t kr =
419 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
420 &info_count);
421 mach_port_deallocate(mach_task_self(), mach_host);
422
423 int n_physical_cores;
424 if (kr != KERN_SUCCESS) {
425 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
426 n_physical_cores = 1;
427 RTC_LOG(LS_ERROR)
428 << "Failed to determine number of physical cores, assuming 1";
429 } else {
430 n_physical_cores = hbi.physical_cpu;
431 RTC_LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
432 }
433
434 // Change init list default for few core systems. The assumption here is that
435 // encoding, which we measure here, takes about 1/4 of the processing of a
436 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
437 // hardware encoding. Since we don't affect the incoming stream here, we only
438 // control about 1/2 of the total processing needs, but this is not taken into
439 // account.
440 if (n_physical_cores == 1)
441 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
442 else if (n_physical_cores == 2)
443 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
444#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
445
446 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
447 // are close to that (when squared). This wide interval makes sure that
448 // scaling up or down does not jump all the way across the interval.
449 low_encode_usage_threshold_percent =
450 (high_encode_usage_threshold_percent - 1) / 2;
451}
452
453std::unique_ptr<OveruseFrameDetector::ProcessingUsage>
Yves Gerey665174f2018-06-19 15:03:05 +0200454OveruseFrameDetector::CreateProcessingUsage(const CpuOveruseOptions& options) {
Niels Möller904f8692017-12-07 11:22:39 +0100455 std::unique_ptr<ProcessingUsage> instance;
Niels Möller83dbeac2017-12-14 16:39:44 +0100456 if (options.filter_time_ms > 0) {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200457 instance = absl::make_unique<SendProcessingUsage2>(options);
Niels Möller83dbeac2017-12-14 16:39:44 +0100458 } else {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200459 instance = absl::make_unique<SendProcessingUsage1>(options);
Niels Möller83dbeac2017-12-14 16:39:44 +0100460 }
sprangc5d62e22017-04-02 23:53:04 -0700461 std::string toggling_interval =
462 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
463 if (!toggling_interval.empty()) {
464 int normal_period_ms = 0;
465 int overuse_period_ms = 0;
466 int underuse_period_ms = 0;
467 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
468 &overuse_period_ms, &underuse_period_ms) == 3) {
469 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
470 underuse_period_ms > 0) {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200471 instance = absl::make_unique<OverdoseInjector>(
Yves Gerey665174f2018-06-19 15:03:05 +0200472 std::move(instance), normal_period_ms, overuse_period_ms,
473 underuse_period_ms);
sprangc5d62e22017-04-02 23:53:04 -0700474 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 RTC_LOG(LS_WARNING)
sprangc5d62e22017-04-02 23:53:04 -0700476 << "Invalid (non-positive) normal/overuse/underuse periods: "
477 << normal_period_ms << " / " << overuse_period_ms << " / "
478 << underuse_period_ms;
479 }
480 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100481 RTC_LOG(LS_WARNING) << "Malformed toggling interval: "
482 << toggling_interval;
sprangc5d62e22017-04-02 23:53:04 -0700483 }
484 }
sprangc5d62e22017-04-02 23:53:04 -0700485 return instance;
486}
487
perkjd52063f2016-09-07 06:32:18 -0700488class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
489 public:
Niels Möller73f29cb2018-01-31 16:09:31 +0100490 CheckOveruseTask(OveruseFrameDetector* overuse_detector,
491 AdaptationObserverInterface* observer)
492 : overuse_detector_(overuse_detector), observer_(observer) {
perkjd52063f2016-09-07 06:32:18 -0700493 rtc::TaskQueue::Current()->PostDelayedTask(
494 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
495 }
496
497 void Stop() {
498 RTC_CHECK(task_checker_.CalledSequentially());
499 overuse_detector_ = nullptr;
500 }
501
502 private:
503 bool Run() override {
504 RTC_CHECK(task_checker_.CalledSequentially());
505 if (!overuse_detector_)
506 return true; // This will make the task queue delete this task.
Niels Möller73f29cb2018-01-31 16:09:31 +0100507 overuse_detector_->CheckForOveruse(observer_);
perkjd52063f2016-09-07 06:32:18 -0700508
509 rtc::TaskQueue::Current()->PostDelayedTask(
510 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
511 // Return false to prevent this task from being deleted. Ownership has been
512 // transferred to the task queue when PostDelayedTask was called.
513 return false;
514 }
515 rtc::SequencedTaskChecker task_checker_;
516 OveruseFrameDetector* overuse_detector_;
Niels Möller73f29cb2018-01-31 16:09:31 +0100517 // Observer getting overuse reports.
518 AdaptationObserverInterface* observer_;
perkjd52063f2016-09-07 06:32:18 -0700519};
520
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000521OveruseFrameDetector::OveruseFrameDetector(
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000522 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700523 : check_overuse_task_(nullptr),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000524 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000525 num_process_times_(0),
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200526 // TODO(nisse): Use absl::optional
nissee0e3bdf2017-01-18 02:16:20 -0800527 last_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700528 num_pixels_(0),
Niels Möller7dc26b72017-12-06 10:27:48 +0100529 max_framerate_(kDefaultFrameRate),
Peter Boströme4499152016-02-05 11:13:28 +0100530 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000531 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000532 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100533 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000534 in_quick_rampup_(false),
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200535 current_rampup_delay_ms_(kStandardRampUpDelayMs) {
perkjd52063f2016-09-07 06:32:18 -0700536 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000537}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000538
539OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700540 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
541}
542
Niels Möller73f29cb2018-01-31 16:09:31 +0100543void OveruseFrameDetector::StartCheckForOveruse(
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200544 const CpuOveruseOptions& options,
Niels Möller73f29cb2018-01-31 16:09:31 +0100545 AdaptationObserverInterface* overuse_observer) {
perkjd52063f2016-09-07 06:32:18 -0700546 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
547 RTC_DCHECK(!check_overuse_task_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100548 RTC_DCHECK(overuse_observer != nullptr);
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200549
550 SetOptions(options);
Niels Möller73f29cb2018-01-31 16:09:31 +0100551 check_overuse_task_ = new CheckOveruseTask(this, overuse_observer);
perkjd52063f2016-09-07 06:32:18 -0700552}
553void OveruseFrameDetector::StopCheckForOveruse() {
554 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller4db138e2018-04-19 09:04:13 +0200555 if (check_overuse_task_) {
556 check_overuse_task_->Stop();
557 check_overuse_task_ = nullptr;
558 }
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000559}
560
Peter Boströme4499152016-02-05 11:13:28 +0100561void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700562 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller213618e2018-07-24 09:29:58 +0200563 encode_usage_percent_ = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000564
Niels Möller213618e2018-07-24 09:29:58 +0200565 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms,
566 *encode_usage_percent_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000567}
568
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000569bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700570 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000571 if (num_pixels != num_pixels_) {
572 return true;
573 }
574 return false;
575}
576
nissee0e3bdf2017-01-18 02:16:20 -0800577bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700578 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800579 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000580 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800581 return (now_us - last_capture_time_us_) >
Yves Gerey665174f2018-06-19 15:03:05 +0200582 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000583}
584
Niels Möller7dc26b72017-12-06 10:27:48 +0100585void OveruseFrameDetector::ResetAll(int num_pixels) {
586 // Reset state, as a result resolution being changed. Do not however change
587 // the current frame rate back to the default.
perkjd52063f2016-09-07 06:32:18 -0700588 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100589 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000590 usage_->Reset();
nissee0e3bdf2017-01-18 02:16:20 -0800591 last_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000592 num_process_times_ = 0;
Niels Möller213618e2018-07-24 09:29:58 +0200593 encode_usage_percent_ = absl::nullopt;
Niels Möller7dc26b72017-12-06 10:27:48 +0100594 OnTargetFramerateUpdated(max_framerate_);
sprangfda496a2017-06-15 04:21:07 -0700595}
596
Niels Möller7dc26b72017-12-06 10:27:48 +0100597void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
perkjd52063f2016-09-07 06:32:18 -0700598 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100599 RTC_DCHECK_GE(framerate_fps, 0);
600 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
601 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
602 kMaxSampleDiffMarginFactor);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000603}
604
Niels Möller7dc26b72017-12-06 10:27:48 +0100605void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
606 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700607 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möllereee7ced2017-12-01 11:25:01 +0100608
Niels Möller7dc26b72017-12-06 10:27:48 +0100609 if (FrameSizeChanged(frame.width() * frame.height()) ||
610 FrameTimeoutDetected(time_when_first_seen_us)) {
611 ResetAll(frame.width() * frame.height());
612 }
613
Niels Möllere08cf3a2017-12-07 15:23:58 +0100614 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100615 last_capture_time_us_ = time_when_first_seen_us;
Niels Möller7dc26b72017-12-06 10:27:48 +0100616}
617
618void OveruseFrameDetector::FrameSent(uint32_t timestamp,
Niels Möller83dbeac2017-12-14 16:39:44 +0100619 int64_t time_sent_in_us,
620 int64_t capture_time_us,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200621 absl::optional<int> encode_duration_us) {
Niels Möller7dc26b72017-12-06 10:27:48 +0100622 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller83dbeac2017-12-14 16:39:44 +0100623 encode_duration_us = usage_->FrameSent(timestamp, time_sent_in_us,
624 capture_time_us, encode_duration_us);
Niels Möllere08cf3a2017-12-07 15:23:58 +0100625
626 if (encode_duration_us) {
627 EncodedFrameTimeMeasured(*encode_duration_us /
628 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100629 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000630}
631
Niels Möller73f29cb2018-01-31 16:09:31 +0100632void OveruseFrameDetector::CheckForOveruse(
633 AdaptationObserverInterface* observer) {
perkjd52063f2016-09-07 06:32:18 -0700634 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100635 RTC_DCHECK(observer);
perkjd52063f2016-09-07 06:32:18 -0700636 ++num_process_times_;
Niels Möller213618e2018-07-24 09:29:58 +0200637 if (num_process_times_ <= options_.min_process_count ||
638 !encode_usage_percent_)
perkjd52063f2016-09-07 06:32:18 -0700639 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000640
nissee0e3bdf2017-01-18 02:16:20 -0800641 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000642
Niels Möller213618e2018-07-24 09:29:58 +0200643 if (IsOverusing(*encode_usage_percent_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000644 // If the last thing we did was going up, and now have to back down, we need
645 // to check if this peak was short. If so we should back off to avoid going
646 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100647 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000648 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800649 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000650 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000651 // Going up was not ok for very long, back off.
652 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
653 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
654 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
655 } else {
656 // Not currently backing off, reset rampup delay.
657 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
658 }
659 }
660
nissee0e3bdf2017-01-18 02:16:20 -0800661 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000662 in_quick_rampup_ = false;
663 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000664 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000665
Niels Möller73f29cb2018-01-31 16:09:31 +0100666 observer->AdaptDown(kScaleReasonCpu);
Niels Möller213618e2018-07-24 09:29:58 +0200667 } else if (IsUnderusing(*encode_usage_percent_, now_ms)) {
nissee0e3bdf2017-01-18 02:16:20 -0800668 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000669 in_quick_rampup_ = true;
670
Niels Möller73f29cb2018-01-31 16:09:31 +0100671 observer->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000672 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000673
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000674 int rampup_delay =
675 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700676
Mirko Bonadei675513b2017-11-09 11:09:25 +0100677 RTC_LOG(LS_VERBOSE) << " Frame stats: "
Niels Möller213618e2018-07-24 09:29:58 +0200678 << " encode usage " << *encode_usage_percent_
Mirko Bonadei675513b2017-11-09 11:09:25 +0100679 << " overuse detections " << num_overuse_detections_
680 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000681}
682
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200683void OveruseFrameDetector::SetOptions(const CpuOveruseOptions& options) {
684 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
685 options_ = options;
686 // Force reset with next frame.
687 num_pixels_ = 0;
688 usage_ = CreateProcessingUsage(options);
689}
690
Niels Möller213618e2018-07-24 09:29:58 +0200691bool OveruseFrameDetector::IsOverusing(int usage_percent) {
perkjd52063f2016-09-07 06:32:18 -0700692 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700693
Niels Möller213618e2018-07-24 09:29:58 +0200694 if (usage_percent >= options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000695 ++checks_above_threshold_;
696 } else {
697 checks_above_threshold_ = 0;
698 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000699 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000700}
701
Niels Möller213618e2018-07-24 09:29:58 +0200702bool OveruseFrameDetector::IsUnderusing(int usage_percent, int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700703 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000704 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100705 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000706 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000707
Niels Möller213618e2018-07-24 09:29:58 +0200708 return usage_percent < options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000709}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000710} // namespace webrtc