blob: 42ee350257f03225ac39aee2062d0ba47f704f05 [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
Peter Boström7623ce42015-12-09 12:13:30 +010011#include "webrtc/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
nisseaf916892017-01-10 07:44:26 -080022#include "webrtc/api/video/video_frame.h"
tommi@webrtc.org7a57f8f2015-02-08 18:27:46 +000023#include "webrtc/base/checks.h"
Peter Boström415d2cd2015-10-26 11:35:17 +010024#include "webrtc/base/logging.h"
tereliusbc5d9212017-01-13 09:14:33 -080025#include "webrtc/base/numerics/exp_filter.h"
pbosa96b60b2016-04-18 21:12:48 -070026#include "webrtc/common_video/include/frame_callback.h"
sprangc5d62e22017-04-02 23:53:04 -070027#include "webrtc/system_wrappers/include/field_trial.h"
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000028
pbosa1025072016-05-14 03:04:19 -070029#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080030#include <mach/mach.h>
pbosa1025072016-05-14 03:04:19 -070031#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080032
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +000033namespace webrtc {
34
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000035namespace {
perkjd52063f2016-09-07 06:32:18 -070036const int64_t kCheckForOveruseIntervalMs = 5000;
37const int64_t kTimeToFirstCheckForOveruseMs = 100;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000038
pbos@webrtc.orga9575702013-08-30 17:16:32 +000039// Delay between consecutive rampups. (Used for quick recovery.)
40const int kQuickRampUpDelayMs = 10 * 1000;
41// Delay between rampup attempts. Initially uses standard, scales up to max.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000042const int kStandardRampUpDelayMs = 40 * 1000;
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +000043const int kMaxRampUpDelayMs = 240 * 1000;
pbos@webrtc.orga9575702013-08-30 17:16:32 +000044// Expontential back-off factor, to prevent annoying up-down behaviour.
45const double kRampUpBackoffFactor = 2.0;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000046
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +000047// Max number of overuses detected before always applying the rampup delay.
asapersson@webrtc.org23a4d852014-08-13 14:33:49 +000048const int kMaxOverusesBeforeApplyRampupDelay = 4;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +000049
50// The maximum exponent to use in VCMExpFilter.
51const float kSampleDiffMs = 33.0f;
52const float kMaxExp = 7.0f;
53
sprangb1ca0732017-02-01 08:38:12 -080054const auto kScaleReasonCpu = AdaptationObserverInterface::AdaptReason::kCpu;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +000055} // namespace
56
torbjorng448468d2016-02-10 08:11:57 -080057CpuOveruseOptions::CpuOveruseOptions()
58 : high_encode_usage_threshold_percent(85),
59 frame_timeout_interval_ms(1500),
60 min_frame_samples(120),
61 min_process_count(3),
62 high_threshold_consecutive_count(2) {
pbosa1025072016-05-14 03:04:19 -070063#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080064 // This is proof-of-concept code for letting the physical core count affect
65 // the interval into which we attempt to scale. For now, the code is Mac OS
66 // specific, since that's the platform were we saw most problems.
67 // TODO(torbjorng): Enhance SystemInfo to return this metric.
68
69 mach_port_t mach_host = mach_host_self();
70 host_basic_info hbi = {};
71 mach_msg_type_number_t info_count = HOST_BASIC_INFO_COUNT;
72 kern_return_t kr =
73 host_info(mach_host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi),
74 &info_count);
75 mach_port_deallocate(mach_task_self(), mach_host);
76
77 int n_physical_cores;
78 if (kr != KERN_SUCCESS) {
79 // If we couldn't get # of physical CPUs, don't panic. Assume we have 1.
80 n_physical_cores = 1;
81 LOG(LS_ERROR) << "Failed to determine number of physical cores, assuming 1";
82 } else {
83 n_physical_cores = hbi.physical_cpu;
84 LOG(LS_INFO) << "Number of physical cores:" << n_physical_cores;
85 }
86
87 // Change init list default for few core systems. The assumption here is that
88 // encoding, which we measure here, takes about 1/4 of the processing of a
89 // two-way call. This is roughly true for x86 using both vp8 and vp9 without
90 // hardware encoding. Since we don't affect the incoming stream here, we only
91 // control about 1/2 of the total processing needs, but this is not taken into
92 // account.
93 if (n_physical_cores == 1)
94 high_encode_usage_threshold_percent = 20; // Roughly 1/4 of 100%.
95 else if (n_physical_cores == 2)
96 high_encode_usage_threshold_percent = 40; // Roughly 1/4 of 200%.
pbosa1025072016-05-14 03:04:19 -070097#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
torbjorng448468d2016-02-10 08:11:57 -080098
torbjorng448468d2016-02-10 08:11:57 -080099 // Note that we make the interval 2x+epsilon wide, since libyuv scaling steps
100 // are close to that (when squared). This wide interval makes sure that
101 // scaling up or down does not jump all the way across the interval.
102 low_encode_usage_threshold_percent =
103 (high_encode_usage_threshold_percent - 1) / 2;
104}
105
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000106// Class for calculating the processing usage on the send-side (the average
107// processing time of a frame divided by the average time difference between
108// captured frames).
109class OveruseFrameDetector::SendProcessingUsage {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000110 public:
Peter Boström4b91bd02015-06-26 06:58:16 +0200111 explicit SendProcessingUsage(const CpuOveruseOptions& options)
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000112 : kWeightFactorFrameDiff(0.998f),
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000113 kWeightFactorProcessing(0.995f),
asapersson@webrtc.orge41dbee2014-05-13 13:45:13 +0000114 kInitialSampleDiffMs(40.0f),
115 kMaxSampleDiffMs(45.0f),
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000116 count_(0),
Peter Boström4b91bd02015-06-26 06:58:16 +0200117 options_(options),
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000118 filtered_processing_ms_(new rtc::ExpFilter(kWeightFactorProcessing)),
minyue@webrtc.org74aaf292014-07-16 21:28:26 +0000119 filtered_frame_diff_ms_(new rtc::ExpFilter(kWeightFactorFrameDiff)) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000120 Reset();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000121 }
sprangc5d62e22017-04-02 23:53:04 -0700122 virtual ~SendProcessingUsage() {}
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000123
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000124 void Reset() {
125 count_ = 0;
126 filtered_frame_diff_ms_->Reset(kWeightFactorFrameDiff);
127 filtered_frame_diff_ms_->Apply(1.0f, kInitialSampleDiffMs);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000128 filtered_processing_ms_->Reset(kWeightFactorProcessing);
129 filtered_processing_ms_->Apply(1.0f, InitialProcessingMs());
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000130 }
131
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000132 void AddCaptureSample(float sample_ms) {
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000133 float exp = sample_ms / kSampleDiffMs;
134 exp = std::min(exp, kMaxExp);
135 filtered_frame_diff_ms_->Apply(exp, sample_ms);
136 }
137
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000138 void AddSample(float processing_ms, int64_t diff_last_sample_ms) {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000139 ++count_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000140 float exp = diff_last_sample_ms / kSampleDiffMs;
141 exp = std::min(exp, kMaxExp);
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000142 filtered_processing_ms_->Apply(exp, processing_ms);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000143 }
144
sprangc5d62e22017-04-02 23:53:04 -0700145 virtual int Value() {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000146 if (count_ < static_cast<uint32_t>(options_.min_frame_samples)) {
147 return static_cast<int>(InitialUsageInPercent() + 0.5f);
148 }
minyue@webrtc.org74aaf292014-07-16 21:28:26 +0000149 float frame_diff_ms = std::max(filtered_frame_diff_ms_->filtered(), 1.0f);
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000150 frame_diff_ms = std::min(frame_diff_ms, kMaxSampleDiffMs);
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000151 float encode_usage_percent =
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000152 100.0f * filtered_processing_ms_->filtered() / frame_diff_ms;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000153 return static_cast<int>(encode_usage_percent + 0.5);
154 }
155
asapersson@webrtc.org2881ab12014-06-12 08:46:46 +0000156 private:
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000157 float InitialUsageInPercent() const {
158 // Start in between the underuse and overuse threshold.
159 return (options_.low_encode_usage_threshold_percent +
160 options_.high_encode_usage_threshold_percent) / 2.0f;
161 }
162
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000163 float InitialProcessingMs() const {
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000164 return InitialUsageInPercent() * kInitialSampleDiffMs / 100;
165 }
166
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000167 const float kWeightFactorFrameDiff;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000168 const float kWeightFactorProcessing;
asapersson@webrtc.orgce12f1f2014-03-24 21:59:16 +0000169 const float kInitialSampleDiffMs;
170 const float kMaxSampleDiffMs;
171 uint64_t count_;
Peter Boström4b91bd02015-06-26 06:58:16 +0200172 const CpuOveruseOptions options_;
kwiberg27f982b2016-03-01 11:52:33 -0800173 std::unique_ptr<rtc::ExpFilter> filtered_processing_ms_;
174 std::unique_ptr<rtc::ExpFilter> filtered_frame_diff_ms_;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000175};
176
sprangc5d62e22017-04-02 23:53:04 -0700177// Class used for manual testing of overuse, enabled via field trial flag.
178class OveruseFrameDetector::OverdoseInjector
179 : public OveruseFrameDetector::SendProcessingUsage {
180 public:
181 OverdoseInjector(const CpuOveruseOptions& options,
182 int64_t normal_period_ms,
183 int64_t overuse_period_ms,
184 int64_t underuse_period_ms)
185 : OveruseFrameDetector::SendProcessingUsage(options),
186 normal_period_ms_(normal_period_ms),
187 overuse_period_ms_(overuse_period_ms),
188 underuse_period_ms_(underuse_period_ms),
189 state_(State::kNormal),
190 last_toggling_ms_(-1) {
191 RTC_DCHECK_GT(overuse_period_ms, 0);
192 RTC_DCHECK_GT(normal_period_ms, 0);
193 LOG(LS_INFO) << "Simulating overuse with intervals " << normal_period_ms
194 << "ms normal mode, " << overuse_period_ms
195 << "ms overuse mode.";
196 }
197
198 ~OverdoseInjector() override {}
199
200 int Value() override {
201 int64_t now_ms = rtc::TimeMillis();
202 if (last_toggling_ms_ == -1) {
203 last_toggling_ms_ = now_ms;
204 } else {
205 switch (state_) {
206 case State::kNormal:
207 if (now_ms > last_toggling_ms_ + normal_period_ms_) {
208 state_ = State::kOveruse;
209 last_toggling_ms_ = now_ms;
210 LOG(LS_INFO) << "Simulating CPU overuse.";
211 }
212 break;
213 case State::kOveruse:
214 if (now_ms > last_toggling_ms_ + overuse_period_ms_) {
215 state_ = State::kUnderuse;
216 last_toggling_ms_ = now_ms;
217 LOG(LS_INFO) << "Simulating CPU underuse.";
218 }
219 break;
220 case State::kUnderuse:
221 if (now_ms > last_toggling_ms_ + underuse_period_ms_) {
222 state_ = State::kNormal;
223 last_toggling_ms_ = now_ms;
224 LOG(LS_INFO) << "Actual CPU overuse measurements in effect.";
225 }
226 break;
227 }
228 }
229
230 rtc::Optional<int> overried_usage_value;
231 switch (state_) {
232 case State::kNormal:
233 break;
234 case State::kOveruse:
235 overried_usage_value.emplace(250);
236 break;
237 case State::kUnderuse:
238 overried_usage_value.emplace(5);
239 break;
240 }
241
242 return overried_usage_value.value_or(SendProcessingUsage::Value());
243 }
244
245 private:
246 const int64_t normal_period_ms_;
247 const int64_t overuse_period_ms_;
248 const int64_t underuse_period_ms_;
249 enum class State { kNormal, kOveruse, kUnderuse } state_;
250 int64_t last_toggling_ms_;
251};
252
253std::unique_ptr<OveruseFrameDetector::SendProcessingUsage>
254OveruseFrameDetector::CreateSendProcessingUsage(
255 const CpuOveruseOptions& options) {
256 std::unique_ptr<SendProcessingUsage> instance;
257 std::string toggling_interval =
258 field_trial::FindFullName("WebRTC-ForceSimulatedOveruseIntervalMs");
259 if (!toggling_interval.empty()) {
260 int normal_period_ms = 0;
261 int overuse_period_ms = 0;
262 int underuse_period_ms = 0;
263 if (sscanf(toggling_interval.c_str(), "%d-%d-%d", &normal_period_ms,
264 &overuse_period_ms, &underuse_period_ms) == 3) {
265 if (normal_period_ms > 0 && overuse_period_ms > 0 &&
266 underuse_period_ms > 0) {
267 instance.reset(new OverdoseInjector(
268 options, normal_period_ms, overuse_period_ms, underuse_period_ms));
269 } else {
270 LOG(LS_WARNING)
271 << "Invalid (non-positive) normal/overuse/underuse periods: "
272 << normal_period_ms << " / " << overuse_period_ms << " / "
273 << underuse_period_ms;
274 }
275 } else {
276 LOG(LS_WARNING) << "Malformed toggling interval: " << toggling_interval;
277 }
278 }
279
280 if (!instance) {
281 // No valid overuse simulation parameters set, use normal usage class.
282 instance.reset(new SendProcessingUsage(options));
283 }
284
285 return instance;
286}
287
perkjd52063f2016-09-07 06:32:18 -0700288class OveruseFrameDetector::CheckOveruseTask : public rtc::QueuedTask {
289 public:
290 explicit CheckOveruseTask(OveruseFrameDetector* overuse_detector)
291 : overuse_detector_(overuse_detector) {
292 rtc::TaskQueue::Current()->PostDelayedTask(
293 std::unique_ptr<rtc::QueuedTask>(this), kTimeToFirstCheckForOveruseMs);
294 }
295
296 void Stop() {
297 RTC_CHECK(task_checker_.CalledSequentially());
298 overuse_detector_ = nullptr;
299 }
300
301 private:
302 bool Run() override {
303 RTC_CHECK(task_checker_.CalledSequentially());
304 if (!overuse_detector_)
305 return true; // This will make the task queue delete this task.
306 overuse_detector_->CheckForOveruse();
307
308 rtc::TaskQueue::Current()->PostDelayedTask(
309 std::unique_ptr<rtc::QueuedTask>(this), kCheckForOveruseIntervalMs);
310 // Return false to prevent this task from being deleted. Ownership has been
311 // transferred to the task queue when PostDelayedTask was called.
312 return false;
313 }
314 rtc::SequencedTaskChecker task_checker_;
315 OveruseFrameDetector* overuse_detector_;
316};
317
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000318OveruseFrameDetector::OveruseFrameDetector(
Peter Boström4b91bd02015-06-26 06:58:16 +0200319 const CpuOveruseOptions& options,
sprangb1ca0732017-02-01 08:38:12 -0800320 AdaptationObserverInterface* observer,
Peter Boströme4499152016-02-05 11:13:28 +0100321 EncodedFrameObserver* encoder_timing,
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000322 CpuOveruseMetricsObserver* metrics_observer)
perkjd52063f2016-09-07 06:32:18 -0700323 : check_overuse_task_(nullptr),
324 options_(options),
Peter Boström4b91bd02015-06-26 06:58:16 +0200325 observer_(observer),
Peter Boströme4499152016-02-05 11:13:28 +0100326 encoder_timing_(encoder_timing),
pbos@webrtc.org3e6e2712015-02-26 12:19:31 +0000327 metrics_observer_(metrics_observer),
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000328 num_process_times_(0),
nissee0e3bdf2017-01-18 02:16:20 -0800329 // TODO(nisse): Use rtc::Optional
330 last_capture_time_us_(-1),
331 last_processed_capture_time_us_(-1),
asapersson74d85e12015-09-24 00:53:32 -0700332 num_pixels_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100333 last_overuse_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000334 checks_above_threshold_(0),
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000335 num_overuse_detections_(0),
Peter Boströme4499152016-02-05 11:13:28 +0100336 last_rampup_time_ms_(-1),
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000337 in_quick_rampup_(false),
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000338 current_rampup_delay_ms_(kStandardRampUpDelayMs),
sprangc5d62e22017-04-02 23:53:04 -0700339 usage_(CreateSendProcessingUsage(options)) {
perkjd52063f2016-09-07 06:32:18 -0700340 task_checker_.Detach();
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000341}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000342
343OveruseFrameDetector::~OveruseFrameDetector() {
perkjd52063f2016-09-07 06:32:18 -0700344 RTC_DCHECK(!check_overuse_task_) << "StopCheckForOverUse must be called.";
345}
346
347void OveruseFrameDetector::StartCheckForOveruse() {
348 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
349 RTC_DCHECK(!check_overuse_task_);
350 check_overuse_task_ = new CheckOveruseTask(this);
351}
352void OveruseFrameDetector::StopCheckForOveruse() {
353 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
354 check_overuse_task_->Stop();
355 check_overuse_task_ = nullptr;
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000356}
357
Peter Boströme4499152016-02-05 11:13:28 +0100358void OveruseFrameDetector::EncodedFrameTimeMeasured(int encode_duration_ms) {
perkjd52063f2016-09-07 06:32:18 -0700359 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100360 if (!metrics_)
361 metrics_ = rtc::Optional<CpuOveruseMetrics>(CpuOveruseMetrics());
362 metrics_->encode_usage_percent = usage_->Value();
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000363
Peter Boströme4499152016-02-05 11:13:28 +0100364 metrics_observer_->OnEncodedFrameTimeMeasured(encode_duration_ms, *metrics_);
asapersson@webrtc.orgab6bf4f2014-05-27 07:43:15 +0000365}
366
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000367bool OveruseFrameDetector::FrameSizeChanged(int num_pixels) const {
perkjd52063f2016-09-07 06:32:18 -0700368 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000369 if (num_pixels != num_pixels_) {
370 return true;
371 }
372 return false;
373}
374
nissee0e3bdf2017-01-18 02:16:20 -0800375bool OveruseFrameDetector::FrameTimeoutDetected(int64_t now_us) const {
perkjd52063f2016-09-07 06:32:18 -0700376 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
nissee0e3bdf2017-01-18 02:16:20 -0800377 if (last_capture_time_us_ == -1)
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000378 return false;
nissee0e3bdf2017-01-18 02:16:20 -0800379 return (now_us - last_capture_time_us_) >
380 options_.frame_timeout_interval_ms * rtc::kNumMicrosecsPerMillisec;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000381}
382
383void OveruseFrameDetector::ResetAll(int num_pixels) {
perkjd52063f2016-09-07 06:32:18 -0700384 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000385 num_pixels_ = num_pixels;
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000386 usage_->Reset();
Peter Boströme4499152016-02-05 11:13:28 +0100387 frame_timing_.clear();
nissee0e3bdf2017-01-18 02:16:20 -0800388 last_capture_time_us_ = -1;
389 last_processed_capture_time_us_ = -1;
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000390 num_process_times_ = 0;
Peter Boströme4499152016-02-05 11:13:28 +0100391 metrics_ = rtc::Optional<CpuOveruseMetrics>();
asapersson@webrtc.orgb60346e2014-02-17 19:02:15 +0000392}
393
perkjd52063f2016-09-07 06:32:18 -0700394void OveruseFrameDetector::FrameCaptured(const VideoFrame& frame,
nissee0e3bdf2017-01-18 02:16:20 -0800395 int64_t time_when_first_seen_us) {
perkjd52063f2016-09-07 06:32:18 -0700396 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000397
Peter Boströme4499152016-02-05 11:13:28 +0100398 if (FrameSizeChanged(frame.width() * frame.height()) ||
nissee0e3bdf2017-01-18 02:16:20 -0800399 FrameTimeoutDetected(time_when_first_seen_us)) {
Peter Boströme4499152016-02-05 11:13:28 +0100400 ResetAll(frame.width() * frame.height());
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000401 }
402
nissee0e3bdf2017-01-18 02:16:20 -0800403 if (last_capture_time_us_ != -1)
404 usage_->AddCaptureSample(
405 1e-3 * (time_when_first_seen_us - last_capture_time_us_));
Åsa Persson746210f2015-09-08 10:52:42 +0200406
nissee0e3bdf2017-01-18 02:16:20 -0800407 last_capture_time_us_ = time_when_first_seen_us;
asapersson@webrtc.org9e5b0342013-12-04 13:47:44 +0000408
nissee0e3bdf2017-01-18 02:16:20 -0800409 frame_timing_.push_back(FrameTiming(frame.timestamp_us(), frame.timestamp(),
410 time_when_first_seen_us));
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000411}
412
perkjd52063f2016-09-07 06:32:18 -0700413void OveruseFrameDetector::FrameSent(uint32_t timestamp,
nissee0e3bdf2017-01-18 02:16:20 -0800414 int64_t time_sent_in_us) {
perkjd52063f2016-09-07 06:32:18 -0700415 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
Peter Boströme4499152016-02-05 11:13:28 +0100416 // Delay before reporting actual encoding time, used to have the ability to
417 // detect total encoding time when encoding more than one layer. Encoding is
418 // here assumed to finish within a second (or that we get enough long-time
419 // samples before one second to trigger an overuse even when this is not the
420 // case).
421 static const int64_t kEncodingTimeMeasureWindowMs = 1000;
Peter Boströme4499152016-02-05 11:13:28 +0100422 for (auto& it : frame_timing_) {
423 if (it.timestamp == timestamp) {
nissee0e3bdf2017-01-18 02:16:20 -0800424 it.last_send_us = time_sent_in_us;
Peter Boströme4499152016-02-05 11:13:28 +0100425 break;
426 }
asapersson@webrtc.org9aed0022014-10-16 06:57:12 +0000427 }
Peter Boströme4499152016-02-05 11:13:28 +0100428 // TODO(pbos): Handle the case/log errors when not finding the corresponding
429 // frame (either very slow encoding or incorrect wrong timestamps returned
430 // from the encoder).
431 // This is currently the case for all frames on ChromeOS, so logging them
432 // would be spammy, and triggering overuse would be wrong.
433 // https://crbug.com/350106
434 while (!frame_timing_.empty()) {
435 FrameTiming timing = frame_timing_.front();
nissee0e3bdf2017-01-18 02:16:20 -0800436 if (time_sent_in_us - timing.capture_us <
sprangc5d62e22017-04-02 23:53:04 -0700437 kEncodingTimeMeasureWindowMs * rtc::kNumMicrosecsPerMillisec) {
Peter Boströme4499152016-02-05 11:13:28 +0100438 break;
sprangc5d62e22017-04-02 23:53:04 -0700439 }
nissee0e3bdf2017-01-18 02:16:20 -0800440 if (timing.last_send_us != -1) {
441 int encode_duration_us =
442 static_cast<int>(timing.last_send_us - timing.capture_us);
Peter Boströme4499152016-02-05 11:13:28 +0100443 if (encoder_timing_) {
nissee0e3bdf2017-01-18 02:16:20 -0800444 // TODO(nisse): Update encoder_timing_ to also use us units.
445 encoder_timing_->OnEncodeTiming(timing.capture_time_us /
446 rtc::kNumMicrosecsPerMillisec,
447 encode_duration_us /
448 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100449 }
nissee0e3bdf2017-01-18 02:16:20 -0800450 if (last_processed_capture_time_us_ != -1) {
451 int64_t diff_us = timing.capture_us - last_processed_capture_time_us_;
452 usage_->AddSample(1e-3 * encode_duration_us, 1e-3 * diff_us);
Peter Boströme4499152016-02-05 11:13:28 +0100453 }
nissee0e3bdf2017-01-18 02:16:20 -0800454 last_processed_capture_time_us_ = timing.capture_us;
455 EncodedFrameTimeMeasured(encode_duration_us /
456 rtc::kNumMicrosecsPerMillisec);
Peter Boströme4499152016-02-05 11:13:28 +0100457 }
458 frame_timing_.pop_front();
459 }
asapersson@webrtc.orgc7ff8f92013-11-26 11:12:33 +0000460}
461
perkjd52063f2016-09-07 06:32:18 -0700462void OveruseFrameDetector::CheckForOveruse() {
463 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
464 ++num_process_times_;
465 if (num_process_times_ <= options_.min_process_count || !metrics_)
466 return;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000467
nissee0e3bdf2017-01-18 02:16:20 -0800468 int64_t now_ms = rtc::TimeMillis();
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000469
perkjd52063f2016-09-07 06:32:18 -0700470 if (IsOverusing(*metrics_)) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000471 // If the last thing we did was going up, and now have to back down, we need
472 // to check if this peak was short. If so we should back off to avoid going
473 // back and forth between this load, the system doesn't seem to handle it.
Peter Boströme4499152016-02-05 11:13:28 +0100474 bool check_for_backoff = last_rampup_time_ms_ > last_overuse_time_ms_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000475 if (check_for_backoff) {
nissee0e3bdf2017-01-18 02:16:20 -0800476 if (now_ms - last_rampup_time_ms_ < kStandardRampUpDelayMs ||
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000477 num_overuse_detections_ > kMaxOverusesBeforeApplyRampupDelay) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000478 // Going up was not ok for very long, back off.
479 current_rampup_delay_ms_ *= kRampUpBackoffFactor;
480 if (current_rampup_delay_ms_ > kMaxRampUpDelayMs)
481 current_rampup_delay_ms_ = kMaxRampUpDelayMs;
482 } else {
483 // Not currently backing off, reset rampup delay.
484 current_rampup_delay_ms_ = kStandardRampUpDelayMs;
485 }
486 }
487
nissee0e3bdf2017-01-18 02:16:20 -0800488 last_overuse_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000489 in_quick_rampup_ = false;
490 checks_above_threshold_ = 0;
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000491 ++num_overuse_detections_;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000492
Peter Boström74f6e9e2016-04-04 17:56:10 +0200493 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800494 observer_->AdaptDown(kScaleReasonCpu);
nissee0e3bdf2017-01-18 02:16:20 -0800495 } else if (IsUnderusing(*metrics_, now_ms)) {
496 last_rampup_time_ms_ = now_ms;
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000497 in_quick_rampup_ = true;
498
Peter Boström74f6e9e2016-04-04 17:56:10 +0200499 if (observer_)
sprangb1ca0732017-02-01 08:38:12 -0800500 observer_->AdaptUp(kScaleReasonCpu);
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000501 }
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000502
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000503 int rampup_delay =
504 in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
asapersson74d85e12015-09-24 00:53:32 -0700505
506 LOG(LS_VERBOSE) << " Frame stats: "
perkjd52063f2016-09-07 06:32:18 -0700507 << " encode usage " << metrics_->encode_usage_percent
asapersson@webrtc.orgd9803072014-06-16 14:27:19 +0000508 << " overuse detections " << num_overuse_detections_
509 << " rampup delay " << rampup_delay;
asapersson@webrtc.orge2af6222013-09-23 20:05:39 +0000510}
511
asapersson74d85e12015-09-24 00:53:32 -0700512bool OveruseFrameDetector::IsOverusing(const CpuOveruseMetrics& metrics) {
perkjd52063f2016-09-07 06:32:18 -0700513 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
sprangc5d62e22017-04-02 23:53:04 -0700514
Peter Boström01f364e2016-01-07 16:38:25 +0100515 if (metrics.encode_usage_percent >=
516 options_.high_encode_usage_threshold_percent) {
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000517 ++checks_above_threshold_;
518 } else {
519 checks_above_threshold_ = 0;
520 }
asapersson@webrtc.org8a8c3ef2014-03-20 13:15:01 +0000521 return checks_above_threshold_ >= options_.high_threshold_consecutive_count;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000522}
523
asapersson74d85e12015-09-24 00:53:32 -0700524bool OveruseFrameDetector::IsUnderusing(const CpuOveruseMetrics& metrics,
525 int64_t time_now) {
perkjd52063f2016-09-07 06:32:18 -0700526 RTC_DCHECK_CALLED_SEQUENTIALLY(&task_checker_);
pbos@webrtc.orga9575702013-08-30 17:16:32 +0000527 int delay = in_quick_rampup_ ? kQuickRampUpDelayMs : current_rampup_delay_ms_;
Peter Boströme4499152016-02-05 11:13:28 +0100528 if (time_now < last_rampup_time_ms_ + delay)
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000529 return false;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000530
Peter Boström01f364e2016-01-07 16:38:25 +0100531 return metrics.encode_usage_percent <
532 options_.low_encode_usage_threshold_percent;
mflodman@webrtc.orgd4412fe2013-07-31 16:42:21 +0000533}
mflodman@webrtc.orge6168f52013-06-26 11:23:01 +0000534} // namespace webrtc