blob: 0c56be80a97f389350f83f1c685c4735127e358e [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 +
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
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200244 absl::optional<int> FrameSent(
245 uint32_t timestamp,
246 int64_t time_sent_in_us,
247 int64_t capture_time_us,
248 absl::optional<int> encode_duration_us) override {
Niels Möller83dbeac2017-12-14 16:39:44 +0100249 if (encode_duration_us) {
250 if (prev_time_us_ != -1) {
251 AddSample(1e-6 * (*encode_duration_us),
252 1e-6 * (capture_time_us - prev_time_us_));
253 }
254 }
255 prev_time_us_ = capture_time_us;
256
257 return encode_duration_us;
258 }
259
260 private:
261 void AddSample(double encode_time, double diff_time) {
262 RTC_CHECK_GE(diff_time, 0.0);
263
264 // Use the filter update
265 //
266 // load <-- x/d (1-exp (-d/T)) + exp (-d/T) load
267 //
268 // where we must take care for small d, using the proper limit
269 // (1 - exp(-d/tau)) / d = 1/tau - d/2tau^2 + O(d^2)
270 double tau = (1e-3 * options_.filter_time_ms);
271 double e = diff_time / tau;
272 double c;
273 if (e < 0.0001) {
274 c = (1 - e / 2) / tau;
275 } else {
276 c = -expm1(-e) / diff_time;
277 }
278 load_estimate_ = c * encode_time + exp(-e) * load_estimate_;
279 }
280
281 int Value() override {
282 return static_cast<int>(100.0 * load_estimate_ + 0.5);
283 }
284
285 private:
286 const CpuOveruseOptions options_;
287 int64_t prev_time_us_ = -1;
288 double load_estimate_;
289};
290
291// Class used for manual testing of overuse, enabled via field trial flag.
292class OverdoseInjector : public OveruseFrameDetector::ProcessingUsage {
293 public:
294 OverdoseInjector(std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage,
sprangc5d62e22017-04-02 23:53:04 -0700295 int64_t normal_period_ms,
296 int64_t overuse_period_ms,
297 int64_t underuse_period_ms)
Niels Möller83dbeac2017-12-14 16:39:44 +0100298 : usage_(std::move(usage)),
sprangc5d62e22017-04-02 23:53:04 -0700299 normal_period_ms_(normal_period_ms),
300 overuse_period_ms_(overuse_period_ms),
301 underuse_period_ms_(underuse_period_ms),
302 state_(State::kNormal),
303 last_toggling_ms_(-1) {
304 RTC_DCHECK_GT(overuse_period_ms, 0);
305 RTC_DCHECK_GT(normal_period_ms, 0);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100306 RTC_LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
307 << "ms normal mode, " << overuse_period_ms
308 << "ms overuse mode.";
sprangc5d62e22017-04-02 23:53:04 -0700309 }
310
311 ~OverdoseInjector() override {}
312
Niels Möller83dbeac2017-12-14 16:39:44 +0100313 void Reset() override { usage_->Reset(); }
314
315 void SetMaxSampleDiffMs(float diff_ms) override {
316 usage_->SetMaxSampleDiffMs(diff_ms);
317 }
318
319 void FrameCaptured(const VideoFrame& frame,
320 int64_t time_when_first_seen_us,
321 int64_t last_capture_time_us) override {
322 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us);
323 }
324
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200325 absl::optional<int> FrameSent(
Niels Möller83dbeac2017-12-14 16:39:44 +0100326 // These two argument used by old estimator.
327 uint32_t timestamp,
328 int64_t time_sent_in_us,
329 // And these two by the new estimator.
330 int64_t capture_time_us,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200331 absl::optional<int> encode_duration_us) override {
Niels Möller83dbeac2017-12-14 16:39:44 +0100332 return usage_->FrameSent(timestamp, time_sent_in_us, capture_time_us,
333 encode_duration_us);
334 }
335
sprangc5d62e22017-04-02 23:53:04 -0700336 int Value() override {
337 int64_t now_ms = rtc::TimeMillis();
338 if (last_toggling_ms_ == -1) {
339 last_toggling_ms_ = now_ms;
340 } else {
341 switch (state_) {
342 case State::kNormal:
343 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
344 state_ = State::kOveruse;
345 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100346 RTC_LOG(LS_INFO) << "Simulating CPU overuse.";
sprangc5d62e22017-04-02 23:53:04 -0700347 }
348 break;
349 case State::kOveruse:
350 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
351 state_ = State::kUnderuse;
352 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100353 RTC_LOG(LS_INFO) << "Simulating CPU underuse.";
sprangc5d62e22017-04-02 23:53:04 -0700354 }
355 break;
356 case State::kUnderuse:
357 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
358 state_ = State::kNormal;
359 last_toggling_ms_ = now_ms;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100360 RTC_LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
sprangc5d62e22017-04-02 23:53:04 -0700361 }
362 break;
363 }
364 }
365
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200366 absl::optional<int> overried_usage_value;
sprangc5d62e22017-04-02 23:53:04 -0700367 switch (state_) {
368 case State::kNormal:
369 break;
370 case State::kOveruse:
371 overried_usage_value.emplace(250);
372 break;
373 case State::kUnderuse:
374 overried_usage_value.emplace(5);
375 break;
376 }
Niels Möller7dc26b72017-12-06 10:27:48 +0100377
Niels Möller83dbeac2017-12-14 16:39:44 +0100378 return overried_usage_value.value_or(usage_->Value());
sprangc5d62e22017-04-02 23:53:04 -0700379 }
380
381 private:
Niels Möller83dbeac2017-12-14 16:39:44 +0100382 const std::unique_ptr<OveruseFrameDetector::ProcessingUsage> usage_;
sprangc5d62e22017-04-02 23:53:04 -0700383 const int64_t normal_period_ms_;
384 const int64_t overuse_period_ms_;
385 const int64_t underuse_period_ms_;
386 enum class State { kNormal, kOveruse, kUnderuse } state_;
387 int64_t last_toggling_ms_;
388};
389
Niels Möller904f8692017-12-07 11:22:39 +0100390} // namespace
391
392CpuOveruseOptions::CpuOveruseOptions()
393 : high_encode_usage_threshold_percent(85),
394 frame_timeout_interval_ms(1500),
395 min_frame_samples(120),
396 min_process_count(3),
Niels Möller83dbeac2017-12-14 16:39:44 +0100397 high_threshold_consecutive_count(2),
398 // Disabled by default.
399 filter_time_ms(0) {
Niels Möller904f8692017-12-07 11:22:39 +0100400#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
401 // This is proof-of-concept code for letting the physical core count affect
402 // the interval into which we attempt to scale. For now, the code is Mac OS
403 // specific, since that's the platform were we saw most problems.
404 // TODO(torbjorng): Enhance SystemInfo to return this metric.
405
406 mach_port_t mach_host = mach_host_self();
407 host_basic_info hbi = {};
408 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
409 kern_return_t kr =
410 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
411 &info_count);
412 mach_port_deallocate(mach_task_self(), mach_host);
413
414 int n_physical_cores;
415 if (kr != KERN_SUCCESS) {
416 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
417 n_physical_cores = 1;
418 RTC_LOG(LS_ERROR)
419 << "Failed to determine number of physical cores, assuming 1";
420 } else {
421 n_physical_cores = hbi.physical_cpu;
422 RTC_LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
423 }
424
425 // Change init list default for few core systems. The assumption here is that
426 // encoding, which we measure here, takes about 1/4 of the processing of a
427 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
428 // hardware encoding. Since we don't affect the incoming stream here, we only
429 // control about 1/2 of the total processing needs, but this is not taken into
430 // account.
431 if (n_physical_cores == 1)
432 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
433 else if (n_physical_cores == 2)
434 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
435#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
436
437 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
438 // are close to that (when squared). This wide interval makes sure that
439 // scaling up or down does not jump all the way across the interval.
440 low_encode_usage_threshold_percent =
441 (high_encode_usage_threshold_percent - 1) / 2;
442}
443
444std::unique_ptr<OveruseFrameDetector::ProcessingUsage>
Niels Möllere08cf3a2017-12-07 15:23:58 +0100445OveruseFrameDetector::CreateProcessingUsage(
Niels Möller6b642f72017-12-08 14:11:14 +0100446 const CpuOveruseOptions& options) {
Niels Möller904f8692017-12-07 11:22:39 +0100447 std::unique_ptr<ProcessingUsage> instance;
Niels Möller83dbeac2017-12-14 16:39:44 +0100448 if (options.filter_time_ms > 0) {
449 instance = rtc::MakeUnique<SendProcessingUsage2>(options);
450 } else {
451 instance = rtc::MakeUnique<SendProcessingUsage1>(options);
452 }
sprangc5d62e22017-04-02 23:53:04 -0700453 std::string toggling_interval =
454 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
455 if (!toggling_interval.empty()) {
456 int normal_period_ms = 0;
457 int overuse_period_ms = 0;
458 int underuse_period_ms = 0;
459 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
460 &overuse_period_ms, &underuse_period_ms) == 3) {
461 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
462 underuse_period_ms > 0) {
Niels Möllere08cf3a2017-12-07 15:23:58 +0100463 instance = rtc::MakeUnique<OverdoseInjector>(
Niels Möller83dbeac2017-12-14 16:39:44 +0100464 std::move(instance), normal_period_ms,
465 overuse_period_ms, underuse_period_ms);
sprangc5d62e22017-04-02 23:53:04 -0700466 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100467 RTC_LOG(LS_WARNING)
sprangc5d62e22017-04-02 23:53:04 -0700468 << "Invalid (non-positive) normal/overuse/underuse periods: "
469 << normal_period_ms << " / " << overuse_period_ms << " / "
470 << underuse_period_ms;
471 }
472 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100473 RTC_LOG(LS_WARNING) << "Malformed toggling interval: "
474 << toggling_interval;
sprangc5d62e22017-04-02 23:53:04 -0700475 }
476 }
sprangc5d62e22017-04-02 23:53:04 -0700477 return instance;
478}
479
perkjd52063f2016-09-07 06:32:18 -0700480class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
481 public:
Niels Möller73f29cb2018-01-31 16:09:31 +0100482 CheckOveruseTask(OveruseFrameDetector* overuse_detector,
483 AdaptationObserverInterface* observer)
484 : overuse_detector_(overuse_detector), observer_(observer) {
perkjd52063f2016-09-07 06:32:18 -0700485 rtc::TaskQueue::Current()->PostDelayedTask(
486 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
487 }
488
489 void Stop() {
490 RTC_CHECK(task_checker_.CalledSequentially());
491 overuse_detector_ = nullptr;
492 }
493
494 private:
495 bool Run() override {
496 RTC_CHECK(task_checker_.CalledSequentially());
497 if (!overuse_detector_)
498 return true; // This will make the task queue delete this task.
Niels Möller73f29cb2018-01-31 16:09:31 +0100499 overuse_detector_->CheckForOveruse(observer_);
perkjd52063f2016-09-07 06:32:18 -0700500
501 rtc::TaskQueue::Current()->PostDelayedTask(
502 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
503 // Return false to prevent this task from being deleted. Ownership has been
504 // transferred to the task queue when PostDelayedTask was called.
505 return false;
506 }
507 rtc::SequencedTaskChecker task_checker_;
508 OveruseFrameDetector* overuse_detector_;
Niels Möller73f29cb2018-01-31 16:09:31 +0100509 // Observer getting overuse reports.
510 AdaptationObserverInterface* observer_;
perkjd52063f2016-09-07 06:32:18 -0700511};
512
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000513OveruseFrameDetector::OveruseFrameDetector(
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000514 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700515 : check_overuse_task_(nullptr),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000516 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000517 num_process_times_(0),
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200518 // TODO(nisse): Use absl::optional
nissee0e3bdf2017-01-18 02:16:20 -0800519 last_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700520 num_pixels_(0),
Niels Möller7dc26b72017-12-06 10:27:48 +0100521 max_framerate_(kDefaultFrameRate),
Peter Boströme4499152016-02-05 11:13:28 +0100522 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000523 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000524 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100525 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000526 in_quick_rampup_(false),
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200527 current_rampup_delay_ms_(kStandardRampUpDelayMs) {
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
Niels Möller73f29cb2018-01-31 16:09:31 +0100535void OveruseFrameDetector::StartCheckForOveruse(
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200536 const CpuOveruseOptions& options,
Niels Möller73f29cb2018-01-31 16:09:31 +0100537 AdaptationObserverInterface* overuse_observer) {
perkjd52063f2016-09-07 06:32:18 -0700538 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
539 RTC_DCHECK(!check_overuse_task_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100540 RTC_DCHECK(overuse_observer != nullptr);
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200541
542 SetOptions(options);
Niels Möller73f29cb2018-01-31 16:09:31 +0100543 check_overuse_task_ = new CheckOveruseTask(this, overuse_observer);
perkjd52063f2016-09-07 06:32:18 -0700544}
545void OveruseFrameDetector::StopCheckForOveruse() {
546 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller4db138e2018-04-19 09:04:13 +0200547 if (check_overuse_task_) {
548 check_overuse_task_->Stop();
549 check_overuse_task_ = nullptr;
550 }
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000551}
552
Peter Boströme4499152016-02-05 11:13:28 +0100553void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700554 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100555 if (!metrics_)
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100556 metrics_ = CpuOveruseMetrics();
Peter Boströme4499152016-02-05 11:13:28 +0100557 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000558
Peter Boströme4499152016-02-05 11:13:28 +0100559 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000560}
561
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000562bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700563 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000564 if (num_pixels != num_pixels_) {
565 return true;
566 }
567 return false;
568}
569
nissee0e3bdf2017-01-18 02:16:20 -0800570bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700571 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800572 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000573 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800574 return (now_us - last_capture_time_us_) >
575 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000576}
577
Niels Möller7dc26b72017-12-06 10:27:48 +0100578void OveruseFrameDetector::ResetAll(int num_pixels) {
579 // Reset state, as a result resolution being changed. Do not however change
580 // the current frame rate back to the default.
perkjd52063f2016-09-07 06:32:18 -0700581 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100582 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000583 usage_->Reset();
nissee0e3bdf2017-01-18 02:16:20 -0800584 last_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000585 num_process_times_ = 0;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200586 metrics_ = absl::nullopt;
Niels Möller7dc26b72017-12-06 10:27:48 +0100587 OnTargetFramerateUpdated(max_framerate_);
sprangfda496a2017-06-15 04:21:07 -0700588}
589
Niels Möller7dc26b72017-12-06 10:27:48 +0100590void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
perkjd52063f2016-09-07 06:32:18 -0700591 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100592 RTC_DCHECK_GE(framerate_fps, 0);
593 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
594 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
595 kMaxSampleDiffMarginFactor);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000596}
597
Niels Möller7dc26b72017-12-06 10:27:48 +0100598void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
599 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700600 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möllereee7ced2017-12-01 11:25:01 +0100601
Niels Möller7dc26b72017-12-06 10:27:48 +0100602 if (FrameSizeChanged(frame.width() * frame.height()) ||
603 FrameTimeoutDetected(time_when_first_seen_us)) {
604 ResetAll(frame.width() * frame.height());
605 }
606
Niels Möllere08cf3a2017-12-07 15:23:58 +0100607 usage_->FrameCaptured(frame, time_when_first_seen_us, last_capture_time_us_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100608 last_capture_time_us_ = time_when_first_seen_us;
Niels Möller7dc26b72017-12-06 10:27:48 +0100609}
610
611void OveruseFrameDetector::FrameSent(uint32_t timestamp,
Niels Möller83dbeac2017-12-14 16:39:44 +0100612 int64_t time_sent_in_us,
613 int64_t capture_time_us,
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200614 absl::optional<int> encode_duration_us) {
Niels Möller7dc26b72017-12-06 10:27:48 +0100615 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller83dbeac2017-12-14 16:39:44 +0100616 encode_duration_us = usage_->FrameSent(timestamp, time_sent_in_us,
617 capture_time_us, encode_duration_us);
Niels Möllere08cf3a2017-12-07 15:23:58 +0100618
619 if (encode_duration_us) {
620 EncodedFrameTimeMeasured(*encode_duration_us /
621 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100622 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000623}
624
Niels Möller73f29cb2018-01-31 16:09:31 +0100625void OveruseFrameDetector::CheckForOveruse(
626 AdaptationObserverInterface* observer) {
perkjd52063f2016-09-07 06:32:18 -0700627 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Niels Möller73f29cb2018-01-31 16:09:31 +0100628 RTC_DCHECK(observer);
perkjd52063f2016-09-07 06:32:18 -0700629 ++num_process_times_;
630 if (num_process_times_ <= options_.min_process_count || !metrics_)
631 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000632
nissee0e3bdf2017-01-18 02:16:20 -0800633 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000634
perkjd52063f2016-09-07 06:32:18 -0700635 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000636 // If the last thing we did was going up, and now have to back down, we need
637 // to check if this peak was short. If so we should back off to avoid going
638 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100639 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000640 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800641 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000642 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000643 // Going up was not ok for very long, back off.
644 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
645 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
646 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
647 } else {
648 // Not currently backing off, reset rampup delay.
649 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
650 }
651 }
652
nissee0e3bdf2017-01-18 02:16:20 -0800653 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000654 in_quick_rampup_ = false;
655 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000656 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000657
Niels Möller73f29cb2018-01-31 16:09:31 +0100658 observer->AdaptDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800659 } else if (IsUnderusing(*metrics_, now_ms)) {
660 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000661 in_quick_rampup_ = true;
662
Niels Möller73f29cb2018-01-31 16:09:31 +0100663 observer->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000664 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000665
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000666 int rampup_delay =
667 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700668
Mirko Bonadei675513b2017-11-09 11:09:25 +0100669 RTC_LOG(LS_VERBOSE) << " Frame stats: "
670 << " encode usage " << metrics_->encode_usage_percent
671 << " overuse detections " << num_overuse_detections_
672 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000673}
674
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200675void OveruseFrameDetector::SetOptions(const CpuOveruseOptions& options) {
676 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
677 options_ = options;
678 // Force reset with next frame.
679 num_pixels_ = 0;
680 usage_ = CreateProcessingUsage(options);
681}
682
asapersson74d85e12015-09-24 00:53:32 -0700683bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700684 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700685
Peter Boström01f364e2016-01-07 16:38:25 +0100686 if (metrics.encode_usage_percent >=
687 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000688 ++checks_above_threshold_;
689 } else {
690 checks_above_threshold_ = 0;
691 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000692 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000693}
694
asapersson74d85e12015-09-24 00:53:32 -0700695bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
696 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700697 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000698 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100699 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000700 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000701
Peter Boström01f364e2016-01-07 16:38:25 +0100702 return metrics.encode_usage_percent <
703 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000704}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000705} // namespace webrtc