blob: ddb76319415a9708ab83e3c00f90cf494c570076 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/location.h"
30#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020031#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010032#include "rtc_base/system/fallthrough.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020035#include "system_wrappers/include/field_trial.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "video/overuse_frame_detector.h"
nisseea3a7982017-05-15 02:42:11 -070037
niklase@google.com470e71d2011-07-07 08:21:25 +000038namespace webrtc {
39
perkj26091b12016-09-01 01:17:40 -070040namespace {
sprangb1ca0732017-02-01 08:38:12 -080041
asapersson6ffb67d2016-09-12 00:10:45 -070042// Time interval for logging frame counts.
43const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070044const int kMinFramerateFps = 2;
perkj26091b12016-09-01 01:17:40 -070045
Sebastian Janssona3177052018-04-10 13:05:49 +020046// Time to keep a single cached pending frame in paused state.
47const int64_t kPendingFrameTimeoutMs = 1000;
48
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020049const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
Niels Möller6bb5ab92019-01-11 11:11:10 +010050constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020051
kthelgason2bc68642017-02-07 07:02:22 -080052// The maximum number of frames to drop at beginning of stream
53// to try and achieve desired bitrate.
54const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020055// When the first change in BWE above this threshold occurs,
56// enable DropFrameDueToSize logic.
57const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 07:02:22 -080058
Niels Möller6bb5ab92019-01-11 11:11:10 +010059// Averaging window spanning 90 frames at default 30fps, matching old media
60// optimization module defaults.
61const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
62
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070063// Initial limits for BALANCED degradation preference.
asaperssonf7e294d2017-06-13 23:25:22 -070064int MinFps(int pixels) {
65 if (pixels <= 320 * 240) {
66 return 7;
67 } else if (pixels <= 480 * 270) {
68 return 10;
69 } else if (pixels <= 640 * 480) {
70 return 15;
71 } else {
72 return std::numeric_limits<int>::max();
73 }
74}
75
76int MaxFps(int pixels) {
77 if (pixels <= 320 * 240) {
78 return 10;
79 } else if (pixels <= 480 * 270) {
80 return 15;
81 } else {
82 return std::numeric_limits<int>::max();
83 }
84}
85
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020086uint32_t abs_diff(uint32_t a, uint32_t b) {
87 return (a < b) ? b - a : a - b;
88}
89
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070090bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
91 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
92 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070093}
94
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070095bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
96 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
97 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070098}
99
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200100// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
101// pipelining encoders better (multiple input frames before something comes
102// out). This should effectively turn off CPU adaptations for systems that
103// remotely cope with the load right now.
104CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 09:29:58 +0200105 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 09:04:13 +0200106 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200107 CpuOveruseOptions options;
108
Niels Möller4db138e2018-04-19 09:04:13 +0200109 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200110 options.low_encode_usage_threshold_percent = 150;
111 options.high_encode_usage_threshold_percent = 200;
112 }
113 if (settings.experiment_cpu_load_estimator) {
114 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
115 }
116
117 return options;
118}
119
perkj26091b12016-09-01 01:17:40 -0700120} // namespace
121
perkja49cbd32016-09-16 07:53:41 -0700122// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700123// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
124// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700125// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700126class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700127 public:
mflodmancc3d4422017-08-03 08:27:51 -0700128 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
129 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700130 degradation_preference_(DegradationPreference::DISABLED),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200131 source_(nullptr),
132 max_framerate_(std::numeric_limits<int>::max()) {}
perkja49cbd32016-09-16 07:53:41 -0700133
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700134 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
135 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700136 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700137 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
138 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700139 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700140 {
141 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700142 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700143 old_source = source_;
144 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700145 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700146 }
147
148 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700149 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700150 }
151
152 if (!source) {
153 return;
154 }
155
mflodmancc3d4422017-08-03 08:27:51 -0700156 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700157 }
158
Åsa Persson8c1bf952018-09-13 10:42:19 +0200159 void SetMaxFramerate(int max_framerate) {
160 RTC_DCHECK_GT(max_framerate, 0);
161 rtc::CritScope lock(&crit_);
162 if (max_framerate == max_framerate_)
163 return;
164
165 RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
166 max_framerate_ = max_framerate;
167 if (source_) {
168 source_->AddOrUpdateSink(video_stream_encoder_,
169 GetActiveSinkWantsInternal());
170 }
171 }
172
perkj803d97f2016-11-01 11:45:46 -0700173 void SetWantsRotationApplied(bool rotation_applied) {
174 rtc::CritScope lock(&crit_);
175 sink_wants_.rotation_applied = rotation_applied;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200176 if (source_) {
177 source_->AddOrUpdateSink(video_stream_encoder_,
178 GetActiveSinkWantsInternal());
179 }
sprangc5d62e22017-04-02 23:53:04 -0700180 }
181
sprangfda496a2017-06-15 04:21:07 -0700182 rtc::VideoSinkWants GetActiveSinkWants() {
183 rtc::CritScope lock(&crit_);
184 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700185 }
186
asaperssonf7e294d2017-06-13 23:25:22 -0700187 void ResetPixelFpsCount() {
188 rtc::CritScope lock(&crit_);
189 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
190 sink_wants_.target_pixel_count.reset();
191 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
192 if (source_)
Åsa Persson8c1bf952018-09-13 10:42:19 +0200193 source_->AddOrUpdateSink(video_stream_encoder_,
194 GetActiveSinkWantsInternal());
asaperssonf7e294d2017-06-13 23:25:22 -0700195 }
196
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100197 bool RequestResolutionLowerThan(int pixel_count,
198 int min_pixels_per_frame,
199 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700200 // Called on the encoder task queue.
201 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700202 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700203 // This can happen since |degradation_preference_| is set on libjingle's
204 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700205 return false;
perkj803d97f2016-11-01 11:45:46 -0700206 }
asapersson13874762017-06-07 00:01:02 -0700207 // The input video frame size will have a resolution less than or equal to
208 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800209 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100210 if (pixels_wanted >= sink_wants_.max_pixel_count) {
211 return false;
212 }
213 if (pixels_wanted < min_pixels_per_frame) {
214 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700215 return false;
asapersson13874762017-06-07 00:01:02 -0700216 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100217 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
218 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700219 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200220 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700221 source_->AddOrUpdateSink(video_stream_encoder_,
222 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700223 return true;
sprangc5d62e22017-04-02 23:53:04 -0700224 }
225
sprangfda496a2017-06-15 04:21:07 -0700226 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700227 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700228 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700229 int framerate_wanted = (fps * 2) / 3;
230 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700231 }
232
asapersson13874762017-06-07 00:01:02 -0700233 bool RequestHigherResolutionThan(int pixel_count) {
234 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700235 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700236 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700237 // This can happen since |degradation_preference_| is set on libjingle's
238 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700239 return false;
perkj803d97f2016-11-01 11:45:46 -0700240 }
asapersson13874762017-06-07 00:01:02 -0700241 int max_pixels_wanted = pixel_count;
242 if (max_pixels_wanted != std::numeric_limits<int>::max())
243 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700244
asapersson13874762017-06-07 00:01:02 -0700245 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
246 return false;
247
248 sink_wants_.max_pixel_count = max_pixels_wanted;
249 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700250 // Remove any constraints.
251 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700252 } else {
253 // On step down we request at most 3/5 the pixel count of the previous
254 // resolution, so in order to take "one step up" we request a resolution
255 // as close as possible to 5/3 of the current resolution. The actual pixel
256 // count selected depends on the capabilities of the source. In order to
257 // not take a too large step up, we cap the requested pixel count to be at
258 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100259 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700260 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100261 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
262 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700263 source_->AddOrUpdateSink(video_stream_encoder_,
264 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700265 return true;
sprangc5d62e22017-04-02 23:53:04 -0700266 }
267
sprangfda496a2017-06-15 04:21:07 -0700268 // Request upgrade in framerate. Returns the new requested frame, or -1 if
269 // no change requested. Note that maxint may be returned if limits due to
270 // adaptation requests are removed completely. In that case, consider
271 // |max_framerate_| to be the current limit (assuming the capturer complies).
272 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700273 // Called on the encoder task queue.
274 // The input frame rate will be scaled up to the last step, with rounding.
275 int framerate_wanted = fps;
276 if (fps != std::numeric_limits<int>::max())
277 framerate_wanted = (fps * 3) / 2;
278
sprangfda496a2017-06-15 04:21:07 -0700279 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700280 }
281
282 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700283 // Called on the encoder task queue.
284 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700285 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
286 return false;
287
288 const int fps_wanted = std::max(kMinFramerateFps, fps);
289 if (fps_wanted >= sink_wants_.max_framerate_fps)
290 return false;
291
Mirko Bonadei675513b2017-11-09 11:09:25 +0100292 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700293 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700294 source_->AddOrUpdateSink(video_stream_encoder_,
295 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700296 return true;
297 }
298
299 bool IncreaseFramerate(int fps) {
300 // Called on the encoder task queue.
301 rtc::CritScope lock(&crit_);
302 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
303 return false;
304
305 const int fps_wanted = std::max(kMinFramerateFps, fps);
306 if (fps_wanted <= sink_wants_.max_framerate_fps)
307 return false;
308
Mirko Bonadei675513b2017-11-09 11:09:25 +0100309 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700310 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700311 source_->AddOrUpdateSink(video_stream_encoder_,
312 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700313 return true;
perkj803d97f2016-11-01 11:45:46 -0700314 }
315
perkja49cbd32016-09-16 07:53:41 -0700316 private:
sprangfda496a2017-06-15 04:21:07 -0700317 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700318 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700319 rtc::VideoSinkWants wants = sink_wants_;
320 // Clear any constraints from the current sink wants that don't apply to
321 // the used degradation_preference.
322 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700323 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 04:21:07 -0700324 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700325 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 04:21:07 -0700326 wants.max_framerate_fps = std::numeric_limits<int>::max();
327 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700328 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 04:21:07 -0700329 wants.max_pixel_count = std::numeric_limits<int>::max();
330 wants.target_pixel_count.reset();
331 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700332 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 04:21:07 -0700333 wants.max_pixel_count = std::numeric_limits<int>::max();
334 wants.target_pixel_count.reset();
335 wants.max_framerate_fps = std::numeric_limits<int>::max();
336 }
Åsa Persson8c1bf952018-09-13 10:42:19 +0200337 // Limit to configured max framerate.
338 wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
sprangfda496a2017-06-15 04:21:07 -0700339 return wants;
340 }
341
perkja49cbd32016-09-16 07:53:41 -0700342 rtc::CriticalSection crit_;
343 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700344 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700345 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700346 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 04:17:22 -0700347 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
Åsa Persson8c1bf952018-09-13 10:42:19 +0200348 int max_framerate_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700349
350 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
351};
352
Åsa Persson0122e842017-10-16 12:19:23 +0200353VideoStreamEncoder::VideoStreamEncoder(
354 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200355 VideoStreamEncoderObserver* encoder_stats_observer,
356 const VideoStreamEncoderSettings& settings,
Åsa Persson0122e842017-10-16 12:19:23 +0200357 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700358 : shutdown_event_(true /* manual_reset */, false),
359 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200360 initial_framedrop_(0),
361 initial_framedrop_on_bwe_enabled_(
362 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssona945aee2018-04-24 16:53:25 +0200363 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700364 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200365 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700366 settings_(settings),
Niels Möllera0565992017-10-24 11:37:08 +0200367 video_sender_(Clock::GetRealTimeClock(), this),
Niels Möller73f29cb2018-01-31 16:09:31 +0100368 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200369 encoder_stats_observer_(encoder_stats_observer),
sprangfda496a2017-06-15 04:21:07 -0700370 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700371 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000372 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200373 crop_width_(0),
374 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700375 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200376 max_data_payload_length_(0),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000377 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000378 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700379 clock_(Clock::GetRealTimeClock()),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700380 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700381 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700382 last_captured_timestamp_(0),
383 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
384 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700385 last_frame_log_ms_(clock_->TimeInMilliseconds()),
386 captured_frame_count_(0),
387 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200388 pending_frame_post_time_us_(0),
sprang1a646ee2016-12-01 06:34:11 -0800389 bitrate_observer_(nullptr),
Niels Möller6bb5ab92019-01-11 11:11:10 +0100390 force_disable_frame_dropper_(false),
391 input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
392 pending_frame_drops_(0),
perkj26091b12016-09-01 01:17:40 -0700393 encoder_queue_("EncoderQueue") {
Niels Möller213618e2018-07-24 09:29:58 +0200394 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 16:09:31 +0100395 RTC_DCHECK(overuse_detector_);
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000396}
397
mflodmancc3d4422017-08-03 08:27:51 -0700398VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700399 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700400 RTC_DCHECK(shutdown_event_.Wait(0))
401 << "Must call ::Stop() before destruction.";
402}
403
mflodmancc3d4422017-08-03 08:27:51 -0700404void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700405 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700406 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700407 encoder_queue_.PostTask([this] {
408 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700409 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100410 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800411 bitrate_observer_ = nullptr;
Niels Möllerbf3dbb42018-03-16 13:38:46 +0100412 video_sender_.RegisterExternalEncoder(nullptr, false);
kthelgason876222f2016-11-29 01:44:11 -0800413 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700414 shutdown_event_.Set();
415 });
416
417 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700418}
419
Niels Möller0327c2d2018-05-21 14:09:31 +0200420void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 06:34:11 -0800421 VideoBitrateAllocationObserver* bitrate_observer) {
422 RTC_DCHECK_RUN_ON(&thread_checker_);
423 encoder_queue_.PostTask([this, bitrate_observer] {
424 RTC_DCHECK_RUN_ON(&encoder_queue_);
425 RTC_DCHECK(!bitrate_observer_);
426 bitrate_observer_ = bitrate_observer;
427 });
428}
429
mflodmancc3d4422017-08-03 08:27:51 -0700430void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700431 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700432 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700433 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700434 source_proxy_->SetSource(source, degradation_preference);
435 encoder_queue_.PostTask([this, degradation_preference] {
436 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700437 if (degradation_preference_ != degradation_preference) {
438 // Reset adaptation state, so that we're not tricked into thinking there's
439 // an already pending request of the same type.
440 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700441 if (degradation_preference == DegradationPreference::BALANCED ||
442 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700443 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
444 // AdaptCounter for all modes.
445 source_proxy_->ResetPixelFpsCount();
446 adapt_counters_.clear();
447 }
sprangc5d62e22017-04-02 23:53:04 -0700448 }
sprangb1ca0732017-02-01 08:38:12 -0800449 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200450
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000451 if (encoder_)
Niels Möller2d061182018-04-24 09:13:08 +0200452 ConfigureQualityScaler();
Niels Möller4db138e2018-04-19 09:04:13 +0200453
Niels Möller7dc26b72017-12-06 10:27:48 +0100454 if (!IsFramerateScalingEnabled(degradation_preference) &&
455 max_framerate_ != -1) {
456 // If frame rate scaling is no longer allowed, remove any potential
457 // allowance for longer frame intervals.
458 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
459 }
perkj803d97f2016-11-01 11:45:46 -0700460 });
perkja49cbd32016-09-16 07:53:41 -0700461}
462
mflodmancc3d4422017-08-03 08:27:51 -0700463void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700464 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700465 encoder_queue_.PostTask([this, sink] {
466 RTC_DCHECK_RUN_ON(&encoder_queue_);
467 sink_ = sink;
468 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000469}
470
mflodmancc3d4422017-08-03 08:27:51 -0700471void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700472 encoder_queue_.PostTask([this, start_bitrate_bps] {
473 RTC_DCHECK_RUN_ON(&encoder_queue_);
474 encoder_start_bitrate_bps_ = start_bitrate_bps;
475 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000476}
Peter Boström00b9d212016-05-19 16:59:03 +0200477
mflodmancc3d4422017-08-03 08:27:51 -0700478void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200479 size_t max_data_payload_length) {
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100480 // TODO(srte): This struct should be replaced by a lambda with move capture
481 // when C++14 lambda is allowed.
482 struct ConfigureEncoderTask {
483 void operator()() {
Yves Gerey665174f2018-06-19 15:03:05 +0200484 encoder->ConfigureEncoderOnTaskQueue(std::move(config),
485 max_data_payload_length);
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100486 }
487 VideoStreamEncoder* encoder;
488 VideoEncoderConfig config;
489 size_t max_data_payload_length;
Sebastian Jansson3dc01252018-03-19 19:27:44 +0100490 };
Yves Gerey665174f2018-06-19 15:03:05 +0200491 encoder_queue_.PostTask(
492 ConfigureEncoderTask{this, std::move(config), max_data_payload_length});
perkj26091b12016-09-01 01:17:40 -0700493}
494
mflodmancc3d4422017-08-03 08:27:51 -0700495void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
496 VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200497 size_t max_data_payload_length) {
perkj26091b12016-09-01 01:17:40 -0700498 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700499 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100500 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200501
502 max_data_payload_length_ = max_data_payload_length;
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000503 pending_encoder_creation_ =
504 (!encoder_ || encoder_config_.video_format != config.video_format);
Pera48ddb72016-09-29 11:48:50 +0200505 encoder_config_ = std::move(config);
perkjfa10b552016-10-02 23:45:26 -0700506 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200507
perkjfa10b552016-10-02 23:45:26 -0700508 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100509 // if the frame resolution is known. Otherwise, the reconfiguration is
510 // deferred until the next frame to minimize the number of reconfigurations.
511 // The codec configuration depends on incoming video frame size.
512 if (last_frame_info_) {
513 ReconfigureEncoder();
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000514 } else if (settings_.encoder_factory
515 ->QueryVideoEncoder(encoder_config_.video_format)
516 .has_internal_source) {
517 last_frame_info_ = VideoFrameInfo(176, 144, false);
518 ReconfigureEncoder();
perkjfa10b552016-10-02 23:45:26 -0700519 }
520}
perkj26091b12016-09-01 01:17:40 -0700521
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800522// TODO(bugs.webrtc.org/8807): Currently this always does a hard
523// reconfiguration, but this isn't always necessary. Add in logic to only update
524// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
525// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700526void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700527 RTC_DCHECK(pending_encoder_reconfiguration_);
528 std::vector<VideoStream> streams =
529 encoder_config_.video_stream_factory->CreateEncoderStreams(
530 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700531
ilnik6b826ef2017-06-16 06:53:48 -0700532 // TODO(ilnik): If configured resolution is significantly less than provided,
533 // e.g. because there are not enough SSRCs for all simulcast streams,
534 // signal new resolutions via SinkWants to video source.
535
536 // Stream dimensions may be not equal to given because of a simulcast
537 // restrictions.
Florent Castelli450b5482018-11-29 17:32:47 +0100538 auto highest_stream = std::max_element(
539 streams.begin(), streams.end(),
540 [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
541 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
542 });
543 int highest_stream_width = static_cast<int>(highest_stream->width);
544 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700545 // Dimension may be reduced to be, e.g. divisible by 4.
546 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
547 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
548 crop_width_ = last_frame_info_->width - highest_stream_width;
549 crop_height_ = last_frame_info_->height - highest_stream_height;
550
Erik Språng08127a92016-11-16 16:41:30 +0100551 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800552 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100553 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100554 }
perkjfa10b552016-10-02 23:45:26 -0700555
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800556 rate_allocator_ =
557 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800558
“Michael277a6562018-06-01 14:09:19 -0500559 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
560 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500561 // Lower max bitrate to the level codec actually can produce.
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100562 streams[0].max_bitrate_bps = std::min<int>(
563 streams[0].max_bitrate_bps, SvcRateAllocator::GetMaxBitrateBps(codec));
“Michael277a6562018-06-01 14:09:19 -0500564 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100565 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500566 streams[0].target_bitrate_bps =
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100567 SvcRateAllocator::GetPaddingBitrateBps(codec);
“Michael277a6562018-06-01 14:09:19 -0500568 }
569
perkjfa10b552016-10-02 23:45:26 -0700570 codec.startBitrate =
571 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
572 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
573 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 04:21:07 -0700574 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200575
576 // Inform source about max configured framerate.
577 int max_framerate = 0;
578 for (const auto& stream : streams) {
579 max_framerate = std::max(stream.max_framerate, max_framerate);
580 }
581 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100582
Niels Möller4db138e2018-04-19 09:04:13 +0200583 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100584 // Encoder creation block is split in two since EncoderInfo needed to start
585 // CPU adaptation with the correct settings should be polled after
586 // encoder_->InitEncode().
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000587 if (pending_encoder_creation_) {
Niels Möller4db138e2018-04-19 09:04:13 +0200588 if (encoder_) {
589 video_sender_.RegisterExternalEncoder(nullptr, false);
590 }
591
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000592 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
593 encoder_config_.video_format);
594 // TODO(nisse): What to do if creating the encoder fails? Crash,
595 // or just discard incoming frames?
596 RTC_CHECK(encoder_);
597
598 const webrtc::VideoEncoderFactory::CodecInfo info =
599 settings_.encoder_factory->QueryVideoEncoder(
600 encoder_config_.video_format);
Niels Möller4db138e2018-04-19 09:04:13 +0200601
Niels Möller4db138e2018-04-19 09:04:13 +0200602 video_sender_.RegisterExternalEncoder(encoder_.get(),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000603 info.has_internal_source);
Niels Möller4db138e2018-04-19 09:04:13 +0200604 }
605 // RegisterSendCodec implies an unconditional call to
606 // encoder_->InitEncode().
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200607 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700608 &codec, number_of_cores_,
609 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100610 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100611 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700612 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000613 }
Peter Boström905f8e72016-03-02 16:59:56 +0100614
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100615 if (pending_encoder_creation_) {
616 overuse_detector_->StopCheckForOveruse();
617 overuse_detector_->StartCheckForOveruse(
618 GetCpuOveruseOptions(
619 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
620 this);
621 pending_encoder_creation_ = false;
622 }
623
Niels Möller6bb5ab92019-01-11 11:11:10 +0100624 int num_layers;
625 if (codec.codecType == kVideoCodecVP8) {
626 num_layers = codec.VP8()->numberOfTemporalLayers;
627 } else if (codec.codecType == kVideoCodecVP9) {
628 num_layers = codec.VP9()->numberOfTemporalLayers;
629 } else if (codec.codecType == kVideoCodecGeneric &&
630 codec.numberOfSimulcastStreams > 0) {
631 // This is mainly for unit testing, disabling frame dropping.
632 // TODO(sprang): Add a better way to disable frame dropping.
633 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
634 } else {
635 num_layers = 1;
636 }
637
638 frame_dropper_.Reset();
639 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
640 uint32_t framerate_fps = GetInputFramerateFps();
641 // Force-disable frame dropper if either:
642 // * We have screensharing with layers.
643 // * "WebRTC-FrameDropper" field trial is "Disabled".
644 force_disable_frame_dropper_ =
645 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
646 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
647
648 if (rate_allocator_ && last_observed_bitrate_bps_ > 0) {
649 // We have a new rate allocator instance and already configured target
650 // bitrate. Update the rate allocation and notify observsers.
651 VideoBitrateAllocation bitrate_allocation =
652 GetBitrateAllocationAndNotifyObserver(last_observed_bitrate_bps_,
653 framerate_fps);
654
655 video_sender_.SetChannelParameters(bitrate_allocation, framerate_fps);
656 }
ilnik35b7de42017-03-15 04:24:21 -0700657
Niels Möller213618e2018-07-24 09:29:58 +0200658 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200659
perkjfa10b552016-10-02 23:45:26 -0700660 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100661
Pera48ddb72016-09-29 11:48:50 +0200662 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700663 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800664
Niels Möller7dc26b72017-12-06 10:27:48 +0100665 // Get the current target framerate, ie the maximum framerate as specified by
666 // the current codec configuration, or any limit imposed by cpu adaption in
667 // maintain-resolution or balanced mode. This is used to make sure overuse
668 // detection doesn't needlessly trigger in low and/or variable framerate
669 // scenarios.
670 int target_framerate = std::min(
671 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
672 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200673
674 ConfigureQualityScaler();
kthelgason2bc68642017-02-07 07:02:22 -0800675}
676
mflodmancc3d4422017-08-03 08:27:51 -0700677void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800678 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språnge2fd86a2018-10-24 11:32:39 +0200679 const auto scaling_settings = encoder_->GetEncoderInfo().scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700680 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700681 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100682 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700683
asapersson36e9eb42017-03-31 05:29:12 -0700684 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700685 if (quality_scaler_.get() == nullptr) {
686 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100687
Åsa Perssona945aee2018-04-24 16:53:25 +0200688 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200689 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200690 if (quality_scaling_experiment_enabled_) {
691 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
692 encoder_config_.codec_type);
693 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200694 // Since the interface is non-public, absl::make_unique can't do this
695 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100696 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200697 quality_scaler_ = absl::make_unique<QualityScaler>(
Åsa Perssona945aee2018-04-24 16:53:25 +0200698 observer, experimental_thresholds ? *experimental_thresholds
699 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200700 has_seen_first_significant_bwe_change_ = false;
701 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800702 }
703 } else {
704 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200705 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800706 }
asapersson09f05612017-05-15 23:40:18 -0700707
Niels Möller213618e2018-07-24 09:29:58 +0200708 encoder_stats_observer_->OnAdaptationChanged(
709 VideoStreamEncoderObserver::AdaptationReason::kNone,
710 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000711}
712
mflodmancc3d4422017-08-03 08:27:51 -0700713void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700714 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700715 VideoFrame incoming_frame = video_frame;
716
717 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700718 int64_t current_time_us = clock_->TimeInMicroseconds();
719 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
720 // In some cases, e.g., when the frame from decoder is fed to encoder,
721 // the timestamp may be set to the future. As the encoding pipeline assumes
722 // capture time to be less than present time, we should reset the capture
723 // timestamps here. Otherwise there may be issues with RTP send stream.
724 if (incoming_frame.timestamp_us() > current_time_us)
725 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700726
727 // Capture time may come from clock with an offset and drift from clock_.
728 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800729 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700730 capture_ntp_time_ms = video_frame.ntp_time_ms();
731 } else if (video_frame.render_time_ms() != 0) {
732 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
733 } else {
nisse1c0dea82017-01-30 02:43:18 -0800734 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700735 }
736 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
737
738 // Convert NTP time, in ms, to RTP timestamp.
739 const int kMsToRtpTimestamp = 90;
740 incoming_frame.set_timestamp(
741 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
742
743 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
744 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100745 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
746 << incoming_frame.ntp_time_ms()
747 << " <= " << last_captured_timestamp_
748 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 01:17:40 -0700749 return;
750 }
751
asapersson6ffb67d2016-09-12 00:10:45 -0700752 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800753 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
754 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700755 log_stats = true;
756 }
757
perkj26091b12016-09-01 01:17:40 -0700758 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200759
760 int64_t post_time_us = rtc::TimeMicros();
761 ++posted_frames_waiting_for_encode_;
762
763 encoder_queue_.PostTask(
764 [this, incoming_frame, post_time_us, log_stats]() {
765 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +0200766 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
767 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200768 ++captured_frame_count_;
769 const int posted_frames_waiting_for_encode =
770 posted_frames_waiting_for_encode_.fetch_sub(1);
771 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
772 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +0200773 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200774 } else {
775 // There is a newer frame in flight. Do not encode this frame.
776 RTC_LOG(LS_VERBOSE)
777 << "Incoming frame dropped due to that the encoder is blocked.";
778 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +0200779 encoder_stats_observer_->OnFrameDropped(
780 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200781 }
782 if (log_stats) {
783 RTC_LOG(LS_INFO) << "Number of frames: captured "
784 << captured_frame_count_
785 << ", dropped (due to encoder blocked) "
786 << dropped_frame_count_ << ", interval_ms "
787 << kFrameLogIntervalMs;
788 captured_frame_count_ = 0;
789 dropped_frame_count_ = 0;
790 }
791 });
perkj26091b12016-09-01 01:17:40 -0700792}
793
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200794void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +0200795 encoder_stats_observer_->OnFrameDropped(
796 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200797}
798
mflodmancc3d4422017-08-03 08:27:51 -0700799bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700800 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000801 // Pause video if paused by caller or as long as the network is down or the
802 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700803 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700804 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700805 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000806}
807
mflodmancc3d4422017-08-03 08:27:51 -0700808void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700809 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000810 // Start trace event only on the first frame after encoder is paused.
811 if (!encoder_paused_and_dropped_frame_) {
812 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
813 }
814 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000815}
816
mflodmancc3d4422017-08-03 08:27:51 -0700817void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700818 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000819 // End trace event on first frame after encoder resumes, if frame was dropped.
820 if (encoder_paused_and_dropped_frame_) {
821 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
822 }
823 encoder_paused_and_dropped_frame_ = false;
824}
825
Niels Möller6bb5ab92019-01-11 11:11:10 +0100826VideoBitrateAllocation
827VideoStreamEncoder::GetBitrateAllocationAndNotifyObserver(
828 const uint32_t target_bitrate_bps,
829 uint32_t framerate_fps) {
830 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
831 // might cap the bitrate to the min bitrate configured.
832 VideoBitrateAllocation bitrate_allocation;
833 if (rate_allocator_ && target_bitrate_bps > 0) {
834 bitrate_allocation =
835 rate_allocator_->GetAllocation(target_bitrate_bps, framerate_fps);
836 }
837
838 if (bitrate_observer_ && bitrate_allocation.get_sum_bps() > 0) {
839 bitrate_observer_->OnBitrateAllocationUpdated(bitrate_allocation);
840 }
841
842 return bitrate_allocation;
843}
844
845uint32_t VideoStreamEncoder::GetInputFramerateFps() {
846 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
847 return input_framerate_.Rate(clock_->TimeInMilliseconds())
848 .value_or(default_fps);
849}
850
Sebastian Janssona3177052018-04-10 13:05:49 +0200851void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
852 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700853 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800854
Per21d45d22016-10-30 21:37:57 +0100855 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700856 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700857 video_frame.is_texture() != last_frame_info_->is_texture) {
858 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100859 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
860 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100861 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
862 << last_frame_info_->width << "x"
863 << last_frame_info_->height
864 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700865 }
866
Niels Möller4db138e2018-04-19 09:04:13 +0200867 // We have to create then encoder before the frame drop logic,
868 // because the latter depends on encoder_->GetScalingSettings.
869 // According to the testcase
870 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
871 // from GetScalingSettings should enable or disable the frame drop.
872
Niels Möller6bb5ab92019-01-11 11:11:10 +0100873 uint32_t framerate_fps = GetInputFramerateFps();
874
Niels Möller4db138e2018-04-19 09:04:13 +0200875 int64_t now_ms = clock_->TimeInMilliseconds();
876 if (pending_encoder_reconfiguration_) {
877 ReconfigureEncoder();
878 last_parameters_update_ms_.emplace(now_ms);
879 } else if (!last_parameters_update_ms_ ||
880 now_ms - *last_parameters_update_ms_ >=
881 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100882 video_sender_.SetChannelParameters(
883 GetBitrateAllocationAndNotifyObserver(last_observed_bitrate_bps_,
884 framerate_fps),
885 framerate_fps);
Niels Möller4db138e2018-04-19 09:04:13 +0200886 last_parameters_update_ms_.emplace(now_ms);
887 }
888
Sebastian Janssona3177052018-04-10 13:05:49 +0200889 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100890 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +0100891 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800892 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +0100893 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +0200894 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +0100895 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200896 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200897 // Storing references to a native buffer risks blocking frame capture.
898 if (video_frame.video_frame_buffer()->type() !=
899 VideoFrameBuffer::Type::kNative) {
900 pending_frame_ = video_frame;
901 pending_frame_post_time_us_ = time_when_posted_us;
902 } else {
903 // Ensure that any previously stored frame is dropped.
904 pending_frame_.reset();
905 }
kthelgason2bc68642017-02-07 07:02:22 -0800906 return;
907 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200908 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800909
perkj26091b12016-09-01 01:17:40 -0700910 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200911 // Storing references to a native buffer risks blocking frame capture.
912 if (video_frame.video_frame_buffer()->type() !=
913 VideoFrameBuffer::Type::kNative) {
914 if (pending_frame_)
915 TraceFrameDropStart();
916 pending_frame_ = video_frame;
917 pending_frame_post_time_us_ = time_when_posted_us;
918 } else {
919 // Ensure that any previously stored frame is dropped.
920 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +0200921 TraceFrameDropStart();
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200922 }
perkj26091b12016-09-01 01:17:40 -0700923 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000924 }
Sebastian Janssona3177052018-04-10 13:05:49 +0200925
926 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +0100927
928 frame_dropper_.Leak(framerate_fps);
929 // Frame dropping is enabled iff frame dropping is not force-disabled, and
930 // rate controller is not trusted.
931 const bool frame_dropping_enabled =
932 !force_disable_frame_dropper_ &&
933 !encoder_info_.has_trusted_rate_controller;
934 frame_dropper_.Enable(frame_dropping_enabled);
935 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
936 RTC_LOG(LS_VERBOSE) << "Drop Frame: "
937 << "target bitrate " << last_observed_bitrate_bps_
938 << ", input frame rate " << framerate_fps;
939 OnDroppedFrame(
940 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
941 return;
942 }
943
Sebastian Janssona3177052018-04-10 13:05:49 +0200944 EncodeVideoFrame(video_frame, time_when_posted_us);
945}
946
947void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
948 int64_t time_when_posted_us) {
949 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700950 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000951
ilnik6b826ef2017-06-16 06:53:48 -0700952 VideoFrame out_frame(video_frame);
953 // Crop frame if needed.
954 if (crop_width_ > 0 || crop_height_ > 0) {
955 int cropped_width = video_frame.width() - crop_width_;
956 int cropped_height = video_frame.height() - crop_height_;
957 rtc::scoped_refptr<I420Buffer> cropped_buffer =
958 I420Buffer::Create(cropped_width, cropped_height);
959 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
960 // happen after SinkWants signaled correctly from ReconfigureEncoder.
961 if (crop_width_ < 4 && crop_height_ < 4) {
962 cropped_buffer->CropAndScaleFrom(
963 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
964 crop_height_ / 2, cropped_width, cropped_height);
965 } else {
966 cropped_buffer->ScaleFrom(
967 *video_frame.video_frame_buffer()->ToI420().get());
968 }
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100969 out_frame = VideoFrame::Builder()
970 .set_video_frame_buffer(cropped_buffer)
971 .set_timestamp_rtp(video_frame.timestamp())
972 .set_timestamp_ms(video_frame.render_time_ms())
973 .set_rotation(video_frame.rotation())
974 .set_id(video_frame.id())
975 .build();
ilnik6b826ef2017-06-16 06:53:48 -0700976 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
977 }
978
Magnus Jedvert26679d62015-04-07 14:07:41 +0200979 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000980 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000981
Niels Möller7dc26b72017-12-06 10:27:48 +0100982 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700983
Erik Språnge2fd86a2018-10-24 11:32:39 +0200984 // Encoder metadata needs to be updated before encode complete callback.
985 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
986 if (info.implementation_name != encoder_info_.implementation_name) {
987 encoder_stats_observer_->OnEncoderImplementationChanged(
988 info.implementation_name);
989 }
990 encoder_info_ = info;
991
Niels Möller6bb5ab92019-01-11 11:11:10 +0100992 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Erik Språngeee39202018-11-15 17:52:43 +0100993 video_sender_.AddVideoFrame(out_frame, nullptr, encoder_info_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000994}
niklase@google.com470e71d2011-07-07 08:21:25 +0000995
mflodmancc3d4422017-08-03 08:27:51 -0700996void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700997 if (!encoder_queue_.IsCurrent()) {
998 encoder_queue_.PostTask([this] { SendKeyFrame(); });
999 return;
1000 }
1001 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001002 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Peter Boströmcd5c25c2016-04-21 16:48:08 +02001003 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001004}
1005
mflodmancc3d4422017-08-03 08:27:51 -07001006EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001007 const EncodedImage& encoded_image,
1008 const CodecSpecificInfo* codec_specific_info,
1009 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -07001010 // Encoded is called on whatever thread the real encoder implementation run
1011 // on. In the case of hardware encoders, there might be several encoders
1012 // running in parallel on different threads.
Niels Möller213618e2018-07-24 09:29:58 +02001013 encoder_stats_observer_->OnSendEncodedImage(encoded_image,
1014 codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001015
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001016 EncodedImageCallback::Result result =
1017 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001018
Niels Möller7dc26b72017-12-06 10:27:48 +01001019 int64_t time_sent_us = rtc::TimeMicros();
Niels Möller23775882018-08-16 10:24:12 +02001020 uint32_t timestamp = encoded_image.Timestamp();
kthelgason876222f2016-11-29 01:44:11 -08001021 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 16:39:44 +01001022 int64_t capture_time_us =
1023 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
1024
Danil Chapovalovb9b146c2018-06-15 12:28:07 +02001025 absl::optional<int> encode_duration_us;
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001026 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
Niels Möller83dbeac2017-12-14 16:39:44 +01001027 encode_duration_us.emplace(
1028 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
1029 rtc::kNumMicrosecsPerMillisec *
1030 (encoded_image.timing_.encode_finish_ms -
1031 encoded_image.timing_.encode_start_ms));
1032 }
1033
Niels Möller6bb5ab92019-01-11 11:11:10 +01001034 // Run post encode tasks, such as overuse detection and frame rate/drop
1035 // stats for internal encoders.
1036 const size_t frame_size = encoded_image.size();
1037 const bool keyframe = encoded_image._frameType == FrameType::kVideoFrameKey;
1038 RunPostEncode(timestamp, time_sent_us, capture_time_us, encode_duration_us,
1039 qp, frame_size, keyframe);
1040
1041 if (result.error == Result::OK) {
1042 // In case of an internal encoder running on a separate thread, the
1043 // decision to drop a frame might be a frame late and signaled via
1044 // atomic flag. This is because we can't easily wait for the worker thread
1045 // without risking deadlocks, eg during shutdown when the worker thread
1046 // might be waiting for the internal encoder threads to stop.
1047 if (pending_frame_drops_.load() > 0) {
1048 int pending_drops = pending_frame_drops_.fetch_sub(1);
1049 RTC_DCHECK_GT(pending_drops, 0);
1050 result.drop_next_frame = true;
1051 }
1052 }
perkj803d97f2016-11-01 11:45:46 -07001053
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001054 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001055}
1056
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001057void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1058 switch (reason) {
1059 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001060 encoder_stats_observer_->OnFrameDropped(
1061 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001062 encoder_queue_.PostTask([this] {
1063 RTC_DCHECK_RUN_ON(&encoder_queue_);
1064 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001065 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001066 });
1067 break;
1068 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001069 encoder_stats_observer_->OnFrameDropped(
1070 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001071 encoder_queue_.PostTask([this] {
1072 RTC_DCHECK_RUN_ON(&encoder_queue_);
1073 if (quality_scaler_)
1074 quality_scaler_->ReportDroppedFrameByEncoder();
1075 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001076 break;
1077 }
kthelgason876222f2016-11-29 01:44:11 -08001078}
1079
mflodmancc3d4422017-08-03 08:27:51 -07001080void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
1081 uint8_t fraction_lost,
1082 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -07001083 if (!encoder_queue_.IsCurrent()) {
1084 encoder_queue_.PostTask(
1085 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
1086 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
1087 });
1088 return;
1089 }
1090 RTC_DCHECK_RUN_ON(&encoder_queue_);
1091 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1092
Mirko Bonadei675513b2017-11-09 11:09:25 +01001093 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
1094 << " packet loss " << static_cast<int>(fraction_lost)
1095 << " rtt " << round_trip_time_ms;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001096 // On significant changes to BWE at the start of the call,
1097 // enable frame drops to quickly react to jumps in available bandwidth.
1098 if (encoder_start_bitrate_bps_ != 0 &&
1099 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1100 initial_framedrop_on_bwe_enabled_ &&
1101 abs_diff(bitrate_bps, encoder_start_bitrate_bps_) >=
1102 kFramedropThreshold * encoder_start_bitrate_bps_) {
1103 // Reset initial framedrop feature when first real BW estimate arrives.
1104 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1105 // without an actual BW estimate.
1106 initial_framedrop_ = 0;
1107 has_seen_first_significant_bwe_change_ = true;
1108 }
perkj26091b12016-09-01 01:17:40 -07001109
Niels Möller6bb5ab92019-01-11 11:11:10 +01001110 uint32_t framerate_fps = GetInputFramerateFps();
1111 frame_dropper_.SetRates((bitrate_bps + 500) / 1000, framerate_fps);
1112
1113 VideoBitrateAllocation bitrate_allocation =
1114 GetBitrateAllocationAndNotifyObserver(bitrate_bps, framerate_fps);
1115 video_sender_.SetChannelParameters(bitrate_allocation, framerate_fps);
perkj26091b12016-09-01 01:17:40 -07001116
1117 encoder_start_bitrate_bps_ =
1118 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +02001119 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +01001120 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -07001121 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +00001122
sprang552c7c72017-02-13 04:41:45 -08001123 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001124 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1125 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001126 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001127 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001128 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1129 !DropDueToSize(pending_frame_->size())) {
1130 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1131 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1132 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1133 pending_frame_.reset();
1134 }
1135}
1136
1137bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001138 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001139 encoder_start_bitrate_bps_ > 0) {
1140 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1141 return pixel_count > 320 * 240;
1142 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1143 return pixel_count > 640 * 480;
1144 }
1145 }
1146 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001147}
1148
mflodmancc3d4422017-08-03 08:27:51 -07001149void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001150 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001151 AdaptationRequest adaptation_request = {
1152 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001153 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001154 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001155
sprangc5d62e22017-04-02 23:53:04 -07001156 bool downgrade_requested =
1157 last_adaptation_request_ &&
1158 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1159
sprangc5d62e22017-04-02 23:53:04 -07001160 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001161 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001162 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001163 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001164 if (downgrade_requested &&
1165 adaptation_request.input_pixel_count_ >=
1166 last_adaptation_request_->input_pixel_count_) {
1167 // Don't request lower resolution if the current resolution is not
1168 // lower than the last time we asked for the resolution to be lowered.
1169 return;
1170 }
1171 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001172 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001173 if (adaptation_request.framerate_fps_ <= 0 ||
1174 (downgrade_requested &&
1175 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1176 // If no input fps estimate available, can't determine how to scale down
1177 // framerate. Otherwise, don't request lower framerate if we don't have
1178 // a valid frame rate. Since framerate, unlike resolution, is a measure
1179 // we have to estimate, and can fluctuate naturally over time, don't
1180 // make the same kind of limitations as for resolution, but trust the
1181 // overuse detector to not trigger too often.
1182 return;
1183 }
1184 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001185 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001186 return;
sprang84a37592017-02-10 07:04:27 -08001187 }
sprangc5d62e22017-04-02 23:53:04 -07001188
sprangc5d62e22017-04-02 23:53:04 -07001189 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001190 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001191 // Try scale down framerate, if lower.
1192 int fps = MinFps(last_frame_info_->pixel_count());
1193 if (source_proxy_->RestrictFramerate(fps)) {
1194 GetAdaptCounter().IncrementFramerate(reason);
1195 break;
1196 }
1197 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001198 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001199 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001200 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001201 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001202 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001203 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001204 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001205 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001206 &min_pixels_reached)) {
1207 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001208 encoder_stats_observer_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -07001209 return;
1210 }
asaperssonf7e294d2017-06-13 23:25:22 -07001211 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001212 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001213 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001214 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001215 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001216 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1217 adaptation_request.framerate_fps_);
1218 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001219 return;
sprangfda496a2017-06-15 04:21:07 -07001220 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001221 overuse_detector_->OnTargetFramerateUpdated(
1222 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001223 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001224 break;
sprangfda496a2017-06-15 04:21:07 -07001225 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001226 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001227 RTC_NOTREACHED();
1228 }
1229
asaperssond0de2952017-04-21 01:47:31 -07001230 last_adaptation_request_.emplace(adaptation_request);
1231
asapersson09f05612017-05-15 23:40:18 -07001232 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001233
Mirko Bonadei675513b2017-11-09 11:09:25 +01001234 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001235}
1236
mflodmancc3d4422017-08-03 08:27:51 -07001237void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001238 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001239
1240 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1241 int num_downgrades = adapt_counter.TotalCount(reason);
1242 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001243 return;
asapersson09f05612017-05-15 23:40:18 -07001244 RTC_DCHECK_GT(num_downgrades, 0);
1245
sprangc5d62e22017-04-02 23:53:04 -07001246 AdaptationRequest adaptation_request = {
1247 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001248 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001249 AdaptationRequest::Mode::kAdaptUp};
1250
1251 bool adapt_up_requested =
1252 last_adaptation_request_ &&
1253 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001254
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001255 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001256 if (adapt_up_requested &&
1257 adaptation_request.input_pixel_count_ <=
1258 last_adaptation_request_->input_pixel_count_) {
1259 // Don't request higher resolution if the current resolution is not
1260 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001261 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001262 }
sprangb1ca0732017-02-01 08:38:12 -08001263 }
sprangc5d62e22017-04-02 23:53:04 -07001264
sprangc5d62e22017-04-02 23:53:04 -07001265 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001266 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001267 // Try scale up framerate, if higher.
1268 int fps = MaxFps(last_frame_info_->pixel_count());
1269 if (source_proxy_->IncreaseFramerate(fps)) {
1270 GetAdaptCounter().DecrementFramerate(reason, fps);
1271 // Reset framerate in case of fewer fps steps down than up.
1272 if (adapt_counter.FramerateCount() == 0 &&
1273 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001274 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001275 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1276 }
1277 break;
1278 }
1279 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001280 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001281 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001282 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001283 // Scale up resolution.
1284 int pixel_count = adaptation_request.input_pixel_count_;
1285 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001286 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001287 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001288 }
asapersson13874762017-06-07 00:01:02 -07001289 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1290 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001291 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001292 break;
asapersson13874762017-06-07 00:01:02 -07001293 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001294 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001295 // Scale up framerate.
1296 int fps = adaptation_request.framerate_fps_;
1297 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001298 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001299 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001300 }
sprangfda496a2017-06-15 04:21:07 -07001301
1302 const int requested_framerate =
1303 source_proxy_->RequestHigherFramerateThan(fps);
1304 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001305 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001306 return;
sprangfda496a2017-06-15 04:21:07 -07001307 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001308 overuse_detector_->OnTargetFramerateUpdated(
1309 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001310 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001311 break;
asapersson13874762017-06-07 00:01:02 -07001312 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001313 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001314 return;
sprangc5d62e22017-04-02 23:53:04 -07001315 }
1316
asaperssond0de2952017-04-21 01:47:31 -07001317 last_adaptation_request_.emplace(adaptation_request);
1318
asapersson09f05612017-05-15 23:40:18 -07001319 UpdateAdaptationStats(reason);
1320
Mirko Bonadei675513b2017-11-09 11:09:25 +01001321 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001322}
1323
Niels Möller213618e2018-07-24 09:29:58 +02001324// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07001325void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001326 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001327 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02001328 encoder_stats_observer_->OnAdaptationChanged(
1329 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1330 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07001331 break;
1332 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02001333 encoder_stats_observer_->OnAdaptationChanged(
1334 VideoStreamEncoderObserver::AdaptationReason::kQuality,
1335 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001336 break;
1337 }
perkj26091b12016-09-01 01:17:40 -07001338}
1339
Niels Möller213618e2018-07-24 09:29:58 +02001340VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07001341 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02001342 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07001343 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001344 switch (reason) {
1345 case kCpu:
1346 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001347 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001348 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001349 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001350 break;
1351 case kQuality:
1352 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1353 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001354 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001355 }
1356 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1357 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001358 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001359 }
1360 break;
sprangc5d62e22017-04-02 23:53:04 -07001361 }
asapersson09f05612017-05-15 23:40:18 -07001362 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001363}
1364
mflodmancc3d4422017-08-03 08:27:51 -07001365VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001366 return adapt_counters_[degradation_preference_];
1367}
1368
mflodmancc3d4422017-08-03 08:27:51 -07001369const VideoStreamEncoder::AdaptCounter&
1370VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001371 return adapt_counters_[degradation_preference_];
1372}
1373
Niels Möller6bb5ab92019-01-11 11:11:10 +01001374void VideoStreamEncoder::RunPostEncode(uint32_t frame_timestamp,
1375 int64_t time_sent_us,
1376 int64_t capture_time_us,
1377 absl::optional<int> encode_durations_us,
1378 int qp,
1379 size_t frame_size_bytes,
1380 bool keyframe) {
1381 if (!encoder_queue_.IsCurrent()) {
1382 encoder_queue_.PostTask([this, frame_timestamp, time_sent_us, qp,
1383 capture_time_us, encode_durations_us,
1384 frame_size_bytes, keyframe] {
1385 RunPostEncode(frame_timestamp, time_sent_us, capture_time_us,
1386 encode_durations_us, qp, frame_size_bytes, keyframe);
1387 });
1388 return;
1389 }
1390
1391 RTC_DCHECK_RUN_ON(&encoder_queue_);
1392 if (frame_size_bytes > 0) {
1393 frame_dropper_.Fill(frame_size_bytes, !keyframe);
1394 }
1395
1396 if (encoder_info_.has_internal_source) {
1397 // Update frame dropper after the fact for internal sources.
1398 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
1399 frame_dropper_.Leak(GetInputFramerateFps());
1400 // Signal to encoder to drop next frame.
1401 if (frame_dropper_.DropFrame()) {
1402 pending_frame_drops_.fetch_add(1);
1403 }
1404 }
1405
1406 overuse_detector_->FrameSent(frame_timestamp, time_sent_us, capture_time_us,
1407 encode_durations_us);
1408 if (quality_scaler_ && qp >= 0)
1409 quality_scaler_->ReportQp(qp);
1410}
1411
asapersson09f05612017-05-15 23:40:18 -07001412// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001413VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001414 fps_counters_.resize(kScaleReasonSize);
1415 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001416 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001417}
1418
mflodmancc3d4422017-08-03 08:27:51 -07001419VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001420
mflodmancc3d4422017-08-03 08:27:51 -07001421std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001422 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001423 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1424 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02001425 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07001426}
1427
Niels Möller213618e2018-07-24 09:29:58 +02001428VideoStreamEncoderObserver::AdaptationSteps
1429VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
1430 VideoStreamEncoderObserver::AdaptationSteps counts;
1431 counts.num_framerate_reductions = fps_counters_[reason];
1432 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07001433 return counts;
1434}
1435
mflodmancc3d4422017-08-03 08:27:51 -07001436void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001437 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001438}
1439
mflodmancc3d4422017-08-03 08:27:51 -07001440void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001441 ++(resolution_counters_[reason]);
1442}
1443
mflodmancc3d4422017-08-03 08:27:51 -07001444void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001445 if (fps_counters_[reason] == 0) {
1446 // Balanced mode: Adapt up is in a different order, switch reason.
1447 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1448 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1449 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1450 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1451 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1452 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1453 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1454 MoveCount(&resolution_counters_, reason);
1455 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1456 }
1457 --(fps_counters_[reason]);
1458 RTC_DCHECK_GE(fps_counters_[reason], 0);
1459}
1460
mflodmancc3d4422017-08-03 08:27:51 -07001461void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001462 if (resolution_counters_[reason] == 0) {
1463 // Balanced mode: Adapt up is in a different order, switch reason.
1464 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1465 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1466 MoveCount(&fps_counters_, reason);
1467 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1468 }
1469 --(resolution_counters_[reason]);
1470 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1471}
1472
mflodmancc3d4422017-08-03 08:27:51 -07001473void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1474 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001475 DecrementFramerate(reason);
1476 // Reset if at max fps (i.e. in case of fewer steps up than down).
1477 if (cur_fps == std::numeric_limits<int>::max())
1478 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001479}
1480
mflodmancc3d4422017-08-03 08:27:51 -07001481int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001482 return Count(fps_counters_);
1483}
1484
mflodmancc3d4422017-08-03 08:27:51 -07001485int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001486 return Count(resolution_counters_);
1487}
1488
mflodmancc3d4422017-08-03 08:27:51 -07001489int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001490 return fps_counters_[reason];
1491}
1492
mflodmancc3d4422017-08-03 08:27:51 -07001493int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001494 return resolution_counters_[reason];
1495}
1496
mflodmancc3d4422017-08-03 08:27:51 -07001497int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001498 return FramerateCount(reason) + ResolutionCount(reason);
1499}
1500
mflodmancc3d4422017-08-03 08:27:51 -07001501int VideoStreamEncoder::AdaptCounter::Count(
1502 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001503 return std::accumulate(counters.begin(), counters.end(), 0);
1504}
1505
mflodmancc3d4422017-08-03 08:27:51 -07001506void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1507 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001508 int to_reason = (from_reason + 1) % kScaleReasonSize;
1509 ++((*counters)[to_reason]);
1510 --((*counters)[from_reason]);
1511}
1512
mflodmancc3d4422017-08-03 08:27:51 -07001513std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001514 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001515 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001516 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1517 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001518 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02001519 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07001520}
1521
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001522} // namespace webrtc