blob: e7bc7e19602167927f3f3ab2115f2fa05c1d4020 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:251/*
stefan@webrtc.org07b45a52012-02-02 08:37:482 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:253 *
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 04:47:3111#include "video/video_stream_encoder.h"
mflodman@webrtc.org84d17832011-12-01 17:02:2312
stefan@webrtc.orgc3cc3752013-06-04 09:36:5613#include <algorithm>
perkj57c21f92016-06-17 14:27:1614#include <limits>
sprangc5d62e22017-04-03 06:53:0415#include <numeric>
Per512ecb32016-09-23 13:52:0616#include <utility>
niklase@google.com470e71d2011-07-07 08:21:2517
Mirko Bonadei92ea95e2017-09-15 04:47:3118#include "api/video/i420_buffer.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3119#include "common_video/include/video_frame.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3120#include "modules/video_coding/include/video_codec_initializer.h"
21#include "modules/video_coding/include/video_coding.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3122#include "rtc_base/arraysize.h"
23#include "rtc_base/checks.h"
Åsa Perssona945aee2018-04-24 14:53:2524#include "rtc_base/experiments/quality_scaling_experiment.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3125#include "rtc_base/location.h"
26#include "rtc_base/logging.h"
Karl Wiberg80ba3332018-02-05 09:33:3527#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3128#include "rtc_base/timeutils.h"
29#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 08:51:4030#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3131#include "video/overuse_frame_detector.h"
nisseea3a7982017-05-15 09:42:1132
niklase@google.com470e71d2011-07-07 08:21:2533namespace webrtc {
34
perkj26091b12016-09-01 08:17:4035namespace {
sprangb1ca0732017-02-01 16:38:1236
asapersson6ffb67d2016-09-12 07:10:4537// Time interval for logging frame counts.
38const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-03 06:53:0439const int kMinFramerateFps = 2;
Mirko Bonadei948b7e32018-08-14 07:23:2140const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 08:17:4041
Sebastian Janssona3177052018-04-10 11:05:4942// Time to keep a single cached pending frame in paused state.
43const int64_t kPendingFrameTimeoutMs = 1000;
44
Kári Tristan Helgason639602a2018-08-02 08:51:4045const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
46
kthelgason2bc68642017-02-07 15:02:2247// The maximum number of frames to drop at beginning of stream
48// to try and achieve desired bitrate.
49const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 08:51:4050// When the first change in BWE above this threshold occurs,
51// enable DropFrameDueToSize logic.
52const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 15:02:2253
Taylor Brandstetter49fcc102018-05-16 21:20:4154// Initial limits for BALANCED degradation preference.
asaperssonf7e294d2017-06-14 06:25:2255int MinFps(int pixels) {
56 if (pixels <= 320 * 240) {
57 return 7;
58 } else if (pixels <= 480 * 270) {
59 return 10;
60 } else if (pixels <= 640 * 480) {
61 return 15;
62 } else {
63 return std::numeric_limits<int>::max();
64 }
65}
66
67int MaxFps(int pixels) {
68 if (pixels <= 320 * 240) {
69 return 10;
70 } else if (pixels <= 480 * 270) {
71 return 15;
72 } else {
73 return std::numeric_limits<int>::max();
74 }
75}
76
Kári Tristan Helgason639602a2018-08-02 08:51:4077uint32_t abs_diff(uint32_t a, uint32_t b) {
78 return (a < b) ? b - a : a - b;
79}
80
Taylor Brandstetter49fcc102018-05-16 21:20:4181bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
82 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
83 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-16 06:40:1884}
85
Taylor Brandstetter49fcc102018-05-16 21:20:4186bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
87 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
88 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-16 06:40:1889}
90
Niels Möllerd1f7eb62018-03-28 14:40:5891// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
92// pipelining encoders better (multiple input frames before something comes
93// out). This should effectively turn off CPU adaptations for systems that
94// remotely cope with the load right now.
95CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 07:29:5896 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 07:04:1397 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 14:40:5898 CpuOveruseOptions options;
99
Niels Möller4db138e2018-04-19 07:04:13100 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 14:40:58101 options.low_encode_usage_threshold_percent = 150;
102 options.high_encode_usage_threshold_percent = 200;
103 }
104 if (settings.experiment_cpu_load_estimator) {
105 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
106 }
107
108 return options;
109}
110
perkj26091b12016-09-01 08:17:40111} // namespace
112
perkja49cbd32016-09-16 14:53:41113// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 15:27:51114// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
115// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 14:53:41116// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 15:27:51117class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 14:53:41118 public:
mflodmancc3d4422017-08-03 15:27:51119 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
120 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 21:20:41121 degradation_preference_(DegradationPreference::DISABLED),
Mirko Bonadei948b7e32018-08-14 07:23:21122 source_(nullptr) {}
perkja49cbd32016-09-16 14:53:41123
Taylor Brandstetter49fcc102018-05-16 21:20:41124 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
125 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 18:45:46126 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 14:53:41127 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
128 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 18:45:46129 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 14:53:41130 {
131 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-03 06:53:04132 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 14:53:41133 old_source = source_;
134 source_ = source;
sprangfda496a2017-06-15 11:21:07135 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 14:53:41136 }
137
138 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 15:27:51139 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 14:53:41140 }
141
142 if (!source) {
143 return;
144 }
145
mflodmancc3d4422017-08-03 15:27:51146 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 14:53:41147 }
148
perkj803d97f2016-11-01 18:45:46149 void SetWantsRotationApplied(bool rotation_applied) {
150 rtc::CritScope lock(&crit_);
151 sink_wants_.rotation_applied = rotation_applied;
Mirko Bonadei948b7e32018-08-14 07:23:21152 if (source_)
153 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-03 06:53:04154 }
155
sprangfda496a2017-06-15 11:21:07156 rtc::VideoSinkWants GetActiveSinkWants() {
157 rtc::CritScope lock(&crit_);
158 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 18:45:46159 }
160
asaperssonf7e294d2017-06-14 06:25:22161 void ResetPixelFpsCount() {
162 rtc::CritScope lock(&crit_);
163 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
164 sink_wants_.target_pixel_count.reset();
165 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
166 if (source_)
Mirko Bonadei948b7e32018-08-14 07:23:21167 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-14 06:25:22168 }
169
Åsa Perssonc3ed6302017-11-16 13:04:52170 bool RequestResolutionLowerThan(int pixel_count,
171 int min_pixels_per_frame,
172 bool* min_pixels_reached) {
perkj803d97f2016-11-01 18:45:46173 // Called on the encoder task queue.
174 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 07:01:02175 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 08:12:52176 // This can happen since |degradation_preference_| is set on libjingle's
177 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 08:47:31178 return false;
perkj803d97f2016-11-01 18:45:46179 }
asapersson13874762017-06-07 07:01:02180 // The input video frame size will have a resolution less than or equal to
181 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 11:59:51182 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 13:04:52183 if (pixels_wanted >= sink_wants_.max_pixel_count) {
184 return false;
185 }
186 if (pixels_wanted < min_pixels_per_frame) {
187 *min_pixels_reached = true;
asaperssond0de2952017-04-21 08:47:31188 return false;
asapersson13874762017-06-07 07:01:02189 }
Mirko Bonadei675513b2017-11-09 10:09:25190 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
191 << pixels_wanted;
sprangc5d62e22017-04-03 06:53:04192 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 10:28:07193 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 15:27:51194 source_->AddOrUpdateSink(video_stream_encoder_,
195 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 08:47:31196 return true;
sprangc5d62e22017-04-03 06:53:04197 }
198
sprangfda496a2017-06-15 11:21:07199 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-03 06:53:04200 // Called on the encoder task queue.
asapersson13874762017-06-07 07:01:02201 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 11:21:07202 int framerate_wanted = (fps * 2) / 3;
203 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 18:45:46204 }
205
asapersson13874762017-06-07 07:01:02206 bool RequestHigherResolutionThan(int pixel_count) {
207 // Called on the encoder task queue.
perkj803d97f2016-11-01 18:45:46208 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 07:01:02209 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 08:12:52210 // This can happen since |degradation_preference_| is set on libjingle's
211 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 07:01:02212 return false;
perkj803d97f2016-11-01 18:45:46213 }
asapersson13874762017-06-07 07:01:02214 int max_pixels_wanted = pixel_count;
215 if (max_pixels_wanted != std::numeric_limits<int>::max())
216 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-03 06:53:04217
asapersson13874762017-06-07 07:01:02218 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
219 return false;
220
221 sink_wants_.max_pixel_count = max_pixels_wanted;
222 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-03 06:53:04223 // Remove any constraints.
224 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-03 06:53:04225 } else {
226 // On step down we request at most 3/5 the pixel count of the previous
227 // resolution, so in order to take "one step up" we request a resolution
228 // as close as possible to 5/3 of the current resolution. The actual pixel
229 // count selected depends on the capabilities of the source. In order to
230 // not take a too large step up, we cap the requested pixel count to be at
231 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 15:45:42232 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-03 06:53:04233 }
Mirko Bonadei675513b2017-11-09 10:09:25234 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
235 << max_pixels_wanted;
mflodmancc3d4422017-08-03 15:27:51236 source_->AddOrUpdateSink(video_stream_encoder_,
237 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 07:01:02238 return true;
sprangc5d62e22017-04-03 06:53:04239 }
240
sprangfda496a2017-06-15 11:21:07241 // Request upgrade in framerate. Returns the new requested frame, or -1 if
242 // no change requested. Note that maxint may be returned if limits due to
243 // adaptation requests are removed completely. In that case, consider
244 // |max_framerate_| to be the current limit (assuming the capturer complies).
245 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 07:01:02246 // Called on the encoder task queue.
247 // The input frame rate will be scaled up to the last step, with rounding.
248 int framerate_wanted = fps;
249 if (fps != std::numeric_limits<int>::max())
250 framerate_wanted = (fps * 3) / 2;
251
sprangfda496a2017-06-15 11:21:07252 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 07:01:02253 }
254
255 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-03 06:53:04256 // Called on the encoder task queue.
257 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 07:01:02258 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
259 return false;
260
261 const int fps_wanted = std::max(kMinFramerateFps, fps);
262 if (fps_wanted >= sink_wants_.max_framerate_fps)
263 return false;
264
Mirko Bonadei675513b2017-11-09 10:09:25265 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 07:01:02266 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 15:27:51267 source_->AddOrUpdateSink(video_stream_encoder_,
268 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 07:01:02269 return true;
270 }
271
272 bool IncreaseFramerate(int fps) {
273 // Called on the encoder task queue.
274 rtc::CritScope lock(&crit_);
275 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
276 return false;
277
278 const int fps_wanted = std::max(kMinFramerateFps, fps);
279 if (fps_wanted <= sink_wants_.max_framerate_fps)
280 return false;
281
Mirko Bonadei675513b2017-11-09 10:09:25282 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 07:01:02283 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 15:27:51284 source_->AddOrUpdateSink(video_stream_encoder_,
285 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 07:01:02286 return true;
perkj803d97f2016-11-01 18:45:46287 }
288
perkja49cbd32016-09-16 14:53:41289 private:
sprangfda496a2017-06-15 11:21:07290 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 11:17:22291 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 11:21:07292 rtc::VideoSinkWants wants = sink_wants_;
293 // Clear any constraints from the current sink wants that don't apply to
294 // the used degradation_preference.
295 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 21:20:41296 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 11:21:07297 break;
Taylor Brandstetter49fcc102018-05-16 21:20:41298 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 11:21:07299 wants.max_framerate_fps = std::numeric_limits<int>::max();
300 break;
Taylor Brandstetter49fcc102018-05-16 21:20:41301 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 11:21:07302 wants.max_pixel_count = std::numeric_limits<int>::max();
303 wants.target_pixel_count.reset();
304 break;
Taylor Brandstetter49fcc102018-05-16 21:20:41305 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 11:21:07306 wants.max_pixel_count = std::numeric_limits<int>::max();
307 wants.target_pixel_count.reset();
308 wants.max_framerate_fps = std::numeric_limits<int>::max();
309 }
310 return wants;
311 }
312
perkja49cbd32016-09-16 14:53:41313 rtc::CriticalSection crit_;
314 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 15:27:51315 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 11:17:22316 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 21:20:41317 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 11:17:22318 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 14:53:41319
320 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
321};
322
Åsa Persson0122e842017-10-16 10:19:23323VideoStreamEncoder::VideoStreamEncoder(
324 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 07:29:58325 VideoStreamEncoderObserver* encoder_stats_observer,
326 const VideoStreamEncoderSettings& settings,
Åsa Persson0122e842017-10-16 10:19:23327 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
Åsa Persson0122e842017-10-16 10:19:23328 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 08:17:40329 : shutdown_event_(true /* manual_reset */, false),
330 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 08:51:40331 initial_framedrop_(0),
332 initial_framedrop_on_bwe_enabled_(
333 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 14:53:25334 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 14:53:41335 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 09:48:50336 sink_(nullptr),
perkj26091b12016-09-01 08:17:40337 settings_(settings),
Niels Möllera0565992017-10-24 09:37:08338 video_sender_(Clock::GetRealTimeClock(), this),
Niels Möller73f29cb2018-01-31 15:09:31339 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 07:29:58340 encoder_stats_observer_(encoder_stats_observer),
perkj26091b12016-09-01 08:17:40341 pre_encode_callback_(pre_encode_callback),
sprangfda496a2017-06-15 11:21:07342 max_framerate_(-1),
perkjfa10b552016-10-03 06:45:26343 pending_encoder_reconfiguration_(false),
Niels Möller4db138e2018-04-19 07:04:13344 pending_encoder_creation_(false),
perkj26091b12016-09-01 08:17:40345 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 09:48:50346 max_data_payload_length_(0),
pbos@webrtc.org143451d2015-03-18 14:40:03347 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26348 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 08:17:40349 clock_(Clock::GetRealTimeClock()),
Taylor Brandstetter49fcc102018-05-16 21:20:41350 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 22:40:52351 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 08:17:40352 last_captured_timestamp_(0),
353 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
354 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 07:10:45355 last_frame_log_ms_(clock_->TimeInMilliseconds()),
356 captured_frame_count_(0),
357 dropped_frame_count_(0),
sprang1a646ee2016-12-01 14:34:11358 bitrate_observer_(nullptr),
perkj26091b12016-09-01 08:17:40359 encoder_queue_("EncoderQueue") {
Niels Möller213618e2018-07-24 07:29:58360 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 15:09:31361 RTC_DCHECK(overuse_detector_);
mflodman@webrtc.org02270cd2015-02-06 13:10:19362}
363
mflodmancc3d4422017-08-03 15:27:51364VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 14:53:41365 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 08:17:40366 RTC_DCHECK(shutdown_event_.Wait(0))
367 << "Must call ::Stop() before destruction.";
368}
369
mflodmancc3d4422017-08-03 15:27:51370void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 14:53:41371 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 21:20:41372 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 14:53:41373 encoder_queue_.PostTask([this] {
374 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 11:21:07375 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 15:41:30376 rate_allocator_.reset();
sprang1a646ee2016-12-01 14:34:11377 bitrate_observer_ = nullptr;
Niels Möllerbf3dbb42018-03-16 12:38:46378 video_sender_.RegisterExternalEncoder(nullptr, false);
kthelgason876222f2016-11-29 09:44:11379 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 14:53:41380 shutdown_event_.Set();
381 });
382
383 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 08:17:40384}
385
Niels Möller0327c2d2018-05-21 12:09:31386void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 14:34:11387 VideoBitrateAllocationObserver* bitrate_observer) {
388 RTC_DCHECK_RUN_ON(&thread_checker_);
389 encoder_queue_.PostTask([this, bitrate_observer] {
390 RTC_DCHECK_RUN_ON(&encoder_queue_);
391 RTC_DCHECK(!bitrate_observer_);
392 bitrate_observer_ = bitrate_observer;
393 });
394}
395
mflodmancc3d4422017-08-03 15:27:51396void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 18:45:46397 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 21:20:41398 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 14:53:41399 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 18:45:46400 source_proxy_->SetSource(source, degradation_preference);
401 encoder_queue_.PostTask([this, degradation_preference] {
402 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-03 06:53:04403 if (degradation_preference_ != degradation_preference) {
404 // Reset adaptation state, so that we're not tricked into thinking there's
405 // an already pending request of the same type.
406 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 21:20:41407 if (degradation_preference == DegradationPreference::BALANCED ||
408 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-14 06:25:22409 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
410 // AdaptCounter for all modes.
411 source_proxy_->ResetPixelFpsCount();
412 adapt_counters_.clear();
413 }
sprangc5d62e22017-04-03 06:53:04414 }
sprangb1ca0732017-02-01 16:38:12415 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 07:04:13416
Niels Möller2d061182018-04-24 07:13:08417 if (encoder_)
418 ConfigureQualityScaler();
Niels Möller4db138e2018-04-19 07:04:13419
Niels Möller7dc26b72017-12-06 09:27:48420 if (!IsFramerateScalingEnabled(degradation_preference) &&
421 max_framerate_ != -1) {
422 // If frame rate scaling is no longer allowed, remove any potential
423 // allowance for longer frame intervals.
424 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
425 }
perkj803d97f2016-11-01 18:45:46426 });
perkja49cbd32016-09-16 14:53:41427}
428
mflodmancc3d4422017-08-03 15:27:51429void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 18:45:46430 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 08:17:40431 encoder_queue_.PostTask([this, sink] {
432 RTC_DCHECK_RUN_ON(&encoder_queue_);
433 sink_ = sink;
434 });
mflodman@webrtc.org84d17832011-12-01 17:02:23435}
436
mflodmancc3d4422017-08-03 15:27:51437void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 08:17:40438 encoder_queue_.PostTask([this, start_bitrate_bps] {
439 RTC_DCHECK_RUN_ON(&encoder_queue_);
440 encoder_start_bitrate_bps_ = start_bitrate_bps;
441 });
mflodman@webrtc.org84d17832011-12-01 17:02:23442}
Peter Boström00b9d212016-05-19 14:59:03443
mflodmancc3d4422017-08-03 15:27:51444void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 07:51:47445 size_t max_data_payload_length) {
Sebastian Jansson3dc0125c2018-03-19 18:27:44446 // TODO(srte): This struct should be replaced by a lambda with move capture
447 // when C++14 lambda is allowed.
448 struct ConfigureEncoderTask {
449 void operator()() {
Yves Gerey665174f2018-06-19 13:03:05450 encoder->ConfigureEncoderOnTaskQueue(std::move(config),
451 max_data_payload_length);
Sebastian Jansson3dc0125c2018-03-19 18:27:44452 }
453 VideoStreamEncoder* encoder;
454 VideoEncoderConfig config;
455 size_t max_data_payload_length;
Sebastian Jansson3dc0125c2018-03-19 18:27:44456 };
Yves Gerey665174f2018-06-19 13:03:05457 encoder_queue_.PostTask(
458 ConfigureEncoderTask{this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 08:17:40459}
460
mflodmancc3d4422017-08-03 15:27:51461void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
462 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 07:51:47463 size_t max_data_payload_length) {
perkj26091b12016-09-01 08:17:40464 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 08:17:40465 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 10:09:25466 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 09:48:50467
468 max_data_payload_length_ = max_data_payload_length;
Niels Möller4db138e2018-04-19 07:04:13469 pending_encoder_creation_ =
470 (!encoder_ || encoder_config_.video_format != config.video_format);
Pera48ddb72016-09-29 09:48:50471 encoder_config_ = std::move(config);
perkjfa10b552016-10-03 06:45:26472 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 09:48:50473
perkjfa10b552016-10-03 06:45:26474 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 20:37:57475 // if the frame resolution is known. Otherwise, the reconfiguration is
476 // deferred until the next frame to minimize the number of reconfigurations.
477 // The codec configuration depends on incoming video frame size.
478 if (last_frame_info_) {
479 ReconfigureEncoder();
Yves Gerey665174f2018-06-19 13:03:05480 } else if (settings_.encoder_factory
481 ->QueryVideoEncoder(encoder_config_.video_format)
482 .has_internal_source) {
Niels Moller0d650b42018-04-18 07:17:07483 last_frame_info_ = VideoFrameInfo(176, 144, false);
484 ReconfigureEncoder();
perkjfa10b552016-10-03 06:45:26485 }
486}
perkj26091b12016-09-01 08:17:40487
Seth Hampsoncc7125f2018-02-02 16:46:16488// TODO(bugs.webrtc.org/8807): Currently this always does a hard
489// reconfiguration, but this isn't always necessary. Add in logic to only update
490// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
491// "soft" reconfiguration.
mflodmancc3d4422017-08-03 15:27:51492void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-03 06:45:26493 RTC_DCHECK(pending_encoder_reconfiguration_);
494 std::vector<VideoStream> streams =
495 encoder_config_.video_stream_factory->CreateEncoderStreams(
496 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 08:17:40497
ilnik6b826ef2017-06-16 13:53:48498 // TODO(ilnik): If configured resolution is significantly less than provided,
499 // e.g. because there are not enough SSRCs for all simulcast streams,
500 // signal new resolutions via SinkWants to video source.
501
502 // Stream dimensions may be not equal to given because of a simulcast
503 // restrictions.
504 int highest_stream_width = static_cast<int>(streams.back().width);
505 int highest_stream_height = static_cast<int>(streams.back().height);
506 // Dimension may be reduced to be, e.g. divisible by 4.
507 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
508 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
509 crop_width_ = last_frame_info_->width - highest_stream_width;
510 crop_height_ = last_frame_info_->height - highest_stream_height;
511
Erik Språng08127a92016-11-16 15:41:30512 VideoCodec codec;
Yves Gerey665174f2018-06-19 13:03:05513 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec,
514 &rate_allocator_)) {
Mirko Bonadei675513b2017-11-09 10:09:25515 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 15:41:30516 }
perkjfa10b552016-10-03 06:45:26517
“Michael277a6562018-06-01 19:09:19518 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
519 if (encoder_config_.codec_type == kVideoCodecVP9) {
520 RTC_DCHECK_EQ(1U, streams.size());
521 int max_encoder_bitrate_kbps = 0;
522 for (int i = 0; i < codec.VP9()->numberOfSpatialLayers; ++i) {
523 max_encoder_bitrate_kbps += codec.spatialLayers[i].maxBitrate;
524 }
525 // Lower max bitrate to the level codec actually can produce.
526 streams[0].max_bitrate_bps =
527 std::min(streams[0].max_bitrate_bps, max_encoder_bitrate_kbps * 1000);
528 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
529 // Pass along the value of maximum padding bit rate from
530 // spatialLayers[].targetBitrate to streams[0].target_bitrate_bps.
531 // TODO(ssilkin): There should be some margin between max padding bitrate
532 // and max encoder bitrate. With the current logic they can be equal.
533 streams[0].target_bitrate_bps =
534 std::min(static_cast<unsigned int>(streams[0].max_bitrate_bps),
535 codec.spatialLayers[codec.VP9()->numberOfSpatialLayers - 1]
536 .targetBitrate *
537 1000);
538 }
539
perkjfa10b552016-10-03 06:45:26540 codec.startBitrate =
541 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
542 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
543 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 11:21:07544 max_framerate_ = codec.maxFramerate;
Mirko Bonadei948b7e32018-08-14 07:23:21545 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 10:11:06546
Niels Möller4db138e2018-04-19 07:04:13547 // Keep the same encoder, as long as the video_format is unchanged.
548 if (pending_encoder_creation_) {
549 pending_encoder_creation_ = false;
550 if (encoder_) {
551 video_sender_.RegisterExternalEncoder(nullptr, false);
552 }
553
Ilya Nikolaevskiyfc9dcb62018-06-11 08:04:54554 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
555 encoder_config_.video_format);
Niels Möller4db138e2018-04-19 07:04:13556 // TODO(nisse): What to do if creating the encoder fails? Crash,
557 // or just discard incoming frames?
558 RTC_CHECK(encoder_);
559
Niels Möller4db138e2018-04-19 07:04:13560 const webrtc::VideoEncoderFactory::CodecInfo info =
561 settings_.encoder_factory->QueryVideoEncoder(
562 encoder_config_.video_format);
563
564 overuse_detector_->StopCheckForOveruse();
565 overuse_detector_->StartCheckForOveruse(
566 GetCpuOveruseOptions(settings_, info.is_hardware_accelerated), this);
567
568 video_sender_.RegisterExternalEncoder(encoder_.get(),
569 info.has_internal_source);
570 }
571 // RegisterSendCodec implies an unconditional call to
572 // encoder_->InitEncode().
Peter Boströmcd5c25c2016-04-21 14:48:08573 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-03 06:45:26574 &codec, number_of_cores_,
575 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 15:59:56576 if (!success) {
Mirko Bonadei675513b2017-11-09 10:09:25577 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 15:24:59578 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23579 }
Peter Boström905f8e72016-03-02 15:59:56580
Niels Möller96d7f762018-01-30 10:27:16581 video_sender_.UpdateChannelParameters(rate_allocator_.get(),
ilnik35b7de42017-03-15 11:24:21582 bitrate_observer_);
583
Niels Möller213618e2018-07-24 07:29:58584 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 13:52:06585
perkjfa10b552016-10-03 06:45:26586 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 15:41:30587
Pera48ddb72016-09-29 09:48:50588 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-03 06:45:26589 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 09:44:11590
Niels Möller7dc26b72017-12-06 09:27:48591 // Get the current target framerate, ie the maximum framerate as specified by
592 // the current codec configuration, or any limit imposed by cpu adaption in
593 // maintain-resolution or balanced mode. This is used to make sure overuse
594 // detection doesn't needlessly trigger in low and/or variable framerate
595 // scenarios.
596 int target_framerate = std::min(
597 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
598 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 07:13:08599
600 ConfigureQualityScaler();
kthelgason2bc68642017-02-07 15:02:22601}
602
mflodmancc3d4422017-08-03 15:27:51603void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 15:02:22604 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller4db138e2018-04-19 07:04:13605 const auto scaling_settings = encoder_->GetScalingSettings();
asapersson36e9eb42017-03-31 12:29:12606 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 07:34:08607 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c787c2018-02-22 14:03:53608 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 07:25:28609
asapersson36e9eb42017-03-31 12:29:12610 if (quality_scaling_allowed) {
asapersson09f05612017-05-16 06:40:18611 if (quality_scaler_.get() == nullptr) {
612 // Quality scaler has not already been configured.
Niels Möller225c787c2018-02-22 14:03:53613
Åsa Perssona945aee2018-04-24 14:53:25614 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 10:28:07615 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 14:53:25616 if (quality_scaling_experiment_enabled_) {
617 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
618 encoder_config_.codec_type);
619 }
Karl Wiberg918f50c2018-07-05 09:40:33620 // Since the interface is non-public, absl::make_unique can't do this
621 // upcast.
Niels Möller225c787c2018-02-22 14:03:53622 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 09:40:33623 quality_scaler_ = absl::make_unique<QualityScaler>(
Åsa Perssona945aee2018-04-24 14:53:25624 observer, experimental_thresholds ? *experimental_thresholds
625 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 08:51:40626 has_seen_first_significant_bwe_change_ = false;
627 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 09:44:11628 }
629 } else {
630 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 08:51:40631 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 09:44:11632 }
asapersson09f05612017-05-16 06:40:18633
Niels Möller213618e2018-07-24 07:29:58634 encoder_stats_observer_->OnAdaptationChanged(
635 VideoStreamEncoderObserver::AdaptationReason::kNone,
636 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23637}
638
mflodmancc3d4422017-08-03 15:27:51639void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 08:17:40640 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 08:17:40641 VideoFrame incoming_frame = video_frame;
642
643 // Local time in webrtc time base.
ilnik04f4d122017-06-19 14:18:55644 int64_t current_time_us = clock_->TimeInMicroseconds();
645 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
646 // In some cases, e.g., when the frame from decoder is fed to encoder,
647 // the timestamp may be set to the future. As the encoding pipeline assumes
648 // capture time to be less than present time, we should reset the capture
649 // timestamps here. Otherwise there may be issues with RTP send stream.
650 if (incoming_frame.timestamp_us() > current_time_us)
651 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 08:17:40652
653 // Capture time may come from clock with an offset and drift from clock_.
654 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 18:02:22655 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 08:17:40656 capture_ntp_time_ms = video_frame.ntp_time_ms();
657 } else if (video_frame.render_time_ms() != 0) {
658 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
659 } else {
nisse1c0dea82017-01-30 10:43:18660 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 08:17:40661 }
662 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
663
664 // Convert NTP time, in ms, to RTP timestamp.
665 const int kMsToRtpTimestamp = 90;
666 incoming_frame.set_timestamp(
667 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
668
669 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
670 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 10:09:25671 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
672 << incoming_frame.ntp_time_ms()
673 << " <= " << last_captured_timestamp_
674 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 08:17:40675 return;
676 }
677
asapersson6ffb67d2016-09-12 07:10:45678 bool log_stats = false;
nisse1c0dea82017-01-30 10:43:18679 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
680 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 07:10:45681 log_stats = true;
682 }
683
perkj26091b12016-09-01 08:17:40684 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 10:30:50685
686 int64_t post_time_us = rtc::TimeMicros();
687 ++posted_frames_waiting_for_encode_;
688
689 encoder_queue_.PostTask(
690 [this, incoming_frame, post_time_us, log_stats]() {
691 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 07:29:58692 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
693 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 10:30:50694 ++captured_frame_count_;
695 const int posted_frames_waiting_for_encode =
696 posted_frames_waiting_for_encode_.fetch_sub(1);
697 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
698 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 11:05:49699 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 10:30:50700 } else {
701 // There is a newer frame in flight. Do not encode this frame.
702 RTC_LOG(LS_VERBOSE)
703 << "Incoming frame dropped due to that the encoder is blocked.";
704 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 07:29:58705 encoder_stats_observer_->OnFrameDropped(
706 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Sebastian Jansson3ab5c402018-04-05 10:30:50707 }
708 if (log_stats) {
709 RTC_LOG(LS_INFO) << "Number of frames: captured "
710 << captured_frame_count_
711 << ", dropped (due to encoder blocked) "
712 << dropped_frame_count_ << ", interval_ms "
713 << kFrameLogIntervalMs;
714 captured_frame_count_ = 0;
715 dropped_frame_count_ = 0;
716 }
717 });
perkj26091b12016-09-01 08:17:40718}
719
Ilya Nikolaevskiyd79314f2017-10-23 08:45:37720void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 07:29:58721 encoder_stats_observer_->OnFrameDropped(
722 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 08:45:37723}
724
mflodmancc3d4422017-08-03 15:27:51725bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 08:17:40726 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08727 // Pause video if paused by caller or as long as the network is down or the
728 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 14:27:16729 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 07:58:48730 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 08:17:40731 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01732}
733
mflodmancc3d4422017-08-03 15:27:51734void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 08:17:40735 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16736 // Start trace event only on the first frame after encoder is paused.
737 if (!encoder_paused_and_dropped_frame_) {
738 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
739 }
740 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16741}
742
mflodmancc3d4422017-08-03 15:27:51743void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 08:17:40744 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16745 // End trace event on first frame after encoder resumes, if frame was dropped.
746 if (encoder_paused_and_dropped_frame_) {
747 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
748 }
749 encoder_paused_and_dropped_frame_ = false;
750}
751
Sebastian Janssona3177052018-04-10 11:05:49752void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
753 int64_t time_when_posted_us) {
perkj26091b12016-09-01 08:17:40754 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 09:44:11755
perkj26091b12016-09-01 08:17:40756 if (pre_encode_callback_)
757 pre_encode_callback_->OnFrame(video_frame);
758
Per21d45d22016-10-30 20:37:57759 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-03 06:45:26760 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-03 06:45:26761 video_frame.is_texture() != last_frame_info_->is_texture) {
762 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 15:45:42763 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
764 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 10:09:25765 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
766 << last_frame_info_->width << "x"
767 << last_frame_info_->height
768 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-03 06:45:26769 }
770
Niels Möller4db138e2018-04-19 07:04:13771 // We have to create then encoder before the frame drop logic,
772 // because the latter depends on encoder_->GetScalingSettings.
773 // According to the testcase
774 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
775 // from GetScalingSettings should enable or disable the frame drop.
776
777 int64_t now_ms = clock_->TimeInMilliseconds();
778 if (pending_encoder_reconfiguration_) {
779 ReconfigureEncoder();
780 last_parameters_update_ms_.emplace(now_ms);
781 } else if (!last_parameters_update_ms_ ||
782 now_ms - *last_parameters_update_ms_ >=
783 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
784 video_sender_.UpdateChannelParameters(rate_allocator_.get(),
785 bitrate_observer_);
786 last_parameters_update_ms_.emplace(now_ms);
787 }
788
Sebastian Janssona3177052018-04-10 11:05:49789 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 10:09:25790 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 07:49:53791 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 15:02:22792 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 07:49:53793 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 07:29:58794 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 07:49:53795 }
Kári Tristan Helgason639602a2018-08-02 08:51:40796 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 11:57:13797 // Storing references to a native buffer risks blocking frame capture.
798 if (video_frame.video_frame_buffer()->type() !=
799 VideoFrameBuffer::Type::kNative) {
800 pending_frame_ = video_frame;
801 pending_frame_post_time_us_ = time_when_posted_us;
802 } else {
803 // Ensure that any previously stored frame is dropped.
804 pending_frame_.reset();
805 }
kthelgason2bc68642017-02-07 15:02:22806 return;
807 }
Kári Tristan Helgason639602a2018-08-02 08:51:40808 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 15:02:22809
perkj26091b12016-09-01 08:17:40810 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 11:57:13811 // Storing references to a native buffer risks blocking frame capture.
812 if (video_frame.video_frame_buffer()->type() !=
813 VideoFrameBuffer::Type::kNative) {
814 if (pending_frame_)
815 TraceFrameDropStart();
816 pending_frame_ = video_frame;
817 pending_frame_post_time_us_ = time_when_posted_us;
818 } else {
819 // Ensure that any previously stored frame is dropped.
820 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 11:05:49821 TraceFrameDropStart();
Sebastian Jansson0d70e372018-04-17 11:57:13822 }
perkj26091b12016-09-01 08:17:40823 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23824 }
Sebastian Janssona3177052018-04-10 11:05:49825
826 pending_frame_.reset();
827 EncodeVideoFrame(video_frame, time_when_posted_us);
828}
829
830void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
831 int64_t time_when_posted_us) {
832 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 08:17:40833 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25834
ilnik6b826ef2017-06-16 13:53:48835 VideoFrame out_frame(video_frame);
836 // Crop frame if needed.
837 if (crop_width_ > 0 || crop_height_ > 0) {
838 int cropped_width = video_frame.width() - crop_width_;
839 int cropped_height = video_frame.height() - crop_height_;
840 rtc::scoped_refptr<I420Buffer> cropped_buffer =
841 I420Buffer::Create(cropped_width, cropped_height);
842 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
843 // happen after SinkWants signaled correctly from ReconfigureEncoder.
844 if (crop_width_ < 4 && crop_height_ < 4) {
845 cropped_buffer->CropAndScaleFrom(
846 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
847 crop_height_ / 2, cropped_width, cropped_height);
848 } else {
849 cropped_buffer->ScaleFrom(
850 *video_frame.video_frame_buffer()->ToI420().get());
851 }
852 out_frame =
853 VideoFrame(cropped_buffer, video_frame.timestamp(),
854 video_frame.render_time_ms(), video_frame.rotation());
855 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
856 }
857
Magnus Jedvert26679d62015-04-07 12:07:41858 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18859 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43860
Niels Möller7dc26b72017-12-06 09:27:48861 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 13:32:18862
ilnik6b826ef2017-06-16 13:53:48863 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25864}
niklase@google.com470e71d2011-07-07 08:21:25865
mflodmancc3d4422017-08-03 15:27:51866void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 08:17:40867 if (!encoder_queue_.IsCurrent()) {
868 encoder_queue_.PostTask([this] { SendKeyFrame(); });
869 return;
870 }
871 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 09:27:23872 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Peter Boströmcd5c25c2016-04-21 14:48:08873 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48874}
875
mflodmancc3d4422017-08-03 15:27:51876EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-03 00:46:41877 const EncodedImage& encoded_image,
878 const CodecSpecificInfo* codec_specific_info,
879 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 08:17:40880 // Encoded is called on whatever thread the real encoder implementation run
881 // on. In the case of hardware encoders, there might be several encoders
882 // running in parallel on different threads.
Niels Möller213618e2018-07-24 07:29:58883 encoder_stats_observer_->OnSendEncodedImage(encoded_image,
884 codec_specific_info);
sprang3911c262016-04-15 08:24:14885
Sergey Ulanov525df3f2016-08-03 00:46:41886 EncodedImageCallback::Result result =
887 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 13:31:25888
Niels Möller7dc26b72017-12-06 09:27:48889 int64_t time_sent_us = rtc::TimeMicros();
Niels Möller23775882018-08-16 08:24:12890 uint32_t timestamp = encoded_image.Timestamp();
kthelgason876222f2016-11-29 09:44:11891 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 15:39:44892 int64_t capture_time_us =
893 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
894
Danil Chapovalovb9b146c2018-06-15 10:28:07895 absl::optional<int> encode_duration_us;
Ilya Nikolaevskiyb6c462d2018-06-05 13:21:32896 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
Niels Möller83dbeac2017-12-14 15:39:44897 encode_duration_us.emplace(
898 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
899 rtc::kNumMicrosecsPerMillisec *
900 (encoded_image.timing_.encode_finish_ms -
901 encoded_image.timing_.encode_start_ms));
902 }
903
904 encoder_queue_.PostTask(
905 [this, timestamp, time_sent_us, qp, capture_time_us, encode_duration_us] {
906 RTC_DCHECK_RUN_ON(&encoder_queue_);
907 overuse_detector_->FrameSent(timestamp, time_sent_us, capture_time_us,
908 encode_duration_us);
909 if (quality_scaler_ && qp >= 0)
Åsa Persson04d5f1d2018-04-20 13:19:11910 quality_scaler_->ReportQp(qp);
Niels Möller83dbeac2017-12-14 15:39:44911 });
perkj803d97f2016-11-01 18:45:46912
Sergey Ulanov525df3f2016-08-03 00:46:41913 return result;
Peter Boströmb7d9a972015-12-18 15:01:11914}
915
Ilya Nikolaevskiyd79314f2017-10-23 08:45:37916void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
917 switch (reason) {
918 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 07:29:58919 encoder_stats_observer_->OnFrameDropped(
920 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 08:45:37921 encoder_queue_.PostTask([this] {
922 RTC_DCHECK_RUN_ON(&encoder_queue_);
923 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 14:53:25924 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 08:45:37925 });
926 break;
927 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 07:29:58928 encoder_stats_observer_->OnFrameDropped(
929 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 14:53:25930 encoder_queue_.PostTask([this] {
931 RTC_DCHECK_RUN_ON(&encoder_queue_);
932 if (quality_scaler_)
933 quality_scaler_->ReportDroppedFrameByEncoder();
934 });
Ilya Nikolaevskiyd79314f2017-10-23 08:45:37935 break;
936 }
kthelgason876222f2016-11-29 09:44:11937}
938
mflodmancc3d4422017-08-03 15:27:51939void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
940 uint8_t fraction_lost,
941 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 08:17:40942 if (!encoder_queue_.IsCurrent()) {
943 encoder_queue_.PostTask(
944 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
945 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
946 });
947 return;
948 }
949 RTC_DCHECK_RUN_ON(&encoder_queue_);
950 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
951
Mirko Bonadei675513b2017-11-09 10:09:25952 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
953 << " packet loss " << static_cast<int>(fraction_lost)
954 << " rtt " << round_trip_time_ms;
Kári Tristan Helgason639602a2018-08-02 08:51:40955 // On significant changes to BWE at the start of the call,
956 // enable frame drops to quickly react to jumps in available bandwidth.
957 if (encoder_start_bitrate_bps_ != 0 &&
958 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
959 initial_framedrop_on_bwe_enabled_ &&
960 abs_diff(bitrate_bps, encoder_start_bitrate_bps_) >=
961 kFramedropThreshold * encoder_start_bitrate_bps_) {
962 // Reset initial framedrop feature when first real BW estimate arrives.
963 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
964 // without an actual BW estimate.
965 initial_framedrop_ = 0;
966 has_seen_first_significant_bwe_change_ = true;
967 }
perkj26091b12016-09-01 08:17:40968
Peter Boströmcd5c25c2016-04-21 14:48:08969 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 14:34:11970 round_trip_time_ms, rate_allocator_.get(),
971 bitrate_observer_);
perkj26091b12016-09-01 08:17:40972
973 encoder_start_bitrate_bps_ =
974 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 15:21:19975 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 15:41:30976 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 08:17:40977 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12978
sprang552c7c72017-02-13 12:41:45979 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 10:09:25980 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
981 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 07:29:58982 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 15:21:19983 }
Sebastian Janssona3177052018-04-10 11:05:49984 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
985 !DropDueToSize(pending_frame_->size())) {
986 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
987 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
988 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
989 pending_frame_.reset();
990 }
991}
992
993bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 08:51:40994 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 11:05:49995 encoder_start_bitrate_bps_ > 0) {
996 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
997 return pixel_count > 320 * 240;
998 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
999 return pixel_count > 640 * 480;
1000 }
1001 }
1002 return false;
niklase@google.com470e71d2011-07-07 08:21:251003}
1004
mflodmancc3d4422017-08-03 15:27:511005void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 13:32:181006 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-03 06:53:041007 AdaptationRequest adaptation_request = {
1008 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 07:29:581009 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-03 06:53:041010 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-16 06:40:181011
sprangc5d62e22017-04-03 06:53:041012 bool downgrade_requested =
1013 last_adaptation_request_ &&
1014 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1015
sprangc5d62e22017-04-03 06:53:041016 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 21:20:411017 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-14 06:25:221018 break;
Taylor Brandstetter49fcc102018-05-16 21:20:411019 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-03 06:53:041020 if (downgrade_requested &&
1021 adaptation_request.input_pixel_count_ >=
1022 last_adaptation_request_->input_pixel_count_) {
1023 // Don't request lower resolution if the current resolution is not
1024 // lower than the last time we asked for the resolution to be lowered.
1025 return;
1026 }
1027 break;
Taylor Brandstetter49fcc102018-05-16 21:20:411028 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-03 06:53:041029 if (adaptation_request.framerate_fps_ <= 0 ||
1030 (downgrade_requested &&
1031 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1032 // If no input fps estimate available, can't determine how to scale down
1033 // framerate. Otherwise, don't request lower framerate if we don't have
1034 // a valid frame rate. Since framerate, unlike resolution, is a measure
1035 // we have to estimate, and can fluctuate naturally over time, don't
1036 // make the same kind of limitations as for resolution, but trust the
1037 // overuse detector to not trigger too often.
1038 return;
1039 }
1040 break;
Taylor Brandstetter49fcc102018-05-16 21:20:411041 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-03 06:53:041042 return;
sprang84a37592017-02-10 15:04:271043 }
sprangc5d62e22017-04-03 06:53:041044
sprangc5d62e22017-04-03 06:53:041045 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 21:20:411046 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-14 06:25:221047 // Try scale down framerate, if lower.
1048 int fps = MinFps(last_frame_info_->pixel_count());
1049 if (source_proxy_->RestrictFramerate(fps)) {
1050 GetAdaptCounter().IncrementFramerate(reason);
1051 break;
1052 }
1053 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 09:33:351054 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-14 06:25:221055 }
Taylor Brandstetter49fcc102018-05-16 21:20:411056 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 07:01:021057 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 13:04:521058 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 08:47:311059 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 15:58:541060 adaptation_request.input_pixel_count_,
Niels Möller4db138e2018-04-19 07:04:131061 encoder_->GetScalingSettings().min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 13:04:521062 &min_pixels_reached)) {
1063 if (min_pixels_reached)
Niels Möller213618e2018-07-24 07:29:581064 encoder_stats_observer_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 08:47:311065 return;
1066 }
asaperssonf7e294d2017-06-14 06:25:221067 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-03 06:53:041068 break;
Åsa Perssonc3ed6302017-11-16 13:04:521069 }
Taylor Brandstetter49fcc102018-05-16 21:20:411070 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 07:01:021071 // Scale down framerate.
sprangfda496a2017-06-15 11:21:071072 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1073 adaptation_request.framerate_fps_);
1074 if (requested_framerate == -1)
asapersson13874762017-06-07 07:01:021075 return;
sprangfda496a2017-06-15 11:21:071076 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 09:27:481077 overuse_detector_->OnTargetFramerateUpdated(
1078 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-14 06:25:221079 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-03 06:53:041080 break;
sprangfda496a2017-06-15 11:21:071081 }
Taylor Brandstetter49fcc102018-05-16 21:20:411082 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-03 06:53:041083 RTC_NOTREACHED();
1084 }
1085
asaperssond0de2952017-04-21 08:47:311086 last_adaptation_request_.emplace(adaptation_request);
1087
asapersson09f05612017-05-16 06:40:181088 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 08:47:311089
Mirko Bonadei675513b2017-11-09 10:09:251090 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 08:17:401091}
1092
mflodmancc3d4422017-08-03 15:27:511093void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 13:32:181094 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-16 06:40:181095
1096 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1097 int num_downgrades = adapt_counter.TotalCount(reason);
1098 if (num_downgrades == 0)
perkj803d97f2016-11-01 18:45:461099 return;
asapersson09f05612017-05-16 06:40:181100 RTC_DCHECK_GT(num_downgrades, 0);
1101
sprangc5d62e22017-04-03 06:53:041102 AdaptationRequest adaptation_request = {
1103 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 07:29:581104 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-03 06:53:041105 AdaptationRequest::Mode::kAdaptUp};
1106
1107 bool adapt_up_requested =
1108 last_adaptation_request_ &&
1109 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-16 06:40:181110
Taylor Brandstetter49fcc102018-05-16 21:20:411111 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-14 06:25:221112 if (adapt_up_requested &&
1113 adaptation_request.input_pixel_count_ <=
1114 last_adaptation_request_->input_pixel_count_) {
1115 // Don't request higher resolution if the current resolution is not
1116 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-03 06:53:041117 return;
asaperssonf7e294d2017-06-14 06:25:221118 }
sprangb1ca0732017-02-01 16:38:121119 }
sprangc5d62e22017-04-03 06:53:041120
sprangc5d62e22017-04-03 06:53:041121 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 21:20:411122 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-14 06:25:221123 // Try scale up framerate, if higher.
1124 int fps = MaxFps(last_frame_info_->pixel_count());
1125 if (source_proxy_->IncreaseFramerate(fps)) {
1126 GetAdaptCounter().DecrementFramerate(reason, fps);
1127 // Reset framerate in case of fewer fps steps down than up.
1128 if (adapt_counter.FramerateCount() == 0 &&
1129 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 10:09:251130 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-14 06:25:221131 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1132 }
1133 break;
1134 }
1135 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 09:33:351136 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-14 06:25:221137 }
Taylor Brandstetter49fcc102018-05-16 21:20:411138 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 07:01:021139 // Scale up resolution.
1140 int pixel_count = adaptation_request.input_pixel_count_;
1141 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 10:09:251142 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 07:01:021143 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-03 06:53:041144 }
asapersson13874762017-06-07 07:01:021145 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1146 return;
asaperssonf7e294d2017-06-14 06:25:221147 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-03 06:53:041148 break;
asapersson13874762017-06-07 07:01:021149 }
Taylor Brandstetter49fcc102018-05-16 21:20:411150 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 07:01:021151 // Scale up framerate.
1152 int fps = adaptation_request.framerate_fps_;
1153 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 10:09:251154 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 07:01:021155 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-03 06:53:041156 }
sprangfda496a2017-06-15 11:21:071157
1158 const int requested_framerate =
1159 source_proxy_->RequestHigherFramerateThan(fps);
1160 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 09:27:481161 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 07:01:021162 return;
sprangfda496a2017-06-15 11:21:071163 }
Niels Möller7dc26b72017-12-06 09:27:481164 overuse_detector_->OnTargetFramerateUpdated(
1165 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-14 06:25:221166 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-03 06:53:041167 break;
asapersson13874762017-06-07 07:01:021168 }
Taylor Brandstetter49fcc102018-05-16 21:20:411169 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-14 06:25:221170 return;
sprangc5d62e22017-04-03 06:53:041171 }
1172
asaperssond0de2952017-04-21 08:47:311173 last_adaptation_request_.emplace(adaptation_request);
1174
asapersson09f05612017-05-16 06:40:181175 UpdateAdaptationStats(reason);
1176
Mirko Bonadei675513b2017-11-09 10:09:251177 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-16 06:40:181178}
1179
Niels Möller213618e2018-07-24 07:29:581180// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 15:27:511181void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 08:47:311182 switch (reason) {
asaperssond0de2952017-04-21 08:47:311183 case kCpu:
Niels Möller213618e2018-07-24 07:29:581184 encoder_stats_observer_->OnAdaptationChanged(
1185 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1186 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-16 06:40:181187 break;
1188 case kQuality:
Niels Möller213618e2018-07-24 07:29:581189 encoder_stats_observer_->OnAdaptationChanged(
1190 VideoStreamEncoderObserver::AdaptationReason::kQuality,
1191 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 08:47:311192 break;
1193 }
perkj26091b12016-09-01 08:17:401194}
1195
Niels Möller213618e2018-07-24 07:29:581196VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 15:27:511197 AdaptReason reason) {
Niels Möller213618e2018-07-24 07:29:581198 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 15:27:511199 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-16 06:40:181200 switch (reason) {
1201 case kCpu:
1202 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 07:29:581203 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-16 06:40:181204 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 07:29:581205 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-16 06:40:181206 break;
1207 case kQuality:
1208 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1209 !quality_scaler_) {
Niels Möller213618e2018-07-24 07:29:581210 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-16 06:40:181211 }
1212 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1213 !quality_scaler_) {
Niels Möller213618e2018-07-24 07:29:581214 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-16 06:40:181215 }
1216 break;
sprangc5d62e22017-04-03 06:53:041217 }
asapersson09f05612017-05-16 06:40:181218 return counts;
sprangc5d62e22017-04-03 06:53:041219}
1220
mflodmancc3d4422017-08-03 15:27:511221VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-16 06:40:181222 return adapt_counters_[degradation_preference_];
1223}
1224
mflodmancc3d4422017-08-03 15:27:511225const VideoStreamEncoder::AdaptCounter&
1226VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-16 06:40:181227 return adapt_counters_[degradation_preference_];
1228}
1229
1230// Class holding adaptation information.
mflodmancc3d4422017-08-03 15:27:511231VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-16 06:40:181232 fps_counters_.resize(kScaleReasonSize);
1233 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-14 06:25:221234 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-16 06:40:181235}
1236
mflodmancc3d4422017-08-03 15:27:511237VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-16 06:40:181238
mflodmancc3d4422017-08-03 15:27:511239std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-16 06:40:181240 std::stringstream ss;
1241 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1242 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1243 return ss.str();
1244}
1245
Niels Möller213618e2018-07-24 07:29:581246VideoStreamEncoderObserver::AdaptationSteps
1247VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
1248 VideoStreamEncoderObserver::AdaptationSteps counts;
1249 counts.num_framerate_reductions = fps_counters_[reason];
1250 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-16 06:40:181251 return counts;
1252}
1253
mflodmancc3d4422017-08-03 15:27:511254void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-14 06:25:221255 ++(fps_counters_[reason]);
asapersson09f05612017-05-16 06:40:181256}
1257
mflodmancc3d4422017-08-03 15:27:511258void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-14 06:25:221259 ++(resolution_counters_[reason]);
1260}
1261
mflodmancc3d4422017-08-03 15:27:511262void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-14 06:25:221263 if (fps_counters_[reason] == 0) {
1264 // Balanced mode: Adapt up is in a different order, switch reason.
1265 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1266 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1267 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1268 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1269 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1270 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1271 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1272 MoveCount(&resolution_counters_, reason);
1273 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1274 }
1275 --(fps_counters_[reason]);
1276 RTC_DCHECK_GE(fps_counters_[reason], 0);
1277}
1278
mflodmancc3d4422017-08-03 15:27:511279void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-14 06:25:221280 if (resolution_counters_[reason] == 0) {
1281 // Balanced mode: Adapt up is in a different order, switch reason.
1282 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1283 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1284 MoveCount(&fps_counters_, reason);
1285 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1286 }
1287 --(resolution_counters_[reason]);
1288 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1289}
1290
mflodmancc3d4422017-08-03 15:27:511291void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1292 int cur_fps) {
asaperssonf7e294d2017-06-14 06:25:221293 DecrementFramerate(reason);
1294 // Reset if at max fps (i.e. in case of fewer steps up than down).
1295 if (cur_fps == std::numeric_limits<int>::max())
1296 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-16 06:40:181297}
1298
mflodmancc3d4422017-08-03 15:27:511299int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-16 06:40:181300 return Count(fps_counters_);
1301}
1302
mflodmancc3d4422017-08-03 15:27:511303int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-16 06:40:181304 return Count(resolution_counters_);
1305}
1306
mflodmancc3d4422017-08-03 15:27:511307int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-16 06:40:181308 return fps_counters_[reason];
1309}
1310
mflodmancc3d4422017-08-03 15:27:511311int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-16 06:40:181312 return resolution_counters_[reason];
1313}
1314
mflodmancc3d4422017-08-03 15:27:511315int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-16 06:40:181316 return FramerateCount(reason) + ResolutionCount(reason);
1317}
1318
mflodmancc3d4422017-08-03 15:27:511319int VideoStreamEncoder::AdaptCounter::Count(
1320 const std::vector<int>& counters) const {
asapersson09f05612017-05-16 06:40:181321 return std::accumulate(counters.begin(), counters.end(), 0);
1322}
1323
mflodmancc3d4422017-08-03 15:27:511324void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1325 int from_reason) {
asaperssonf7e294d2017-06-14 06:25:221326 int to_reason = (from_reason + 1) % kScaleReasonSize;
1327 ++((*counters)[to_reason]);
1328 --((*counters)[from_reason]);
1329}
1330
mflodmancc3d4422017-08-03 15:27:511331std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-16 06:40:181332 const std::vector<int>& counters) const {
1333 std::stringstream ss;
1334 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1335 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-03 06:53:041336 }
asapersson09f05612017-05-16 06:40:181337 return ss.str();
sprangc5d62e22017-04-03 06:53:041338}
1339
mflodman@webrtc.org84d17832011-12-01 17:02:231340} // namespace webrtc