blob: 0cb6c3b2e03f0084946738dcd63698e8dba6a783 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/timeutils.h"
34#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 Dvornicic1ec2a162018-12-10 09:47:34 +0000584 if (pending_encoder_creation_) {
585 pending_encoder_creation_ = false;
Niels Möller4db138e2018-04-19 09:04:13 +0200586 if (encoder_) {
587 video_sender_.RegisterExternalEncoder(nullptr, false);
588 }
589
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000590 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
591 encoder_config_.video_format);
592 // TODO(nisse): What to do if creating the encoder fails? Crash,
593 // or just discard incoming frames?
594 RTC_CHECK(encoder_);
595
596 const webrtc::VideoEncoderFactory::CodecInfo info =
597 settings_.encoder_factory->QueryVideoEncoder(
598 encoder_config_.video_format);
Niels Möller4db138e2018-04-19 09:04:13 +0200599
600 overuse_detector_->StopCheckForOveruse();
601 overuse_detector_->StartCheckForOveruse(
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000602 GetCpuOveruseOptions(settings_, info.is_hardware_accelerated), this);
Niels Möller4db138e2018-04-19 09:04:13 +0200603
604 video_sender_.RegisterExternalEncoder(encoder_.get(),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000605 info.has_internal_source);
Niels Möller4db138e2018-04-19 09:04:13 +0200606 }
607 // RegisterSendCodec implies an unconditional call to
608 // encoder_->InitEncode().
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200609 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700610 &codec, number_of_cores_,
611 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100612 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100613 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700614 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000615 }
Peter Boström905f8e72016-03-02 16:59:56 +0100616
Niels Möller6bb5ab92019-01-11 11:11:10 +0100617 int num_layers;
618 if (codec.codecType == kVideoCodecVP8) {
619 num_layers = codec.VP8()->numberOfTemporalLayers;
620 } else if (codec.codecType == kVideoCodecVP9) {
621 num_layers = codec.VP9()->numberOfTemporalLayers;
622 } else if (codec.codecType == kVideoCodecGeneric &&
623 codec.numberOfSimulcastStreams > 0) {
624 // This is mainly for unit testing, disabling frame dropping.
625 // TODO(sprang): Add a better way to disable frame dropping.
626 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
627 } else {
628 num_layers = 1;
629 }
630
631 frame_dropper_.Reset();
632 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
633 uint32_t framerate_fps = GetInputFramerateFps();
634 // Force-disable frame dropper if either:
635 // * We have screensharing with layers.
636 // * "WebRTC-FrameDropper" field trial is "Disabled".
637 force_disable_frame_dropper_ =
638 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
639 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
640
641 if (rate_allocator_ && last_observed_bitrate_bps_ > 0) {
642 // We have a new rate allocator instance and already configured target
643 // bitrate. Update the rate allocation and notify observsers.
644 VideoBitrateAllocation bitrate_allocation =
645 GetBitrateAllocationAndNotifyObserver(last_observed_bitrate_bps_,
646 framerate_fps);
647
648 video_sender_.SetChannelParameters(bitrate_allocation, framerate_fps);
649 }
ilnik35b7de42017-03-15 04:24:21 -0700650
Niels Möller213618e2018-07-24 09:29:58 +0200651 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200652
perkjfa10b552016-10-02 23:45:26 -0700653 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100654
Pera48ddb72016-09-29 11:48:50 +0200655 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700656 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800657
Niels Möller7dc26b72017-12-06 10:27:48 +0100658 // Get the current target framerate, ie the maximum framerate as specified by
659 // the current codec configuration, or any limit imposed by cpu adaption in
660 // maintain-resolution or balanced mode. This is used to make sure overuse
661 // detection doesn't needlessly trigger in low and/or variable framerate
662 // scenarios.
663 int target_framerate = std::min(
664 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
665 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200666
667 ConfigureQualityScaler();
kthelgason2bc68642017-02-07 07:02:22 -0800668}
669
mflodmancc3d4422017-08-03 08:27:51 -0700670void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800671 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språnge2fd86a2018-10-24 11:32:39 +0200672 const auto scaling_settings = encoder_->GetEncoderInfo().scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700673 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700674 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100675 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700676
asapersson36e9eb42017-03-31 05:29:12 -0700677 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700678 if (quality_scaler_.get() == nullptr) {
679 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100680
Åsa Perssona945aee2018-04-24 16:53:25 +0200681 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200682 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200683 if (quality_scaling_experiment_enabled_) {
684 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
685 encoder_config_.codec_type);
686 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200687 // Since the interface is non-public, absl::make_unique can't do this
688 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100689 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200690 quality_scaler_ = absl::make_unique<QualityScaler>(
Åsa Perssona945aee2018-04-24 16:53:25 +0200691 observer, experimental_thresholds ? *experimental_thresholds
692 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200693 has_seen_first_significant_bwe_change_ = false;
694 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800695 }
696 } else {
697 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200698 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800699 }
asapersson09f05612017-05-15 23:40:18 -0700700
Niels Möller213618e2018-07-24 09:29:58 +0200701 encoder_stats_observer_->OnAdaptationChanged(
702 VideoStreamEncoderObserver::AdaptationReason::kNone,
703 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000704}
705
mflodmancc3d4422017-08-03 08:27:51 -0700706void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700707 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700708 VideoFrame incoming_frame = video_frame;
709
710 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700711 int64_t current_time_us = clock_->TimeInMicroseconds();
712 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
713 // In some cases, e.g., when the frame from decoder is fed to encoder,
714 // the timestamp may be set to the future. As the encoding pipeline assumes
715 // capture time to be less than present time, we should reset the capture
716 // timestamps here. Otherwise there may be issues with RTP send stream.
717 if (incoming_frame.timestamp_us() > current_time_us)
718 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700719
720 // Capture time may come from clock with an offset and drift from clock_.
721 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800722 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700723 capture_ntp_time_ms = video_frame.ntp_time_ms();
724 } else if (video_frame.render_time_ms() != 0) {
725 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
726 } else {
nisse1c0dea82017-01-30 02:43:18 -0800727 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700728 }
729 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
730
731 // Convert NTP time, in ms, to RTP timestamp.
732 const int kMsToRtpTimestamp = 90;
733 incoming_frame.set_timestamp(
734 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
735
736 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
737 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
739 << incoming_frame.ntp_time_ms()
740 << " <= " << last_captured_timestamp_
741 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 01:17:40 -0700742 return;
743 }
744
asapersson6ffb67d2016-09-12 00:10:45 -0700745 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800746 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
747 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700748 log_stats = true;
749 }
750
perkj26091b12016-09-01 01:17:40 -0700751 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200752
753 int64_t post_time_us = rtc::TimeMicros();
754 ++posted_frames_waiting_for_encode_;
755
756 encoder_queue_.PostTask(
757 [this, incoming_frame, post_time_us, log_stats]() {
758 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +0200759 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
760 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200761 ++captured_frame_count_;
762 const int posted_frames_waiting_for_encode =
763 posted_frames_waiting_for_encode_.fetch_sub(1);
764 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
765 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +0200766 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200767 } else {
768 // There is a newer frame in flight. Do not encode this frame.
769 RTC_LOG(LS_VERBOSE)
770 << "Incoming frame dropped due to that the encoder is blocked.";
771 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +0200772 encoder_stats_observer_->OnFrameDropped(
773 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200774 }
775 if (log_stats) {
776 RTC_LOG(LS_INFO) << "Number of frames: captured "
777 << captured_frame_count_
778 << ", dropped (due to encoder blocked) "
779 << dropped_frame_count_ << ", interval_ms "
780 << kFrameLogIntervalMs;
781 captured_frame_count_ = 0;
782 dropped_frame_count_ = 0;
783 }
784 });
perkj26091b12016-09-01 01:17:40 -0700785}
786
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200787void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +0200788 encoder_stats_observer_->OnFrameDropped(
789 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200790}
791
mflodmancc3d4422017-08-03 08:27:51 -0700792bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700793 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000794 // Pause video if paused by caller or as long as the network is down or the
795 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700796 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700797 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700798 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000799}
800
mflodmancc3d4422017-08-03 08:27:51 -0700801void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700802 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000803 // Start trace event only on the first frame after encoder is paused.
804 if (!encoder_paused_and_dropped_frame_) {
805 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
806 }
807 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000808}
809
mflodmancc3d4422017-08-03 08:27:51 -0700810void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700811 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000812 // End trace event on first frame after encoder resumes, if frame was dropped.
813 if (encoder_paused_and_dropped_frame_) {
814 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
815 }
816 encoder_paused_and_dropped_frame_ = false;
817}
818
Niels Möller6bb5ab92019-01-11 11:11:10 +0100819VideoBitrateAllocation
820VideoStreamEncoder::GetBitrateAllocationAndNotifyObserver(
821 const uint32_t target_bitrate_bps,
822 uint32_t framerate_fps) {
823 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
824 // might cap the bitrate to the min bitrate configured.
825 VideoBitrateAllocation bitrate_allocation;
826 if (rate_allocator_ && target_bitrate_bps > 0) {
827 bitrate_allocation =
828 rate_allocator_->GetAllocation(target_bitrate_bps, framerate_fps);
829 }
830
831 if (bitrate_observer_ && bitrate_allocation.get_sum_bps() > 0) {
832 bitrate_observer_->OnBitrateAllocationUpdated(bitrate_allocation);
833 }
834
835 return bitrate_allocation;
836}
837
838uint32_t VideoStreamEncoder::GetInputFramerateFps() {
839 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
840 return input_framerate_.Rate(clock_->TimeInMilliseconds())
841 .value_or(default_fps);
842}
843
Sebastian Janssona3177052018-04-10 13:05:49 +0200844void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
845 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700846 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800847
Per21d45d22016-10-30 21:37:57 +0100848 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700849 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700850 video_frame.is_texture() != last_frame_info_->is_texture) {
851 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100852 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
853 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100854 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
855 << last_frame_info_->width << "x"
856 << last_frame_info_->height
857 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700858 }
859
Niels Möller4db138e2018-04-19 09:04:13 +0200860 // We have to create then encoder before the frame drop logic,
861 // because the latter depends on encoder_->GetScalingSettings.
862 // According to the testcase
863 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
864 // from GetScalingSettings should enable or disable the frame drop.
865
Niels Möller6bb5ab92019-01-11 11:11:10 +0100866 uint32_t framerate_fps = GetInputFramerateFps();
867
Niels Möller4db138e2018-04-19 09:04:13 +0200868 int64_t now_ms = clock_->TimeInMilliseconds();
869 if (pending_encoder_reconfiguration_) {
870 ReconfigureEncoder();
871 last_parameters_update_ms_.emplace(now_ms);
872 } else if (!last_parameters_update_ms_ ||
873 now_ms - *last_parameters_update_ms_ >=
874 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100875 video_sender_.SetChannelParameters(
876 GetBitrateAllocationAndNotifyObserver(last_observed_bitrate_bps_,
877 framerate_fps),
878 framerate_fps);
Niels Möller4db138e2018-04-19 09:04:13 +0200879 last_parameters_update_ms_.emplace(now_ms);
880 }
881
Sebastian Janssona3177052018-04-10 13:05:49 +0200882 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100883 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +0100884 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800885 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +0100886 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +0200887 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +0100888 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200889 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200890 // Storing references to a native buffer risks blocking frame capture.
891 if (video_frame.video_frame_buffer()->type() !=
892 VideoFrameBuffer::Type::kNative) {
893 pending_frame_ = video_frame;
894 pending_frame_post_time_us_ = time_when_posted_us;
895 } else {
896 // Ensure that any previously stored frame is dropped.
897 pending_frame_.reset();
898 }
kthelgason2bc68642017-02-07 07:02:22 -0800899 return;
900 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200901 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800902
perkj26091b12016-09-01 01:17:40 -0700903 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200904 // Storing references to a native buffer risks blocking frame capture.
905 if (video_frame.video_frame_buffer()->type() !=
906 VideoFrameBuffer::Type::kNative) {
907 if (pending_frame_)
908 TraceFrameDropStart();
909 pending_frame_ = video_frame;
910 pending_frame_post_time_us_ = time_when_posted_us;
911 } else {
912 // Ensure that any previously stored frame is dropped.
913 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +0200914 TraceFrameDropStart();
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200915 }
perkj26091b12016-09-01 01:17:40 -0700916 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000917 }
Sebastian Janssona3177052018-04-10 13:05:49 +0200918
919 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +0100920
921 frame_dropper_.Leak(framerate_fps);
922 // Frame dropping is enabled iff frame dropping is not force-disabled, and
923 // rate controller is not trusted.
924 const bool frame_dropping_enabled =
925 !force_disable_frame_dropper_ &&
926 !encoder_info_.has_trusted_rate_controller;
927 frame_dropper_.Enable(frame_dropping_enabled);
928 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
929 RTC_LOG(LS_VERBOSE) << "Drop Frame: "
930 << "target bitrate " << last_observed_bitrate_bps_
931 << ", input frame rate " << framerate_fps;
932 OnDroppedFrame(
933 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
934 return;
935 }
936
Sebastian Janssona3177052018-04-10 13:05:49 +0200937 EncodeVideoFrame(video_frame, time_when_posted_us);
938}
939
940void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
941 int64_t time_when_posted_us) {
942 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700943 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000944
ilnik6b826ef2017-06-16 06:53:48 -0700945 VideoFrame out_frame(video_frame);
946 // Crop frame if needed.
947 if (crop_width_ > 0 || crop_height_ > 0) {
948 int cropped_width = video_frame.width() - crop_width_;
949 int cropped_height = video_frame.height() - crop_height_;
950 rtc::scoped_refptr<I420Buffer> cropped_buffer =
951 I420Buffer::Create(cropped_width, cropped_height);
952 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
953 // happen after SinkWants signaled correctly from ReconfigureEncoder.
954 if (crop_width_ < 4 && crop_height_ < 4) {
955 cropped_buffer->CropAndScaleFrom(
956 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
957 crop_height_ / 2, cropped_width, cropped_height);
958 } else {
959 cropped_buffer->ScaleFrom(
960 *video_frame.video_frame_buffer()->ToI420().get());
961 }
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100962 out_frame = VideoFrame::Builder()
963 .set_video_frame_buffer(cropped_buffer)
964 .set_timestamp_rtp(video_frame.timestamp())
965 .set_timestamp_ms(video_frame.render_time_ms())
966 .set_rotation(video_frame.rotation())
967 .set_id(video_frame.id())
968 .build();
ilnik6b826ef2017-06-16 06:53:48 -0700969 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
970 }
971
Magnus Jedvert26679d62015-04-07 14:07:41 +0200972 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000973 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000974
Niels Möller7dc26b72017-12-06 10:27:48 +0100975 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700976
Erik Språnge2fd86a2018-10-24 11:32:39 +0200977 // Encoder metadata needs to be updated before encode complete callback.
978 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
979 if (info.implementation_name != encoder_info_.implementation_name) {
980 encoder_stats_observer_->OnEncoderImplementationChanged(
981 info.implementation_name);
982 }
983 encoder_info_ = info;
984
Niels Möller6bb5ab92019-01-11 11:11:10 +0100985 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Erik Språngeee39202018-11-15 17:52:43 +0100986 video_sender_.AddVideoFrame(out_frame, nullptr, encoder_info_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000987}
niklase@google.com470e71d2011-07-07 08:21:25 +0000988
mflodmancc3d4422017-08-03 08:27:51 -0700989void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700990 if (!encoder_queue_.IsCurrent()) {
991 encoder_queue_.PostTask([this] { SendKeyFrame(); });
992 return;
993 }
994 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +0100995 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200996 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +0000997}
998
mflodmancc3d4422017-08-03 08:27:51 -0700999EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001000 const EncodedImage& encoded_image,
1001 const CodecSpecificInfo* codec_specific_info,
1002 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -07001003 // Encoded is called on whatever thread the real encoder implementation run
1004 // on. In the case of hardware encoders, there might be several encoders
1005 // running in parallel on different threads.
Niels Möller213618e2018-07-24 09:29:58 +02001006 encoder_stats_observer_->OnSendEncodedImage(encoded_image,
1007 codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001008
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001009 EncodedImageCallback::Result result =
1010 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001011
Niels Möller7dc26b72017-12-06 10:27:48 +01001012 int64_t time_sent_us = rtc::TimeMicros();
Niels Möller23775882018-08-16 10:24:12 +02001013 uint32_t timestamp = encoded_image.Timestamp();
kthelgason876222f2016-11-29 01:44:11 -08001014 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 16:39:44 +01001015 int64_t capture_time_us =
1016 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
1017
Danil Chapovalovb9b146c2018-06-15 12:28:07 +02001018 absl::optional<int> encode_duration_us;
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001019 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
Niels Möller83dbeac2017-12-14 16:39:44 +01001020 encode_duration_us.emplace(
1021 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
1022 rtc::kNumMicrosecsPerMillisec *
1023 (encoded_image.timing_.encode_finish_ms -
1024 encoded_image.timing_.encode_start_ms));
1025 }
1026
Niels Möller6bb5ab92019-01-11 11:11:10 +01001027 // Run post encode tasks, such as overuse detection and frame rate/drop
1028 // stats for internal encoders.
1029 const size_t frame_size = encoded_image.size();
1030 const bool keyframe = encoded_image._frameType == FrameType::kVideoFrameKey;
1031 RunPostEncode(timestamp, time_sent_us, capture_time_us, encode_duration_us,
1032 qp, frame_size, keyframe);
1033
1034 if (result.error == Result::OK) {
1035 // In case of an internal encoder running on a separate thread, the
1036 // decision to drop a frame might be a frame late and signaled via
1037 // atomic flag. This is because we can't easily wait for the worker thread
1038 // without risking deadlocks, eg during shutdown when the worker thread
1039 // might be waiting for the internal encoder threads to stop.
1040 if (pending_frame_drops_.load() > 0) {
1041 int pending_drops = pending_frame_drops_.fetch_sub(1);
1042 RTC_DCHECK_GT(pending_drops, 0);
1043 result.drop_next_frame = true;
1044 }
1045 }
perkj803d97f2016-11-01 11:45:46 -07001046
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001047 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001048}
1049
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001050void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1051 switch (reason) {
1052 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001053 encoder_stats_observer_->OnFrameDropped(
1054 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001055 encoder_queue_.PostTask([this] {
1056 RTC_DCHECK_RUN_ON(&encoder_queue_);
1057 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001058 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001059 });
1060 break;
1061 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001062 encoder_stats_observer_->OnFrameDropped(
1063 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001064 encoder_queue_.PostTask([this] {
1065 RTC_DCHECK_RUN_ON(&encoder_queue_);
1066 if (quality_scaler_)
1067 quality_scaler_->ReportDroppedFrameByEncoder();
1068 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001069 break;
1070 }
kthelgason876222f2016-11-29 01:44:11 -08001071}
1072
mflodmancc3d4422017-08-03 08:27:51 -07001073void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
1074 uint8_t fraction_lost,
1075 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -07001076 if (!encoder_queue_.IsCurrent()) {
1077 encoder_queue_.PostTask(
1078 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
1079 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
1080 });
1081 return;
1082 }
1083 RTC_DCHECK_RUN_ON(&encoder_queue_);
1084 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1085
Mirko Bonadei675513b2017-11-09 11:09:25 +01001086 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
1087 << " packet loss " << static_cast<int>(fraction_lost)
1088 << " rtt " << round_trip_time_ms;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001089 // On significant changes to BWE at the start of the call,
1090 // enable frame drops to quickly react to jumps in available bandwidth.
1091 if (encoder_start_bitrate_bps_ != 0 &&
1092 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1093 initial_framedrop_on_bwe_enabled_ &&
1094 abs_diff(bitrate_bps, encoder_start_bitrate_bps_) >=
1095 kFramedropThreshold * encoder_start_bitrate_bps_) {
1096 // Reset initial framedrop feature when first real BW estimate arrives.
1097 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1098 // without an actual BW estimate.
1099 initial_framedrop_ = 0;
1100 has_seen_first_significant_bwe_change_ = true;
1101 }
perkj26091b12016-09-01 01:17:40 -07001102
Niels Möller6bb5ab92019-01-11 11:11:10 +01001103 uint32_t framerate_fps = GetInputFramerateFps();
1104 frame_dropper_.SetRates((bitrate_bps + 500) / 1000, framerate_fps);
1105
1106 VideoBitrateAllocation bitrate_allocation =
1107 GetBitrateAllocationAndNotifyObserver(bitrate_bps, framerate_fps);
1108 video_sender_.SetChannelParameters(bitrate_allocation, framerate_fps);
perkj26091b12016-09-01 01:17:40 -07001109
1110 encoder_start_bitrate_bps_ =
1111 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +02001112 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +01001113 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -07001114 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +00001115
sprang552c7c72017-02-13 04:41:45 -08001116 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001117 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1118 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001119 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001120 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001121 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1122 !DropDueToSize(pending_frame_->size())) {
1123 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1124 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1125 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1126 pending_frame_.reset();
1127 }
1128}
1129
1130bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001131 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001132 encoder_start_bitrate_bps_ > 0) {
1133 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1134 return pixel_count > 320 * 240;
1135 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1136 return pixel_count > 640 * 480;
1137 }
1138 }
1139 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001140}
1141
mflodmancc3d4422017-08-03 08:27:51 -07001142void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001143 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001144 AdaptationRequest adaptation_request = {
1145 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001146 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001147 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001148
sprangc5d62e22017-04-02 23:53:04 -07001149 bool downgrade_requested =
1150 last_adaptation_request_ &&
1151 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1152
sprangc5d62e22017-04-02 23:53:04 -07001153 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001154 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001155 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001156 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001157 if (downgrade_requested &&
1158 adaptation_request.input_pixel_count_ >=
1159 last_adaptation_request_->input_pixel_count_) {
1160 // Don't request lower resolution if the current resolution is not
1161 // lower than the last time we asked for the resolution to be lowered.
1162 return;
1163 }
1164 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001165 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001166 if (adaptation_request.framerate_fps_ <= 0 ||
1167 (downgrade_requested &&
1168 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1169 // If no input fps estimate available, can't determine how to scale down
1170 // framerate. Otherwise, don't request lower framerate if we don't have
1171 // a valid frame rate. Since framerate, unlike resolution, is a measure
1172 // we have to estimate, and can fluctuate naturally over time, don't
1173 // make the same kind of limitations as for resolution, but trust the
1174 // overuse detector to not trigger too often.
1175 return;
1176 }
1177 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001178 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001179 return;
sprang84a37592017-02-10 07:04:27 -08001180 }
sprangc5d62e22017-04-02 23:53:04 -07001181
sprangc5d62e22017-04-02 23:53:04 -07001182 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001183 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001184 // Try scale down framerate, if lower.
1185 int fps = MinFps(last_frame_info_->pixel_count());
1186 if (source_proxy_->RestrictFramerate(fps)) {
1187 GetAdaptCounter().IncrementFramerate(reason);
1188 break;
1189 }
1190 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001191 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001192 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001193 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001194 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001195 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001196 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001197 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001198 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001199 &min_pixels_reached)) {
1200 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001201 encoder_stats_observer_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -07001202 return;
1203 }
asaperssonf7e294d2017-06-13 23:25:22 -07001204 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001205 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001206 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001207 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001208 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001209 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1210 adaptation_request.framerate_fps_);
1211 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001212 return;
sprangfda496a2017-06-15 04:21:07 -07001213 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001214 overuse_detector_->OnTargetFramerateUpdated(
1215 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001216 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001217 break;
sprangfda496a2017-06-15 04:21:07 -07001218 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001219 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001220 RTC_NOTREACHED();
1221 }
1222
asaperssond0de2952017-04-21 01:47:31 -07001223 last_adaptation_request_.emplace(adaptation_request);
1224
asapersson09f05612017-05-15 23:40:18 -07001225 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001226
Mirko Bonadei675513b2017-11-09 11:09:25 +01001227 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001228}
1229
mflodmancc3d4422017-08-03 08:27:51 -07001230void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001231 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001232
1233 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1234 int num_downgrades = adapt_counter.TotalCount(reason);
1235 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001236 return;
asapersson09f05612017-05-15 23:40:18 -07001237 RTC_DCHECK_GT(num_downgrades, 0);
1238
sprangc5d62e22017-04-02 23:53:04 -07001239 AdaptationRequest adaptation_request = {
1240 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001241 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001242 AdaptationRequest::Mode::kAdaptUp};
1243
1244 bool adapt_up_requested =
1245 last_adaptation_request_ &&
1246 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001247
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001248 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001249 if (adapt_up_requested &&
1250 adaptation_request.input_pixel_count_ <=
1251 last_adaptation_request_->input_pixel_count_) {
1252 // Don't request higher resolution if the current resolution is not
1253 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001254 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001255 }
sprangb1ca0732017-02-01 08:38:12 -08001256 }
sprangc5d62e22017-04-02 23:53:04 -07001257
sprangc5d62e22017-04-02 23:53:04 -07001258 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001259 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001260 // Try scale up framerate, if higher.
1261 int fps = MaxFps(last_frame_info_->pixel_count());
1262 if (source_proxy_->IncreaseFramerate(fps)) {
1263 GetAdaptCounter().DecrementFramerate(reason, fps);
1264 // Reset framerate in case of fewer fps steps down than up.
1265 if (adapt_counter.FramerateCount() == 0 &&
1266 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001267 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001268 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1269 }
1270 break;
1271 }
1272 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001273 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001274 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001275 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001276 // Scale up resolution.
1277 int pixel_count = adaptation_request.input_pixel_count_;
1278 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001279 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001280 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001281 }
asapersson13874762017-06-07 00:01:02 -07001282 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1283 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001284 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001285 break;
asapersson13874762017-06-07 00:01:02 -07001286 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001287 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001288 // Scale up framerate.
1289 int fps = adaptation_request.framerate_fps_;
1290 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001291 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001292 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001293 }
sprangfda496a2017-06-15 04:21:07 -07001294
1295 const int requested_framerate =
1296 source_proxy_->RequestHigherFramerateThan(fps);
1297 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001298 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001299 return;
sprangfda496a2017-06-15 04:21:07 -07001300 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001301 overuse_detector_->OnTargetFramerateUpdated(
1302 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001303 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001304 break;
asapersson13874762017-06-07 00:01:02 -07001305 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001306 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001307 return;
sprangc5d62e22017-04-02 23:53:04 -07001308 }
1309
asaperssond0de2952017-04-21 01:47:31 -07001310 last_adaptation_request_.emplace(adaptation_request);
1311
asapersson09f05612017-05-15 23:40:18 -07001312 UpdateAdaptationStats(reason);
1313
Mirko Bonadei675513b2017-11-09 11:09:25 +01001314 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001315}
1316
Niels Möller213618e2018-07-24 09:29:58 +02001317// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07001318void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001319 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001320 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02001321 encoder_stats_observer_->OnAdaptationChanged(
1322 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1323 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07001324 break;
1325 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02001326 encoder_stats_observer_->OnAdaptationChanged(
1327 VideoStreamEncoderObserver::AdaptationReason::kQuality,
1328 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001329 break;
1330 }
perkj26091b12016-09-01 01:17:40 -07001331}
1332
Niels Möller213618e2018-07-24 09:29:58 +02001333VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07001334 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02001335 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07001336 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001337 switch (reason) {
1338 case kCpu:
1339 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001340 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001341 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001342 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001343 break;
1344 case kQuality:
1345 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1346 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001347 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001348 }
1349 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1350 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001351 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001352 }
1353 break;
sprangc5d62e22017-04-02 23:53:04 -07001354 }
asapersson09f05612017-05-15 23:40:18 -07001355 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001356}
1357
mflodmancc3d4422017-08-03 08:27:51 -07001358VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001359 return adapt_counters_[degradation_preference_];
1360}
1361
mflodmancc3d4422017-08-03 08:27:51 -07001362const VideoStreamEncoder::AdaptCounter&
1363VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001364 return adapt_counters_[degradation_preference_];
1365}
1366
Niels Möller6bb5ab92019-01-11 11:11:10 +01001367void VideoStreamEncoder::RunPostEncode(uint32_t frame_timestamp,
1368 int64_t time_sent_us,
1369 int64_t capture_time_us,
1370 absl::optional<int> encode_durations_us,
1371 int qp,
1372 size_t frame_size_bytes,
1373 bool keyframe) {
1374 if (!encoder_queue_.IsCurrent()) {
1375 encoder_queue_.PostTask([this, frame_timestamp, time_sent_us, qp,
1376 capture_time_us, encode_durations_us,
1377 frame_size_bytes, keyframe] {
1378 RunPostEncode(frame_timestamp, time_sent_us, capture_time_us,
1379 encode_durations_us, qp, frame_size_bytes, keyframe);
1380 });
1381 return;
1382 }
1383
1384 RTC_DCHECK_RUN_ON(&encoder_queue_);
1385 if (frame_size_bytes > 0) {
1386 frame_dropper_.Fill(frame_size_bytes, !keyframe);
1387 }
1388
1389 if (encoder_info_.has_internal_source) {
1390 // Update frame dropper after the fact for internal sources.
1391 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
1392 frame_dropper_.Leak(GetInputFramerateFps());
1393 // Signal to encoder to drop next frame.
1394 if (frame_dropper_.DropFrame()) {
1395 pending_frame_drops_.fetch_add(1);
1396 }
1397 }
1398
1399 overuse_detector_->FrameSent(frame_timestamp, time_sent_us, capture_time_us,
1400 encode_durations_us);
1401 if (quality_scaler_ && qp >= 0)
1402 quality_scaler_->ReportQp(qp);
1403}
1404
asapersson09f05612017-05-15 23:40:18 -07001405// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001406VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001407 fps_counters_.resize(kScaleReasonSize);
1408 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001409 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001410}
1411
mflodmancc3d4422017-08-03 08:27:51 -07001412VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001413
mflodmancc3d4422017-08-03 08:27:51 -07001414std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001415 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001416 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1417 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02001418 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07001419}
1420
Niels Möller213618e2018-07-24 09:29:58 +02001421VideoStreamEncoderObserver::AdaptationSteps
1422VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
1423 VideoStreamEncoderObserver::AdaptationSteps counts;
1424 counts.num_framerate_reductions = fps_counters_[reason];
1425 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07001426 return counts;
1427}
1428
mflodmancc3d4422017-08-03 08:27:51 -07001429void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001430 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001431}
1432
mflodmancc3d4422017-08-03 08:27:51 -07001433void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001434 ++(resolution_counters_[reason]);
1435}
1436
mflodmancc3d4422017-08-03 08:27:51 -07001437void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001438 if (fps_counters_[reason] == 0) {
1439 // Balanced mode: Adapt up is in a different order, switch reason.
1440 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1441 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1442 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1443 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1444 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1445 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1446 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1447 MoveCount(&resolution_counters_, reason);
1448 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1449 }
1450 --(fps_counters_[reason]);
1451 RTC_DCHECK_GE(fps_counters_[reason], 0);
1452}
1453
mflodmancc3d4422017-08-03 08:27:51 -07001454void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001455 if (resolution_counters_[reason] == 0) {
1456 // Balanced mode: Adapt up is in a different order, switch reason.
1457 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1458 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1459 MoveCount(&fps_counters_, reason);
1460 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1461 }
1462 --(resolution_counters_[reason]);
1463 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1464}
1465
mflodmancc3d4422017-08-03 08:27:51 -07001466void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1467 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001468 DecrementFramerate(reason);
1469 // Reset if at max fps (i.e. in case of fewer steps up than down).
1470 if (cur_fps == std::numeric_limits<int>::max())
1471 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001472}
1473
mflodmancc3d4422017-08-03 08:27:51 -07001474int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001475 return Count(fps_counters_);
1476}
1477
mflodmancc3d4422017-08-03 08:27:51 -07001478int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001479 return Count(resolution_counters_);
1480}
1481
mflodmancc3d4422017-08-03 08:27:51 -07001482int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001483 return fps_counters_[reason];
1484}
1485
mflodmancc3d4422017-08-03 08:27:51 -07001486int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001487 return resolution_counters_[reason];
1488}
1489
mflodmancc3d4422017-08-03 08:27:51 -07001490int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001491 return FramerateCount(reason) + ResolutionCount(reason);
1492}
1493
mflodmancc3d4422017-08-03 08:27:51 -07001494int VideoStreamEncoder::AdaptCounter::Count(
1495 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001496 return std::accumulate(counters.begin(), counters.end(), 0);
1497}
1498
mflodmancc3d4422017-08-03 08:27:51 -07001499void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1500 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001501 int to_reason = (from_reason + 1) % kScaleReasonSize;
1502 ++((*counters)[to_reason]);
1503 --((*counters)[from_reason]);
1504}
1505
mflodmancc3d4422017-08-03 08:27:51 -07001506std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001507 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001508 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001509 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1510 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001511 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02001512 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07001513}
1514
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001515} // namespace webrtc