blob: ea59b0aba098ed2497ac22188bdb26902e73ccd8 [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(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100663 std::move(streams), encoder_config_.content_type,
664 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800665
Niels Möller7dc26b72017-12-06 10:27:48 +0100666 // Get the current target framerate, ie the maximum framerate as specified by
667 // the current codec configuration, or any limit imposed by cpu adaption in
668 // maintain-resolution or balanced mode. This is used to make sure overuse
669 // detection doesn't needlessly trigger in low and/or variable framerate
670 // scenarios.
671 int target_framerate = std::min(
672 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
673 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +0200674
675 ConfigureQualityScaler();
kthelgason2bc68642017-02-07 07:02:22 -0800676}
677
mflodmancc3d4422017-08-03 08:27:51 -0700678void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800679 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språnge2fd86a2018-10-24 11:32:39 +0200680 const auto scaling_settings = encoder_->GetEncoderInfo().scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -0700681 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700682 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +0100683 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -0700684
asapersson36e9eb42017-03-31 05:29:12 -0700685 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700686 if (quality_scaler_.get() == nullptr) {
687 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +0100688
Åsa Perssona945aee2018-04-24 16:53:25 +0200689 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200690 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +0200691 if (quality_scaling_experiment_enabled_) {
692 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
693 encoder_config_.codec_type);
694 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200695 // Since the interface is non-public, absl::make_unique can't do this
696 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +0100697 AdaptationObserverInterface* observer = this;
Karl Wiberg918f50c2018-07-05 11:40:33 +0200698 quality_scaler_ = absl::make_unique<QualityScaler>(
Åsa Perssona945aee2018-04-24 16:53:25 +0200699 observer, experimental_thresholds ? *experimental_thresholds
700 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200701 has_seen_first_significant_bwe_change_ = false;
702 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -0800703 }
704 } else {
705 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200706 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800707 }
asapersson09f05612017-05-15 23:40:18 -0700708
Niels Möller213618e2018-07-24 09:29:58 +0200709 encoder_stats_observer_->OnAdaptationChanged(
710 VideoStreamEncoderObserver::AdaptationReason::kNone,
711 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000712}
713
mflodmancc3d4422017-08-03 08:27:51 -0700714void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700715 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700716 VideoFrame incoming_frame = video_frame;
717
718 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700719 int64_t current_time_us = clock_->TimeInMicroseconds();
720 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
721 // In some cases, e.g., when the frame from decoder is fed to encoder,
722 // the timestamp may be set to the future. As the encoding pipeline assumes
723 // capture time to be less than present time, we should reset the capture
724 // timestamps here. Otherwise there may be issues with RTP send stream.
725 if (incoming_frame.timestamp_us() > current_time_us)
726 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700727
728 // Capture time may come from clock with an offset and drift from clock_.
729 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800730 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700731 capture_ntp_time_ms = video_frame.ntp_time_ms();
732 } else if (video_frame.render_time_ms() != 0) {
733 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
734 } else {
nisse1c0dea82017-01-30 02:43:18 -0800735 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700736 }
737 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
738
739 // Convert NTP time, in ms, to RTP timestamp.
740 const int kMsToRtpTimestamp = 90;
741 incoming_frame.set_timestamp(
742 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
743
744 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
745 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100746 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
747 << incoming_frame.ntp_time_ms()
748 << " <= " << last_captured_timestamp_
749 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 01:17:40 -0700750 return;
751 }
752
asapersson6ffb67d2016-09-12 00:10:45 -0700753 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800754 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
755 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700756 log_stats = true;
757 }
758
perkj26091b12016-09-01 01:17:40 -0700759 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200760
761 int64_t post_time_us = rtc::TimeMicros();
762 ++posted_frames_waiting_for_encode_;
763
764 encoder_queue_.PostTask(
765 [this, incoming_frame, post_time_us, log_stats]() {
766 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +0200767 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
768 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200769 ++captured_frame_count_;
770 const int posted_frames_waiting_for_encode =
771 posted_frames_waiting_for_encode_.fetch_sub(1);
772 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
773 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +0200774 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200775 } else {
776 // There is a newer frame in flight. Do not encode this frame.
777 RTC_LOG(LS_VERBOSE)
778 << "Incoming frame dropped due to that the encoder is blocked.";
779 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +0200780 encoder_stats_observer_->OnFrameDropped(
781 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +0200782 }
783 if (log_stats) {
784 RTC_LOG(LS_INFO) << "Number of frames: captured "
785 << captured_frame_count_
786 << ", dropped (due to encoder blocked) "
787 << dropped_frame_count_ << ", interval_ms "
788 << kFrameLogIntervalMs;
789 captured_frame_count_ = 0;
790 dropped_frame_count_ = 0;
791 }
792 });
perkj26091b12016-09-01 01:17:40 -0700793}
794
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200795void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +0200796 encoder_stats_observer_->OnFrameDropped(
797 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200798}
799
mflodmancc3d4422017-08-03 08:27:51 -0700800bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700801 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000802 // Pause video if paused by caller or as long as the network is down or the
803 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700804 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700805 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700806 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000807}
808
mflodmancc3d4422017-08-03 08:27:51 -0700809void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700810 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000811 // Start trace event only on the first frame after encoder is paused.
812 if (!encoder_paused_and_dropped_frame_) {
813 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
814 }
815 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000816}
817
mflodmancc3d4422017-08-03 08:27:51 -0700818void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700819 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000820 // End trace event on first frame after encoder resumes, if frame was dropped.
821 if (encoder_paused_and_dropped_frame_) {
822 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
823 }
824 encoder_paused_and_dropped_frame_ = false;
825}
826
Niels Möller6bb5ab92019-01-11 11:11:10 +0100827VideoBitrateAllocation
828VideoStreamEncoder::GetBitrateAllocationAndNotifyObserver(
829 const uint32_t target_bitrate_bps,
830 uint32_t framerate_fps) {
831 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
832 // might cap the bitrate to the min bitrate configured.
833 VideoBitrateAllocation bitrate_allocation;
834 if (rate_allocator_ && target_bitrate_bps > 0) {
835 bitrate_allocation =
836 rate_allocator_->GetAllocation(target_bitrate_bps, framerate_fps);
837 }
838
839 if (bitrate_observer_ && bitrate_allocation.get_sum_bps() > 0) {
840 bitrate_observer_->OnBitrateAllocationUpdated(bitrate_allocation);
841 }
842
843 return bitrate_allocation;
844}
845
846uint32_t VideoStreamEncoder::GetInputFramerateFps() {
847 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
848 return input_framerate_.Rate(clock_->TimeInMilliseconds())
849 .value_or(default_fps);
850}
851
Sebastian Janssona3177052018-04-10 13:05:49 +0200852void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
853 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700854 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800855
Per21d45d22016-10-30 21:37:57 +0100856 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700857 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700858 video_frame.is_texture() != last_frame_info_->is_texture) {
859 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100860 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
861 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
863 << last_frame_info_->width << "x"
864 << last_frame_info_->height
865 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700866 }
867
Niels Möller4db138e2018-04-19 09:04:13 +0200868 // We have to create then encoder before the frame drop logic,
869 // because the latter depends on encoder_->GetScalingSettings.
870 // According to the testcase
871 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
872 // from GetScalingSettings should enable or disable the frame drop.
873
Niels Möller6bb5ab92019-01-11 11:11:10 +0100874 uint32_t framerate_fps = GetInputFramerateFps();
875
Niels Möller4db138e2018-04-19 09:04:13 +0200876 int64_t now_ms = clock_->TimeInMilliseconds();
877 if (pending_encoder_reconfiguration_) {
878 ReconfigureEncoder();
879 last_parameters_update_ms_.emplace(now_ms);
880 } else if (!last_parameters_update_ms_ ||
881 now_ms - *last_parameters_update_ms_ >=
882 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100883 video_sender_.SetChannelParameters(
884 GetBitrateAllocationAndNotifyObserver(last_observed_bitrate_bps_,
885 framerate_fps),
886 framerate_fps);
Niels Möller4db138e2018-04-19 09:04:13 +0200887 last_parameters_update_ms_.emplace(now_ms);
888 }
889
Sebastian Janssona3177052018-04-10 13:05:49 +0200890 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson875841d2018-01-08 08:49:53 +0100892 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800893 AdaptDown(kQuality);
Åsa Persson875841d2018-01-08 08:49:53 +0100894 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
Niels Möller213618e2018-07-24 09:29:58 +0200895 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +0100896 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200897 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200898 // Storing references to a native buffer risks blocking frame capture.
899 if (video_frame.video_frame_buffer()->type() !=
900 VideoFrameBuffer::Type::kNative) {
901 pending_frame_ = video_frame;
902 pending_frame_post_time_us_ = time_when_posted_us;
903 } else {
904 // Ensure that any previously stored frame is dropped.
905 pending_frame_.reset();
906 }
kthelgason2bc68642017-02-07 07:02:22 -0800907 return;
908 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200909 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800910
perkj26091b12016-09-01 01:17:40 -0700911 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200912 // Storing references to a native buffer risks blocking frame capture.
913 if (video_frame.video_frame_buffer()->type() !=
914 VideoFrameBuffer::Type::kNative) {
915 if (pending_frame_)
916 TraceFrameDropStart();
917 pending_frame_ = video_frame;
918 pending_frame_post_time_us_ = time_when_posted_us;
919 } else {
920 // Ensure that any previously stored frame is dropped.
921 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +0200922 TraceFrameDropStart();
Sebastian Jansson0d70e372018-04-17 13:57:13 +0200923 }
perkj26091b12016-09-01 01:17:40 -0700924 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000925 }
Sebastian Janssona3177052018-04-10 13:05:49 +0200926
927 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +0100928
929 frame_dropper_.Leak(framerate_fps);
930 // Frame dropping is enabled iff frame dropping is not force-disabled, and
931 // rate controller is not trusted.
932 const bool frame_dropping_enabled =
933 !force_disable_frame_dropper_ &&
934 !encoder_info_.has_trusted_rate_controller;
935 frame_dropper_.Enable(frame_dropping_enabled);
936 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
937 RTC_LOG(LS_VERBOSE) << "Drop Frame: "
938 << "target bitrate " << last_observed_bitrate_bps_
939 << ", input frame rate " << framerate_fps;
940 OnDroppedFrame(
941 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
942 return;
943 }
944
Sebastian Janssona3177052018-04-10 13:05:49 +0200945 EncodeVideoFrame(video_frame, time_when_posted_us);
946}
947
948void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
949 int64_t time_when_posted_us) {
950 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700951 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000952
ilnik6b826ef2017-06-16 06:53:48 -0700953 VideoFrame out_frame(video_frame);
954 // Crop frame if needed.
955 if (crop_width_ > 0 || crop_height_ > 0) {
956 int cropped_width = video_frame.width() - crop_width_;
957 int cropped_height = video_frame.height() - crop_height_;
958 rtc::scoped_refptr<I420Buffer> cropped_buffer =
959 I420Buffer::Create(cropped_width, cropped_height);
960 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
961 // happen after SinkWants signaled correctly from ReconfigureEncoder.
962 if (crop_width_ < 4 && crop_height_ < 4) {
963 cropped_buffer->CropAndScaleFrom(
964 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
965 crop_height_ / 2, cropped_width, cropped_height);
966 } else {
967 cropped_buffer->ScaleFrom(
968 *video_frame.video_frame_buffer()->ToI420().get());
969 }
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100970 out_frame = VideoFrame::Builder()
971 .set_video_frame_buffer(cropped_buffer)
972 .set_timestamp_rtp(video_frame.timestamp())
973 .set_timestamp_ms(video_frame.render_time_ms())
974 .set_rotation(video_frame.rotation())
975 .set_id(video_frame.id())
976 .build();
ilnik6b826ef2017-06-16 06:53:48 -0700977 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
978 }
979
Magnus Jedvert26679d62015-04-07 14:07:41 +0200980 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000981 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000982
Niels Möller7dc26b72017-12-06 10:27:48 +0100983 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700984
Erik Språnge2fd86a2018-10-24 11:32:39 +0200985 // Encoder metadata needs to be updated before encode complete callback.
986 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
987 if (info.implementation_name != encoder_info_.implementation_name) {
988 encoder_stats_observer_->OnEncoderImplementationChanged(
989 info.implementation_name);
990 }
991 encoder_info_ = info;
992
Niels Möller6bb5ab92019-01-11 11:11:10 +0100993 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Erik Språngeee39202018-11-15 17:52:43 +0100994 video_sender_.AddVideoFrame(out_frame, nullptr, encoder_info_);
niklase@google.com470e71d2011-07-07 08:21:25 +0000995}
niklase@google.com470e71d2011-07-07 08:21:25 +0000996
mflodmancc3d4422017-08-03 08:27:51 -0700997void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700998 if (!encoder_queue_.IsCurrent()) {
999 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1000 return;
1001 }
1002 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001003 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Peter Boströmcd5c25c2016-04-21 16:48:08 +02001004 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001005}
1006
mflodmancc3d4422017-08-03 08:27:51 -07001007EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001008 const EncodedImage& encoded_image,
1009 const CodecSpecificInfo* codec_specific_info,
1010 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -07001011 // Encoded is called on whatever thread the real encoder implementation run
1012 // on. In the case of hardware encoders, there might be several encoders
1013 // running in parallel on different threads.
Niels Möller213618e2018-07-24 09:29:58 +02001014 encoder_stats_observer_->OnSendEncodedImage(encoded_image,
1015 codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001016
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001017 EncodedImageCallback::Result result =
1018 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001019
Niels Möller7dc26b72017-12-06 10:27:48 +01001020 int64_t time_sent_us = rtc::TimeMicros();
Niels Möller23775882018-08-16 10:24:12 +02001021 uint32_t timestamp = encoded_image.Timestamp();
kthelgason876222f2016-11-29 01:44:11 -08001022 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 16:39:44 +01001023 int64_t capture_time_us =
1024 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
1025
Danil Chapovalovb9b146c2018-06-15 12:28:07 +02001026 absl::optional<int> encode_duration_us;
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001027 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
Niels Möller83dbeac2017-12-14 16:39:44 +01001028 encode_duration_us.emplace(
1029 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
1030 rtc::kNumMicrosecsPerMillisec *
1031 (encoded_image.timing_.encode_finish_ms -
1032 encoded_image.timing_.encode_start_ms));
1033 }
1034
Niels Möller6bb5ab92019-01-11 11:11:10 +01001035 // Run post encode tasks, such as overuse detection and frame rate/drop
1036 // stats for internal encoders.
1037 const size_t frame_size = encoded_image.size();
1038 const bool keyframe = encoded_image._frameType == FrameType::kVideoFrameKey;
1039 RunPostEncode(timestamp, time_sent_us, capture_time_us, encode_duration_us,
1040 qp, frame_size, keyframe);
1041
1042 if (result.error == Result::OK) {
1043 // In case of an internal encoder running on a separate thread, the
1044 // decision to drop a frame might be a frame late and signaled via
1045 // atomic flag. This is because we can't easily wait for the worker thread
1046 // without risking deadlocks, eg during shutdown when the worker thread
1047 // might be waiting for the internal encoder threads to stop.
1048 if (pending_frame_drops_.load() > 0) {
1049 int pending_drops = pending_frame_drops_.fetch_sub(1);
1050 RTC_DCHECK_GT(pending_drops, 0);
1051 result.drop_next_frame = true;
1052 }
1053 }
perkj803d97f2016-11-01 11:45:46 -07001054
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001055 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001056}
1057
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001058void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1059 switch (reason) {
1060 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001061 encoder_stats_observer_->OnFrameDropped(
1062 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001063 encoder_queue_.PostTask([this] {
1064 RTC_DCHECK_RUN_ON(&encoder_queue_);
1065 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001066 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001067 });
1068 break;
1069 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001070 encoder_stats_observer_->OnFrameDropped(
1071 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001072 encoder_queue_.PostTask([this] {
1073 RTC_DCHECK_RUN_ON(&encoder_queue_);
1074 if (quality_scaler_)
1075 quality_scaler_->ReportDroppedFrameByEncoder();
1076 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001077 break;
1078 }
kthelgason876222f2016-11-29 01:44:11 -08001079}
1080
mflodmancc3d4422017-08-03 08:27:51 -07001081void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
1082 uint8_t fraction_lost,
1083 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -07001084 if (!encoder_queue_.IsCurrent()) {
1085 encoder_queue_.PostTask(
1086 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
1087 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
1088 });
1089 return;
1090 }
1091 RTC_DCHECK_RUN_ON(&encoder_queue_);
1092 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1093
Mirko Bonadei675513b2017-11-09 11:09:25 +01001094 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
1095 << " packet loss " << static_cast<int>(fraction_lost)
1096 << " rtt " << round_trip_time_ms;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001097 // On significant changes to BWE at the start of the call,
1098 // enable frame drops to quickly react to jumps in available bandwidth.
1099 if (encoder_start_bitrate_bps_ != 0 &&
1100 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1101 initial_framedrop_on_bwe_enabled_ &&
1102 abs_diff(bitrate_bps, encoder_start_bitrate_bps_) >=
1103 kFramedropThreshold * encoder_start_bitrate_bps_) {
1104 // Reset initial framedrop feature when first real BW estimate arrives.
1105 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1106 // without an actual BW estimate.
1107 initial_framedrop_ = 0;
1108 has_seen_first_significant_bwe_change_ = true;
1109 }
perkj26091b12016-09-01 01:17:40 -07001110
Niels Möller6bb5ab92019-01-11 11:11:10 +01001111 uint32_t framerate_fps = GetInputFramerateFps();
1112 frame_dropper_.SetRates((bitrate_bps + 500) / 1000, framerate_fps);
1113
1114 VideoBitrateAllocation bitrate_allocation =
1115 GetBitrateAllocationAndNotifyObserver(bitrate_bps, framerate_fps);
1116 video_sender_.SetChannelParameters(bitrate_allocation, framerate_fps);
perkj26091b12016-09-01 01:17:40 -07001117
1118 encoder_start_bitrate_bps_ =
1119 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +02001120 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +01001121 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -07001122 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +00001123
sprang552c7c72017-02-13 04:41:45 -08001124 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001125 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1126 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001127 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001128 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001129 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1130 !DropDueToSize(pending_frame_->size())) {
1131 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1132 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1133 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1134 pending_frame_.reset();
1135 }
1136}
1137
1138bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001139 if (initial_framedrop_ < kMaxInitialFramedrop &&
Sebastian Janssona3177052018-04-10 13:05:49 +02001140 encoder_start_bitrate_bps_ > 0) {
1141 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1142 return pixel_count > 320 * 240;
1143 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1144 return pixel_count > 640 * 480;
1145 }
1146 }
1147 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001148}
1149
mflodmancc3d4422017-08-03 08:27:51 -07001150void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001151 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001152 AdaptationRequest adaptation_request = {
1153 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001154 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001155 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001156
sprangc5d62e22017-04-02 23:53:04 -07001157 bool downgrade_requested =
1158 last_adaptation_request_ &&
1159 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1160
sprangc5d62e22017-04-02 23:53:04 -07001161 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001162 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001163 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001164 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001165 if (downgrade_requested &&
1166 adaptation_request.input_pixel_count_ >=
1167 last_adaptation_request_->input_pixel_count_) {
1168 // Don't request lower resolution if the current resolution is not
1169 // lower than the last time we asked for the resolution to be lowered.
1170 return;
1171 }
1172 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001173 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001174 if (adaptation_request.framerate_fps_ <= 0 ||
1175 (downgrade_requested &&
1176 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1177 // If no input fps estimate available, can't determine how to scale down
1178 // framerate. Otherwise, don't request lower framerate if we don't have
1179 // a valid frame rate. Since framerate, unlike resolution, is a measure
1180 // we have to estimate, and can fluctuate naturally over time, don't
1181 // make the same kind of limitations as for resolution, but trust the
1182 // overuse detector to not trigger too often.
1183 return;
1184 }
1185 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001186 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001187 return;
sprang84a37592017-02-10 07:04:27 -08001188 }
sprangc5d62e22017-04-02 23:53:04 -07001189
sprangc5d62e22017-04-02 23:53:04 -07001190 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001191 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001192 // Try scale down framerate, if lower.
1193 int fps = MinFps(last_frame_info_->pixel_count());
1194 if (source_proxy_->RestrictFramerate(fps)) {
1195 GetAdaptCounter().IncrementFramerate(reason);
1196 break;
1197 }
1198 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001199 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001200 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001201 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001202 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001203 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07001204 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07001205 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02001206 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001207 &min_pixels_reached)) {
1208 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02001209 encoder_stats_observer_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -07001210 return;
1211 }
asaperssonf7e294d2017-06-13 23:25:22 -07001212 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001213 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01001214 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001215 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001216 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001217 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1218 adaptation_request.framerate_fps_);
1219 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001220 return;
sprangfda496a2017-06-15 04:21:07 -07001221 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001222 overuse_detector_->OnTargetFramerateUpdated(
1223 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001224 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001225 break;
sprangfda496a2017-06-15 04:21:07 -07001226 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001227 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07001228 RTC_NOTREACHED();
1229 }
1230
asaperssond0de2952017-04-21 01:47:31 -07001231 last_adaptation_request_.emplace(adaptation_request);
1232
asapersson09f05612017-05-15 23:40:18 -07001233 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001234
Mirko Bonadei675513b2017-11-09 11:09:25 +01001235 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001236}
1237
mflodmancc3d4422017-08-03 08:27:51 -07001238void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001239 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001240
1241 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1242 int num_downgrades = adapt_counter.TotalCount(reason);
1243 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001244 return;
asapersson09f05612017-05-15 23:40:18 -07001245 RTC_DCHECK_GT(num_downgrades, 0);
1246
sprangc5d62e22017-04-02 23:53:04 -07001247 AdaptationRequest adaptation_request = {
1248 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001249 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001250 AdaptationRequest::Mode::kAdaptUp};
1251
1252 bool adapt_up_requested =
1253 last_adaptation_request_ &&
1254 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001255
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001256 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07001257 if (adapt_up_requested &&
1258 adaptation_request.input_pixel_count_ <=
1259 last_adaptation_request_->input_pixel_count_) {
1260 // Don't request higher resolution if the current resolution is not
1261 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001262 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001263 }
sprangb1ca0732017-02-01 08:38:12 -08001264 }
sprangc5d62e22017-04-02 23:53:04 -07001265
sprangc5d62e22017-04-02 23:53:04 -07001266 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001267 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001268 // Try scale up framerate, if higher.
1269 int fps = MaxFps(last_frame_info_->pixel_count());
1270 if (source_proxy_->IncreaseFramerate(fps)) {
1271 GetAdaptCounter().DecrementFramerate(reason, fps);
1272 // Reset framerate in case of fewer fps steps down than up.
1273 if (adapt_counter.FramerateCount() == 0 &&
1274 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001275 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001276 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1277 }
1278 break;
1279 }
1280 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001281 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001282 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001283 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07001284 // Scale up resolution.
1285 int pixel_count = adaptation_request.input_pixel_count_;
1286 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001287 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001288 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001289 }
asapersson13874762017-06-07 00:01:02 -07001290 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1291 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001292 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001293 break;
asapersson13874762017-06-07 00:01:02 -07001294 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001295 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07001296 // Scale up framerate.
1297 int fps = adaptation_request.framerate_fps_;
1298 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001299 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001300 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001301 }
sprangfda496a2017-06-15 04:21:07 -07001302
1303 const int requested_framerate =
1304 source_proxy_->RequestHigherFramerateThan(fps);
1305 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001306 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001307 return;
sprangfda496a2017-06-15 04:21:07 -07001308 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001309 overuse_detector_->OnTargetFramerateUpdated(
1310 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001311 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001312 break;
asapersson13874762017-06-07 00:01:02 -07001313 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001314 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07001315 return;
sprangc5d62e22017-04-02 23:53:04 -07001316 }
1317
asaperssond0de2952017-04-21 01:47:31 -07001318 last_adaptation_request_.emplace(adaptation_request);
1319
asapersson09f05612017-05-15 23:40:18 -07001320 UpdateAdaptationStats(reason);
1321
Mirko Bonadei675513b2017-11-09 11:09:25 +01001322 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001323}
1324
Niels Möller213618e2018-07-24 09:29:58 +02001325// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07001326void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001327 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001328 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02001329 encoder_stats_observer_->OnAdaptationChanged(
1330 VideoStreamEncoderObserver::AdaptationReason::kCpu,
1331 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07001332 break;
1333 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02001334 encoder_stats_observer_->OnAdaptationChanged(
1335 VideoStreamEncoderObserver::AdaptationReason::kQuality,
1336 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001337 break;
1338 }
perkj26091b12016-09-01 01:17:40 -07001339}
1340
Niels Möller213618e2018-07-24 09:29:58 +02001341VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07001342 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02001343 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07001344 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001345 switch (reason) {
1346 case kCpu:
1347 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001348 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001349 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02001350 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001351 break;
1352 case kQuality:
1353 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1354 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001355 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001356 }
1357 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1358 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02001359 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07001360 }
1361 break;
sprangc5d62e22017-04-02 23:53:04 -07001362 }
asapersson09f05612017-05-15 23:40:18 -07001363 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001364}
1365
mflodmancc3d4422017-08-03 08:27:51 -07001366VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001367 return adapt_counters_[degradation_preference_];
1368}
1369
mflodmancc3d4422017-08-03 08:27:51 -07001370const VideoStreamEncoder::AdaptCounter&
1371VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001372 return adapt_counters_[degradation_preference_];
1373}
1374
Niels Möller6bb5ab92019-01-11 11:11:10 +01001375void VideoStreamEncoder::RunPostEncode(uint32_t frame_timestamp,
1376 int64_t time_sent_us,
1377 int64_t capture_time_us,
1378 absl::optional<int> encode_durations_us,
1379 int qp,
1380 size_t frame_size_bytes,
1381 bool keyframe) {
1382 if (!encoder_queue_.IsCurrent()) {
1383 encoder_queue_.PostTask([this, frame_timestamp, time_sent_us, qp,
1384 capture_time_us, encode_durations_us,
1385 frame_size_bytes, keyframe] {
1386 RunPostEncode(frame_timestamp, time_sent_us, capture_time_us,
1387 encode_durations_us, qp, frame_size_bytes, keyframe);
1388 });
1389 return;
1390 }
1391
1392 RTC_DCHECK_RUN_ON(&encoder_queue_);
1393 if (frame_size_bytes > 0) {
1394 frame_dropper_.Fill(frame_size_bytes, !keyframe);
1395 }
1396
1397 if (encoder_info_.has_internal_source) {
1398 // Update frame dropper after the fact for internal sources.
1399 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
1400 frame_dropper_.Leak(GetInputFramerateFps());
1401 // Signal to encoder to drop next frame.
1402 if (frame_dropper_.DropFrame()) {
1403 pending_frame_drops_.fetch_add(1);
1404 }
1405 }
1406
1407 overuse_detector_->FrameSent(frame_timestamp, time_sent_us, capture_time_us,
1408 encode_durations_us);
1409 if (quality_scaler_ && qp >= 0)
1410 quality_scaler_->ReportQp(qp);
1411}
1412
asapersson09f05612017-05-15 23:40:18 -07001413// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001414VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001415 fps_counters_.resize(kScaleReasonSize);
1416 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001417 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001418}
1419
mflodmancc3d4422017-08-03 08:27:51 -07001420VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001421
mflodmancc3d4422017-08-03 08:27:51 -07001422std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001423 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001424 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1425 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02001426 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07001427}
1428
Niels Möller213618e2018-07-24 09:29:58 +02001429VideoStreamEncoderObserver::AdaptationSteps
1430VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
1431 VideoStreamEncoderObserver::AdaptationSteps counts;
1432 counts.num_framerate_reductions = fps_counters_[reason];
1433 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07001434 return counts;
1435}
1436
mflodmancc3d4422017-08-03 08:27:51 -07001437void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001438 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001439}
1440
mflodmancc3d4422017-08-03 08:27:51 -07001441void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001442 ++(resolution_counters_[reason]);
1443}
1444
mflodmancc3d4422017-08-03 08:27:51 -07001445void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001446 if (fps_counters_[reason] == 0) {
1447 // Balanced mode: Adapt up is in a different order, switch reason.
1448 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1449 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1450 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1451 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1452 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1453 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1454 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1455 MoveCount(&resolution_counters_, reason);
1456 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1457 }
1458 --(fps_counters_[reason]);
1459 RTC_DCHECK_GE(fps_counters_[reason], 0);
1460}
1461
mflodmancc3d4422017-08-03 08:27:51 -07001462void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001463 if (resolution_counters_[reason] == 0) {
1464 // Balanced mode: Adapt up is in a different order, switch reason.
1465 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1466 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1467 MoveCount(&fps_counters_, reason);
1468 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1469 }
1470 --(resolution_counters_[reason]);
1471 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1472}
1473
mflodmancc3d4422017-08-03 08:27:51 -07001474void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1475 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001476 DecrementFramerate(reason);
1477 // Reset if at max fps (i.e. in case of fewer steps up than down).
1478 if (cur_fps == std::numeric_limits<int>::max())
1479 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001480}
1481
mflodmancc3d4422017-08-03 08:27:51 -07001482int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001483 return Count(fps_counters_);
1484}
1485
mflodmancc3d4422017-08-03 08:27:51 -07001486int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001487 return Count(resolution_counters_);
1488}
1489
mflodmancc3d4422017-08-03 08:27:51 -07001490int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001491 return fps_counters_[reason];
1492}
1493
mflodmancc3d4422017-08-03 08:27:51 -07001494int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001495 return resolution_counters_[reason];
1496}
1497
mflodmancc3d4422017-08-03 08:27:51 -07001498int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001499 return FramerateCount(reason) + ResolutionCount(reason);
1500}
1501
mflodmancc3d4422017-08-03 08:27:51 -07001502int VideoStreamEncoder::AdaptCounter::Count(
1503 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001504 return std::accumulate(counters.begin(), counters.end(), 0);
1505}
1506
mflodmancc3d4422017-08-03 08:27:51 -07001507void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1508 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001509 int to_reason = (from_reason + 1) % kScaleReasonSize;
1510 ++((*counters)[to_reason]);
1511 --((*counters)[from_reason]);
1512}
1513
mflodmancc3d4422017-08-03 08:27:51 -07001514std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001515 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02001516 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07001517 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1518 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001519 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02001520 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07001521}
1522
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001523} // namespace webrtc