blob: 8dcb8d92cd7cc7cebf3b2a20ee3e1ae642748d37 [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
Niels Möller6bb5ab92019-01-11 11:11:10 +010018#include "absl/memory/memory.h"
Niels Möller4dc66c52018-10-05 14:17:58 +020019#include "api/video/encoded_image.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/video/i420_buffer.h"
Jiawei Ouc2ebe212018-11-08 10:02:56 -080021#include "api/video/video_bitrate_allocator_factory.h"
Sergey Silkin8b9b5f92018-12-10 09:28:53 +010022#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "modules/video_coding/include/video_codec_initializer.h"
24#include "modules/video_coding/include/video_coding.h"
Niels Möller6bb5ab92019-01-11 11:11:10 +010025#include "modules/video_coding/utility/default_video_bitrate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/arraysize.h"
27#include "rtc_base/checks.h"
Åsa Perssona945aee2018-04-24 16:53:25 +020028#include "rtc_base/experiments/quality_scaling_experiment.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010029#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/location.h"
31#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020032#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010033#include "rtc_base/system/fallthrough.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020036#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "video/overuse_frame_detector.h"
nisseea3a7982017-05-15 02:42:11 -070038
niklase@google.com470e71d2011-07-07 08:21:25 +000039namespace webrtc {
40
perkj26091b12016-09-01 01:17:40 -070041namespace {
sprangb1ca0732017-02-01 08:38:12 -080042
asapersson6ffb67d2016-09-12 00:10:45 -070043// Time interval for logging frame counts.
44const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070045const int kMinFramerateFps = 2;
perkj26091b12016-09-01 01:17:40 -070046
Sebastian Janssona3177052018-04-10 13:05:49 +020047// Time to keep a single cached pending frame in paused state.
48const int64_t kPendingFrameTimeoutMs = 1000;
49
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020050const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
Niels Möller6bb5ab92019-01-11 11:11:10 +010051constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020052
kthelgason2bc68642017-02-07 07:02:22 -080053// The maximum number of frames to drop at beginning of stream
54// to try and achieve desired bitrate.
55const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020056// When the first change in BWE above this threshold occurs,
57// enable DropFrameDueToSize logic.
58const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 07:02:22 -080059
Niels Möller6bb5ab92019-01-11 11:11:10 +010060// Averaging window spanning 90 frames at default 30fps, matching old media
61// optimization module defaults.
62const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
63
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070064// Initial limits for BALANCED degradation preference.
asaperssonf7e294d2017-06-13 23:25:22 -070065int MinFps(int pixels) {
66 if (pixels <= 320 * 240) {
67 return 7;
68 } else if (pixels <= 480 * 270) {
69 return 10;
70 } else if (pixels <= 640 * 480) {
71 return 15;
72 } else {
73 return std::numeric_limits<int>::max();
74 }
75}
76
77int MaxFps(int pixels) {
78 if (pixels <= 320 * 240) {
79 return 10;
80 } else if (pixels <= 480 * 270) {
81 return 15;
82 } else {
83 return std::numeric_limits<int>::max();
84 }
85}
86
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020087uint32_t abs_diff(uint32_t a, uint32_t b) {
88 return (a < b) ? b - a : a - b;
89}
90
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070091bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
92 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
93 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070094}
95
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070096bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
97 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
98 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070099}
100
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200101// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
102// pipelining encoders better (multiple input frames before something comes
103// out). This should effectively turn off CPU adaptations for systems that
104// remotely cope with the load right now.
105CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 09:29:58 +0200106 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 09:04:13 +0200107 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200108 CpuOveruseOptions options;
109
Niels Möller4db138e2018-04-19 09:04:13 +0200110 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200111 options.low_encode_usage_threshold_percent = 150;
112 options.high_encode_usage_threshold_percent = 200;
113 }
114 if (settings.experiment_cpu_load_estimator) {
115 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
116 }
117
118 return options;
119}
120
perkj26091b12016-09-01 01:17:40 -0700121} // namespace
122
perkja49cbd32016-09-16 07:53:41 -0700123// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700124// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
125// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700126// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700127class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700128 public:
mflodmancc3d4422017-08-03 08:27:51 -0700129 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
130 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700131 degradation_preference_(DegradationPreference::DISABLED),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200132 source_(nullptr),
133 max_framerate_(std::numeric_limits<int>::max()) {}
perkja49cbd32016-09-16 07:53:41 -0700134
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700135 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
136 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700137 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700138 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
139 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700140 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700141 {
142 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700143 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700144 old_source = source_;
145 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700146 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700147 }
148
149 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700150 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700151 }
152
153 if (!source) {
154 return;
155 }
156
mflodmancc3d4422017-08-03 08:27:51 -0700157 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700158 }
159
Åsa Persson8c1bf952018-09-13 10:42:19 +0200160 void SetMaxFramerate(int max_framerate) {
161 RTC_DCHECK_GT(max_framerate, 0);
162 rtc::CritScope lock(&crit_);
163 if (max_framerate == max_framerate_)
164 return;
165
166 RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
167 max_framerate_ = max_framerate;
168 if (source_) {
169 source_->AddOrUpdateSink(video_stream_encoder_,
170 GetActiveSinkWantsInternal());
171 }
172 }
173
perkj803d97f2016-11-01 11:45:46 -0700174 void SetWantsRotationApplied(bool rotation_applied) {
175 rtc::CritScope lock(&crit_);
176 sink_wants_.rotation_applied = rotation_applied;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200177 if (source_) {
178 source_->AddOrUpdateSink(video_stream_encoder_,
179 GetActiveSinkWantsInternal());
180 }
sprangc5d62e22017-04-02 23:53:04 -0700181 }
182
sprangfda496a2017-06-15 04:21:07 -0700183 rtc::VideoSinkWants GetActiveSinkWants() {
184 rtc::CritScope lock(&crit_);
185 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700186 }
187
asaperssonf7e294d2017-06-13 23:25:22 -0700188 void ResetPixelFpsCount() {
189 rtc::CritScope lock(&crit_);
190 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
191 sink_wants_.target_pixel_count.reset();
192 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
193 if (source_)
Åsa Persson8c1bf952018-09-13 10:42:19 +0200194 source_->AddOrUpdateSink(video_stream_encoder_,
195 GetActiveSinkWantsInternal());
asaperssonf7e294d2017-06-13 23:25:22 -0700196 }
197
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100198 bool RequestResolutionLowerThan(int pixel_count,
199 int min_pixels_per_frame,
200 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700201 // Called on the encoder task queue.
202 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700203 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700204 // This can happen since |degradation_preference_| is set on libjingle's
205 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700206 return false;
perkj803d97f2016-11-01 11:45:46 -0700207 }
asapersson13874762017-06-07 00:01:02 -0700208 // The input video frame size will have a resolution less than or equal to
209 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800210 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100211 if (pixels_wanted >= sink_wants_.max_pixel_count) {
212 return false;
213 }
214 if (pixels_wanted < min_pixels_per_frame) {
215 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700216 return false;
asapersson13874762017-06-07 00:01:02 -0700217 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100218 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
219 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700220 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200221 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700222 source_->AddOrUpdateSink(video_stream_encoder_,
223 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700224 return true;
sprangc5d62e22017-04-02 23:53:04 -0700225 }
226
sprangfda496a2017-06-15 04:21:07 -0700227 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700228 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700229 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700230 int framerate_wanted = (fps * 2) / 3;
231 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700232 }
233
asapersson13874762017-06-07 00:01:02 -0700234 bool RequestHigherResolutionThan(int pixel_count) {
235 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700236 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700237 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700238 // This can happen since |degradation_preference_| is set on libjingle's
239 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700240 return false;
perkj803d97f2016-11-01 11:45:46 -0700241 }
asapersson13874762017-06-07 00:01:02 -0700242 int max_pixels_wanted = pixel_count;
243 if (max_pixels_wanted != std::numeric_limits<int>::max())
244 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700245
asapersson13874762017-06-07 00:01:02 -0700246 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
247 return false;
248
249 sink_wants_.max_pixel_count = max_pixels_wanted;
250 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700251 // Remove any constraints.
252 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700253 } else {
254 // On step down we request at most 3/5 the pixel count of the previous
255 // resolution, so in order to take "one step up" we request a resolution
256 // as close as possible to 5/3 of the current resolution. The actual pixel
257 // count selected depends on the capabilities of the source. In order to
258 // not take a too large step up, we cap the requested pixel count to be at
259 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100260 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700261 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100262 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
263 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700264 source_->AddOrUpdateSink(video_stream_encoder_,
265 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700266 return true;
sprangc5d62e22017-04-02 23:53:04 -0700267 }
268
sprangfda496a2017-06-15 04:21:07 -0700269 // Request upgrade in framerate. Returns the new requested frame, or -1 if
270 // no change requested. Note that maxint may be returned if limits due to
271 // adaptation requests are removed completely. In that case, consider
272 // |max_framerate_| to be the current limit (assuming the capturer complies).
273 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700274 // Called on the encoder task queue.
275 // The input frame rate will be scaled up to the last step, with rounding.
276 int framerate_wanted = fps;
277 if (fps != std::numeric_limits<int>::max())
278 framerate_wanted = (fps * 3) / 2;
279
sprangfda496a2017-06-15 04:21:07 -0700280 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700281 }
282
283 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700284 // Called on the encoder task queue.
285 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700286 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
287 return false;
288
289 const int fps_wanted = std::max(kMinFramerateFps, fps);
290 if (fps_wanted >= sink_wants_.max_framerate_fps)
291 return false;
292
Mirko Bonadei675513b2017-11-09 11:09:25 +0100293 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700294 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700295 source_->AddOrUpdateSink(video_stream_encoder_,
296 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700297 return true;
298 }
299
300 bool IncreaseFramerate(int fps) {
301 // Called on the encoder task queue.
302 rtc::CritScope lock(&crit_);
303 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
304 return false;
305
306 const int fps_wanted = std::max(kMinFramerateFps, fps);
307 if (fps_wanted <= sink_wants_.max_framerate_fps)
308 return false;
309
Mirko Bonadei675513b2017-11-09 11:09:25 +0100310 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700311 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700312 source_->AddOrUpdateSink(video_stream_encoder_,
313 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700314 return true;
perkj803d97f2016-11-01 11:45:46 -0700315 }
316
perkja49cbd32016-09-16 07:53:41 -0700317 private:
sprangfda496a2017-06-15 04:21:07 -0700318 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700319 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700320 rtc::VideoSinkWants wants = sink_wants_;
321 // Clear any constraints from the current sink wants that don't apply to
322 // the used degradation_preference.
323 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700324 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 04:21:07 -0700325 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700326 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 04:21:07 -0700327 wants.max_framerate_fps = std::numeric_limits<int>::max();
328 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700329 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 04:21:07 -0700330 wants.max_pixel_count = std::numeric_limits<int>::max();
331 wants.target_pixel_count.reset();
332 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700333 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 04:21:07 -0700334 wants.max_pixel_count = std::numeric_limits<int>::max();
335 wants.target_pixel_count.reset();
336 wants.max_framerate_fps = std::numeric_limits<int>::max();
337 }
Åsa Persson8c1bf952018-09-13 10:42:19 +0200338 // Limit to configured max framerate.
339 wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
sprangfda496a2017-06-15 04:21:07 -0700340 return wants;
341 }
342
perkja49cbd32016-09-16 07:53:41 -0700343 rtc::CriticalSection crit_;
344 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700345 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700346 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700347 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 04:17:22 -0700348 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
Åsa Persson8c1bf952018-09-13 10:42:19 +0200349 int max_framerate_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700350
351 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
352};
353
Åsa Persson0122e842017-10-16 12:19:23 +0200354VideoStreamEncoder::VideoStreamEncoder(
355 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200356 VideoStreamEncoderObserver* encoder_stats_observer,
357 const VideoStreamEncoderSettings& settings,
Åsa Persson0122e842017-10-16 12:19:23 +0200358 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700359 : shutdown_event_(true /* manual_reset */, false),
360 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200361 initial_framedrop_(0),
362 initial_framedrop_on_bwe_enabled_(
363 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 16:53:25 +0200364 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700365 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200366 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700367 settings_(settings),
Erik Språng7ca375c2019-02-06 16:20:17 +0100368 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
Niels Möller73f29cb2018-01-31 16:09:31 +0100369 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200370 encoder_stats_observer_(encoder_stats_observer),
sprangfda496a2017-06-15 04:21:07 -0700371 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700372 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000373 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200374 crop_width_(0),
375 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700376 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200377 max_data_payload_length_(0),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000378 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000379 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700380 clock_(Clock::GetRealTimeClock()),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700381 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700382 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700383 last_captured_timestamp_(0),
384 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
385 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700386 last_frame_log_ms_(clock_->TimeInMilliseconds()),
387 captured_frame_count_(0),
388 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200389 pending_frame_post_time_us_(0),
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100390 accumulated_update_rect_{0, 0, 0, 0},
sprang1a646ee2016-12-01 06:34:11 -0800391 bitrate_observer_(nullptr),
Niels Möller6bb5ab92019-01-11 11:11:10 +0100392 force_disable_frame_dropper_(false),
393 input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
394 pending_frame_drops_(0),
Erik Språngd7329ca2019-02-21 21:19:53 +0100395 generic_encoder_(nullptr),
396 generic_encoder_callback_(this),
397 codec_database_(&generic_encoder_callback_),
398 next_frame_types_(1, kVideoFrameDelta),
perkj26091b12016-09-01 01:17:40 -0700399 encoder_queue_("EncoderQueue") {
Niels Möller213618e2018-07-24 09:29:58 +0200400 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 16:09:31 +0100401 RTC_DCHECK(overuse_detector_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100402 RTC_DCHECK_GE(number_of_cores, 1);
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000403}
404
mflodmancc3d4422017-08-03 08:27:51 -0700405VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700406 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700407 RTC_DCHECK(shutdown_event_.Wait(0))
408 << "Must call ::Stop() before destruction.";
409}
410
mflodmancc3d4422017-08-03 08:27:51 -0700411void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700412 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700413 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700414 encoder_queue_.PostTask([this] {
415 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700416 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100417 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800418 bitrate_observer_ = nullptr;
Erik Språngd7329ca2019-02-21 21:19:53 +0100419 codec_database_.DeregisterExternalEncoder();
420 generic_encoder_ = nullptr;
kthelgason876222f2016-11-29 01:44:11 -0800421 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700422 shutdown_event_.Set();
423 });
424
425 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700426}
427
Niels Möller0327c2d2018-05-21 14:09:31 +0200428void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 06:34:11 -0800429 VideoBitrateAllocationObserver* bitrate_observer) {
430 RTC_DCHECK_RUN_ON(&thread_checker_);
431 encoder_queue_.PostTask([this, bitrate_observer] {
432 RTC_DCHECK_RUN_ON(&encoder_queue_);
433 RTC_DCHECK(!bitrate_observer_);
434 bitrate_observer_ = bitrate_observer;
435 });
436}
437
mflodmancc3d4422017-08-03 08:27:51 -0700438void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700439 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700440 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700441 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700442 source_proxy_->SetSource(source, degradation_preference);
443 encoder_queue_.PostTask([this, degradation_preference] {
444 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700445 if (degradation_preference_ != degradation_preference) {
446 // Reset adaptation state, so that we're not tricked into thinking there's
447 // an already pending request of the same type.
448 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700449 if (degradation_preference == DegradationPreference::BALANCED ||
450 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700451 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
452 // AdaptCounter for all modes.
453 source_proxy_->ResetPixelFpsCount();
454 adapt_counters_.clear();
455 }
sprangc5d62e22017-04-02 23:53:04 -0700456 }
sprangb1ca0732017-02-01 08:38:12 -0800457 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200458
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000459 if (encoder_)
Erik Språng7ca375c2019-02-06 16:20:17 +0100460 ConfigureQualityScaler(encoder_->GetEncoderInfo());
Niels Möller4db138e2018-04-19 09:04:13 +0200461
Niels Möller7dc26b72017-12-06 10:27:48 +0100462 if (!IsFramerateScalingEnabled(degradation_preference) &&
463 max_framerate_ != -1) {
464 // If frame rate scaling is no longer allowed, remove any potential
465 // allowance for longer frame intervals.
466 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
467 }
perkj803d97f2016-11-01 11:45:46 -0700468 });
perkja49cbd32016-09-16 07:53:41 -0700469}
470
mflodmancc3d4422017-08-03 08:27:51 -0700471void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700472 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700473 encoder_queue_.PostTask([this, sink] {
474 RTC_DCHECK_RUN_ON(&encoder_queue_);
475 sink_ = sink;
476 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000477}
478
mflodmancc3d4422017-08-03 08:27:51 -0700479void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700480 encoder_queue_.PostTask([this, start_bitrate_bps] {
481 RTC_DCHECK_RUN_ON(&encoder_queue_);
482 encoder_start_bitrate_bps_ = start_bitrate_bps;
483 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000484}
Peter Boström00b9d212016-05-19 16:59:03 +0200485
mflodmancc3d4422017-08-03 08:27:51 -0700486void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200487 size_t max_data_payload_length) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100488 // TODO(srte): This struct should be replaced by a lambda with move capture
489 // when C++14 lambda is allowed.
490 struct ConfigureEncoderTask {
491 void operator()() {
Yves Gerey665174f2018-06-19 15:03:05 +0200492 encoder->ConfigureEncoderOnTaskQueue(std::move(config),
493 max_data_payload_length);
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100494 }
495 VideoStreamEncoder* encoder;
496 VideoEncoderConfig config;
497 size_t max_data_payload_length;
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100498 };
Yves Gerey665174f2018-06-19 15:03:05 +0200499 encoder_queue_.PostTask(
500 ConfigureEncoderTask{this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 01:17:40 -0700501}
502
mflodmancc3d4422017-08-03 08:27:51 -0700503void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
504 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200505 size_t max_data_payload_length) {
perkj26091b12016-09-01 01:17:40 -0700506 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700507 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100508 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200509
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000510 pending_encoder_creation_ =
Erik Språngd7329ca2019-02-21 21:19:53 +0100511 (!encoder_ || encoder_config_.video_format != config.video_format ||
512 max_data_payload_length_ != max_data_payload_length);
Pera48ddb72016-09-29 11:48:50 +0200513 encoder_config_ = std::move(config);
Erik Språngd7329ca2019-02-21 21:19:53 +0100514 max_data_payload_length_ = max_data_payload_length;
perkjfa10b552016-10-02 23:45:26 -0700515 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200516
perkjfa10b552016-10-02 23:45:26 -0700517 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100518 // if the frame resolution is known. Otherwise, the reconfiguration is
519 // deferred until the next frame to minimize the number of reconfigurations.
520 // The codec configuration depends on incoming video frame size.
521 if (last_frame_info_) {
522 ReconfigureEncoder();
Erik Språngd7329ca2019-02-21 21:19:53 +0100523 } else {
524 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
525 encoder_config_.video_format);
526 if (HasInternalSource()) {
527 last_frame_info_ = VideoFrameInfo(176, 144, false);
528 ReconfigureEncoder();
529 }
perkjfa10b552016-10-02 23:45:26 -0700530 }
531}
perkj26091b12016-09-01 01:17:40 -0700532
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800533// TODO(bugs.webrtc.org/8807): Currently this always does a hard
534// reconfiguration, but this isn't always necessary. Add in logic to only update
535// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
536// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700537void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700538 RTC_DCHECK(pending_encoder_reconfiguration_);
539 std::vector<VideoStream> streams =
540 encoder_config_.video_stream_factory->CreateEncoderStreams(
541 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700542
ilnik6b826ef2017-06-16 06:53:48 -0700543 // TODO(ilnik): If configured resolution is significantly less than provided,
544 // e.g. because there are not enough SSRCs for all simulcast streams,
545 // signal new resolutions via SinkWants to video source.
546
547 // Stream dimensions may be not equal to given because of a simulcast
548 // restrictions.
Florent Castelli450b5482018-11-29 17:32:47 +0100549 auto highest_stream = std::max_element(
550 streams.begin(), streams.end(),
551 [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
552 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
553 });
554 int highest_stream_width = static_cast<int>(highest_stream->width);
555 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700556 // Dimension may be reduced to be, e.g. divisible by 4.
557 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
558 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
559 crop_width_ = last_frame_info_->width - highest_stream_width;
560 crop_height_ = last_frame_info_->height - highest_stream_height;
561
Erik Språng08127a92016-11-16 16:41:30 +0100562 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800563 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100564 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100565 }
perkjfa10b552016-10-02 23:45:26 -0700566
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800567 rate_allocator_ =
568 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800569
“Michael277a6562018-06-01 14:09:19 -0500570 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
571 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500572 // Lower max bitrate to the level codec actually can produce.
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100573 streams[0].max_bitrate_bps = std::min<int>(
574 streams[0].max_bitrate_bps, SvcRateAllocator::GetMaxBitrateBps(codec));
“Michael277a6562018-06-01 14:09:19 -0500575 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100576 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500577 streams[0].target_bitrate_bps =
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100578 SvcRateAllocator::GetPaddingBitrateBps(codec);
“Michael277a6562018-06-01 14:09:19 -0500579 }
580
perkjfa10b552016-10-02 23:45:26 -0700581 codec.startBitrate =
582 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
583 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
584 codec.expect_encode_from_texture = last_frame_info_->is_texture;
Erik Språngd7329ca2019-02-21 21:19:53 +0100585 // Make sure the start bit rate is sane...
586 RTC_DCHECK_LE(codec.startBitrate, 1000000);
sprangfda496a2017-06-15 04:21:07 -0700587 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200588
589 // Inform source about max configured framerate.
590 int max_framerate = 0;
591 for (const auto& stream : streams) {
592 max_framerate = std::max(stream.max_framerate, max_framerate);
593 }
594 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100595
Niels Möller4db138e2018-04-19 09:04:13 +0200596 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100597 // Encoder creation block is split in two since EncoderInfo needed to start
598 // CPU adaptation with the correct settings should be polled after
599 // encoder_->InitEncode().
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000600 if (pending_encoder_creation_) {
Niels Möller4db138e2018-04-19 09:04:13 +0200601 if (encoder_) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100602 codec_database_.DeregisterExternalEncoder();
603 generic_encoder_ = nullptr;
Niels Möller4db138e2018-04-19 09:04:13 +0200604 }
605
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000606 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
607 encoder_config_.video_format);
608 // TODO(nisse): What to do if creating the encoder fails? Crash,
609 // or just discard incoming frames?
610 RTC_CHECK(encoder_);
611
Erik Språngd7329ca2019-02-21 21:19:53 +0100612 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
613 encoder_config_.video_format);
Niels Möller4db138e2018-04-19 09:04:13 +0200614
Erik Språngd7329ca2019-02-21 21:19:53 +0100615 codec_database_.RegisterExternalEncoder(encoder_.get(),
616 HasInternalSource());
Niels Möller4db138e2018-04-19 09:04:13 +0200617 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100618
619 // SetSendCodec implies an unconditional call to encoder_->InitEncode().
620 bool success = codec_database_.SetSendCodec(&codec, number_of_cores_,
621 max_data_payload_length_);
622 generic_encoder_ = codec_database_.GetEncoder();
623
624 if (success) {
625 RTC_DCHECK(generic_encoder_);
626 next_frame_types_.clear();
627 next_frame_types_.resize(
628 std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
629 kVideoFrameKey);
630 RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
631 << " start bitrate " << codec.startBitrate
632 << " max frame rate " << codec.maxFramerate
633 << " max payload size " << max_data_payload_length_;
634 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100635 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700636 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000637 }
Peter Boström905f8e72016-03-02 16:59:56 +0100638
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100639 if (pending_encoder_creation_) {
640 overuse_detector_->StopCheckForOveruse();
641 overuse_detector_->StartCheckForOveruse(
642 GetCpuOveruseOptions(
643 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
644 this);
645 pending_encoder_creation_ = false;
646 }
647
Niels Möller6bb5ab92019-01-11 11:11:10 +0100648 int num_layers;
649 if (codec.codecType == kVideoCodecVP8) {
650 num_layers = codec.VP8()->numberOfTemporalLayers;
651 } else if (codec.codecType == kVideoCodecVP9) {
652 num_layers = codec.VP9()->numberOfTemporalLayers;
Johnny Lee1a1c52b2019-02-08 14:25:40 -0500653 } else if (codec.codecType == kVideoCodecH264) {
654 num_layers = codec.H264()->numberOfTemporalLayers;
Niels Möller6bb5ab92019-01-11 11:11:10 +0100655 } else if (codec.codecType == kVideoCodecGeneric &&
656 codec.numberOfSimulcastStreams > 0) {
657 // This is mainly for unit testing, disabling frame dropping.
658 // TODO(sprang): Add a better way to disable frame dropping.
659 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
660 } else {
661 num_layers = 1;
662 }
663
664 frame_dropper_.Reset();
665 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100666 // Force-disable frame dropper if either:
667 // * We have screensharing with layers.
668 // * "WebRTC-FrameDropper" field trial is "Disabled".
669 force_disable_frame_dropper_ =
670 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
671 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
672
Erik Språng7ca375c2019-02-06 16:20:17 +0100673 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
674 if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
675 bitrate_adjuster_ = absl::make_unique<EncoderBitrateAdjuster>(codec);
676 bitrate_adjuster_->OnEncoderInfo(info);
677 }
678
Niels Möller6bb5ab92019-01-11 11:11:10 +0100679 if (rate_allocator_ && last_observed_bitrate_bps_ > 0) {
680 // We have a new rate allocator instance and already configured target
681 // bitrate. Update the rate allocation and notify observsers.
Erik Språngd7329ca2019-02-21 21:19:53 +0100682 const uint32_t framerate_fps = GetInputFramerateFps();
683 SetEncoderRates(GetBitrateAllocationAndNotifyObserver(
684 last_observed_bitrate_bps_, framerate_fps),
685 framerate_fps);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100686 }
ilnik35b7de42017-03-15 04:24:21 -0700687
Niels Möller213618e2018-07-24 09:29:58 +0200688 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200689
perkjfa10b552016-10-02 23:45:26 -0700690 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100691
Pera48ddb72016-09-29 11:48:50 +0200692 sink_->OnEncoderConfigurationChanged(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100693 std::move(streams), encoder_config_.content_type,
694 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800695
Niels Möller7dc26b72017-12-06 10:27:48 +0100696 // Get the current target framerate, ie the maximum framerate as specified by
697 // the current codec configuration, or any limit imposed by cpu adaption in
698 // maintain-resolution or balanced mode. This is used to make sure overuse
699 // detection doesn't needlessly trigger in low and/or variable framerate
700 // scenarios.
701 int target_framerate = std::min(
702 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
703 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200704
Erik Språng7ca375c2019-02-06 16:20:17 +0100705 ConfigureQualityScaler(info);
kthelgason2bc68642017-02-07 07:02:22 -0800706}
707
Erik Språng7ca375c2019-02-06 16:20:17 +0100708void VideoStreamEncoder::ConfigureQualityScaler(
709 const VideoEncoder::EncoderInfo& encoder_info) {
kthelgason2bc68642017-02-07 07:02:22 -0800710 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +0100711 const auto scaling_settings = encoder_info.scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700712 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700713 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100714 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700715
asapersson36e9eb42017-03-31 05:29:12 -0700716 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700717 if (quality_scaler_.get() == nullptr) {
718 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100719
Åsa Perssona945aee2018-04-24 16:53:25 +0200720 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200721 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200722 if (quality_scaling_experiment_enabled_) {
723 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
724 encoder_config_.codec_type);
725 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200726 // Since the interface is non-public, absl::make_unique can't do this
727 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100728 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200729 quality_scaler_ = absl::make_unique<QualityScaler>(
Åsa Perssona945aee2018-04-24 16:53:25 +0200730 observer, experimental_thresholds ? *experimental_thresholds
731 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200732 has_seen_first_significant_bwe_change_ = false;
733 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800734 }
735 } else {
736 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200737 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800738 }
asapersson09f05612017-05-15 23:40:18 -0700739
Niels Möller213618e2018-07-24 09:29:58 +0200740 encoder_stats_observer_->OnAdaptationChanged(
741 VideoStreamEncoderObserver::AdaptationReason::kNone,
742 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000743}
744
mflodmancc3d4422017-08-03 08:27:51 -0700745void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700746 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700747 VideoFrame incoming_frame = video_frame;
748
749 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700750 int64_t current_time_us = clock_->TimeInMicroseconds();
751 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
752 // In some cases, e.g., when the frame from decoder is fed to encoder,
753 // the timestamp may be set to the future. As the encoding pipeline assumes
754 // capture time to be less than present time, we should reset the capture
755 // timestamps here. Otherwise there may be issues with RTP send stream.
756 if (incoming_frame.timestamp_us() > current_time_us)
757 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700758
759 // Capture time may come from clock with an offset and drift from clock_.
760 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800761 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700762 capture_ntp_time_ms = video_frame.ntp_time_ms();
763 } else if (video_frame.render_time_ms() != 0) {
764 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
765 } else {
nisse1c0dea82017-01-30 02:43:18 -0800766 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700767 }
768 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
769
770 // Convert NTP time, in ms, to RTP timestamp.
771 const int kMsToRtpTimestamp = 90;
772 incoming_frame.set_timestamp(
773 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
774
775 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
776 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100777 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
778 << incoming_frame.ntp_time_ms()
779 << " <= " << last_captured_timestamp_
780 << ") for incoming frame. Dropping.";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100781 encoder_queue_.PostTask([this, incoming_frame]() {
782 RTC_DCHECK_RUN_ON(&encoder_queue_);
783 accumulated_update_rect_.Union(incoming_frame.update_rect());
784 });
perkj26091b12016-09-01 01:17:40 -0700785 return;
786 }
787
asapersson6ffb67d2016-09-12 00:10:45 -0700788 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800789 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
790 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700791 log_stats = true;
792 }
793
perkj26091b12016-09-01 01:17:40 -0700794 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200795
796 int64_t post_time_us = rtc::TimeMicros();
797 ++posted_frames_waiting_for_encode_;
798
799 encoder_queue_.PostTask(
800 [this, incoming_frame, post_time_us, log_stats]() {
801 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +0200802 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
803 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200804 ++captured_frame_count_;
805 const int posted_frames_waiting_for_encode =
806 posted_frames_waiting_for_encode_.fetch_sub(1);
807 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
808 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +0200809 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200810 } else {
811 // There is a newer frame in flight. Do not encode this frame.
812 RTC_LOG(LS_VERBOSE)
813 << "Incoming frame dropped due to that the encoder is blocked.";
814 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +0200815 encoder_stats_observer_->OnFrameDropped(
816 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100817 accumulated_update_rect_.Union(incoming_frame.update_rect());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200818 }
819 if (log_stats) {
820 RTC_LOG(LS_INFO) << "Number of frames: captured "
821 << captured_frame_count_
822 << ", dropped (due to encoder blocked) "
823 << dropped_frame_count_ << ", interval_ms "
824 << kFrameLogIntervalMs;
825 captured_frame_count_ = 0;
826 dropped_frame_count_ = 0;
827 }
828 });
perkj26091b12016-09-01 01:17:40 -0700829}
830
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200831void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +0200832 encoder_stats_observer_->OnFrameDropped(
833 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200834}
835
mflodmancc3d4422017-08-03 08:27:51 -0700836bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700837 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000838 // Pause video if paused by caller or as long as the network is down or the
839 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700840 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700841 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700842 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000843}
844
mflodmancc3d4422017-08-03 08:27:51 -0700845void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700846 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000847 // Start trace event only on the first frame after encoder is paused.
848 if (!encoder_paused_and_dropped_frame_) {
849 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
850 }
851 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000852}
853
mflodmancc3d4422017-08-03 08:27:51 -0700854void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700855 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000856 // End trace event on first frame after encoder resumes, if frame was dropped.
857 if (encoder_paused_and_dropped_frame_) {
858 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
859 }
860 encoder_paused_and_dropped_frame_ = false;
861}
862
Niels Möller6bb5ab92019-01-11 11:11:10 +0100863VideoBitrateAllocation
864VideoStreamEncoder::GetBitrateAllocationAndNotifyObserver(
865 const uint32_t target_bitrate_bps,
866 uint32_t framerate_fps) {
867 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
868 // might cap the bitrate to the min bitrate configured.
869 VideoBitrateAllocation bitrate_allocation;
870 if (rate_allocator_ && target_bitrate_bps > 0) {
871 bitrate_allocation =
872 rate_allocator_->GetAllocation(target_bitrate_bps, framerate_fps);
873 }
874
875 if (bitrate_observer_ && bitrate_allocation.get_sum_bps() > 0) {
876 bitrate_observer_->OnBitrateAllocationUpdated(bitrate_allocation);
877 }
878
Erik Språng7ca375c2019-02-06 16:20:17 +0100879 if (bitrate_adjuster_) {
Erik Språng0e1a1f92019-02-18 18:45:13 +0100880 VideoBitrateAllocation adjusted_allocation =
881 bitrate_adjuster_->AdjustRateAllocation(bitrate_allocation,
882 framerate_fps);
883 RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = " << framerate_fps
884 << ", from " << bitrate_allocation.ToString() << ", to "
885 << adjusted_allocation.ToString();
886 return adjusted_allocation;
Erik Språng7ca375c2019-02-06 16:20:17 +0100887 }
Niels Möller6bb5ab92019-01-11 11:11:10 +0100888 return bitrate_allocation;
889}
890
891uint32_t VideoStreamEncoder::GetInputFramerateFps() {
892 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
Erik Språngd7329ca2019-02-21 21:19:53 +0100893 absl::optional<uint32_t> input_fps =
894 input_framerate_.Rate(clock_->TimeInMilliseconds());
895 if (!input_fps || *input_fps == 0) {
896 return default_fps;
897 }
898 return *input_fps;
899}
900
901void VideoStreamEncoder::SetEncoderRates(
902 const VideoBitrateAllocation& bitrate_allocation,
903 uint32_t framerate_fps) {
904 if (!generic_encoder_) {
905 return;
906 }
907
908 // |bitrate_allocation| is 0 it means that the network is down or the send
909 // pacer is full. We currently only report this if the encoder has an internal
910 // source. If the encoder does not have an internal source, higher levels
911 // are expected to not call AddVideoFrame. We do this since its unclear
912 // how current encoder implementations behave when given a zero target
913 // bitrate.
914 // TODO(perkj): Make sure all known encoder implementations handle zero
915 // target bitrate and remove this check.
916 if (!HasInternalSource() && bitrate_allocation.get_sum_bps() == 0) {
917 return;
918 }
919
920 RTC_DCHECK_GT(framerate_fps, 0);
921 generic_encoder_->SetEncoderParameters(bitrate_allocation, framerate_fps);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100922}
923
Sebastian Janssona3177052018-04-10 13:05:49 +0200924void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
925 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700926 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800927
Per21d45d22016-10-30 21:37:57 +0100928 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700929 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700930 video_frame.is_texture() != last_frame_info_->is_texture) {
931 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100932 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
933 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100934 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
935 << last_frame_info_->width << "x"
936 << last_frame_info_->height
937 << ", texture=" << last_frame_info_->is_texture << ".";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100938 // Force full frame update, since resolution has changed.
939 accumulated_update_rect_ =
940 VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
perkjfa10b552016-10-02 23:45:26 -0700941 }
942
Niels Möller4db138e2018-04-19 09:04:13 +0200943 // We have to create then encoder before the frame drop logic,
944 // because the latter depends on encoder_->GetScalingSettings.
945 // According to the testcase
946 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
947 // from GetScalingSettings should enable or disable the frame drop.
948
Erik Språnga8d48ab2019-02-08 14:17:40 +0100949 // Update input frame rate before we start using it. If we update it after
Erik Språngd7329ca2019-02-21 21:19:53 +0100950 // any potential frame drop we are going to artificially increase frame sizes.
951 // Poll the rate before updating, otherwise we risk the rate being estimated
952 // a little too high at the start of the call when then window is small.
Niels Möller6bb5ab92019-01-11 11:11:10 +0100953 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språngd7329ca2019-02-21 21:19:53 +0100954 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Niels Möller6bb5ab92019-01-11 11:11:10 +0100955
Niels Möller4db138e2018-04-19 09:04:13 +0200956 int64_t now_ms = clock_->TimeInMilliseconds();
957 if (pending_encoder_reconfiguration_) {
958 ReconfigureEncoder();
959 last_parameters_update_ms_.emplace(now_ms);
960 } else if (!last_parameters_update_ms_ ||
961 now_ms - *last_parameters_update_ms_ >=
962 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100963 SetEncoderRates(GetBitrateAllocationAndNotifyObserver(
964 last_observed_bitrate_bps_, framerate_fps),
965 framerate_fps);
Niels Möller4db138e2018-04-19 09:04:13 +0200966 last_parameters_update_ms_.emplace(now_ms);
967 }
968
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100969 // Because pending frame will be dropped in any case, we need to
970 // remember its updated region.
971 if (pending_frame_) {
972 encoder_stats_observer_->OnFrameDropped(
973 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
974 accumulated_update_rect_.Union(pending_frame_->update_rect());
975 }
976
Sebastian Janssona3177052018-04-10 13:05:49 +0200977 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100978 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +0100979 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800980 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +0100981 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +0200982 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +0100983 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200984 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200985 // Storing references to a native buffer risks blocking frame capture.
986 if (video_frame.video_frame_buffer()->type() !=
987 VideoFrameBuffer::Type::kNative) {
988 pending_frame_ = video_frame;
989 pending_frame_post_time_us_ = time_when_posted_us;
990 } else {
991 // Ensure that any previously stored frame is dropped.
992 pending_frame_.reset();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100993 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200994 }
kthelgason2bc68642017-02-07 07:02:22 -0800995 return;
996 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200997 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800998
perkj26091b12016-09-01 01:17:40 -0700999 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001000 // Storing references to a native buffer risks blocking frame capture.
1001 if (video_frame.video_frame_buffer()->type() !=
1002 VideoFrameBuffer::Type::kNative) {
1003 if (pending_frame_)
1004 TraceFrameDropStart();
1005 pending_frame_ = video_frame;
1006 pending_frame_post_time_us_ = time_when_posted_us;
1007 } else {
1008 // Ensure that any previously stored frame is dropped.
1009 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +02001010 TraceFrameDropStart();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001011 accumulated_update_rect_.Union(video_frame.update_rect());
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001012 }
perkj26091b12016-09-01 01:17:40 -07001013 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001014 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001015
1016 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001017
1018 frame_dropper_.Leak(framerate_fps);
1019 // Frame dropping is enabled iff frame dropping is not force-disabled, and
1020 // rate controller is not trusted.
1021 const bool frame_dropping_enabled =
1022 !force_disable_frame_dropper_ &&
1023 !encoder_info_.has_trusted_rate_controller;
1024 frame_dropper_.Enable(frame_dropping_enabled);
1025 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
1026 RTC_LOG(LS_VERBOSE) << "Drop Frame: "
1027 << "target bitrate " << last_observed_bitrate_bps_
1028 << ", input frame rate " << framerate_fps;
1029 OnDroppedFrame(
1030 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001031 accumulated_update_rect_.Union(video_frame.update_rect());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001032 return;
1033 }
1034
Sebastian Janssona3177052018-04-10 13:05:49 +02001035 EncodeVideoFrame(video_frame, time_when_posted_us);
1036}
1037
1038void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
1039 int64_t time_when_posted_us) {
1040 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -07001041 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +00001042
ilnik6b826ef2017-06-16 06:53:48 -07001043 VideoFrame out_frame(video_frame);
1044 // Crop frame if needed.
1045 if (crop_width_ > 0 || crop_height_ > 0) {
1046 int cropped_width = video_frame.width() - crop_width_;
1047 int cropped_height = video_frame.height() - crop_height_;
1048 rtc::scoped_refptr<I420Buffer> cropped_buffer =
1049 I420Buffer::Create(cropped_width, cropped_height);
1050 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
1051 // happen after SinkWants signaled correctly from ReconfigureEncoder.
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001052 VideoFrame::UpdateRect update_rect = video_frame.update_rect();
ilnik6b826ef2017-06-16 06:53:48 -07001053 if (crop_width_ < 4 && crop_height_ < 4) {
1054 cropped_buffer->CropAndScaleFrom(
1055 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
1056 crop_height_ / 2, cropped_width, cropped_height);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001057 update_rect.offset_x -= crop_width_ / 2;
1058 update_rect.offset_y -= crop_height_ / 2;
1059 update_rect.Intersect(
1060 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
1061
ilnik6b826ef2017-06-16 06:53:48 -07001062 } else {
1063 cropped_buffer->ScaleFrom(
1064 *video_frame.video_frame_buffer()->ToI420().get());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001065 update_rect = VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
ilnik6b826ef2017-06-16 06:53:48 -07001066 }
Artem Titov1ebfb6a2019-01-03 23:49:37 +01001067 out_frame = VideoFrame::Builder()
1068 .set_video_frame_buffer(cropped_buffer)
1069 .set_timestamp_rtp(video_frame.timestamp())
1070 .set_timestamp_ms(video_frame.render_time_ms())
1071 .set_rotation(video_frame.rotation())
1072 .set_id(video_frame.id())
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001073 .set_update_rect(update_rect)
Artem Titov1ebfb6a2019-01-03 23:49:37 +01001074 .build();
ilnik6b826ef2017-06-16 06:53:48 -07001075 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001076 // Since accumulated_update_rect_ is constructed before cropping,
1077 // we can't trust it. If any changes were pending, we invalidate whole
1078 // frame here.
1079 if (!accumulated_update_rect_.IsEmpty()) {
1080 accumulated_update_rect_ =
1081 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1082 }
1083 }
1084
1085 if (!accumulated_update_rect_.IsEmpty()) {
1086 accumulated_update_rect_.Union(out_frame.update_rect());
1087 accumulated_update_rect_.Intersect(
1088 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
1089 out_frame.set_update_rect(accumulated_update_rect_);
1090 accumulated_update_rect_.MakeEmptyUpdate();
ilnik6b826ef2017-06-16 06:53:48 -07001091 }
1092
Magnus Jedvert26679d62015-04-07 14:07:41 +02001093 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +00001094 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +00001095
Niels Möller7dc26b72017-12-06 10:27:48 +01001096 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -07001097
Erik Språnge2fd86a2018-10-24 11:32:39 +02001098 // Encoder metadata needs to be updated before encode complete callback.
1099 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
1100 if (info.implementation_name != encoder_info_.implementation_name) {
1101 encoder_stats_observer_->OnEncoderImplementationChanged(
1102 info.implementation_name);
Erik Språng7ca375c2019-02-06 16:20:17 +01001103 if (bitrate_adjuster_) {
1104 // Encoder implementation changed, reset overshoot detector states.
1105 bitrate_adjuster_->Reset();
1106 }
Erik Språnge2fd86a2018-10-24 11:32:39 +02001107 }
Erik Språng7ca375c2019-02-06 16:20:17 +01001108
1109 if (bitrate_adjuster_) {
1110 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1111 if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
1112 bitrate_adjuster_->OnEncoderInfo(info);
1113 break;
1114 }
1115 }
1116 }
1117
Erik Språnge2fd86a2018-10-24 11:32:39 +02001118 encoder_info_ = info;
Erik Språngd7329ca2019-02-21 21:19:53 +01001119 RTC_DCHECK(generic_encoder_);
1120 RTC_DCHECK(codec_database_.MatchesCurrentResolution(out_frame.width(),
1121 out_frame.height()));
1122 const VideoFrameBuffer::Type buffer_type =
1123 out_frame.video_frame_buffer()->type();
1124 const bool is_buffer_type_supported =
1125 buffer_type == VideoFrameBuffer::Type::kI420 ||
1126 (buffer_type == VideoFrameBuffer::Type::kNative &&
1127 encoder_info_.supports_native_handle);
1128
1129 if (!is_buffer_type_supported) {
1130 // This module only supports software encoding.
1131 rtc::scoped_refptr<I420BufferInterface> converted_buffer(
1132 out_frame.video_frame_buffer()->ToI420());
1133
1134 if (!converted_buffer) {
1135 RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
1136 return;
1137 }
1138
1139 // UpdatedRect is not propagated because buffer was converted,
1140 // therefore we can't guarantee that pixels outside of UpdateRect didn't
1141 // change comparing to the previous frame.
1142 out_frame = VideoFrame::Builder()
1143 .set_video_frame_buffer(converted_buffer)
1144 .set_timestamp_rtp(out_frame.timestamp())
1145 .set_timestamp_ms(out_frame.render_time_ms())
1146 .set_rotation(out_frame.rotation())
1147 .set_id(out_frame.id())
1148 .build();
1149 }
1150 const int32_t encode_status =
1151 generic_encoder_->Encode(out_frame, nullptr, next_frame_types_);
1152 if (encode_status < 0) {
1153 RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
1154 << encode_status;
1155 return;
1156 }
1157
1158 for (auto& it : next_frame_types_) {
1159 it = kVideoFrameDelta;
1160 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001161}
niklase@google.com470e71d2011-07-07 08:21:25 +00001162
mflodmancc3d4422017-08-03 08:27:51 -07001163void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -07001164 if (!encoder_queue_.IsCurrent()) {
1165 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1166 return;
1167 }
1168 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001169 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Erik Språngd7329ca2019-02-21 21:19:53 +01001170 RTC_DCHECK(!next_frame_types_.empty());
1171 next_frame_types_[0] = kVideoFrameKey;
1172 if (HasInternalSource()) {
1173 // Try to request the frame if we have an external encoder with
1174 // internal source since AddVideoFrame never will be called.
1175 RTC_DCHECK(generic_encoder_);
1176 if (generic_encoder_->RequestFrame(next_frame_types_) ==
1177 WEBRTC_VIDEO_CODEC_OK) {
1178 // Try to remove just-performed keyframe request, if stream still exists.
1179 next_frame_types_[0] = kVideoFrameDelta;
1180 }
1181 }
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001182}
1183
mflodmancc3d4422017-08-03 08:27:51 -07001184EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001185 const EncodedImage& encoded_image,
1186 const CodecSpecificInfo* codec_specific_info,
1187 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -07001188 // Encoded is called on whatever thread the real encoder implementation run
1189 // on. In the case of hardware encoders, there might be several encoders
1190 // running in parallel on different threads.
Niels Möller213618e2018-07-24 09:29:58 +02001191 encoder_stats_observer_->OnSendEncodedImage(encoded_image,
1192 codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001193
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001194 EncodedImageCallback::Result result =
1195 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001196
Niels Möller7dc26b72017-12-06 10:27:48 +01001197 int64_t time_sent_us = rtc::TimeMicros();
Erik Språng7ca375c2019-02-06 16:20:17 +01001198 // We are only interested in propagating the meta-data about the image, not
1199 // encoded data itself, to the post encode function. Since we cannot be sure
1200 // the pointer will still be valid when run on the task queue, set it to null.
1201 EncodedImage encoded_image_metadata = encoded_image;
1202 encoded_image_metadata.set_buffer(nullptr, 0);
Niels Möller83dbeac2017-12-14 16:39:44 +01001203
Erik Språng7ca375c2019-02-06 16:20:17 +01001204 int temporal_index = 0;
1205 if (codec_specific_info) {
1206 if (codec_specific_info->codecType == kVideoCodecVP9) {
1207 temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
1208 } else if (codec_specific_info->codecType == kVideoCodecVP8) {
1209 temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
1210 }
1211 }
1212 if (temporal_index == kNoTemporalIdx) {
1213 temporal_index = 0;
Niels Möller83dbeac2017-12-14 16:39:44 +01001214 }
1215
Erik Språng7ca375c2019-02-06 16:20:17 +01001216 RunPostEncode(encoded_image_metadata, time_sent_us, temporal_index);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001217
1218 if (result.error == Result::OK) {
1219 // In case of an internal encoder running on a separate thread, the
1220 // decision to drop a frame might be a frame late and signaled via
1221 // atomic flag. This is because we can't easily wait for the worker thread
1222 // without risking deadlocks, eg during shutdown when the worker thread
1223 // might be waiting for the internal encoder threads to stop.
1224 if (pending_frame_drops_.load() > 0) {
1225 int pending_drops = pending_frame_drops_.fetch_sub(1);
1226 RTC_DCHECK_GT(pending_drops, 0);
1227 result.drop_next_frame = true;
1228 }
1229 }
perkj803d97f2016-11-01 11:45:46 -07001230
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001231 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001232}
1233
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001234void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1235 switch (reason) {
1236 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001237 encoder_stats_observer_->OnFrameDropped(
1238 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001239 encoder_queue_.PostTask([this] {
1240 RTC_DCHECK_RUN_ON(&encoder_queue_);
1241 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001242 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001243 });
1244 break;
1245 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001246 encoder_stats_observer_->OnFrameDropped(
1247 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001248 encoder_queue_.PostTask([this] {
1249 RTC_DCHECK_RUN_ON(&encoder_queue_);
1250 if (quality_scaler_)
1251 quality_scaler_->ReportDroppedFrameByEncoder();
1252 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001253 break;
1254 }
kthelgason876222f2016-11-29 01:44:11 -08001255}
1256
mflodmancc3d4422017-08-03 08:27:51 -07001257void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
1258 uint8_t fraction_lost,
1259 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -07001260 if (!encoder_queue_.IsCurrent()) {
1261 encoder_queue_.PostTask(
1262 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
1263 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
1264 });
1265 return;
1266 }
1267 RTC_DCHECK_RUN_ON(&encoder_queue_);
1268 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1269
Mirko Bonadei675513b2017-11-09 11:09:25 +01001270 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
1271 << " packet loss " << static_cast<int>(fraction_lost)
1272 << " rtt " << round_trip_time_ms;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001273 // On significant changes to BWE at the start of the call,
1274 // enable frame drops to quickly react to jumps in available bandwidth.
1275 if (encoder_start_bitrate_bps_ != 0 &&
1276 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1277 initial_framedrop_on_bwe_enabled_ &&
1278 abs_diff(bitrate_bps, encoder_start_bitrate_bps_) >=
1279 kFramedropThreshold * encoder_start_bitrate_bps_) {
1280 // Reset initial framedrop feature when first real BW estimate arrives.
1281 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1282 // without an actual BW estimate.
1283 initial_framedrop_ = 0;
1284 has_seen_first_significant_bwe_change_ = true;
1285 }
perkj26091b12016-09-01 01:17:40 -07001286
Niels Möller6bb5ab92019-01-11 11:11:10 +01001287 uint32_t framerate_fps = GetInputFramerateFps();
1288 frame_dropper_.SetRates((bitrate_bps + 500) / 1000, framerate_fps);
Erik Språngd7329ca2019-02-21 21:19:53 +01001289 SetEncoderRates(
1290 GetBitrateAllocationAndNotifyObserver(bitrate_bps, framerate_fps),
1291 framerate_fps);
perkj26091b12016-09-01 01:17:40 -07001292
1293 encoder_start_bitrate_bps_ =
1294 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +02001295 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +01001296 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -07001297 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +00001298
sprang552c7c72017-02-13 04:41:45 -08001299 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001300 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1301 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001302 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001303 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001304 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1305 !DropDueToSize(pending_frame_->size())) {
1306 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1307 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1308 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1309 pending_frame_.reset();
1310 }
1311}
1312
1313bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001314 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001315 encoder_start_bitrate_bps_ > 0) {
1316 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1317 return pixel_count > 320 * 240;
1318 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1319 return pixel_count > 640 * 480;
1320 }
1321 }
1322 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001323}
1324
mflodmancc3d4422017-08-03 08:27:51 -07001325void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001326 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001327 AdaptationRequest adaptation_request = {
1328 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001329 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001330 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001331
sprangc5d62e22017-04-02 23:53:04 -07001332 bool downgrade_requested =
1333 last_adaptation_request_ &&
1334 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1335
sprangc5d62e22017-04-02 23:53:04 -07001336 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001337 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001338 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001339 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001340 if (downgrade_requested &&
1341 adaptation_request.input_pixel_count_ >=
1342 last_adaptation_request_->input_pixel_count_) {
1343 // Don't request lower resolution if the current resolution is not
1344 // lower than the last time we asked for the resolution to be lowered.
1345 return;
1346 }
1347 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001348 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001349 if (adaptation_request.framerate_fps_ <= 0 ||
1350 (downgrade_requested &&
1351 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1352 // If no input fps estimate available, can't determine how to scale down
1353 // framerate. Otherwise, don't request lower framerate if we don't have
1354 // a valid frame rate. Since framerate, unlike resolution, is a measure
1355 // we have to estimate, and can fluctuate naturally over time, don't
1356 // make the same kind of limitations as for resolution, but trust the
1357 // overuse detector to not trigger too often.
1358 return;
1359 }
1360 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001361 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001362 return;
sprang84a37592017-02-10 07:04:27 -08001363 }
sprangc5d62e22017-04-02 23:53:04 -07001364
sprangc5d62e22017-04-02 23:53:04 -07001365 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001366 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001367 // Try scale down framerate, if lower.
1368 int fps = MinFps(last_frame_info_->pixel_count());
1369 if (source_proxy_->RestrictFramerate(fps)) {
1370 GetAdaptCounter().IncrementFramerate(reason);
1371 break;
1372 }
1373 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001374 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001375 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001376 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001377 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001378 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001379 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001380 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001381 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001382 &min_pixels_reached)) {
1383 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001384 encoder_stats_observer_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -07001385 return;
1386 }
asaperssonf7e294d2017-06-13 23:25:22 -07001387 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001388 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001389 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001390 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001391 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001392 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1393 adaptation_request.framerate_fps_);
1394 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001395 return;
sprangfda496a2017-06-15 04:21:07 -07001396 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001397 overuse_detector_->OnTargetFramerateUpdated(
1398 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001399 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001400 break;
sprangfda496a2017-06-15 04:21:07 -07001401 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001402 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001403 RTC_NOTREACHED();
1404 }
1405
asaperssond0de2952017-04-21 01:47:31 -07001406 last_adaptation_request_.emplace(adaptation_request);
1407
asapersson09f05612017-05-15 23:40:18 -07001408 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001409
Mirko Bonadei675513b2017-11-09 11:09:25 +01001410 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001411}
1412
mflodmancc3d4422017-08-03 08:27:51 -07001413void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001414 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001415
1416 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1417 int num_downgrades = adapt_counter.TotalCount(reason);
1418 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001419 return;
asapersson09f05612017-05-15 23:40:18 -07001420 RTC_DCHECK_GT(num_downgrades, 0);
1421
sprangc5d62e22017-04-02 23:53:04 -07001422 AdaptationRequest adaptation_request = {
1423 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001424 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001425 AdaptationRequest::Mode::kAdaptUp};
1426
1427 bool adapt_up_requested =
1428 last_adaptation_request_ &&
1429 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001430
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001431 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001432 if (adapt_up_requested &&
1433 adaptation_request.input_pixel_count_ <=
1434 last_adaptation_request_->input_pixel_count_) {
1435 // Don't request higher resolution if the current resolution is not
1436 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001437 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001438 }
sprangb1ca0732017-02-01 08:38:12 -08001439 }
sprangc5d62e22017-04-02 23:53:04 -07001440
sprangc5d62e22017-04-02 23:53:04 -07001441 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001442 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001443 // Try scale up framerate, if higher.
1444 int fps = MaxFps(last_frame_info_->pixel_count());
1445 if (source_proxy_->IncreaseFramerate(fps)) {
1446 GetAdaptCounter().DecrementFramerate(reason, fps);
1447 // Reset framerate in case of fewer fps steps down than up.
1448 if (adapt_counter.FramerateCount() == 0 &&
1449 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001450 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001451 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1452 }
1453 break;
1454 }
1455 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001456 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001457 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001458 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001459 // Scale up resolution.
1460 int pixel_count = adaptation_request.input_pixel_count_;
1461 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001462 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001463 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001464 }
asapersson13874762017-06-07 00:01:02 -07001465 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1466 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001467 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001468 break;
asapersson13874762017-06-07 00:01:02 -07001469 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001470 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001471 // Scale up framerate.
1472 int fps = adaptation_request.framerate_fps_;
1473 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001474 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001475 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001476 }
sprangfda496a2017-06-15 04:21:07 -07001477
1478 const int requested_framerate =
1479 source_proxy_->RequestHigherFramerateThan(fps);
1480 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001481 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001482 return;
sprangfda496a2017-06-15 04:21:07 -07001483 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001484 overuse_detector_->OnTargetFramerateUpdated(
1485 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001486 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001487 break;
asapersson13874762017-06-07 00:01:02 -07001488 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001489 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001490 return;
sprangc5d62e22017-04-02 23:53:04 -07001491 }
1492
asaperssond0de2952017-04-21 01:47:31 -07001493 last_adaptation_request_.emplace(adaptation_request);
1494
asapersson09f05612017-05-15 23:40:18 -07001495 UpdateAdaptationStats(reason);
1496
Mirko Bonadei675513b2017-11-09 11:09:25 +01001497 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001498}
1499
Niels Möller213618e2018-07-24 09:29:58 +02001500// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07001501void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001502 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001503 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02001504 encoder_stats_observer_->OnAdaptationChanged(
1505 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1506 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07001507 break;
1508 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02001509 encoder_stats_observer_->OnAdaptationChanged(
1510 VideoStreamEncoderObserver::AdaptationReason::kQuality,
1511 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001512 break;
1513 }
perkj26091b12016-09-01 01:17:40 -07001514}
1515
Niels Möller213618e2018-07-24 09:29:58 +02001516VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07001517 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02001518 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07001519 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001520 switch (reason) {
1521 case kCpu:
1522 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001523 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001524 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001525 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001526 break;
1527 case kQuality:
1528 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1529 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001530 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001531 }
1532 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1533 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001534 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001535 }
1536 break;
sprangc5d62e22017-04-02 23:53:04 -07001537 }
asapersson09f05612017-05-15 23:40:18 -07001538 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001539}
1540
mflodmancc3d4422017-08-03 08:27:51 -07001541VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001542 return adapt_counters_[degradation_preference_];
1543}
1544
mflodmancc3d4422017-08-03 08:27:51 -07001545const VideoStreamEncoder::AdaptCounter&
1546VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001547 return adapt_counters_[degradation_preference_];
1548}
1549
Erik Språng7ca375c2019-02-06 16:20:17 +01001550void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
Niels Möller6bb5ab92019-01-11 11:11:10 +01001551 int64_t time_sent_us,
Erik Språng7ca375c2019-02-06 16:20:17 +01001552 int temporal_index) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001553 if (!encoder_queue_.IsCurrent()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01001554 encoder_queue_.PostTask(
1555 [this, encoded_image, time_sent_us, temporal_index] {
1556 RunPostEncode(encoded_image, time_sent_us, temporal_index);
1557 });
Niels Möller6bb5ab92019-01-11 11:11:10 +01001558 return;
1559 }
1560
1561 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01001562
1563 absl::optional<int> encode_duration_us;
1564 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
1565 encode_duration_us =
1566 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
1567 rtc::kNumMicrosecsPerMillisec *
1568 (encoded_image.timing_.encode_finish_ms -
1569 encoded_image.timing_.encode_start_ms);
1570 }
1571
1572 // Run post encode tasks, such as overuse detection and frame rate/drop
1573 // stats for internal encoders.
1574 const size_t frame_size = encoded_image.size();
1575 const bool keyframe = encoded_image._frameType == FrameType::kVideoFrameKey;
1576
1577 if (frame_size > 0) {
1578 frame_dropper_.Fill(frame_size, !keyframe);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001579 }
1580
Erik Språngd7329ca2019-02-21 21:19:53 +01001581 if (HasInternalSource()) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001582 // Update frame dropper after the fact for internal sources.
1583 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
1584 frame_dropper_.Leak(GetInputFramerateFps());
1585 // Signal to encoder to drop next frame.
1586 if (frame_dropper_.DropFrame()) {
1587 pending_frame_drops_.fetch_add(1);
1588 }
1589 }
1590
Erik Språng7ca375c2019-02-06 16:20:17 +01001591 overuse_detector_->FrameSent(
1592 encoded_image.Timestamp(), time_sent_us,
1593 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
1594 encode_duration_us);
1595 if (quality_scaler_ && encoded_image.qp_ >= 0)
1596 quality_scaler_->ReportQp(encoded_image.qp_);
1597 if (bitrate_adjuster_) {
1598 bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
1599 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001600}
1601
Erik Språngd7329ca2019-02-21 21:19:53 +01001602bool VideoStreamEncoder::HasInternalSource() const {
1603 // TODO(sprang): Checking both info from encoder and from encoder factory
1604 // until we have deprecated and removed the encoder factory info.
1605 return codec_info_.has_internal_source || encoder_info_.has_internal_source;
1606}
1607
asapersson09f05612017-05-15 23:40:18 -07001608// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001609VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001610 fps_counters_.resize(kScaleReasonSize);
1611 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001612 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001613}
1614
mflodmancc3d4422017-08-03 08:27:51 -07001615VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001616
mflodmancc3d4422017-08-03 08:27:51 -07001617std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001618 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001619 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1620 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02001621 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07001622}
1623
Niels Möller213618e2018-07-24 09:29:58 +02001624VideoStreamEncoderObserver::AdaptationSteps
1625VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
1626 VideoStreamEncoderObserver::AdaptationSteps counts;
1627 counts.num_framerate_reductions = fps_counters_[reason];
1628 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07001629 return counts;
1630}
1631
mflodmancc3d4422017-08-03 08:27:51 -07001632void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001633 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001634}
1635
mflodmancc3d4422017-08-03 08:27:51 -07001636void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001637 ++(resolution_counters_[reason]);
1638}
1639
mflodmancc3d4422017-08-03 08:27:51 -07001640void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001641 if (fps_counters_[reason] == 0) {
1642 // Balanced mode: Adapt up is in a different order, switch reason.
1643 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1644 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1645 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1646 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1647 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1648 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1649 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1650 MoveCount(&resolution_counters_, reason);
1651 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1652 }
1653 --(fps_counters_[reason]);
1654 RTC_DCHECK_GE(fps_counters_[reason], 0);
1655}
1656
mflodmancc3d4422017-08-03 08:27:51 -07001657void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001658 if (resolution_counters_[reason] == 0) {
1659 // Balanced mode: Adapt up is in a different order, switch reason.
1660 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1661 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1662 MoveCount(&fps_counters_, reason);
1663 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1664 }
1665 --(resolution_counters_[reason]);
1666 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1667}
1668
mflodmancc3d4422017-08-03 08:27:51 -07001669void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1670 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001671 DecrementFramerate(reason);
1672 // Reset if at max fps (i.e. in case of fewer steps up than down).
1673 if (cur_fps == std::numeric_limits<int>::max())
1674 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001675}
1676
mflodmancc3d4422017-08-03 08:27:51 -07001677int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001678 return Count(fps_counters_);
1679}
1680
mflodmancc3d4422017-08-03 08:27:51 -07001681int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001682 return Count(resolution_counters_);
1683}
1684
mflodmancc3d4422017-08-03 08:27:51 -07001685int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001686 return fps_counters_[reason];
1687}
1688
mflodmancc3d4422017-08-03 08:27:51 -07001689int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001690 return resolution_counters_[reason];
1691}
1692
mflodmancc3d4422017-08-03 08:27:51 -07001693int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001694 return FramerateCount(reason) + ResolutionCount(reason);
1695}
1696
mflodmancc3d4422017-08-03 08:27:51 -07001697int VideoStreamEncoder::AdaptCounter::Count(
1698 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001699 return std::accumulate(counters.begin(), counters.end(), 0);
1700}
1701
mflodmancc3d4422017-08-03 08:27:51 -07001702void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1703 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001704 int to_reason = (from_reason + 1) % kScaleReasonSize;
1705 ++((*counters)[to_reason]);
1706 --((*counters)[from_reason]);
1707}
1708
mflodmancc3d4422017-08-03 08:27:51 -07001709std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001710 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001711 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001712 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1713 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001714 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02001715 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07001716}
1717
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001718} // namespace webrtc