blob: 1b7f2f782c90d49a30c169cf34b51b72b4370a8d [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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/video_stream_encoder.h"
mflodman@webrtc.org84d17832011-12-01 17:02:23 +000012
stefan@webrtc.orgc3cc3752013-06-04 09:36:56 +000013#include <algorithm>
perkj57c21f92016-06-17 07:27:16 -070014#include <limits>
sprangc5d62e22017-04-02 23:53:04 -070015#include <numeric>
Per512ecb32016-09-23 15:52:06 +020016#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/video/i420_buffer.h"
19#include "common_video/include/video_bitrate_allocator.h"
20#include "common_video/include/video_frame.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "modules/video_coding/include/video_codec_initializer.h"
22#include "modules/video_coding/include/video_coding.h"
23#include "modules/video_coding/include/video_coding_defines.h"
24#include "rtc_base/arraysize.h"
25#include "rtc_base/checks.h"
Åsa Perssona945aee2018-04-24 16:53:25 +020026#include "rtc_base/experiments/quality_scaling_experiment.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/location.h"
28#include "rtc_base/logging.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010029#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/timeutils.h"
31#include "rtc_base/trace_event.h"
32#include "video/overuse_frame_detector.h"
33#include "video/send_statistics_proxy.h"
nisseea3a7982017-05-15 02:42:11 -070034
niklase@google.com470e71d2011-07-07 08:21:25 +000035namespace webrtc {
36
perkj26091b12016-09-01 01:17:40 -070037namespace {
sprangb1ca0732017-02-01 08:38:12 -080038
asapersson6ffb67d2016-09-12 00:10:45 -070039// Time interval for logging frame counts.
40const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070041const int kMinFramerateFps = 2;
sprangfda496a2017-06-15 04:21:07 -070042const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 01:17:40 -070043
Sebastian Janssona3177052018-04-10 13:05:49 +020044// Time to keep a single cached pending frame in paused state.
45const int64_t kPendingFrameTimeoutMs = 1000;
46
kthelgason2bc68642017-02-07 07:02:22 -080047// The maximum number of frames to drop at beginning of stream
48// to try and achieve desired bitrate.
49const int kMaxInitialFramedrop = 4;
50
asaperssonf7e294d2017-06-13 23:25:22 -070051// Initial limits for kBalanced degradation preference.
52int MinFps(int pixels) {
53 if (pixels <= 320 * 240) {
54 return 7;
55 } else if (pixels <= 480 * 270) {
56 return 10;
57 } else if (pixels <= 640 * 480) {
58 return 15;
59 } else {
60 return std::numeric_limits<int>::max();
61 }
62}
63
64int MaxFps(int pixels) {
65 if (pixels <= 320 * 240) {
66 return 10;
67 } else if (pixels <= 480 * 270) {
68 return 15;
69 } else {
70 return std::numeric_limits<int>::max();
71 }
72}
73
asapersson09f05612017-05-15 23:40:18 -070074bool IsResolutionScalingEnabled(
75 VideoSendStream::DegradationPreference degradation_preference) {
76 return degradation_preference ==
77 VideoSendStream::DegradationPreference::kMaintainFramerate ||
78 degradation_preference ==
79 VideoSendStream::DegradationPreference::kBalanced;
80}
81
82bool IsFramerateScalingEnabled(
83 VideoSendStream::DegradationPreference degradation_preference) {
84 return degradation_preference ==
85 VideoSendStream::DegradationPreference::kMaintainResolution ||
86 degradation_preference ==
87 VideoSendStream::DegradationPreference::kBalanced;
88}
89
Niels Möllerd1f7eb62018-03-28 16:40:58 +020090// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
91// pipelining encoders better (multiple input frames before something comes
92// out). This should effectively turn off CPU adaptations for systems that
93// remotely cope with the load right now.
94CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller4db138e2018-04-19 09:04:13 +020095 const VideoSendStream::Config::EncoderSettings& settings,
96 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020097 CpuOveruseOptions options;
98
Niels Möller4db138e2018-04-19 09:04:13 +020099 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200100 options.low_encode_usage_threshold_percent = 150;
101 options.high_encode_usage_threshold_percent = 200;
102 }
103 if (settings.experiment_cpu_load_estimator) {
104 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
105 }
106
107 return options;
108}
109
perkj26091b12016-09-01 01:17:40 -0700110} // namespace
111
perkja49cbd32016-09-16 07:53:41 -0700112// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700113// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
114// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700115// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700116class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700117 public:
mflodmancc3d4422017-08-03 08:27:51 -0700118 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
119 : video_stream_encoder_(video_stream_encoder),
hbos8d609f62017-04-10 07:39:05 -0700120 degradation_preference_(
121 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj803d97f2016-11-01 11:45:46 -0700122 source_(nullptr) {}
perkja49cbd32016-09-16 07:53:41 -0700123
hbos8d609f62017-04-10 07:39:05 -0700124 void SetSource(
125 rtc::VideoSourceInterface<VideoFrame>* source,
126 const VideoSendStream::DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700127 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700128 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
129 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700130 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700131 {
132 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700133 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700134 old_source = source_;
135 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700136 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700137 }
138
139 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700140 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700141 }
142
143 if (!source) {
144 return;
145 }
146
mflodmancc3d4422017-08-03 08:27:51 -0700147 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700148 }
149
perkj803d97f2016-11-01 11:45:46 -0700150 void SetWantsRotationApplied(bool rotation_applied) {
151 rtc::CritScope lock(&crit_);
152 sink_wants_.rotation_applied = rotation_applied;
sprangc5d62e22017-04-02 23:53:04 -0700153 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700154 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-02 23:53:04 -0700155 }
156
sprangfda496a2017-06-15 04:21:07 -0700157 rtc::VideoSinkWants GetActiveSinkWants() {
158 rtc::CritScope lock(&crit_);
159 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700160 }
161
asaperssonf7e294d2017-06-13 23:25:22 -0700162 void ResetPixelFpsCount() {
163 rtc::CritScope lock(&crit_);
164 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
165 sink_wants_.target_pixel_count.reset();
166 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
167 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700168 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-13 23:25:22 -0700169 }
170
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100171 bool RequestResolutionLowerThan(int pixel_count,
172 int min_pixels_per_frame,
173 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700174 // Called on the encoder task queue.
175 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700176 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700177 // This can happen since |degradation_preference_| is set on libjingle's
178 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700179 return false;
perkj803d97f2016-11-01 11:45:46 -0700180 }
asapersson13874762017-06-07 00:01:02 -0700181 // The input video frame size will have a resolution less than or equal to
182 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800183 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100184 if (pixels_wanted >= sink_wants_.max_pixel_count) {
185 return false;
186 }
187 if (pixels_wanted < min_pixels_per_frame) {
188 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700189 return false;
asapersson13874762017-06-07 00:01:02 -0700190 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100191 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
192 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700193 sink_wants_.max_pixel_count = pixels_wanted;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100194 sink_wants_.target_pixel_count = rtc::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700195 source_->AddOrUpdateSink(video_stream_encoder_,
196 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700197 return true;
sprangc5d62e22017-04-02 23:53:04 -0700198 }
199
sprangfda496a2017-06-15 04:21:07 -0700200 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700201 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700202 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700203 int framerate_wanted = (fps * 2) / 3;
204 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700205 }
206
asapersson13874762017-06-07 00:01:02 -0700207 bool RequestHigherResolutionThan(int pixel_count) {
208 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700209 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700210 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700211 // This can happen since |degradation_preference_| is set on libjingle's
212 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700213 return false;
perkj803d97f2016-11-01 11:45:46 -0700214 }
asapersson13874762017-06-07 00:01:02 -0700215 int max_pixels_wanted = pixel_count;
216 if (max_pixels_wanted != std::numeric_limits<int>::max())
217 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700218
asapersson13874762017-06-07 00:01:02 -0700219 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
220 return false;
221
222 sink_wants_.max_pixel_count = max_pixels_wanted;
223 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700224 // Remove any constraints.
225 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700226 } else {
227 // On step down we request at most 3/5 the pixel count of the previous
228 // resolution, so in order to take "one step up" we request a resolution
229 // as close as possible to 5/3 of the current resolution. The actual pixel
230 // count selected depends on the capabilities of the source. In order to
231 // not take a too large step up, we cap the requested pixel count to be at
232 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100233 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700234 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100235 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
236 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700237 source_->AddOrUpdateSink(video_stream_encoder_,
238 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700239 return true;
sprangc5d62e22017-04-02 23:53:04 -0700240 }
241
sprangfda496a2017-06-15 04:21:07 -0700242 // Request upgrade in framerate. Returns the new requested frame, or -1 if
243 // no change requested. Note that maxint may be returned if limits due to
244 // adaptation requests are removed completely. In that case, consider
245 // |max_framerate_| to be the current limit (assuming the capturer complies).
246 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700247 // Called on the encoder task queue.
248 // The input frame rate will be scaled up to the last step, with rounding.
249 int framerate_wanted = fps;
250 if (fps != std::numeric_limits<int>::max())
251 framerate_wanted = (fps * 3) / 2;
252
sprangfda496a2017-06-15 04:21:07 -0700253 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700254 }
255
256 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700257 // Called on the encoder task queue.
258 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700259 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
260 return false;
261
262 const int fps_wanted = std::max(kMinFramerateFps, fps);
263 if (fps_wanted >= sink_wants_.max_framerate_fps)
264 return false;
265
Mirko Bonadei675513b2017-11-09 11:09:25 +0100266 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700267 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700268 source_->AddOrUpdateSink(video_stream_encoder_,
269 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700270 return true;
271 }
272
273 bool IncreaseFramerate(int fps) {
274 // Called on the encoder task queue.
275 rtc::CritScope lock(&crit_);
276 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
277 return false;
278
279 const int fps_wanted = std::max(kMinFramerateFps, fps);
280 if (fps_wanted <= sink_wants_.max_framerate_fps)
281 return false;
282
Mirko Bonadei675513b2017-11-09 11:09:25 +0100283 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700284 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700285 source_->AddOrUpdateSink(video_stream_encoder_,
286 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700287 return true;
perkj803d97f2016-11-01 11:45:46 -0700288 }
289
perkja49cbd32016-09-16 07:53:41 -0700290 private:
sprangfda496a2017-06-15 04:21:07 -0700291 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700292 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700293 rtc::VideoSinkWants wants = sink_wants_;
294 // Clear any constraints from the current sink wants that don't apply to
295 // the used degradation_preference.
296 switch (degradation_preference_) {
297 case VideoSendStream::DegradationPreference::kBalanced:
298 break;
299 case VideoSendStream::DegradationPreference::kMaintainFramerate:
300 wants.max_framerate_fps = std::numeric_limits<int>::max();
301 break;
302 case VideoSendStream::DegradationPreference::kMaintainResolution:
303 wants.max_pixel_count = std::numeric_limits<int>::max();
304 wants.target_pixel_count.reset();
305 break;
306 case VideoSendStream::DegradationPreference::kDegradationDisabled:
307 wants.max_pixel_count = std::numeric_limits<int>::max();
308 wants.target_pixel_count.reset();
309 wants.max_framerate_fps = std::numeric_limits<int>::max();
310 }
311 return wants;
312 }
313
perkja49cbd32016-09-16 07:53:41 -0700314 rtc::CriticalSection crit_;
315 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700316 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700317 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
hbos8d609f62017-04-10 07:39:05 -0700318 VideoSendStream::DegradationPreference degradation_preference_
danilchapa37de392017-09-09 04:17:22 -0700319 RTC_GUARDED_BY(&crit_);
320 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700321
322 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
323};
324
Åsa Persson0122e842017-10-16 12:19:23 +0200325VideoStreamEncoder::VideoStreamEncoder(
326 uint32_t number_of_cores,
327 SendStatisticsProxy* stats_proxy,
328 const VideoSendStream::Config::EncoderSettings& settings,
329 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
Åsa Persson0122e842017-10-16 12:19:23 +0200330 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700331 : shutdown_event_(true /* manual_reset */, false),
332 number_of_cores_(number_of_cores),
kthelgason2bc68642017-02-07 07:02:22 -0800333 initial_rampup_(0),
Åsa Perssona945aee2018-04-24 16:53:25 +0200334 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700335 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200336 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700337 settings_(settings),
Niels Möllera0565992017-10-24 11:37:08 +0200338 video_sender_(Clock::GetRealTimeClock(), this),
Niels Möller73f29cb2018-01-31 16:09:31 +0100339 overuse_detector_(std::move(overuse_detector)),
Peter Boström7083e112015-09-22 16:28:51 +0200340 stats_proxy_(stats_proxy),
perkj26091b12016-09-01 01:17:40 -0700341 pre_encode_callback_(pre_encode_callback),
sprangfda496a2017-06-15 04:21:07 -0700342 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700343 pending_encoder_reconfiguration_(false),
Niels Möller4db138e2018-04-19 09:04:13 +0200344 pending_encoder_creation_(false),
perkj26091b12016-09-01 01:17:40 -0700345 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200346 max_data_payload_length_(0),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000347 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000348 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700349 clock_(Clock::GetRealTimeClock()),
hbos8d609f62017-04-10 07:39:05 -0700350 degradation_preference_(
351 VideoSendStream::DegradationPreference::kDegradationDisabled),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700352 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700353 last_captured_timestamp_(0),
354 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
355 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700356 last_frame_log_ms_(clock_->TimeInMilliseconds()),
357 captured_frame_count_(0),
358 dropped_frame_count_(0),
sprang1a646ee2016-12-01 06:34:11 -0800359 bitrate_observer_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700360 encoder_queue_("EncoderQueue") {
sprang552c7c72017-02-13 04:41:45 -0800361 RTC_DCHECK(stats_proxy);
Niels Möller73f29cb2018-01-31 16:09:31 +0100362 RTC_DCHECK(overuse_detector_);
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000363}
364
mflodmancc3d4422017-08-03 08:27:51 -0700365VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700366 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700367 RTC_DCHECK(shutdown_event_.Wait(0))
368 << "Must call ::Stop() before destruction.";
369}
370
mflodmancc3d4422017-08-03 08:27:51 -0700371void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700372 RTC_DCHECK_RUN_ON(&thread_checker_);
hbos8d609f62017-04-10 07:39:05 -0700373 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700374 encoder_queue_.PostTask([this] {
375 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700376 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100377 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800378 bitrate_observer_ = nullptr;
Niels Möllerbf3dbb42018-03-16 13:38:46 +0100379 video_sender_.RegisterExternalEncoder(nullptr, false);
kthelgason876222f2016-11-29 01:44:11 -0800380 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700381 shutdown_event_.Set();
382 });
383
384 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700385}
386
mflodmancc3d4422017-08-03 08:27:51 -0700387void VideoStreamEncoder::SetBitrateObserver(
sprang1a646ee2016-12-01 06:34:11 -0800388 VideoBitrateAllocationObserver* bitrate_observer) {
389 RTC_DCHECK_RUN_ON(&thread_checker_);
390 encoder_queue_.PostTask([this, bitrate_observer] {
391 RTC_DCHECK_RUN_ON(&encoder_queue_);
392 RTC_DCHECK(!bitrate_observer_);
393 bitrate_observer_ = bitrate_observer;
394 });
395}
396
mflodmancc3d4422017-08-03 08:27:51 -0700397void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700398 rtc::VideoSourceInterface<VideoFrame>* source,
asapersson09f05612017-05-15 23:40:18 -0700399 const VideoSendStream::DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700400 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700401 source_proxy_->SetSource(source, degradation_preference);
402 encoder_queue_.PostTask([this, degradation_preference] {
403 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700404 if (degradation_preference_ != degradation_preference) {
405 // Reset adaptation state, so that we're not tricked into thinking there's
406 // an already pending request of the same type.
407 last_adaptation_request_.reset();
asaperssonf7e294d2017-06-13 23:25:22 -0700408 if (degradation_preference ==
409 VideoSendStream::DegradationPreference::kBalanced ||
410 degradation_preference_ ==
411 VideoSendStream::DegradationPreference::kBalanced) {
412 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
413 // AdaptCounter for all modes.
414 source_proxy_->ResetPixelFpsCount();
415 adapt_counters_.clear();
416 }
sprangc5d62e22017-04-02 23:53:04 -0700417 }
sprangb1ca0732017-02-01 08:38:12 -0800418 degradation_preference_ = degradation_preference;
asapersson91914e22017-06-01 00:34:08 -0700419 bool allow_scaling = IsResolutionScalingEnabled(degradation_preference_);
sprangc5d62e22017-04-02 23:53:04 -0700420 initial_rampup_ = allow_scaling ? 0 : kMaxInitialFramedrop;
Niels Möller4db138e2018-04-19 09:04:13 +0200421
Niels Möller2d061182018-04-24 09:13:08 +0200422 if (encoder_)
423 ConfigureQualityScaler();
Niels Möller4db138e2018-04-19 09:04:13 +0200424
Niels Möller7dc26b72017-12-06 10:27:48 +0100425 if (!IsFramerateScalingEnabled(degradation_preference) &&
426 max_framerate_ != -1) {
427 // If frame rate scaling is no longer allowed, remove any potential
428 // allowance for longer frame intervals.
429 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
430 }
perkj803d97f2016-11-01 11:45:46 -0700431 });
perkja49cbd32016-09-16 07:53:41 -0700432}
433
mflodmancc3d4422017-08-03 08:27:51 -0700434void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700435 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700436 encoder_queue_.PostTask([this, sink] {
437 RTC_DCHECK_RUN_ON(&encoder_queue_);
438 sink_ = sink;
439 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000440}
441
mflodmancc3d4422017-08-03 08:27:51 -0700442void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700443 encoder_queue_.PostTask([this, start_bitrate_bps] {
444 RTC_DCHECK_RUN_ON(&encoder_queue_);
445 encoder_start_bitrate_bps_ = start_bitrate_bps;
446 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000447}
Peter Boström00b9d212016-05-19 16:59:03 +0200448
mflodmancc3d4422017-08-03 08:27:51 -0700449void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200450 size_t max_data_payload_length) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100451 // TODO(srte): This struct should be replaced by a lambda with move capture
452 // when C++14 lambda is allowed.
453 struct ConfigureEncoderTask {
454 void operator()() {
455 encoder->ConfigureEncoderOnTaskQueue(
Niels Möllerf1338562018-04-26 09:51:47 +0200456 std::move(config), max_data_payload_length);
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100457 }
458 VideoStreamEncoder* encoder;
459 VideoEncoderConfig config;
460 size_t max_data_payload_length;
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100461 };
462 encoder_queue_.PostTask(ConfigureEncoderTask{
Niels Möllerf1338562018-04-26 09:51:47 +0200463 this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 01:17:40 -0700464}
465
mflodmancc3d4422017-08-03 08:27:51 -0700466void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
467 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200468 size_t max_data_payload_length) {
perkj26091b12016-09-01 01:17:40 -0700469 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700470 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100471 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200472
473 max_data_payload_length_ = max_data_payload_length;
Niels Möller4db138e2018-04-19 09:04:13 +0200474 pending_encoder_creation_ =
475 (!encoder_ || encoder_config_.video_format != config.video_format);
Pera48ddb72016-09-29 11:48:50 +0200476 encoder_config_ = std::move(config);
perkjfa10b552016-10-02 23:45:26 -0700477 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200478
perkjfa10b552016-10-02 23:45:26 -0700479 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100480 // if the frame resolution is known. Otherwise, the reconfiguration is
481 // deferred until the next frame to minimize the number of reconfigurations.
482 // The codec configuration depends on incoming video frame size.
483 if (last_frame_info_) {
484 ReconfigureEncoder();
Niels Möller4db138e2018-04-19 09:04:13 +0200485 } else if (settings_.encoder_factory->QueryVideoEncoder(
486 encoder_config_.video_format).has_internal_source) {
Niels Moller0d650b42018-04-18 07:17:07 +0000487 last_frame_info_ = VideoFrameInfo(176, 144, false);
488 ReconfigureEncoder();
perkjfa10b552016-10-02 23:45:26 -0700489 }
490}
perkj26091b12016-09-01 01:17:40 -0700491
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800492// TODO(bugs.webrtc.org/8807): Currently this always does a hard
493// reconfiguration, but this isn't always necessary. Add in logic to only update
494// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
495// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700496void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700497 RTC_DCHECK(pending_encoder_reconfiguration_);
498 std::vector<VideoStream> streams =
499 encoder_config_.video_stream_factory->CreateEncoderStreams(
500 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700501
ilnik6b826ef2017-06-16 06:53:48 -0700502 // TODO(ilnik): If configured resolution is significantly less than provided,
503 // e.g. because there are not enough SSRCs for all simulcast streams,
504 // signal new resolutions via SinkWants to video source.
505
506 // Stream dimensions may be not equal to given because of a simulcast
507 // restrictions.
508 int highest_stream_width = static_cast<int>(streams.back().width);
509 int highest_stream_height = static_cast<int>(streams.back().height);
510 // Dimension may be reduced to be, e.g. divisible by 4.
511 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
512 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
513 crop_width_ = last_frame_info_->width - highest_stream_width;
514 crop_height_ = last_frame_info_->height - highest_stream_height;
515
Erik Språng08127a92016-11-16 16:41:30 +0100516 VideoCodec codec;
Niels Möller259a4972018-04-05 15:36:51 +0200517 if (!VideoCodecInitializer::SetupCodec(
Niels Möllerf1338562018-04-26 09:51:47 +0200518 encoder_config_, streams, &codec, &rate_allocator_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100519 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100520 }
perkjfa10b552016-10-02 23:45:26 -0700521
522 codec.startBitrate =
523 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
524 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
525 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 04:21:07 -0700526 max_framerate_ = codec.maxFramerate;
527 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 11:11:06 +0100528
Niels Möller4db138e2018-04-19 09:04:13 +0200529 // Keep the same encoder, as long as the video_format is unchanged.
530 if (pending_encoder_creation_) {
531 pending_encoder_creation_ = false;
532 if (encoder_) {
533 video_sender_.RegisterExternalEncoder(nullptr, false);
534 }
535
536 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
537 encoder_config_.video_format);
538 // TODO(nisse): What to do if creating the encoder fails? Crash,
539 // or just discard incoming frames?
540 RTC_CHECK(encoder_);
541
Niels Möller4db138e2018-04-19 09:04:13 +0200542 const webrtc::VideoEncoderFactory::CodecInfo info =
543 settings_.encoder_factory->QueryVideoEncoder(
544 encoder_config_.video_format);
545
546 overuse_detector_->StopCheckForOveruse();
547 overuse_detector_->StartCheckForOveruse(
548 GetCpuOveruseOptions(settings_, info.is_hardware_accelerated), this);
549
550 video_sender_.RegisterExternalEncoder(encoder_.get(),
551 info.has_internal_source);
552 }
553 // RegisterSendCodec implies an unconditional call to
554 // encoder_->InitEncode().
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200555 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700556 &codec, number_of_cores_,
557 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100558 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100559 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700560 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000561 }
Peter Boström905f8e72016-03-02 16:59:56 +0100562
Niels Möller96d7f762018-01-30 11:27:16 +0100563 video_sender_.UpdateChannelParameters(rate_allocator_.get(),
ilnik35b7de42017-03-15 04:24:21 -0700564 bitrate_observer_);
565
sprangfda496a2017-06-15 04:21:07 -0700566 // Get the current actual framerate, as measured by the stats proxy. This is
567 // used to get the correct bitrate layer allocation.
568 int current_framerate = stats_proxy_->GetSendFrameRate();
569 if (current_framerate == 0)
570 current_framerate = codec.maxFramerate;
sprang552c7c72017-02-13 04:41:45 -0800571 stats_proxy_->OnEncoderReconfigured(
Åsa Perssonaa329e72017-12-15 15:54:44 +0100572 encoder_config_, streams,
sprangfda496a2017-06-15 04:21:07 -0700573 rate_allocator_.get()
574 ? rate_allocator_->GetPreferredBitrateBps(current_framerate)
575 : codec.maxBitrate);
Per512ecb32016-09-23 15:52:06 +0200576
perkjfa10b552016-10-02 23:45:26 -0700577 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100578
Pera48ddb72016-09-29 11:48:50 +0200579 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700580 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800581
Niels Möller7dc26b72017-12-06 10:27:48 +0100582 // Get the current target framerate, ie the maximum framerate as specified by
583 // the current codec configuration, or any limit imposed by cpu adaption in
584 // maintain-resolution or balanced mode. This is used to make sure overuse
585 // detection doesn't needlessly trigger in low and/or variable framerate
586 // scenarios.
587 int target_framerate = std::min(
588 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
589 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200590
591 ConfigureQualityScaler();
kthelgason2bc68642017-02-07 07:02:22 -0800592}
593
mflodmancc3d4422017-08-03 08:27:51 -0700594void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800595 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller4db138e2018-04-19 09:04:13 +0200596 const auto scaling_settings = encoder_->GetScalingSettings();
asapersson36e9eb42017-03-31 05:29:12 -0700597 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700598 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100599 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700600
asapersson36e9eb42017-03-31 05:29:12 -0700601 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700602 if (quality_scaler_.get() == nullptr) {
603 // Quality scaler has not already been configured.
604 // Drop frames and scale down until desired quality is achieved.
Niels Möller225c7872018-02-22 15:03:53 +0100605
Åsa Perssona945aee2018-04-24 16:53:25 +0200606 // Use experimental thresholds if available.
607 rtc::Optional<VideoEncoder::QpThresholds> experimental_thresholds;
608 if (quality_scaling_experiment_enabled_) {
609 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
610 encoder_config_.codec_type);
611 }
Niels Möller225c7872018-02-22 15:03:53 +0100612 // Since the interface is non-public, MakeUnique can't do this upcast.
613 AdaptationObserverInterface* observer = this;
614 quality_scaler_ = rtc::MakeUnique<QualityScaler>(
Åsa Perssona945aee2018-04-24 16:53:25 +0200615 observer, experimental_thresholds ? *experimental_thresholds
616 : *(scaling_settings.thresholds));
kthelgason876222f2016-11-29 01:44:11 -0800617 }
618 } else {
619 quality_scaler_.reset(nullptr);
kthelgasonad9010c2017-02-14 00:46:51 -0800620 initial_rampup_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800621 }
asapersson09f05612017-05-15 23:40:18 -0700622
623 stats_proxy_->SetAdaptationStats(GetActiveCounts(kCpu),
624 GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000625}
626
mflodmancc3d4422017-08-03 08:27:51 -0700627void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700628 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700629 VideoFrame incoming_frame = video_frame;
630
631 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700632 int64_t current_time_us = clock_->TimeInMicroseconds();
633 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
634 // In some cases, e.g., when the frame from decoder is fed to encoder,
635 // the timestamp may be set to the future. As the encoding pipeline assumes
636 // capture time to be less than present time, we should reset the capture
637 // timestamps here. Otherwise there may be issues with RTP send stream.
638 if (incoming_frame.timestamp_us() > current_time_us)
639 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700640
641 // Capture time may come from clock with an offset and drift from clock_.
642 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800643 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700644 capture_ntp_time_ms = video_frame.ntp_time_ms();
645 } else if (video_frame.render_time_ms() != 0) {
646 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
647 } else {
nisse1c0dea82017-01-30 02:43:18 -0800648 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700649 }
650 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
651
652 // Convert NTP time, in ms, to RTP timestamp.
653 const int kMsToRtpTimestamp = 90;
654 incoming_frame.set_timestamp(
655 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
656
657 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
658 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100659 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
660 << incoming_frame.ntp_time_ms()
661 << " <= " << last_captured_timestamp_
662 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 01:17:40 -0700663 return;
664 }
665
asapersson6ffb67d2016-09-12 00:10:45 -0700666 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800667 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
668 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700669 log_stats = true;
670 }
671
perkj26091b12016-09-01 01:17:40 -0700672 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200673
674 int64_t post_time_us = rtc::TimeMicros();
675 ++posted_frames_waiting_for_encode_;
676
677 encoder_queue_.PostTask(
678 [this, incoming_frame, post_time_us, log_stats]() {
679 RTC_DCHECK_RUN_ON(&encoder_queue_);
680 stats_proxy_->OnIncomingFrame(incoming_frame.width(),
681 incoming_frame.height());
682 ++captured_frame_count_;
683 const int posted_frames_waiting_for_encode =
684 posted_frames_waiting_for_encode_.fetch_sub(1);
685 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
686 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +0200687 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200688 } else {
689 // There is a newer frame in flight. Do not encode this frame.
690 RTC_LOG(LS_VERBOSE)
691 << "Incoming frame dropped due to that the encoder is blocked.";
692 ++dropped_frame_count_;
693 stats_proxy_->OnFrameDroppedInEncoderQueue();
694 }
695 if (log_stats) {
696 RTC_LOG(LS_INFO) << "Number of frames: captured "
697 << captured_frame_count_
698 << ", dropped (due to encoder blocked) "
699 << dropped_frame_count_ << ", interval_ms "
700 << kFrameLogIntervalMs;
701 captured_frame_count_ = 0;
702 dropped_frame_count_ = 0;
703 }
704 });
perkj26091b12016-09-01 01:17:40 -0700705}
706
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200707void VideoStreamEncoder::OnDiscardedFrame() {
708 stats_proxy_->OnFrameDroppedBySource();
709}
710
mflodmancc3d4422017-08-03 08:27:51 -0700711bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700712 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000713 // Pause video if paused by caller or as long as the network is down or the
714 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700715 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700716 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700717 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000718}
719
mflodmancc3d4422017-08-03 08:27:51 -0700720void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700721 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000722 // Start trace event only on the first frame after encoder is paused.
723 if (!encoder_paused_and_dropped_frame_) {
724 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
725 }
726 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000727}
728
mflodmancc3d4422017-08-03 08:27:51 -0700729void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700730 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000731 // End trace event on first frame after encoder resumes, if frame was dropped.
732 if (encoder_paused_and_dropped_frame_) {
733 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
734 }
735 encoder_paused_and_dropped_frame_ = false;
736}
737
Sebastian Janssona3177052018-04-10 13:05:49 +0200738void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
739 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700740 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800741
perkj26091b12016-09-01 01:17:40 -0700742 if (pre_encode_callback_)
743 pre_encode_callback_->OnFrame(video_frame);
744
Per21d45d22016-10-30 21:37:57 +0100745 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700746 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700747 video_frame.is_texture() != last_frame_info_->is_texture) {
748 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100749 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
750 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100751 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
752 << last_frame_info_->width << "x"
753 << last_frame_info_->height
754 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700755 }
756
Niels Möller4db138e2018-04-19 09:04:13 +0200757 // We have to create then encoder before the frame drop logic,
758 // because the latter depends on encoder_->GetScalingSettings.
759 // According to the testcase
760 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
761 // from GetScalingSettings should enable or disable the frame drop.
762
763 int64_t now_ms = clock_->TimeInMilliseconds();
764 if (pending_encoder_reconfiguration_) {
765 ReconfigureEncoder();
766 last_parameters_update_ms_.emplace(now_ms);
767 } else if (!last_parameters_update_ms_ ||
768 now_ms - *last_parameters_update_ms_ >=
769 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
770 video_sender_.UpdateChannelParameters(rate_allocator_.get(),
771 bitrate_observer_);
772 last_parameters_update_ms_.emplace(now_ms);
773 }
774
Sebastian Janssona3177052018-04-10 13:05:49 +0200775 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100776 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +0100777 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800778 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +0100779 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
780 stats_proxy_->OnInitialQualityResolutionAdaptDown();
781 }
kthelgason2bc68642017-02-07 07:02:22 -0800782 ++initial_rampup_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200783 // Storing references to a native buffer risks blocking frame capture.
784 if (video_frame.video_frame_buffer()->type() !=
785 VideoFrameBuffer::Type::kNative) {
786 pending_frame_ = video_frame;
787 pending_frame_post_time_us_ = time_when_posted_us;
788 } else {
789 // Ensure that any previously stored frame is dropped.
790 pending_frame_.reset();
791 }
kthelgason2bc68642017-02-07 07:02:22 -0800792 return;
793 }
794 initial_rampup_ = kMaxInitialFramedrop;
795
perkjfa10b552016-10-02 23:45:26 -0700796
perkj26091b12016-09-01 01:17:40 -0700797 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200798 // Storing references to a native buffer risks blocking frame capture.
799 if (video_frame.video_frame_buffer()->type() !=
800 VideoFrameBuffer::Type::kNative) {
801 if (pending_frame_)
802 TraceFrameDropStart();
803 pending_frame_ = video_frame;
804 pending_frame_post_time_us_ = time_when_posted_us;
805 } else {
806 // Ensure that any previously stored frame is dropped.
807 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +0200808 TraceFrameDropStart();
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200809 }
perkj26091b12016-09-01 01:17:40 -0700810 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000811 }
Sebastian Janssona3177052018-04-10 13:05:49 +0200812
813 pending_frame_.reset();
814 EncodeVideoFrame(video_frame, time_when_posted_us);
815}
816
817void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
818 int64_t time_when_posted_us) {
819 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700820 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000821
ilnik6b826ef2017-06-16 06:53:48 -0700822 VideoFrame out_frame(video_frame);
823 // Crop frame if needed.
824 if (crop_width_ > 0 || crop_height_ > 0) {
825 int cropped_width = video_frame.width() - crop_width_;
826 int cropped_height = video_frame.height() - crop_height_;
827 rtc::scoped_refptr<I420Buffer> cropped_buffer =
828 I420Buffer::Create(cropped_width, cropped_height);
829 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
830 // happen after SinkWants signaled correctly from ReconfigureEncoder.
831 if (crop_width_ < 4 && crop_height_ < 4) {
832 cropped_buffer->CropAndScaleFrom(
833 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
834 crop_height_ / 2, cropped_width, cropped_height);
835 } else {
836 cropped_buffer->ScaleFrom(
837 *video_frame.video_frame_buffer()->ToI420().get());
838 }
839 out_frame =
840 VideoFrame(cropped_buffer, video_frame.timestamp(),
841 video_frame.render_time_ms(), video_frame.rotation());
842 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
843 }
844
Magnus Jedvert26679d62015-04-07 14:07:41 +0200845 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000846 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000847
Niels Möller7dc26b72017-12-06 10:27:48 +0100848 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700849
ilnik6b826ef2017-06-16 06:53:48 -0700850 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000851}
niklase@google.com470e71d2011-07-07 08:21:25 +0000852
mflodmancc3d4422017-08-03 08:27:51 -0700853void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700854 if (!encoder_queue_.IsCurrent()) {
855 encoder_queue_.PostTask([this] { SendKeyFrame(); });
856 return;
857 }
858 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +0100859 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200860 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +0000861}
862
mflodmancc3d4422017-08-03 08:27:51 -0700863EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700864 const EncodedImage& encoded_image,
865 const CodecSpecificInfo* codec_specific_info,
866 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -0700867 // Encoded is called on whatever thread the real encoder implementation run
868 // on. In the case of hardware encoders, there might be several encoders
869 // running in parallel on different threads.
sprang552c7c72017-02-13 04:41:45 -0800870 stats_proxy_->OnSendEncodedImage(encoded_image, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -0700871
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700872 EncodedImageCallback::Result result =
873 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -0700874
Niels Möller7dc26b72017-12-06 10:27:48 +0100875 int64_t time_sent_us = rtc::TimeMicros();
876 uint32_t timestamp = encoded_image._timeStamp;
kthelgason876222f2016-11-29 01:44:11 -0800877 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 16:39:44 +0100878 int64_t capture_time_us =
879 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
880
881 rtc::Optional<int> encode_duration_us;
882 if (encoded_image.timing_.flags != TimingFrameFlags::kInvalid) {
883 encode_duration_us.emplace(
884 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
885 rtc::kNumMicrosecsPerMillisec *
886 (encoded_image.timing_.encode_finish_ms -
887 encoded_image.timing_.encode_start_ms));
888 }
889
890 encoder_queue_.PostTask(
891 [this, timestamp, time_sent_us, qp, capture_time_us, encode_duration_us] {
892 RTC_DCHECK_RUN_ON(&encoder_queue_);
893 overuse_detector_->FrameSent(timestamp, time_sent_us, capture_time_us,
894 encode_duration_us);
895 if (quality_scaler_ && qp >= 0)
Åsa Persson04d5f1d2018-04-20 15:19:11 +0200896 quality_scaler_->ReportQp(qp);
Niels Möller83dbeac2017-12-14 16:39:44 +0100897 });
perkj803d97f2016-11-01 11:45:46 -0700898
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700899 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +0100900}
901
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200902void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
903 switch (reason) {
904 case DropReason::kDroppedByMediaOptimizations:
905 stats_proxy_->OnFrameDroppedByMediaOptimizations();
906 encoder_queue_.PostTask([this] {
907 RTC_DCHECK_RUN_ON(&encoder_queue_);
908 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +0200909 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200910 });
911 break;
912 case DropReason::kDroppedByEncoder:
913 stats_proxy_->OnFrameDroppedByEncoder();
Åsa Perssona945aee2018-04-24 16:53:25 +0200914 encoder_queue_.PostTask([this] {
915 RTC_DCHECK_RUN_ON(&encoder_queue_);
916 if (quality_scaler_)
917 quality_scaler_->ReportDroppedFrameByEncoder();
918 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200919 break;
920 }
kthelgason876222f2016-11-29 01:44:11 -0800921}
922
mflodmancc3d4422017-08-03 08:27:51 -0700923void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
924 uint8_t fraction_lost,
925 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -0700926 if (!encoder_queue_.IsCurrent()) {
927 encoder_queue_.PostTask(
928 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
929 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
930 });
931 return;
932 }
933 RTC_DCHECK_RUN_ON(&encoder_queue_);
934 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
935
Mirko Bonadei675513b2017-11-09 11:09:25 +0100936 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
937 << " packet loss " << static_cast<int>(fraction_lost)
938 << " rtt " << round_trip_time_ms;
perkj26091b12016-09-01 01:17:40 -0700939
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200940 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 06:34:11 -0800941 round_trip_time_ms, rate_allocator_.get(),
942 bitrate_observer_);
perkj26091b12016-09-01 01:17:40 -0700943
944 encoder_start_bitrate_bps_ =
945 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +0200946 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +0100947 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -0700948 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +0000949
sprang552c7c72017-02-13 04:41:45 -0800950 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
952 << (video_is_suspended ? "suspended" : "not suspended");
Peter Boström7083e112015-09-22 16:28:51 +0200953 stats_proxy_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +0200954 }
Sebastian Janssona3177052018-04-10 13:05:49 +0200955 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
956 !DropDueToSize(pending_frame_->size())) {
957 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
958 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
959 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
960 pending_frame_.reset();
961 }
962}
963
964bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
965 if (initial_rampup_ < kMaxInitialFramedrop &&
966 encoder_start_bitrate_bps_ > 0) {
967 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
968 return pixel_count > 320 * 240;
969 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
970 return pixel_count > 640 * 480;
971 }
972 }
973 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +0000974}
975
mflodmancc3d4422017-08-03 08:27:51 -0700976void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -0700977 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700978 AdaptationRequest adaptation_request = {
979 last_frame_info_->pixel_count(),
980 stats_proxy_->GetStats().input_frame_rate,
981 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -0700982
sprangc5d62e22017-04-02 23:53:04 -0700983 bool downgrade_requested =
984 last_adaptation_request_ &&
985 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
986
sprangc5d62e22017-04-02 23:53:04 -0700987 switch (degradation_preference_) {
hbos8d609f62017-04-10 07:39:05 -0700988 case VideoSendStream::DegradationPreference::kBalanced:
asaperssonf7e294d2017-06-13 23:25:22 -0700989 break;
hbos8d609f62017-04-10 07:39:05 -0700990 case VideoSendStream::DegradationPreference::kMaintainFramerate:
sprangc5d62e22017-04-02 23:53:04 -0700991 if (downgrade_requested &&
992 adaptation_request.input_pixel_count_ >=
993 last_adaptation_request_->input_pixel_count_) {
994 // Don't request lower resolution if the current resolution is not
995 // lower than the last time we asked for the resolution to be lowered.
996 return;
997 }
998 break;
hbos8d609f62017-04-10 07:39:05 -0700999 case VideoSendStream::DegradationPreference::kMaintainResolution:
sprangc5d62e22017-04-02 23:53:04 -07001000 if (adaptation_request.framerate_fps_ <= 0 ||
1001 (downgrade_requested &&
1002 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1003 // If no input fps estimate available, can't determine how to scale down
1004 // framerate. Otherwise, don't request lower framerate if we don't have
1005 // a valid frame rate. Since framerate, unlike resolution, is a measure
1006 // we have to estimate, and can fluctuate naturally over time, don't
1007 // make the same kind of limitations as for resolution, but trust the
1008 // overuse detector to not trigger too often.
1009 return;
1010 }
1011 break;
hbos8d609f62017-04-10 07:39:05 -07001012 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -07001013 return;
sprang84a37592017-02-10 07:04:27 -08001014 }
sprangc5d62e22017-04-02 23:53:04 -07001015
sprangc5d62e22017-04-02 23:53:04 -07001016 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -07001017 case VideoSendStream::DegradationPreference::kBalanced: {
1018 // Try scale down framerate, if lower.
1019 int fps = MinFps(last_frame_info_->pixel_count());
1020 if (source_proxy_->RestrictFramerate(fps)) {
1021 GetAdaptCounter().IncrementFramerate(reason);
1022 break;
1023 }
1024 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001025 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001026 }
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001027 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
asapersson13874762017-06-07 00:01:02 -07001028 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001029 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001030 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001031 adaptation_request.input_pixel_count_,
Niels Möller4db138e2018-04-19 09:04:13 +02001032 encoder_->GetScalingSettings().min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001033 &min_pixels_reached)) {
1034 if (min_pixels_reached)
1035 stats_proxy_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -07001036 return;
1037 }
asaperssonf7e294d2017-06-13 23:25:22 -07001038 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001039 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001040 }
sprangfda496a2017-06-15 04:21:07 -07001041 case VideoSendStream::DegradationPreference::kMaintainResolution: {
asapersson13874762017-06-07 00:01:02 -07001042 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001043 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1044 adaptation_request.framerate_fps_);
1045 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001046 return;
sprangfda496a2017-06-15 04:21:07 -07001047 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001048 overuse_detector_->OnTargetFramerateUpdated(
1049 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001050 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001051 break;
sprangfda496a2017-06-15 04:21:07 -07001052 }
hbos8d609f62017-04-10 07:39:05 -07001053 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -07001054 RTC_NOTREACHED();
1055 }
1056
asaperssond0de2952017-04-21 01:47:31 -07001057 last_adaptation_request_.emplace(adaptation_request);
1058
asapersson09f05612017-05-15 23:40:18 -07001059 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001060
Mirko Bonadei675513b2017-11-09 11:09:25 +01001061 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001062}
1063
mflodmancc3d4422017-08-03 08:27:51 -07001064void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001065 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001066
1067 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1068 int num_downgrades = adapt_counter.TotalCount(reason);
1069 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001070 return;
asapersson09f05612017-05-15 23:40:18 -07001071 RTC_DCHECK_GT(num_downgrades, 0);
1072
sprangc5d62e22017-04-02 23:53:04 -07001073 AdaptationRequest adaptation_request = {
1074 last_frame_info_->pixel_count(),
1075 stats_proxy_->GetStats().input_frame_rate,
1076 AdaptationRequest::Mode::kAdaptUp};
1077
1078 bool adapt_up_requested =
1079 last_adaptation_request_ &&
1080 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001081
asaperssonf7e294d2017-06-13 23:25:22 -07001082 if (degradation_preference_ ==
1083 VideoSendStream::DegradationPreference::kMaintainFramerate) {
1084 if (adapt_up_requested &&
1085 adaptation_request.input_pixel_count_ <=
1086 last_adaptation_request_->input_pixel_count_) {
1087 // Don't request higher resolution if the current resolution is not
1088 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001089 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001090 }
sprangb1ca0732017-02-01 08:38:12 -08001091 }
sprangc5d62e22017-04-02 23:53:04 -07001092
sprangc5d62e22017-04-02 23:53:04 -07001093 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -07001094 case VideoSendStream::DegradationPreference::kBalanced: {
1095 // Try scale up framerate, if higher.
1096 int fps = MaxFps(last_frame_info_->pixel_count());
1097 if (source_proxy_->IncreaseFramerate(fps)) {
1098 GetAdaptCounter().DecrementFramerate(reason, fps);
1099 // Reset framerate in case of fewer fps steps down than up.
1100 if (adapt_counter.FramerateCount() == 0 &&
1101 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001102 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001103 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1104 }
1105 break;
1106 }
1107 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001108 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001109 }
asapersson13874762017-06-07 00:01:02 -07001110 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
1111 // Scale up resolution.
1112 int pixel_count = adaptation_request.input_pixel_count_;
1113 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001114 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001115 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001116 }
asapersson13874762017-06-07 00:01:02 -07001117 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1118 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001119 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001120 break;
asapersson13874762017-06-07 00:01:02 -07001121 }
1122 case VideoSendStream::DegradationPreference::kMaintainResolution: {
1123 // Scale up framerate.
1124 int fps = adaptation_request.framerate_fps_;
1125 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001126 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001127 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001128 }
sprangfda496a2017-06-15 04:21:07 -07001129
1130 const int requested_framerate =
1131 source_proxy_->RequestHigherFramerateThan(fps);
1132 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001133 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001134 return;
sprangfda496a2017-06-15 04:21:07 -07001135 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001136 overuse_detector_->OnTargetFramerateUpdated(
1137 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001138 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001139 break;
asapersson13874762017-06-07 00:01:02 -07001140 }
hbos8d609f62017-04-10 07:39:05 -07001141 case VideoSendStream::DegradationPreference::kDegradationDisabled:
asaperssonf7e294d2017-06-13 23:25:22 -07001142 return;
sprangc5d62e22017-04-02 23:53:04 -07001143 }
1144
asaperssond0de2952017-04-21 01:47:31 -07001145 last_adaptation_request_.emplace(adaptation_request);
1146
asapersson09f05612017-05-15 23:40:18 -07001147 UpdateAdaptationStats(reason);
1148
Mirko Bonadei675513b2017-11-09 11:09:25 +01001149 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001150}
1151
mflodmancc3d4422017-08-03 08:27:51 -07001152void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001153 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001154 case kCpu:
asapersson09f05612017-05-15 23:40:18 -07001155 stats_proxy_->OnCpuAdaptationChanged(GetActiveCounts(kCpu),
1156 GetActiveCounts(kQuality));
1157 break;
1158 case kQuality:
1159 stats_proxy_->OnQualityAdaptationChanged(GetActiveCounts(kCpu),
1160 GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001161 break;
1162 }
perkj26091b12016-09-01 01:17:40 -07001163}
1164
mflodmancc3d4422017-08-03 08:27:51 -07001165VideoStreamEncoder::AdaptCounts VideoStreamEncoder::GetActiveCounts(
1166 AdaptReason reason) {
1167 VideoStreamEncoder::AdaptCounts counts =
1168 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001169 switch (reason) {
1170 case kCpu:
1171 if (!IsFramerateScalingEnabled(degradation_preference_))
1172 counts.fps = -1;
1173 if (!IsResolutionScalingEnabled(degradation_preference_))
1174 counts.resolution = -1;
1175 break;
1176 case kQuality:
1177 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1178 !quality_scaler_) {
1179 counts.fps = -1;
1180 }
1181 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1182 !quality_scaler_) {
1183 counts.resolution = -1;
1184 }
1185 break;
sprangc5d62e22017-04-02 23:53:04 -07001186 }
asapersson09f05612017-05-15 23:40:18 -07001187 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001188}
1189
mflodmancc3d4422017-08-03 08:27:51 -07001190VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001191 return adapt_counters_[degradation_preference_];
1192}
1193
mflodmancc3d4422017-08-03 08:27:51 -07001194const VideoStreamEncoder::AdaptCounter&
1195VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001196 return adapt_counters_[degradation_preference_];
1197}
1198
1199// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001200VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001201 fps_counters_.resize(kScaleReasonSize);
1202 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001203 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001204}
1205
mflodmancc3d4422017-08-03 08:27:51 -07001206VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001207
mflodmancc3d4422017-08-03 08:27:51 -07001208std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-15 23:40:18 -07001209 std::stringstream ss;
1210 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1211 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1212 return ss.str();
1213}
1214
mflodmancc3d4422017-08-03 08:27:51 -07001215VideoStreamEncoder::AdaptCounts VideoStreamEncoder::AdaptCounter::Counts(
1216 int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001217 AdaptCounts counts;
1218 counts.fps = fps_counters_[reason];
1219 counts.resolution = resolution_counters_[reason];
1220 return counts;
1221}
1222
mflodmancc3d4422017-08-03 08:27:51 -07001223void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001224 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001225}
1226
mflodmancc3d4422017-08-03 08:27:51 -07001227void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001228 ++(resolution_counters_[reason]);
1229}
1230
mflodmancc3d4422017-08-03 08:27:51 -07001231void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001232 if (fps_counters_[reason] == 0) {
1233 // Balanced mode: Adapt up is in a different order, switch reason.
1234 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1235 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1236 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1237 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1238 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1239 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1240 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1241 MoveCount(&resolution_counters_, reason);
1242 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1243 }
1244 --(fps_counters_[reason]);
1245 RTC_DCHECK_GE(fps_counters_[reason], 0);
1246}
1247
mflodmancc3d4422017-08-03 08:27:51 -07001248void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001249 if (resolution_counters_[reason] == 0) {
1250 // Balanced mode: Adapt up is in a different order, switch reason.
1251 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1252 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1253 MoveCount(&fps_counters_, reason);
1254 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1255 }
1256 --(resolution_counters_[reason]);
1257 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1258}
1259
mflodmancc3d4422017-08-03 08:27:51 -07001260void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1261 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001262 DecrementFramerate(reason);
1263 // Reset if at max fps (i.e. in case of fewer steps up than down).
1264 if (cur_fps == std::numeric_limits<int>::max())
1265 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001266}
1267
mflodmancc3d4422017-08-03 08:27:51 -07001268int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001269 return Count(fps_counters_);
1270}
1271
mflodmancc3d4422017-08-03 08:27:51 -07001272int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001273 return Count(resolution_counters_);
1274}
1275
mflodmancc3d4422017-08-03 08:27:51 -07001276int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001277 return fps_counters_[reason];
1278}
1279
mflodmancc3d4422017-08-03 08:27:51 -07001280int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001281 return resolution_counters_[reason];
1282}
1283
mflodmancc3d4422017-08-03 08:27:51 -07001284int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001285 return FramerateCount(reason) + ResolutionCount(reason);
1286}
1287
mflodmancc3d4422017-08-03 08:27:51 -07001288int VideoStreamEncoder::AdaptCounter::Count(
1289 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001290 return std::accumulate(counters.begin(), counters.end(), 0);
1291}
1292
mflodmancc3d4422017-08-03 08:27:51 -07001293void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1294 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001295 int to_reason = (from_reason + 1) % kScaleReasonSize;
1296 ++((*counters)[to_reason]);
1297 --((*counters)[from_reason]);
1298}
1299
mflodmancc3d4422017-08-03 08:27:51 -07001300std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001301 const std::vector<int>& counters) const {
1302 std::stringstream ss;
1303 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1304 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001305 }
asapersson09f05612017-05-15 23:40:18 -07001306 return ss.str();
sprangc5d62e22017-04-02 23:53:04 -07001307}
1308
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001309} // namespace webrtc