blob: f110e1c9cb5b5d75b2fd6bda97a5865b4b7bd4f7 [file] [log] [blame]
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +00001/*
2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "video/overuse_frame_detector.h"
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000012
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000013#include <assert.h>
pbos@webrtc.orga9575702013-08-30 17:16:32 +000014#include <math.h>
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000015
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000016#include <algorithm>
17#include <list>
asapersson@webrtc.org734a5322014-06-10 06:35:22 +000018#include <map>
sprangc5d62e22017-04-02 23:53:04 -070019#include <string>
20#include <utility>
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000021
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/video/video_frame.h"
23#include "common_video/include/frame_callback.h"
24#include "rtc_base/checks.h"
25#include "rtc_base/logging.h"
26#include "rtc_base/numerics/exp_filter.h"
27#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
51// The maximum exponent to use in VCMExpFilter.
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000052const float kMaxExp = 7.0f;
sprangfda496a2017-06-15 04:21:07 -070053// 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;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000066
sprangb1ca0732017-02-01 08:38:12 -080067const auto kScaleReasonCpu = AdaptationObserverInterface::AdaptReason::kCpu;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000068} // namespace
69
torbjorng448468d2016-02-10 08:11:57 -080070CpuOveruseOptions::CpuOveruseOptions()
71 : high_encode_usage_threshold_percent(85),
72 frame_timeout_interval_ms(1500),
73 min_frame_samples(120),
74 min_process_count(3),
75 high_threshold_consecutive_count(2) {
pbosa1025072016-05-14 03:04:19 -070076#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080077 // This is proof-of-concept code for letting the physical core count affect
78 // the interval into which we attempt to scale. For now, the code is Mac OS
79 // specific, since that's the platform were we saw most problems.
80 // TODO(torbjorng): Enhance SystemInfo to return this metric.
81
82 mach_port_t mach_host = mach_host_self();
83 host_basic_info hbi = {};
84 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
85 kern_return_t kr =
86 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
87 &info_count);
88 mach_port_deallocate(mach_task_self(), mach_host);
89
90 int n_physical_cores;
91 if (kr != KERN_SUCCESS) {
92 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
93 n_physical_cores = 1;
94 LOG(LS_ERROR) << "Failed to determine number of physical cores, assuming 1";
95 } else {
96 n_physical_cores = hbi.physical_cpu;
97 LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
98 }
99
100 // Change init list default for few core systems. The assumption here is that
101 // encoding, which we measure here, takes about 1/4 of the processing of a
102 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
103 // hardware encoding. Since we don't affect the incoming stream here, we only
104 // control about 1/2 of the total processing needs, but this is not taken into
105 // account.
106 if (n_physical_cores == 1)
107 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
108 else if (n_physical_cores == 2)
109 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
pbosa1025072016-05-14 03:04:19 -0700110#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -0800111
torbjorng448468d2016-02-10 08:11:57 -0800112 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
113 // are close to that (when squared). This wide interval makes sure that
114 // scaling up or down does not jump all the way across the interval.
115 low_encode_usage_threshold_percent =
116 (high_encode_usage_threshold_percent - 1) / 2;
117}
118
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000119// Class for calculating the processing usage on the send-side (the average
120// processing time of a frame divided by the average time difference between
121// captured frames).
122class OveruseFrameDetector::SendProcessingUsage {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000123 public:
Peter Boström4b91bd02015-06-26 06:58:16 +0200124 explicit SendProcessingUsage(const CpuOveruseOptions& options)
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000125 : kWeightFactorFrameDiff(0.998f),
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000126 kWeightFactorProcessing(0.995f),
asapersson@webrtc.orge41dbee2014-05-13 13:45:13 +0000127 kInitialSampleDiffMs(40.0f),
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000128 count_(0),
Peter Boström4b91bd02015-06-26 06:58:16 +0200129 options_(options),
sprangfda496a2017-06-15 04:21:07 -0700130 max_sample_diff_ms_(kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor),
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000131 filtered_processing_ms_(new rtc::ExpFilter(kWeightFactorProcessing)),
minyue@webrtc.org74aaf292014-07-16 21:28:26 +0000132 filtered_frame_diff_ms_(new rtc::ExpFilter(kWeightFactorFrameDiff)) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000133 Reset();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000134 }
sprangc5d62e22017-04-02 23:53:04 -0700135 virtual ~SendProcessingUsage() {}
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000136
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000137 void Reset() {
138 count_ = 0;
sprangfda496a2017-06-15 04:21:07 -0700139 max_sample_diff_ms_ = kDefaultSampleDiffMs * kMaxSampleDiffMarginFactor;
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000140 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
141 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000142 filtered_processing_ms_->Reset(kWeightFactorProcessing);
143 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000144 }
145
sprangfda496a2017-06-15 04:21:07 -0700146 void SetMaxSampleDiffMs(float diff_ms) { max_sample_diff_ms_ = diff_ms; }
147
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000148 void AddCaptureSample(float sample_ms) {
sprangfda496a2017-06-15 04:21:07 -0700149 float exp = sample_ms / kDefaultSampleDiffMs;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000150 exp = std::min(exp, kMaxExp);
151 filtered_frame_diff_ms_->Apply(exp, sample_ms);
152 }
153
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000154 void AddSample(float processing_ms, int64_t diff_last_sample_ms) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000155 ++count_;
sprangfda496a2017-06-15 04:21:07 -0700156 float exp = diff_last_sample_ms / kDefaultSampleDiffMs;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000157 exp = std::min(exp, kMaxExp);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000158 filtered_processing_ms_->Apply(exp, processing_ms);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000159 }
160
sprangc5d62e22017-04-02 23:53:04 -0700161 virtual int Value() {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000162 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
163 return static_cast<int>(InitialUsageInPercent() + 0.5f);
164 }
minyue@webrtc.org74aaf292014-07-16 21:28:26 +0000165 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
sprangfda496a2017-06-15 04:21:07 -0700166 frame_diff_ms = std::min(frame_diff_ms, max_sample_diff_ms_);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000167 float encode_usage_percent =
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000168 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000169 return static_cast<int>(encode_usage_percent + 0.5);
170 }
171
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000172 private:
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000173 float InitialUsageInPercent() const {
174 // Start in between the underuse and overuse threshold.
175 return (options_.low_encode_usage_threshold_percent +
176 options_.high_encode_usage_threshold_percent) / 2.0f;
177 }
178
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000179 float InitialProcessingMs() const {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000180 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
181 }
182
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000183 const float kWeightFactorFrameDiff;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000184 const float kWeightFactorProcessing;
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000185 const float kInitialSampleDiffMs;
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000186 uint64_t count_;
Peter Boström4b91bd02015-06-26 06:58:16 +0200187 const CpuOveruseOptions options_;
sprangfda496a2017-06-15 04:21:07 -0700188 float max_sample_diff_ms_;
kwiberg27f982b2016-03-01 11:52:33 -0800189 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
190 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000191};
192
sprangc5d62e22017-04-02 23:53:04 -0700193// Class used for manual testing of overuse, enabled via field trial flag.
194class OveruseFrameDetector::OverdoseInjector
195 : public OveruseFrameDetector::SendProcessingUsage {
196 public:
197 OverdoseInjector(const CpuOveruseOptions& options,
198 int64_t normal_period_ms,
199 int64_t overuse_period_ms,
200 int64_t underuse_period_ms)
201 : OveruseFrameDetector::SendProcessingUsage(options),
202 normal_period_ms_(normal_period_ms),
203 overuse_period_ms_(overuse_period_ms),
204 underuse_period_ms_(underuse_period_ms),
205 state_(State::kNormal),
206 last_toggling_ms_(-1) {
207 RTC_DCHECK_GT(overuse_period_ms, 0);
208 RTC_DCHECK_GT(normal_period_ms, 0);
209 LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
210 << "ms normal mode, " << overuse_period_ms
211 << "ms overuse mode.";
212 }
213
214 ~OverdoseInjector() override {}
215
216 int Value() override {
217 int64_t now_ms = rtc::TimeMillis();
218 if (last_toggling_ms_ == -1) {
219 last_toggling_ms_ = now_ms;
220 } else {
221 switch (state_) {
222 case State::kNormal:
223 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
224 state_ = State::kOveruse;
225 last_toggling_ms_ = now_ms;
226 LOG(LS_INFO) << "Simulating CPU overuse.";
227 }
228 break;
229 case State::kOveruse:
230 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
231 state_ = State::kUnderuse;
232 last_toggling_ms_ = now_ms;
233 LOG(LS_INFO) << "Simulating CPU underuse.";
234 }
235 break;
236 case State::kUnderuse:
237 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
238 state_ = State::kNormal;
239 last_toggling_ms_ = now_ms;
240 LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
241 }
242 break;
243 }
244 }
245
246 rtc::Optional<int> overried_usage_value;
247 switch (state_) {
248 case State::kNormal:
249 break;
250 case State::kOveruse:
251 overried_usage_value.emplace(250);
252 break;
253 case State::kUnderuse:
254 overried_usage_value.emplace(5);
255 break;
256 }
257
258 return overried_usage_value.value_or(SendProcessingUsage::Value());
259 }
260
261 private:
262 const int64_t normal_period_ms_;
263 const int64_t overuse_period_ms_;
264 const int64_t underuse_period_ms_;
265 enum class State { kNormal, kOveruse, kUnderuse } state_;
266 int64_t last_toggling_ms_;
267};
268
269std::unique_ptr<OveruseFrameDetector::SendProcessingUsage>
270OveruseFrameDetector::CreateSendProcessingUsage(
271 const CpuOveruseOptions& options) {
272 std::unique_ptr<SendProcessingUsage> instance;
273 std::string toggling_interval =
274 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
275 if (!toggling_interval.empty()) {
276 int normal_period_ms = 0;
277 int overuse_period_ms = 0;
278 int underuse_period_ms = 0;
279 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
280 &overuse_period_ms, &underuse_period_ms) == 3) {
281 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
282 underuse_period_ms > 0) {
283 instance.reset(new OverdoseInjector(
284 options, normal_period_ms, overuse_period_ms, underuse_period_ms));
285 } else {
286 LOG(LS_WARNING)
287 << "Invalid (non-positive) normal/overuse/underuse periods: "
288 << normal_period_ms << " / " << overuse_period_ms << " / "
289 << underuse_period_ms;
290 }
291 } else {
292 LOG(LS_WARNING) << "Malformed toggling interval: " << toggling_interval;
293 }
294 }
295
296 if (!instance) {
297 // No valid overuse simulation parameters set, use normal usage class.
298 instance.reset(new SendProcessingUsage(options));
299 }
300
301 return instance;
302}
303
perkjd52063f2016-09-07 06:32:18 -0700304class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
305 public:
306 explicit CheckOveruseTask(OveruseFrameDetector* overuse_detector)
307 : overuse_detector_(overuse_detector) {
308 rtc::TaskQueue::Current()->PostDelayedTask(
309 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
310 }
311
312 void Stop() {
313 RTC_CHECK(task_checker_.CalledSequentially());
314 overuse_detector_ = nullptr;
315 }
316
317 private:
318 bool Run() override {
319 RTC_CHECK(task_checker_.CalledSequentially());
320 if (!overuse_detector_)
321 return true; // This will make the task queue delete this task.
322 overuse_detector_->CheckForOveruse();
323
324 rtc::TaskQueue::Current()->PostDelayedTask(
325 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
326 // Return false to prevent this task from being deleted. Ownership has been
327 // transferred to the task queue when PostDelayedTask was called.
328 return false;
329 }
330 rtc::SequencedTaskChecker task_checker_;
331 OveruseFrameDetector* overuse_detector_;
332};
333
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000334OveruseFrameDetector::OveruseFrameDetector(
Peter Boström4b91bd02015-06-26 06:58:16 +0200335 const CpuOveruseOptions& options,
sprangb1ca0732017-02-01 08:38:12 -0800336 AdaptationObserverInterface* observer,
Peter Boströme4499152016-02-05 11:13:28 +0100337 EncodedFrameObserver* encoder_timing,
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000338 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700339 : check_overuse_task_(nullptr),
340 options_(options),
Peter Boström4b91bd02015-06-26 06:58:16 +0200341 observer_(observer),
Peter Boströme4499152016-02-05 11:13:28 +0100342 encoder_timing_(encoder_timing),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000343 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000344 num_process_times_(0),
nissee0e3bdf2017-01-18 02:16:20 -0800345 // TODO(nisse): Use rtc::Optional
346 last_capture_time_us_(-1),
347 last_processed_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700348 num_pixels_(0),
sprangfda496a2017-06-15 04:21:07 -0700349 max_framerate_(kDefaultFrameRate),
Peter Boströme4499152016-02-05 11:13:28 +0100350 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000351 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000352 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100353 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000354 in_quick_rampup_(false),
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000355 current_rampup_delay_ms_(kStandardRampUpDelayMs),
sprangc5d62e22017-04-02 23:53:04 -0700356 usage_(CreateSendProcessingUsage(options)) {
perkjd52063f2016-09-07 06:32:18 -0700357 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000358}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000359
360OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700361 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
362}
363
364void OveruseFrameDetector::StartCheckForOveruse() {
365 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
366 RTC_DCHECK(!check_overuse_task_);
367 check_overuse_task_ = new CheckOveruseTask(this);
368}
369void OveruseFrameDetector::StopCheckForOveruse() {
370 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
371 check_overuse_task_->Stop();
372 check_overuse_task_ = nullptr;
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000373}
374
Peter Boströme4499152016-02-05 11:13:28 +0100375void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700376 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100377 if (!metrics_)
378 metrics_ = rtc::Optional<CpuOveruseMetrics>(CpuOveruseMetrics());
379 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000380
Peter Boströme4499152016-02-05 11:13:28 +0100381 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000382}
383
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000384bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700385 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000386 if (num_pixels != num_pixels_) {
387 return true;
388 }
389 return false;
390}
391
nissee0e3bdf2017-01-18 02:16:20 -0800392bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700393 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800394 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000395 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800396 return (now_us - last_capture_time_us_) >
397 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000398}
399
400void OveruseFrameDetector::ResetAll(int num_pixels) {
sprangfda496a2017-06-15 04:21:07 -0700401 // Reset state, as a result resolution being changed. Do not however change
402 // the current frame rate back to the default.
perkjd52063f2016-09-07 06:32:18 -0700403 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000404 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000405 usage_->Reset();
Peter Boströme4499152016-02-05 11:13:28 +0100406 frame_timing_.clear();
nissee0e3bdf2017-01-18 02:16:20 -0800407 last_capture_time_us_ = -1;
408 last_processed_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000409 num_process_times_ = 0;
Peter Boströme4499152016-02-05 11:13:28 +0100410 metrics_ = rtc::Optional<CpuOveruseMetrics>();
sprangfda496a2017-06-15 04:21:07 -0700411 OnTargetFramerateUpdated(max_framerate_);
412}
413
414void OveruseFrameDetector::OnTargetFramerateUpdated(int framerate_fps) {
415 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
416 RTC_DCHECK_GE(framerate_fps, 0);
417 max_framerate_ = std::min(kMaxFramerate, framerate_fps);
418 usage_->SetMaxSampleDiffMs((1000 / std::max(kMinFramerate, max_framerate_)) *
419 kMaxSampleDiffMarginFactor);
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000420}
421
perkjd52063f2016-09-07 06:32:18 -0700422void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
nissee0e3bdf2017-01-18 02:16:20 -0800423 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700424 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000425
Peter Boströme4499152016-02-05 11:13:28 +0100426 if (FrameSizeChanged(frame.width() * frame.height()) ||
nissee0e3bdf2017-01-18 02:16:20 -0800427 FrameTimeoutDetected(time_when_first_seen_us)) {
Peter Boströme4499152016-02-05 11:13:28 +0100428 ResetAll(frame.width() * frame.height());
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000429 }
430
nissee0e3bdf2017-01-18 02:16:20 -0800431 if (last_capture_time_us_ != -1)
432 usage_->AddCaptureSample(
433 1e-3 * (time_when_first_seen_us - last_capture_time_us_));
Åsa Persson746210f2015-09-08 10:52:42 +0200434
nissee0e3bdf2017-01-18 02:16:20 -0800435 last_capture_time_us_ = time_when_first_seen_us;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000436
nissee0e3bdf2017-01-18 02:16:20 -0800437 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
438 time_when_first_seen_us));
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000439}
440
perkjd52063f2016-09-07 06:32:18 -0700441void OveruseFrameDetector::FrameSent(uint32_t timestamp,
nissee0e3bdf2017-01-18 02:16:20 -0800442 int64_t time_sent_in_us) {
perkjd52063f2016-09-07 06:32:18 -0700443 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100444 // Delay before reporting actual encoding time, used to have the ability to
445 // detect total encoding time when encoding more than one layer. Encoding is
446 // here assumed to finish within a second (or that we get enough long-time
447 // samples before one second to trigger an overuse even when this is not the
448 // case).
449 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
Peter Boströme4499152016-02-05 11:13:28 +0100450 for (auto& it : frame_timing_) {
451 if (it.timestamp == timestamp) {
nissee0e3bdf2017-01-18 02:16:20 -0800452 it.last_send_us = time_sent_in_us;
Peter Boströme4499152016-02-05 11:13:28 +0100453 break;
454 }
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000455 }
Peter Boströme4499152016-02-05 11:13:28 +0100456 // TODO(pbos): Handle the case/log errors when not finding the corresponding
457 // frame (either very slow encoding or incorrect wrong timestamps returned
458 // from the encoder).
459 // This is currently the case for all frames on ChromeOS, so logging them
460 // would be spammy, and triggering overuse would be wrong.
461 // https://crbug.com/350106
462 while (!frame_timing_.empty()) {
463 FrameTiming timing = frame_timing_.front();
nissee0e3bdf2017-01-18 02:16:20 -0800464 if (time_sent_in_us - timing.capture_us <
sprangc5d62e22017-04-02 23:53:04 -0700465 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec) {
Peter Boströme4499152016-02-05 11:13:28 +0100466 break;
sprangc5d62e22017-04-02 23:53:04 -0700467 }
nissee0e3bdf2017-01-18 02:16:20 -0800468 if (timing.last_send_us != -1) {
469 int encode_duration_us =
470 static_cast<int>(timing.last_send_us - timing.capture_us);
Peter Boströme4499152016-02-05 11:13:28 +0100471 if (encoder_timing_) {
nissee0e3bdf2017-01-18 02:16:20 -0800472 // TODO(nisse): Update encoder_timing_ to also use us units.
473 encoder_timing_->OnEncodeTiming(timing.capture_time_us /
474 rtc::kNumMicrosecsPerMillisec,
475 encode_duration_us /
476 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100477 }
nissee0e3bdf2017-01-18 02:16:20 -0800478 if (last_processed_capture_time_us_ != -1) {
479 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
480 usage_->AddSample(1e-3 * encode_duration_us, 1e-3 * diff_us);
Peter Boströme4499152016-02-05 11:13:28 +0100481 }
nissee0e3bdf2017-01-18 02:16:20 -0800482 last_processed_capture_time_us_ = timing.capture_us;
483 EncodedFrameTimeMeasured(encode_duration_us /
484 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100485 }
486 frame_timing_.pop_front();
487 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000488}
489
perkjd52063f2016-09-07 06:32:18 -0700490void OveruseFrameDetector::CheckForOveruse() {
491 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
492 ++num_process_times_;
493 if (num_process_times_ <= options_.min_process_count || !metrics_)
494 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000495
nissee0e3bdf2017-01-18 02:16:20 -0800496 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000497
perkjd52063f2016-09-07 06:32:18 -0700498 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000499 // If the last thing we did was going up, and now have to back down, we need
500 // to check if this peak was short. If so we should back off to avoid going
501 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100502 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000503 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800504 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000505 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000506 // Going up was not ok for very long, back off.
507 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
508 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
509 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
510 } else {
511 // Not currently backing off, reset rampup delay.
512 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
513 }
514 }
515
nissee0e3bdf2017-01-18 02:16:20 -0800516 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000517 in_quick_rampup_ = false;
518 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000519 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000520
Peter Boström74f6e9e2016-04-04 17:56:10 +0200521 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800522 observer_->AdaptDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800523 } else if (IsUnderusing(*metrics_, now_ms)) {
524 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000525 in_quick_rampup_ = true;
526
Peter Boström74f6e9e2016-04-04 17:56:10 +0200527 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800528 observer_->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000529 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000530
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000531 int rampup_delay =
532 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700533
534 LOG(LS_VERBOSE) << " Frame stats: "
perkjd52063f2016-09-07 06:32:18 -0700535 << " encode usage " << metrics_->encode_usage_percent
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000536 << " overuse detections " << num_overuse_detections_
537 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000538}
539
asapersson74d85e12015-09-24 00:53:32 -0700540bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700541 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700542
Peter Boström01f364e2016-01-07 16:38:25 +0100543 if (metrics.encode_usage_percent >=
544 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000545 ++checks_above_threshold_;
546 } else {
547 checks_above_threshold_ = 0;
548 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000549 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000550}
551
asapersson74d85e12015-09-24 00:53:32 -0700552bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
553 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700554 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000555 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100556 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000557 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000558
Peter Boström01f364e2016-01-07 16:38:25 +0100559 return metrics.encode_usage_percent <
560 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000561}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000562} // namespace webrtc