blob: 05615f665292f2cc07457ea0e70ccb5d3a5c388d [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>
Evan Shrubsolecc62b162019-09-09 11:26:45 +020014#include <array>
perkj57c21f92016-06-17 07:27:16 -070015#include <limits>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020016#include <memory>
sprangc5d62e22017-04-02 23:53:04 -070017#include <numeric>
Per512ecb32016-09-23 15:52:06 +020018#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000019
Steve Antonbd631a02019-03-28 10:51:27 -070020#include "absl/algorithm/container.h"
Niels Möller4dc66c52018-10-05 14:17:58 +020021#include "api/video/encoded_image.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/video/i420_buffer.h"
Jiawei Ouc2ebe212018-11-08 10:02:56 -080023#include "api/video/video_bitrate_allocator_factory.h"
Evan Shrubsolecc62b162019-09-09 11:26:45 +020024#include "api/video/video_codec_constants.h"
Elad Alon370f93a2019-06-11 14:57:57 +020025#include "api/video_codecs/video_encoder.h"
Sergey Silkin8b9b5f92018-12-10 09:28:53 +010026#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/video_coding/include/video_codec_initializer.h"
Niels Möller6bb5ab92019-01-11 11:11:10 +010028#include "modules/video_coding/utility/default_video_bitrate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/arraysize.h"
30#include "rtc_base/checks.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010031#include "rtc_base/experiments/alr_experiment.h"
Åsa Perssona945aee2018-04-24 16:53:25 +020032#include "rtc_base/experiments/quality_scaling_experiment.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010033#include "rtc_base/experiments/rate_control_settings.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/location.h"
35#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020036#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010037#include "rtc_base/system/fallthrough.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/trace_event.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020040#include "system_wrappers/include/field_trial.h"
nisseea3a7982017-05-15 02:42:11 -070041
niklase@google.com470e71d2011-07-07 08:21:25 +000042namespace webrtc {
43
perkj26091b12016-09-01 01:17:40 -070044namespace {
sprangb1ca0732017-02-01 08:38:12 -080045
asapersson6ffb67d2016-09-12 00:10:45 -070046// Time interval for logging frame counts.
47const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070048const int kMinFramerateFps = 2;
perkj26091b12016-09-01 01:17:40 -070049
Sebastian Janssona3177052018-04-10 13:05:49 +020050// Time to keep a single cached pending frame in paused state.
51const int64_t kPendingFrameTimeoutMs = 1000;
52
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020053const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
Niels Möller6bb5ab92019-01-11 11:11:10 +010054constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020055
kthelgason2bc68642017-02-07 07:02:22 -080056// The maximum number of frames to drop at beginning of stream
57// to try and achieve desired bitrate.
58const int kMaxInitialFramedrop = 4;
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020059// When the first change in BWE above this threshold occurs,
60// enable DropFrameDueToSize logic.
61const float kFramedropThreshold = 0.3;
kthelgason2bc68642017-02-07 07:02:22 -080062
Niels Möller6bb5ab92019-01-11 11:11:10 +010063// Averaging window spanning 90 frames at default 30fps, matching old media
64// optimization module defaults.
65const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
66
Erik Språngb7cb7b52019-02-26 15:52:33 +010067const size_t kDefaultPayloadSize = 1440;
68
Niels Möllerfe407b72019-09-10 10:48:48 +020069const int64_t kParameterUpdateIntervalMs = 1000;
70
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020071uint32_t abs_diff(uint32_t a, uint32_t b) {
72 return (a < b) ? b - a : a - b;
73}
74
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070075bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
76 return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
77 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070078}
79
Taylor Brandstetter49fcc102018-05-16 14:20:41 -070080bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
81 return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
82 degradation_preference == DegradationPreference::BALANCED;
asapersson09f05612017-05-15 23:40:18 -070083}
84
Niels Möllerd1f7eb62018-03-28 16:40:58 +020085// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
86// pipelining encoders better (multiple input frames before something comes
87// out). This should effectively turn off CPU adaptations for systems that
88// remotely cope with the load right now.
89CpuOveruseOptions GetCpuOveruseOptions(
Niels Möller213618e2018-07-24 09:29:58 +020090 const VideoStreamEncoderSettings& settings,
Niels Möller4db138e2018-04-19 09:04:13 +020091 bool full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020092 CpuOveruseOptions options;
93
Niels Möller4db138e2018-04-19 09:04:13 +020094 if (full_overuse_time) {
Niels Möllerd1f7eb62018-03-28 16:40:58 +020095 options.low_encode_usage_threshold_percent = 150;
96 options.high_encode_usage_threshold_percent = 200;
97 }
98 if (settings.experiment_cpu_load_estimator) {
99 options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
100 }
101
102 return options;
103}
104
Sergey Silkin5ee69672019-07-02 14:18:34 +0200105bool RequiresEncoderReset(const VideoCodec& prev_send_codec,
106 const VideoCodec& new_send_codec,
107 bool was_encode_called_since_last_initialization) {
108 // Does not check max/minBitrate or maxFramerate.
109 if (new_send_codec.codecType != prev_send_codec.codecType ||
110 new_send_codec.width != prev_send_codec.width ||
111 new_send_codec.height != prev_send_codec.height ||
112 new_send_codec.qpMax != prev_send_codec.qpMax ||
Erik Språngb7cb7b52019-02-26 15:52:33 +0100113 new_send_codec.numberOfSimulcastStreams !=
Sergey Silkin5ee69672019-07-02 14:18:34 +0200114 prev_send_codec.numberOfSimulcastStreams ||
115 new_send_codec.mode != prev_send_codec.mode) {
116 return true;
117 }
118
119 if (!was_encode_called_since_last_initialization &&
120 (new_send_codec.startBitrate != prev_send_codec.startBitrate)) {
121 // If start bitrate has changed reconfigure encoder only if encoding had not
122 // yet started.
Erik Språngb7cb7b52019-02-26 15:52:33 +0100123 return true;
124 }
125
126 switch (new_send_codec.codecType) {
127 case kVideoCodecVP8:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200128 if (new_send_codec.VP8() != prev_send_codec.VP8()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100129 return true;
130 }
131 break;
132
133 case kVideoCodecVP9:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200134 if (new_send_codec.VP9() != prev_send_codec.VP9()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100135 return true;
136 }
137 break;
138
139 case kVideoCodecH264:
Sergey Silkin5ee69672019-07-02 14:18:34 +0200140 if (new_send_codec.H264() != prev_send_codec.H264()) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100141 return true;
142 }
143 break;
144
145 default:
146 break;
147 }
148
149 for (unsigned char i = 0; i < new_send_codec.numberOfSimulcastStreams; ++i) {
Sergey Silkin5ee69672019-07-02 14:18:34 +0200150 if (new_send_codec.simulcastStream[i].width !=
151 prev_send_codec.simulcastStream[i].width ||
152 new_send_codec.simulcastStream[i].height !=
153 prev_send_codec.simulcastStream[i].height ||
154 new_send_codec.simulcastStream[i].numberOfTemporalLayers !=
155 prev_send_codec.simulcastStream[i].numberOfTemporalLayers ||
156 new_send_codec.simulcastStream[i].qpMax !=
157 prev_send_codec.simulcastStream[i].qpMax ||
158 new_send_codec.simulcastStream[i].active !=
159 prev_send_codec.simulcastStream[i].active) {
Erik Språngb7cb7b52019-02-26 15:52:33 +0100160 return true;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200161 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100162 }
163 return false;
164}
Erik Språng6a7baa72019-02-26 18:31:00 +0100165
166std::array<uint8_t, 2> GetExperimentGroups() {
167 std::array<uint8_t, 2> experiment_groups;
168 absl::optional<AlrExperimentSettings> experiment_settings =
169 AlrExperimentSettings::CreateFromFieldTrial(
170 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
171 if (experiment_settings) {
172 experiment_groups[0] = experiment_settings->group_id + 1;
173 } else {
174 experiment_groups[0] = 0;
175 }
176 experiment_settings = AlrExperimentSettings::CreateFromFieldTrial(
177 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
178 if (experiment_settings) {
179 experiment_groups[1] = experiment_settings->group_id + 1;
180 } else {
181 experiment_groups[1] = 0;
182 }
183 return experiment_groups;
184}
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100185
186// Limit allocation across TLs in bitrate allocation according to number of TLs
187// in EncoderInfo.
188VideoBitrateAllocation UpdateAllocationFromEncoderInfo(
189 const VideoBitrateAllocation& allocation,
190 const VideoEncoder::EncoderInfo& encoder_info) {
191 if (allocation.get_sum_bps() == 0) {
192 return allocation;
193 }
194 VideoBitrateAllocation new_allocation;
195 for (int si = 0; si < kMaxSpatialLayers; ++si) {
196 if (encoder_info.fps_allocation[si].size() == 1 &&
197 allocation.IsSpatialLayerUsed(si)) {
198 // One TL is signalled to be used by the encoder. Do not distribute
199 // bitrate allocation across TLs (use sum at ti:0).
200 new_allocation.SetBitrate(si, 0, allocation.GetSpatialLayerSum(si));
201 } else {
202 for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
203 if (allocation.HasBitrate(si, ti))
204 new_allocation.SetBitrate(si, ti, allocation.GetBitrate(si, ti));
205 }
206 }
207 }
208 return new_allocation;
209}
perkj26091b12016-09-01 01:17:40 -0700210} // namespace
211
perkja49cbd32016-09-16 07:53:41 -0700212// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700213// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
214// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700215// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700216class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700217 public:
mflodmancc3d4422017-08-03 08:27:51 -0700218 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
219 : video_stream_encoder_(video_stream_encoder),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700220 degradation_preference_(DegradationPreference::DISABLED),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200221 source_(nullptr),
222 max_framerate_(std::numeric_limits<int>::max()) {}
perkja49cbd32016-09-16 07:53:41 -0700223
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700224 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
225 const DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700226 // Called on libjingle's worker thread.
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200227 RTC_DCHECK_RUN_ON(&main_checker_);
perkja49cbd32016-09-16 07:53:41 -0700228 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700229 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700230 {
231 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700232 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700233 old_source = source_;
234 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700235 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700236 }
237
238 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700239 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700240 }
241
242 if (!source) {
243 return;
244 }
245
mflodmancc3d4422017-08-03 08:27:51 -0700246 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700247 }
248
Åsa Persson8c1bf952018-09-13 10:42:19 +0200249 void SetMaxFramerate(int max_framerate) {
250 RTC_DCHECK_GT(max_framerate, 0);
251 rtc::CritScope lock(&crit_);
252 if (max_framerate == max_framerate_)
253 return;
254
255 RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
256 max_framerate_ = max_framerate;
257 if (source_) {
258 source_->AddOrUpdateSink(video_stream_encoder_,
259 GetActiveSinkWantsInternal());
260 }
261 }
262
perkj803d97f2016-11-01 11:45:46 -0700263 void SetWantsRotationApplied(bool rotation_applied) {
264 rtc::CritScope lock(&crit_);
265 sink_wants_.rotation_applied = rotation_applied;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200266 if (source_) {
267 source_->AddOrUpdateSink(video_stream_encoder_,
268 GetActiveSinkWantsInternal());
269 }
sprangc5d62e22017-04-02 23:53:04 -0700270 }
271
sprangfda496a2017-06-15 04:21:07 -0700272 rtc::VideoSinkWants GetActiveSinkWants() {
273 rtc::CritScope lock(&crit_);
274 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700275 }
276
asaperssonf7e294d2017-06-13 23:25:22 -0700277 void ResetPixelFpsCount() {
278 rtc::CritScope lock(&crit_);
279 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
280 sink_wants_.target_pixel_count.reset();
281 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
282 if (source_)
Åsa Persson8c1bf952018-09-13 10:42:19 +0200283 source_->AddOrUpdateSink(video_stream_encoder_,
284 GetActiveSinkWantsInternal());
asaperssonf7e294d2017-06-13 23:25:22 -0700285 }
286
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100287 bool RequestResolutionLowerThan(int pixel_count,
288 int min_pixels_per_frame,
289 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700290 // Called on the encoder task queue.
291 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700292 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700293 // This can happen since |degradation_preference_| is set on libjingle's
294 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700295 return false;
perkj803d97f2016-11-01 11:45:46 -0700296 }
asapersson13874762017-06-07 00:01:02 -0700297 // The input video frame size will have a resolution less than or equal to
298 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800299 const int pixels_wanted = (pixel_count * 3) / 5;
Åsa Perssonc3ed6302017-11-16 14:04:52 +0100300 if (pixels_wanted >= sink_wants_.max_pixel_count) {
301 return false;
302 }
303 if (pixels_wanted < min_pixels_per_frame) {
304 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700305 return false;
asapersson13874762017-06-07 00:01:02 -0700306 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100307 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
308 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700309 sink_wants_.max_pixel_count = pixels_wanted;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200310 sink_wants_.target_pixel_count = absl::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700311 source_->AddOrUpdateSink(video_stream_encoder_,
312 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700313 return true;
sprangc5d62e22017-04-02 23:53:04 -0700314 }
315
sprangfda496a2017-06-15 04:21:07 -0700316 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700317 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700318 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700319 int framerate_wanted = (fps * 2) / 3;
320 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700321 }
322
Sergey Silkin41c650b2019-10-14 13:12:19 +0200323 int GetHigherResolutionThan(int pixel_count) const {
324 // On step down we request at most 3/5 the pixel count of the previous
325 // resolution, so in order to take "one step up" we request a resolution
326 // as close as possible to 5/3 of the current resolution. The actual pixel
327 // count selected depends on the capabilities of the source. In order to
328 // not take a too large step up, we cap the requested pixel count to be at
329 // most four time the current number of pixels.
330 return (pixel_count * 5) / 3;
331 }
332
asapersson13874762017-06-07 00:01:02 -0700333 bool RequestHigherResolutionThan(int pixel_count) {
334 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700335 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700336 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700337 // This can happen since |degradation_preference_| is set on libjingle's
338 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700339 return false;
perkj803d97f2016-11-01 11:45:46 -0700340 }
asapersson13874762017-06-07 00:01:02 -0700341 int max_pixels_wanted = pixel_count;
342 if (max_pixels_wanted != std::numeric_limits<int>::max())
343 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700344
asapersson13874762017-06-07 00:01:02 -0700345 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
346 return false;
347
348 sink_wants_.max_pixel_count = max_pixels_wanted;
349 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700350 // Remove any constraints.
351 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700352 } else {
Sergey Silkin41c650b2019-10-14 13:12:19 +0200353 sink_wants_.target_pixel_count = GetHigherResolutionThan(pixel_count);
sprangc5d62e22017-04-02 23:53:04 -0700354 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100355 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
356 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700357 source_->AddOrUpdateSink(video_stream_encoder_,
358 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700359 return true;
sprangc5d62e22017-04-02 23:53:04 -0700360 }
361
sprangfda496a2017-06-15 04:21:07 -0700362 // Request upgrade in framerate. Returns the new requested frame, or -1 if
363 // no change requested. Note that maxint may be returned if limits due to
364 // adaptation requests are removed completely. In that case, consider
365 // |max_framerate_| to be the current limit (assuming the capturer complies).
366 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700367 // Called on the encoder task queue.
368 // The input frame rate will be scaled up to the last step, with rounding.
369 int framerate_wanted = fps;
370 if (fps != std::numeric_limits<int>::max())
371 framerate_wanted = (fps * 3) / 2;
372
sprangfda496a2017-06-15 04:21:07 -0700373 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700374 }
375
376 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700377 // Called on the encoder task queue.
378 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700379 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
380 return false;
381
382 const int fps_wanted = std::max(kMinFramerateFps, fps);
383 if (fps_wanted >= sink_wants_.max_framerate_fps)
384 return false;
385
Mirko Bonadei675513b2017-11-09 11:09:25 +0100386 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700387 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700388 source_->AddOrUpdateSink(video_stream_encoder_,
389 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700390 return true;
391 }
392
393 bool IncreaseFramerate(int fps) {
394 // Called on the encoder task queue.
395 rtc::CritScope lock(&crit_);
396 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
397 return false;
398
399 const int fps_wanted = std::max(kMinFramerateFps, fps);
400 if (fps_wanted <= sink_wants_.max_framerate_fps)
401 return false;
402
Mirko Bonadei675513b2017-11-09 11:09:25 +0100403 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700404 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700405 source_->AddOrUpdateSink(video_stream_encoder_,
406 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700407 return true;
perkj803d97f2016-11-01 11:45:46 -0700408 }
409
perkja49cbd32016-09-16 07:53:41 -0700410 private:
sprangfda496a2017-06-15 04:21:07 -0700411 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700412 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700413 rtc::VideoSinkWants wants = sink_wants_;
414 // Clear any constraints from the current sink wants that don't apply to
415 // the used degradation_preference.
416 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700417 case DegradationPreference::BALANCED:
sprangfda496a2017-06-15 04:21:07 -0700418 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700419 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangfda496a2017-06-15 04:21:07 -0700420 wants.max_framerate_fps = std::numeric_limits<int>::max();
421 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700422 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangfda496a2017-06-15 04:21:07 -0700423 wants.max_pixel_count = std::numeric_limits<int>::max();
424 wants.target_pixel_count.reset();
425 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700426 case DegradationPreference::DISABLED:
sprangfda496a2017-06-15 04:21:07 -0700427 wants.max_pixel_count = std::numeric_limits<int>::max();
428 wants.target_pixel_count.reset();
429 wants.max_framerate_fps = std::numeric_limits<int>::max();
430 }
Åsa Persson8c1bf952018-09-13 10:42:19 +0200431 // Limit to configured max framerate.
432 wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
sprangfda496a2017-06-15 04:21:07 -0700433 return wants;
434 }
435
perkja49cbd32016-09-16 07:53:41 -0700436 rtc::CriticalSection crit_;
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200437 SequenceChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700438 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700439 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700440 DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
danilchapa37de392017-09-09 04:17:22 -0700441 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
Åsa Persson8c1bf952018-09-13 10:42:19 +0200442 int max_framerate_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700443
444 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
445};
446
Erik Språng4c6ca302019-04-08 15:14:01 +0200447VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings()
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200448 : rate_control(),
Florent Castellia8336d32019-09-09 13:36:55 +0200449 encoder_target(DataRate::Zero()),
450 stable_encoder_target(DataRate::Zero()) {}
Erik Språng4c6ca302019-04-08 15:14:01 +0200451
452VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings(
453 const VideoBitrateAllocation& bitrate,
454 double framerate_fps,
455 DataRate bandwidth_allocation,
Florent Castellia8336d32019-09-09 13:36:55 +0200456 DataRate encoder_target,
457 DataRate stable_encoder_target)
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200458 : rate_control(bitrate, framerate_fps, bandwidth_allocation),
Florent Castellia8336d32019-09-09 13:36:55 +0200459 encoder_target(encoder_target),
460 stable_encoder_target(stable_encoder_target) {}
Erik Språng4c6ca302019-04-08 15:14:01 +0200461
462bool VideoStreamEncoder::EncoderRateSettings::operator==(
463 const EncoderRateSettings& rhs) const {
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200464 return rate_control == rhs.rate_control &&
Florent Castellia8336d32019-09-09 13:36:55 +0200465 encoder_target == rhs.encoder_target &&
466 stable_encoder_target == rhs.stable_encoder_target;
Erik Språng4c6ca302019-04-08 15:14:01 +0200467}
468
469bool VideoStreamEncoder::EncoderRateSettings::operator!=(
470 const EncoderRateSettings& rhs) const {
471 return !(*this == rhs);
472}
473
Åsa Persson0122e842017-10-16 12:19:23 +0200474VideoStreamEncoder::VideoStreamEncoder(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100475 Clock* clock,
Åsa Persson0122e842017-10-16 12:19:23 +0200476 uint32_t number_of_cores,
Niels Möller213618e2018-07-24 09:29:58 +0200477 VideoStreamEncoderObserver* encoder_stats_observer,
478 const VideoStreamEncoderSettings& settings,
Sebastian Jansson74682c12019-03-01 11:50:20 +0100479 std::unique_ptr<OveruseFrameDetector> overuse_detector,
480 TaskQueueFactory* task_queue_factory)
perkj26091b12016-09-01 01:17:40 -0700481 : shutdown_event_(true /* manual_reset */, false),
482 number_of_cores_(number_of_cores),
Kári Tristan Helgason639602a2018-08-02 10:51:40 +0200483 initial_framedrop_(0),
484 initial_framedrop_on_bwe_enabled_(
485 webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
Åsa Perssone644a032019-11-08 15:56:00 +0100486 quality_rampup_done_(false),
487 quality_rampup_experiment_(QualityRampupExperiment::ParseSettings()),
Åsa Perssona945aee2018-04-24 16:53:25 +0200488 quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
perkja49cbd32016-09-16 07:53:41 -0700489 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200490 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700491 settings_(settings),
Erik Språng7ca375c2019-02-06 16:20:17 +0100492 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200493 quality_scaler_settings_(QualityScalerSettings::ParseFromFieldTrials()),
Niels Möller73f29cb2018-01-31 16:09:31 +0100494 overuse_detector_(std::move(overuse_detector)),
Niels Möller213618e2018-07-24 09:29:58 +0200495 encoder_stats_observer_(encoder_stats_observer),
Erik Språng6a7baa72019-02-26 18:31:00 +0100496 encoder_initialized_(false),
sprangfda496a2017-06-15 04:21:07 -0700497 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700498 pending_encoder_reconfiguration_(false),
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000499 pending_encoder_creation_(false),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200500 crop_width_(0),
501 crop_height_(0),
perkj26091b12016-09-01 01:17:40 -0700502 encoder_start_bitrate_bps_(0),
Åsa Persson139f4dc2019-08-02 09:29:58 +0200503 set_start_bitrate_bps_(0),
504 set_start_bitrate_time_ms_(0),
505 has_seen_first_bwe_drop_(false),
Pera48ddb72016-09-29 11:48:50 +0200506 max_data_payload_length_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000507 encoder_paused_and_dropped_frame_(false),
Sergey Silkin5ee69672019-07-02 14:18:34 +0200508 was_encode_called_since_last_initialization_(false),
philipele8ed8302019-07-03 11:53:48 +0200509 encoder_failed_(false),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100510 clock_(clock),
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700511 degradation_preference_(DegradationPreference::DISABLED),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700512 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700513 last_captured_timestamp_(0),
514 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
515 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700516 last_frame_log_ms_(clock_->TimeInMilliseconds()),
517 captured_frame_count_(0),
518 dropped_frame_count_(0),
Erik Språnge2fd86a2018-10-24 11:32:39 +0200519 pending_frame_post_time_us_(0),
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100520 accumulated_update_rect_{0, 0, 0, 0},
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +0100521 accumulated_update_rect_is_valid_(true),
sprang1a646ee2016-12-01 06:34:11 -0800522 bitrate_observer_(nullptr),
Elad Alon8f01c4e2019-06-28 15:19:43 +0200523 fec_controller_override_(nullptr),
Niels Möller6bb5ab92019-01-11 11:11:10 +0100524 force_disable_frame_dropper_(false),
525 input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
526 pending_frame_drops_(0),
Niels Möller8f7ce222019-03-21 15:43:58 +0100527 next_frame_types_(1, VideoFrameType::kVideoFrameDelta),
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200528 frame_encode_metadata_writer_(this),
Erik Språng6a7baa72019-02-26 18:31:00 +0100529 experiment_groups_(GetExperimentGroups()),
philipelda5aa4d2019-04-26 13:37:37 +0200530 next_frame_id_(0),
philipele5d0fe02019-10-15 11:02:53 +0200531 encoder_switch_experiment_(ParseEncoderSwitchFieldTrial()),
532 encoder_switch_requested_(false),
Sebastian Jansson74682c12019-03-01 11:50:20 +0100533 encoder_queue_(task_queue_factory->CreateTaskQueue(
534 "EncoderQueue",
philipele5d0fe02019-10-15 11:02:53 +0200535 TaskQueueFactory::Priority::NORMAL)) {
Niels Möller213618e2018-07-24 09:29:58 +0200536 RTC_DCHECK(encoder_stats_observer);
Niels Möller73f29cb2018-01-31 16:09:31 +0100537 RTC_DCHECK(overuse_detector_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100538 RTC_DCHECK_GE(number_of_cores, 1);
philipelda5aa4d2019-04-26 13:37:37 +0200539
540 for (auto& state : encoder_buffer_state_)
541 state.fill(std::numeric_limits<int64_t>::max());
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000542}
543
mflodmancc3d4422017-08-03 08:27:51 -0700544VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700545 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700546 RTC_DCHECK(shutdown_event_.Wait(0))
547 << "Must call ::Stop() before destruction.";
548}
549
mflodmancc3d4422017-08-03 08:27:51 -0700550void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700551 RTC_DCHECK_RUN_ON(&thread_checker_);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700552 source_proxy_->SetSource(nullptr, DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700553 encoder_queue_.PostTask([this] {
554 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700555 overuse_detector_->StopCheckForOveruse();
Erik Språngb7cb7b52019-02-26 15:52:33 +0100556 rate_allocator_ = nullptr;
sprang1a646ee2016-12-01 06:34:11 -0800557 bitrate_observer_ = nullptr;
Erik Språng6a7baa72019-02-26 18:31:00 +0100558 ReleaseEncoder();
kthelgason876222f2016-11-29 01:44:11 -0800559 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700560 shutdown_event_.Set();
561 });
562
563 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700564}
565
Niels Möller0327c2d2018-05-21 14:09:31 +0200566void VideoStreamEncoder::SetBitrateAllocationObserver(
sprang1a646ee2016-12-01 06:34:11 -0800567 VideoBitrateAllocationObserver* bitrate_observer) {
568 RTC_DCHECK_RUN_ON(&thread_checker_);
569 encoder_queue_.PostTask([this, bitrate_observer] {
570 RTC_DCHECK_RUN_ON(&encoder_queue_);
571 RTC_DCHECK(!bitrate_observer_);
572 bitrate_observer_ = bitrate_observer;
573 });
574}
575
Elad Alon8f01c4e2019-06-28 15:19:43 +0200576void VideoStreamEncoder::SetFecControllerOverride(
577 FecControllerOverride* fec_controller_override) {
578 encoder_queue_.PostTask([this, fec_controller_override] {
579 RTC_DCHECK_RUN_ON(&encoder_queue_);
580 RTC_DCHECK(!fec_controller_override_);
581 fec_controller_override_ = fec_controller_override;
582 if (encoder_) {
583 encoder_->SetFecControllerOverride(fec_controller_override_);
584 }
585 });
586}
587
mflodmancc3d4422017-08-03 08:27:51 -0700588void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700589 rtc::VideoSourceInterface<VideoFrame>* source,
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700590 const DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700591 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700592 source_proxy_->SetSource(source, degradation_preference);
593 encoder_queue_.PostTask([this, degradation_preference] {
594 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700595 if (degradation_preference_ != degradation_preference) {
596 // Reset adaptation state, so that we're not tricked into thinking there's
597 // an already pending request of the same type.
598 last_adaptation_request_.reset();
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700599 if (degradation_preference == DegradationPreference::BALANCED ||
600 degradation_preference_ == DegradationPreference::BALANCED) {
asaperssonf7e294d2017-06-13 23:25:22 -0700601 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
602 // AdaptCounter for all modes.
603 source_proxy_->ResetPixelFpsCount();
604 adapt_counters_.clear();
605 }
sprangc5d62e22017-04-02 23:53:04 -0700606 }
sprangb1ca0732017-02-01 08:38:12 -0800607 degradation_preference_ = degradation_preference;
Niels Möller4db138e2018-04-19 09:04:13 +0200608
Mirta Dvornicic1ec2a162018-12-10 09:47:34 +0000609 if (encoder_)
Erik Språng7ca375c2019-02-06 16:20:17 +0100610 ConfigureQualityScaler(encoder_->GetEncoderInfo());
Niels Möller4db138e2018-04-19 09:04:13 +0200611
Niels Möller7dc26b72017-12-06 10:27:48 +0100612 if (!IsFramerateScalingEnabled(degradation_preference) &&
613 max_framerate_ != -1) {
614 // If frame rate scaling is no longer allowed, remove any potential
615 // allowance for longer frame intervals.
616 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
617 }
perkj803d97f2016-11-01 11:45:46 -0700618 });
perkja49cbd32016-09-16 07:53:41 -0700619}
620
mflodmancc3d4422017-08-03 08:27:51 -0700621void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700622 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700623 encoder_queue_.PostTask([this, sink] {
624 RTC_DCHECK_RUN_ON(&encoder_queue_);
625 sink_ = sink;
626 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000627}
628
mflodmancc3d4422017-08-03 08:27:51 -0700629void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700630 encoder_queue_.PostTask([this, start_bitrate_bps] {
631 RTC_DCHECK_RUN_ON(&encoder_queue_);
632 encoder_start_bitrate_bps_ = start_bitrate_bps;
Åsa Persson139f4dc2019-08-02 09:29:58 +0200633 set_start_bitrate_bps_ = start_bitrate_bps;
634 set_start_bitrate_time_ms_ = clock_->TimeInMilliseconds();
perkj26091b12016-09-01 01:17:40 -0700635 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000636}
Peter Boström00b9d212016-05-19 16:59:03 +0200637
mflodmancc3d4422017-08-03 08:27:51 -0700638void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
Niels Möllerf1338562018-04-26 09:51:47 +0200639 size_t max_data_payload_length) {
Yves Gerey665174f2018-06-19 15:03:05 +0200640 encoder_queue_.PostTask(
Sebastian Jansson86314cf2019-09-17 20:29:59 +0200641 [this, config = std::move(config), max_data_payload_length]() mutable {
642 RTC_DCHECK_RUN_ON(&encoder_queue_);
643 RTC_DCHECK(sink_);
644 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
perkj26091b12016-09-01 01:17:40 -0700645
Sebastian Jansson86314cf2019-09-17 20:29:59 +0200646 pending_encoder_creation_ =
647 (!encoder_ || encoder_config_.video_format != config.video_format ||
648 max_data_payload_length_ != max_data_payload_length);
649 encoder_config_ = std::move(config);
650 max_data_payload_length_ = max_data_payload_length;
651 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200652
Sebastian Jansson86314cf2019-09-17 20:29:59 +0200653 // Reconfigure the encoder now if the encoder has an internal source or
654 // if the frame resolution is known. Otherwise, the reconfiguration is
655 // deferred until the next frame to minimize the number of
656 // reconfigurations. The codec configuration depends on incoming video
657 // frame size.
658 if (last_frame_info_) {
659 ReconfigureEncoder();
660 } else {
661 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
662 encoder_config_.video_format);
663 if (HasInternalSource()) {
664 last_frame_info_ = VideoFrameInfo(176, 144, false);
665 ReconfigureEncoder();
666 }
667 }
668 });
perkjfa10b552016-10-02 23:45:26 -0700669}
perkj26091b12016-09-01 01:17:40 -0700670
Sergey Silkin6456e352019-07-08 17:56:40 +0200671static absl::optional<VideoEncoder::ResolutionBitrateLimits>
672GetEncoderBitrateLimits(const VideoEncoder::EncoderInfo& encoder_info,
673 int frame_size_pixels) {
674 std::vector<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
675 encoder_info.resolution_bitrate_limits;
676
677 // Sort the list of bitrate limits by resolution.
678 sort(bitrate_limits.begin(), bitrate_limits.end(),
679 [](const VideoEncoder::ResolutionBitrateLimits& lhs,
680 const VideoEncoder::ResolutionBitrateLimits& rhs) {
681 return lhs.frame_size_pixels < rhs.frame_size_pixels;
682 });
683
684 for (size_t i = 0; i < bitrate_limits.size(); ++i) {
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200685 RTC_DCHECK_GT(bitrate_limits[i].min_bitrate_bps, 0);
686 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
687 bitrate_limits[i].min_bitrate_bps);
688 RTC_DCHECK_GT(bitrate_limits[i].max_bitrate_bps,
689 bitrate_limits[i].min_start_bitrate_bps);
Sergey Silkin6456e352019-07-08 17:56:40 +0200690 if (i > 0) {
691 // The bitrate limits aren't expected to decrease with resolution.
692 RTC_DCHECK_GE(bitrate_limits[i].min_bitrate_bps,
693 bitrate_limits[i - 1].min_bitrate_bps);
694 RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
695 bitrate_limits[i - 1].min_start_bitrate_bps);
696 RTC_DCHECK_GE(bitrate_limits[i].max_bitrate_bps,
697 bitrate_limits[i - 1].max_bitrate_bps);
698 }
699
700 if (bitrate_limits[i].frame_size_pixels >= frame_size_pixels) {
701 return absl::optional<VideoEncoder::ResolutionBitrateLimits>(
702 bitrate_limits[i]);
703 }
704 }
705
706 return absl::nullopt;
707}
708
Seth Hampsoncc7125f2018-02-02 08:46:16 -0800709// TODO(bugs.webrtc.org/8807): Currently this always does a hard
710// reconfiguration, but this isn't always necessary. Add in logic to only update
711// the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
712// "soft" reconfiguration.
mflodmancc3d4422017-08-03 08:27:51 -0700713void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700714 RTC_DCHECK(pending_encoder_reconfiguration_);
philipeld9cc8c02019-09-16 14:53:40 +0200715
716 if (encoder_switch_experiment_.IsPixelCountBelowThreshold(
717 last_frame_info_->width * last_frame_info_->height) &&
718 !encoder_switch_requested_ && settings_.encoder_switch_request_callback) {
719 EncoderSwitchRequestCallback::Config conf;
720 conf.codec_name = encoder_switch_experiment_.to_codec;
721 conf.param = encoder_switch_experiment_.to_param;
722 conf.value = encoder_switch_experiment_.to_value;
723 settings_.encoder_switch_request_callback->RequestEncoderSwitch(conf);
724
725 encoder_switch_requested_ = true;
726 }
727
perkjfa10b552016-10-02 23:45:26 -0700728 std::vector<VideoStream> streams =
729 encoder_config_.video_stream_factory->CreateEncoderStreams(
730 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700731
ilnik6b826ef2017-06-16 06:53:48 -0700732 // TODO(ilnik): If configured resolution is significantly less than provided,
733 // e.g. because there are not enough SSRCs for all simulcast streams,
734 // signal new resolutions via SinkWants to video source.
735
736 // Stream dimensions may be not equal to given because of a simulcast
737 // restrictions.
Steve Antonbd631a02019-03-28 10:51:27 -0700738 auto highest_stream = absl::c_max_element(
739 streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
Florent Castelli450b5482018-11-29 17:32:47 +0100740 return std::tie(a.width, a.height) < std::tie(b.width, b.height);
741 });
742 int highest_stream_width = static_cast<int>(highest_stream->width);
743 int highest_stream_height = static_cast<int>(highest_stream->height);
ilnik6b826ef2017-06-16 06:53:48 -0700744 // Dimension may be reduced to be, e.g. divisible by 4.
745 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
746 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
747 crop_width_ = last_frame_info_->width - highest_stream_width;
748 crop_height_ = last_frame_info_->height - highest_stream_height;
749
Sergey Silkin6456e352019-07-08 17:56:40 +0200750 bool encoder_reset_required = false;
751 if (pending_encoder_creation_) {
752 // Destroy existing encoder instance before creating a new one. Otherwise
753 // attempt to create another instance will fail if encoder factory
754 // supports only single instance of encoder of given type.
755 encoder_.reset();
756
757 encoder_ = settings_.encoder_factory->CreateVideoEncoder(
758 encoder_config_.video_format);
759 // TODO(nisse): What to do if creating the encoder fails? Crash,
760 // or just discard incoming frames?
761 RTC_CHECK(encoder_);
762
763 encoder_->SetFecControllerOverride(fec_controller_override_);
764
765 codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
766 encoder_config_.video_format);
767
768 encoder_reset_required = true;
769 }
770
771 encoder_bitrate_limits_ = GetEncoderBitrateLimits(
772 encoder_->GetEncoderInfo(),
773 last_frame_info_->width * last_frame_info_->height);
774
Sergey Silkin6b2cec12019-08-09 16:04:05 +0200775 if (streams.size() == 1 && encoder_bitrate_limits_) {
776 // Use bitrate limits recommended by encoder only if app didn't set any of
777 // them.
778 if (encoder_config_.max_bitrate_bps <= 0 &&
779 (encoder_config_.simulcast_layers.empty() ||
780 encoder_config_.simulcast_layers[0].min_bitrate_bps <= 0)) {
781 streams.back().min_bitrate_bps = encoder_bitrate_limits_->min_bitrate_bps;
782 streams.back().max_bitrate_bps = encoder_bitrate_limits_->max_bitrate_bps;
783 streams.back().target_bitrate_bps =
784 std::min(streams.back().target_bitrate_bps,
785 encoder_bitrate_limits_->max_bitrate_bps);
786 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200787 }
788
Erik Språng08127a92016-11-16 16:41:30 +0100789 VideoCodec codec;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800790 if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100791 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100792 }
perkjfa10b552016-10-02 23:45:26 -0700793
“Michael277a6562018-06-01 14:09:19 -0500794 // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
795 if (encoder_config_.codec_type == kVideoCodecVP9) {
“Michael277a6562018-06-01 14:09:19 -0500796 // Lower max bitrate to the level codec actually can produce.
Erik Språngcf9cbf52019-09-04 14:30:57 +0200797 streams[0].max_bitrate_bps =
798 std::min(streams[0].max_bitrate_bps,
799 SvcRateAllocator::GetMaxBitrate(codec).bps<int>());
“Michael277a6562018-06-01 14:09:19 -0500800 streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100801 // target_bitrate_bps specifies the maximum padding bitrate.
“Michael277a6562018-06-01 14:09:19 -0500802 streams[0].target_bitrate_bps =
Erik Språngcf9cbf52019-09-04 14:30:57 +0200803 SvcRateAllocator::GetPaddingBitrate(codec).bps<int>();
“Michael277a6562018-06-01 14:09:19 -0500804 }
805
Ilya Nikolaevskiyfbf75a72019-09-26 17:39:26 +0200806 char log_stream_buf[4 * 1024];
807 rtc::SimpleStringBuilder log_stream(log_stream_buf);
808 log_stream << "ReconfigureEncoder:\n";
809 log_stream << "Simulcast streams:\n";
810 for (size_t i = 0; i < codec.numberOfSimulcastStreams; ++i) {
811 log_stream << i << ": " << codec.simulcastStream[i].width << "x"
812 << codec.simulcastStream[i].height
813 << " fps: " << codec.simulcastStream[i].maxFramerate
814 << " min_bps: " << codec.simulcastStream[i].minBitrate
815 << " target_bps: " << codec.simulcastStream[i].targetBitrate
816 << " max_bps: " << codec.simulcastStream[i].maxBitrate
817 << " max_qp: " << codec.simulcastStream[i].qpMax
818 << " num_tl: " << codec.simulcastStream[i].numberOfTemporalLayers
819 << " active: "
820 << (codec.simulcastStream[i].active ? "true" : "false") << "\n";
821 }
822 if (encoder_config_.codec_type == kVideoCodecVP9) {
823 size_t num_spatial_layers = codec.VP9()->numberOfSpatialLayers;
824 log_stream << "Spatial layers:\n";
825 for (size_t i = 0; i < num_spatial_layers; ++i) {
826 log_stream << i << ": " << codec.spatialLayers[i].width << "x"
827 << codec.spatialLayers[i].height
828 << " fps: " << codec.spatialLayers[i].maxFramerate
829 << " min_bps: " << codec.spatialLayers[i].minBitrate
830 << " target_bps: " << codec.spatialLayers[i].targetBitrate
831 << " max_bps: " << codec.spatialLayers[i].maxBitrate
832 << " max_qp: " << codec.spatialLayers[i].qpMax
833 << " num_tl: " << codec.spatialLayers[i].numberOfTemporalLayers
834 << " active: "
835 << (codec.spatialLayers[i].active ? "true" : "false") << "\n";
836 }
837 }
838 RTC_LOG(LS_INFO) << log_stream.str();
839
perkjfa10b552016-10-02 23:45:26 -0700840 codec.startBitrate =
841 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
842 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
843 codec.expect_encode_from_texture = last_frame_info_->is_texture;
Erik Språngd7329ca2019-02-21 21:19:53 +0100844 // Make sure the start bit rate is sane...
845 RTC_DCHECK_LE(codec.startBitrate, 1000000);
sprangfda496a2017-06-15 04:21:07 -0700846 max_framerate_ = codec.maxFramerate;
Åsa Persson8c1bf952018-09-13 10:42:19 +0200847
848 // Inform source about max configured framerate.
849 int max_framerate = 0;
850 for (const auto& stream : streams) {
851 max_framerate = std::max(stream.max_framerate, max_framerate);
852 }
853 source_proxy_->SetMaxFramerate(max_framerate);
Stefan Holmere5904162015-03-26 11:11:06 +0100854
Erik Språngb7cb7b52019-02-26 15:52:33 +0100855 if (codec.maxBitrate == 0) {
856 // max is one bit per pixel
857 codec.maxBitrate =
858 (static_cast<int>(codec.height) * static_cast<int>(codec.width) *
859 static_cast<int>(codec.maxFramerate)) /
860 1000;
861 if (codec.startBitrate > codec.maxBitrate) {
862 // But if the user tries to set a higher start bit rate we will
863 // increase the max accordingly.
864 codec.maxBitrate = codec.startBitrate;
865 }
866 }
867
868 if (codec.startBitrate > codec.maxBitrate) {
869 codec.startBitrate = codec.maxBitrate;
870 }
871
Sergey Silkin65d9c4d2019-06-12 11:02:30 +0200872 rate_allocator_ =
873 settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
874
Erik Språngb7cb7b52019-02-26 15:52:33 +0100875 // Reset (release existing encoder) if one exists and anything except
Elad Alonfb087812019-05-02 23:25:34 +0200876 // start bitrate or max framerate has changed.
Sergey Silkin6456e352019-07-08 17:56:40 +0200877 if (!encoder_reset_required) {
878 encoder_reset_required = RequiresEncoderReset(
879 codec, send_codec_, was_encode_called_since_last_initialization_);
880 }
Erik Språngb7cb7b52019-02-26 15:52:33 +0100881 send_codec_ = codec;
882
philipeld9cc8c02019-09-16 14:53:40 +0200883 encoder_switch_experiment_.SetCodec(send_codec_.codecType);
Åsa Perssone644a032019-11-08 15:56:00 +0100884 quality_rampup_experiment_.SetMaxBitrate(
885 last_frame_info_->width * last_frame_info_->height, codec.maxBitrate);
philipeld9cc8c02019-09-16 14:53:40 +0200886
Niels Möller4db138e2018-04-19 09:04:13 +0200887 // Keep the same encoder, as long as the video_format is unchanged.
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100888 // Encoder creation block is split in two since EncoderInfo needed to start
889 // CPU adaptation with the correct settings should be polled after
890 // encoder_->InitEncode().
Erik Språngb7cb7b52019-02-26 15:52:33 +0100891 bool success = true;
Sergey Silkin6456e352019-07-08 17:56:40 +0200892 if (encoder_reset_required) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100893 ReleaseEncoder();
Elad Alon370f93a2019-06-11 14:57:57 +0200894 const size_t max_data_payload_length = max_data_payload_length_ > 0
895 ? max_data_payload_length_
896 : kDefaultPayloadSize;
897 if (encoder_->InitEncode(
898 &send_codec_,
899 VideoEncoder::Settings(settings_.capabilities, number_of_cores_,
900 max_data_payload_length)) != 0) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100901 RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
902 "codec type: "
903 << CodecTypeToPayloadString(send_codec_.codecType)
904 << " (" << send_codec_.codecType << ")";
905 ReleaseEncoder();
906 success = false;
907 } else {
908 encoder_initialized_ = true;
909 encoder_->RegisterEncodeCompleteCallback(this);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200910 frame_encode_metadata_writer_.OnEncoderInit(send_codec_,
911 HasInternalSource());
Erik Språng6a7baa72019-02-26 18:31:00 +0100912 }
913
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200914 frame_encode_metadata_writer_.Reset();
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100915 last_encode_info_ms_ = absl::nullopt;
Sergey Silkin5ee69672019-07-02 14:18:34 +0200916 was_encode_called_since_last_initialization_ = false;
Erik Språngb7cb7b52019-02-26 15:52:33 +0100917 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100918
919 if (success) {
Erik Språngd7329ca2019-02-21 21:19:53 +0100920 next_frame_types_.clear();
921 next_frame_types_.resize(
922 std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
Niels Möller8f7ce222019-03-21 15:43:58 +0100923 VideoFrameType::kVideoFrameKey);
Erik Språngd7329ca2019-02-21 21:19:53 +0100924 RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
925 << " start bitrate " << codec.startBitrate
926 << " max frame rate " << codec.maxFramerate
927 << " max payload size " << max_data_payload_length_;
928 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100929 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
Erik Språngb7cb7b52019-02-26 15:52:33 +0100930 rate_allocator_ = nullptr;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000931 }
Peter Boström905f8e72016-03-02 16:59:56 +0100932
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100933 if (pending_encoder_creation_) {
934 overuse_detector_->StopCheckForOveruse();
935 overuse_detector_->StartCheckForOveruse(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100936 &encoder_queue_,
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100937 GetCpuOveruseOptions(
938 settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
939 this);
940 pending_encoder_creation_ = false;
941 }
942
Niels Möller6bb5ab92019-01-11 11:11:10 +0100943 int num_layers;
944 if (codec.codecType == kVideoCodecVP8) {
945 num_layers = codec.VP8()->numberOfTemporalLayers;
946 } else if (codec.codecType == kVideoCodecVP9) {
947 num_layers = codec.VP9()->numberOfTemporalLayers;
Johnny Lee1a1c52b2019-02-08 14:25:40 -0500948 } else if (codec.codecType == kVideoCodecH264) {
949 num_layers = codec.H264()->numberOfTemporalLayers;
Niels Möller6bb5ab92019-01-11 11:11:10 +0100950 } else if (codec.codecType == kVideoCodecGeneric &&
951 codec.numberOfSimulcastStreams > 0) {
952 // This is mainly for unit testing, disabling frame dropping.
953 // TODO(sprang): Add a better way to disable frame dropping.
954 num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
955 } else {
956 num_layers = 1;
957 }
958
959 frame_dropper_.Reset();
960 frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100961 // Force-disable frame dropper if either:
962 // * We have screensharing with layers.
963 // * "WebRTC-FrameDropper" field trial is "Disabled".
964 force_disable_frame_dropper_ =
965 field_trial::IsDisabled(kFrameDropperFieldTrial) ||
966 (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
967
Erik Språng7ca375c2019-02-06 16:20:17 +0100968 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
969 if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200970 bitrate_adjuster_ = std::make_unique<EncoderBitrateAdjuster>(codec);
Erik Språng7ca375c2019-02-06 16:20:17 +0100971 bitrate_adjuster_->OnEncoderInfo(info);
972 }
973
Erik Språng4c6ca302019-04-08 15:14:01 +0200974 if (rate_allocator_ && last_encoder_rate_settings_) {
Niels Möller6bb5ab92019-01-11 11:11:10 +0100975 // We have a new rate allocator instance and already configured target
Erik Språng4c6ca302019-04-08 15:14:01 +0200976 // bitrate. Update the rate allocation and notify observers.
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +0200977 // We must invalidate the last_encoder_rate_settings_ to ensure
978 // the changes get propagated to all listeners.
979 EncoderRateSettings rate_settings = *last_encoder_rate_settings_;
980 last_encoder_rate_settings_.reset();
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200981 rate_settings.rate_control.framerate_fps = GetInputFramerateFps();
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +0200982
983 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(rate_settings));
Niels Möller6bb5ab92019-01-11 11:11:10 +0100984 }
ilnik35b7de42017-03-15 04:24:21 -0700985
Niels Möller213618e2018-07-24 09:29:58 +0200986 encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
Per512ecb32016-09-23 15:52:06 +0200987
perkjfa10b552016-10-02 23:45:26 -0700988 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100989
Pera48ddb72016-09-29 11:48:50 +0200990 sink_->OnEncoderConfigurationChanged(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100991 std::move(streams), encoder_config_.content_type,
992 encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800993
Niels Möller7dc26b72017-12-06 10:27:48 +0100994 // Get the current target framerate, ie the maximum framerate as specified by
995 // the current codec configuration, or any limit imposed by cpu adaption in
996 // maintain-resolution or balanced mode. This is used to make sure overuse
997 // detection doesn't needlessly trigger in low and/or variable framerate
998 // scenarios.
999 int target_framerate = std::min(
1000 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
1001 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
Niels Möller2d061182018-04-24 09:13:08 +02001002
Erik Språng7ca375c2019-02-06 16:20:17 +01001003 ConfigureQualityScaler(info);
kthelgason2bc68642017-02-07 07:02:22 -08001004}
1005
Erik Språng7ca375c2019-02-06 16:20:17 +01001006void VideoStreamEncoder::ConfigureQualityScaler(
1007 const VideoEncoder::EncoderInfo& encoder_info) {
kthelgason2bc68642017-02-07 07:02:22 -08001008 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01001009 const auto scaling_settings = encoder_info.scaling_settings;
asapersson36e9eb42017-03-31 05:29:12 -07001010 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -07001011 IsResolutionScalingEnabled(degradation_preference_) &&
Niels Möller225c7872018-02-22 15:03:53 +01001012 scaling_settings.thresholds;
kthelgason3af6cc02017-03-22 00:25:28 -07001013
asapersson36e9eb42017-03-31 05:29:12 -07001014 if (quality_scaling_allowed) {
Benjamin Wright1f4173e2019-03-13 17:59:32 -07001015 if (quality_scaler_ == nullptr) {
asapersson09f05612017-05-15 23:40:18 -07001016 // Quality scaler has not already been configured.
Niels Möller225c7872018-02-22 15:03:53 +01001017
Åsa Perssona945aee2018-04-24 16:53:25 +02001018 // Use experimental thresholds if available.
Danil Chapovalovb9b146c2018-06-15 12:28:07 +02001019 absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
Åsa Perssona945aee2018-04-24 16:53:25 +02001020 if (quality_scaling_experiment_enabled_) {
1021 experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
1022 encoder_config_.codec_type);
1023 }
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001024 // Since the interface is non-public, std::make_unique can't do this
Karl Wiberg918f50c2018-07-05 11:40:33 +02001025 // upcast.
Niels Möller225c7872018-02-22 15:03:53 +01001026 AdaptationObserverInterface* observer = this;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001027 quality_scaler_ = std::make_unique<QualityScaler>(
Sebastian Janssoncda86dd2019-03-11 17:26:36 +01001028 &encoder_queue_, observer,
1029 experimental_thresholds ? *experimental_thresholds
1030 : *(scaling_settings.thresholds));
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001031 has_seen_first_significant_bwe_change_ = false;
1032 initial_framedrop_ = 0;
kthelgason876222f2016-11-29 01:44:11 -08001033 }
1034 } else {
1035 quality_scaler_.reset(nullptr);
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001036 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -08001037 }
asapersson09f05612017-05-15 23:40:18 -07001038
Åsa Persson12314192019-06-20 15:45:07 +02001039 if (degradation_preference_ == DegradationPreference::BALANCED &&
1040 quality_scaler_ && last_frame_info_) {
1041 absl::optional<VideoEncoder::QpThresholds> thresholds =
1042 balanced_settings_.GetQpThresholds(encoder_config_.codec_type,
1043 last_frame_info_->pixel_count());
1044 if (thresholds) {
1045 quality_scaler_->SetQpThresholds(*thresholds);
1046 }
1047 }
1048
Niels Möller213618e2018-07-24 09:29:58 +02001049 encoder_stats_observer_->OnAdaptationChanged(
1050 VideoStreamEncoderObserver::AdaptationReason::kNone,
1051 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001052}
1053
mflodmancc3d4422017-08-03 08:27:51 -07001054void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -07001055 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -07001056 VideoFrame incoming_frame = video_frame;
1057
1058 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -07001059 int64_t current_time_us = clock_->TimeInMicroseconds();
1060 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
1061 // In some cases, e.g., when the frame from decoder is fed to encoder,
1062 // the timestamp may be set to the future. As the encoding pipeline assumes
1063 // capture time to be less than present time, we should reset the capture
1064 // timestamps here. Otherwise there may be issues with RTP send stream.
1065 if (incoming_frame.timestamp_us() > current_time_us)
1066 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -07001067
1068 // Capture time may come from clock with an offset and drift from clock_.
1069 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -08001070 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -07001071 capture_ntp_time_ms = video_frame.ntp_time_ms();
1072 } else if (video_frame.render_time_ms() != 0) {
1073 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
1074 } else {
nisse1c0dea82017-01-30 02:43:18 -08001075 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -07001076 }
1077 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
1078
1079 // Convert NTP time, in ms, to RTP timestamp.
1080 const int kMsToRtpTimestamp = 90;
1081 incoming_frame.set_timestamp(
1082 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
1083
1084 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
1085 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001086 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
1087 << incoming_frame.ntp_time_ms()
1088 << " <= " << last_captured_timestamp_
1089 << ") for incoming frame. Dropping.";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001090 encoder_queue_.PostTask([this, incoming_frame]() {
1091 RTC_DCHECK_RUN_ON(&encoder_queue_);
1092 accumulated_update_rect_.Union(incoming_frame.update_rect());
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001093 accumulated_update_rect_is_valid_ &= incoming_frame.has_update_rect();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001094 });
perkj26091b12016-09-01 01:17:40 -07001095 return;
1096 }
1097
asapersson6ffb67d2016-09-12 00:10:45 -07001098 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -08001099 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
1100 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -07001101 log_stats = true;
1102 }
1103
perkj26091b12016-09-01 01:17:40 -07001104 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001105
1106 int64_t post_time_us = rtc::TimeMicros();
1107 ++posted_frames_waiting_for_encode_;
1108
1109 encoder_queue_.PostTask(
1110 [this, incoming_frame, post_time_us, log_stats]() {
1111 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller213618e2018-07-24 09:29:58 +02001112 encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
1113 incoming_frame.height());
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001114 ++captured_frame_count_;
1115 const int posted_frames_waiting_for_encode =
1116 posted_frames_waiting_for_encode_.fetch_sub(1);
1117 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
1118 if (posted_frames_waiting_for_encode == 1) {
Sebastian Janssona3177052018-04-10 13:05:49 +02001119 MaybeEncodeVideoFrame(incoming_frame, post_time_us);
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001120 } else {
1121 // There is a newer frame in flight. Do not encode this frame.
1122 RTC_LOG(LS_VERBOSE)
1123 << "Incoming frame dropped due to that the encoder is blocked.";
1124 ++dropped_frame_count_;
Niels Möller213618e2018-07-24 09:29:58 +02001125 encoder_stats_observer_->OnFrameDropped(
1126 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001127 accumulated_update_rect_.Union(incoming_frame.update_rect());
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001128 accumulated_update_rect_is_valid_ &= incoming_frame.has_update_rect();
Sebastian Jansson3ab5c402018-04-05 12:30:50 +02001129 }
1130 if (log_stats) {
1131 RTC_LOG(LS_INFO) << "Number of frames: captured "
1132 << captured_frame_count_
1133 << ", dropped (due to encoder blocked) "
1134 << dropped_frame_count_ << ", interval_ms "
1135 << kFrameLogIntervalMs;
1136 captured_frame_count_ = 0;
1137 dropped_frame_count_ = 0;
1138 }
1139 });
perkj26091b12016-09-01 01:17:40 -07001140}
1141
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001142void VideoStreamEncoder::OnDiscardedFrame() {
Niels Möller213618e2018-07-24 09:29:58 +02001143 encoder_stats_observer_->OnFrameDropped(
1144 VideoStreamEncoderObserver::DropReason::kSource);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001145}
1146
mflodmancc3d4422017-08-03 08:27:51 -07001147bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -07001148 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +00001149 // Pause video if paused by caller or as long as the network is down or the
1150 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -07001151 // If the pacer queue has grown too large or the network is down,
Erik Språng4c6ca302019-04-08 15:14:01 +02001152 // |last_encoder_rate_settings_->encoder_target| will be 0.
1153 return !last_encoder_rate_settings_ ||
1154 last_encoder_rate_settings_->encoder_target == DataRate::Zero();
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +00001155}
1156
mflodmancc3d4422017-08-03 08:27:51 -07001157void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -07001158 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001159 // Start trace event only on the first frame after encoder is paused.
1160 if (!encoder_paused_and_dropped_frame_) {
1161 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
1162 }
1163 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001164}
1165
mflodmancc3d4422017-08-03 08:27:51 -07001166void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -07001167 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +00001168 // End trace event on first frame after encoder resumes, if frame was dropped.
1169 if (encoder_paused_and_dropped_frame_) {
1170 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
1171 }
1172 encoder_paused_and_dropped_frame_ = false;
1173}
1174
Erik Språng4c6ca302019-04-08 15:14:01 +02001175VideoStreamEncoder::EncoderRateSettings
1176VideoStreamEncoder::UpdateBitrateAllocationAndNotifyObserver(
1177 const EncoderRateSettings& rate_settings) {
1178 VideoBitrateAllocation new_allocation;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001179 // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
1180 // might cap the bitrate to the min bitrate configured.
Erik Språng4c6ca302019-04-08 15:14:01 +02001181 if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) {
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02001182 new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters(
Florent Castellia8336d32019-09-09 13:36:55 +02001183 rate_settings.encoder_target, rate_settings.stable_encoder_target,
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001184 rate_settings.rate_control.framerate_fps));
Niels Möller6bb5ab92019-01-11 11:11:10 +01001185 }
1186
Erik Språng4c6ca302019-04-08 15:14:01 +02001187 if (bitrate_observer_ && new_allocation.get_sum_bps() > 0) {
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001188 if (encoder_ && encoder_initialized_) {
1189 // Avoid too old encoder_info_.
1190 const int64_t kMaxDiffMs = 100;
1191 const bool updated_recently =
1192 (last_encode_info_ms_ && ((clock_->TimeInMilliseconds() -
1193 *last_encode_info_ms_) < kMaxDiffMs));
1194 // Update allocation according to info from encoder.
1195 bitrate_observer_->OnBitrateAllocationUpdated(
1196 UpdateAllocationFromEncoderInfo(
Erik Språng4c6ca302019-04-08 15:14:01 +02001197 new_allocation,
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001198 updated_recently ? encoder_info_ : encoder_->GetEncoderInfo()));
1199 } else {
Erik Språng4c6ca302019-04-08 15:14:01 +02001200 bitrate_observer_->OnBitrateAllocationUpdated(new_allocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001201 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001202 }
1203
Erik Språng3d11e2f2019-04-15 14:48:30 +02001204 EncoderRateSettings new_rate_settings = rate_settings;
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001205 new_rate_settings.rate_control.bitrate = new_allocation;
Erik Språng5056af02019-09-02 15:53:11 +02001206 // VideoBitrateAllocator subclasses may allocate a bitrate higher than the
1207 // target in order to sustain the min bitrate of the video codec. In this
1208 // case, make sure the bandwidth allocation is at least equal the allocation
1209 // as that is part of the document contract for that field.
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001210 new_rate_settings.rate_control.bandwidth_allocation = std::max(
1211 new_rate_settings.rate_control.bandwidth_allocation,
1212 DataRate::bps(new_rate_settings.rate_control.bitrate.get_sum_bps()));
Erik Språng3d11e2f2019-04-15 14:48:30 +02001213
Erik Språng7ca375c2019-02-06 16:20:17 +01001214 if (bitrate_adjuster_) {
Erik Språng0e1a1f92019-02-18 18:45:13 +01001215 VideoBitrateAllocation adjusted_allocation =
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001216 bitrate_adjuster_->AdjustRateAllocation(new_rate_settings.rate_control);
Erik Språng4c6ca302019-04-08 15:14:01 +02001217 RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = "
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001218 << rate_settings.rate_control.framerate_fps << ", from "
Erik Språng4c6ca302019-04-08 15:14:01 +02001219 << new_allocation.ToString() << ", to "
Erik Språng0e1a1f92019-02-18 18:45:13 +01001220 << adjusted_allocation.ToString();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001221 new_rate_settings.rate_control.bitrate = adjusted_allocation;
Erik Språng7ca375c2019-02-06 16:20:17 +01001222 }
Erik Språng4c6ca302019-04-08 15:14:01 +02001223
Evan Shrubsolecc62b162019-09-09 11:26:45 +02001224 encoder_stats_observer_->OnBitrateAllocationUpdated(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001225 send_codec_, new_rate_settings.rate_control.bitrate);
Evan Shrubsolecc62b162019-09-09 11:26:45 +02001226
Erik Språng3d11e2f2019-04-15 14:48:30 +02001227 return new_rate_settings;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001228}
1229
1230uint32_t VideoStreamEncoder::GetInputFramerateFps() {
1231 const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
Erik Språngd7329ca2019-02-21 21:19:53 +01001232 absl::optional<uint32_t> input_fps =
1233 input_framerate_.Rate(clock_->TimeInMilliseconds());
1234 if (!input_fps || *input_fps == 0) {
1235 return default_fps;
1236 }
1237 return *input_fps;
1238}
1239
1240void VideoStreamEncoder::SetEncoderRates(
Erik Språng4c6ca302019-04-08 15:14:01 +02001241 const EncoderRateSettings& rate_settings) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001242 RTC_DCHECK_GT(rate_settings.rate_control.framerate_fps, 0.0);
1243 bool rate_control_changed =
1244 (!last_encoder_rate_settings_.has_value() ||
1245 last_encoder_rate_settings_->rate_control != rate_settings.rate_control);
1246 if (last_encoder_rate_settings_ != rate_settings) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001247 last_encoder_rate_settings_ = rate_settings;
1248 }
1249
Erik Språng6a7baa72019-02-26 18:31:00 +01001250 if (!encoder_) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001251 return;
1252 }
1253
1254 // |bitrate_allocation| is 0 it means that the network is down or the send
1255 // pacer is full. We currently only report this if the encoder has an internal
1256 // source. If the encoder does not have an internal source, higher levels
1257 // are expected to not call AddVideoFrame. We do this since its unclear
1258 // how current encoder implementations behave when given a zero target
1259 // bitrate.
1260 // TODO(perkj): Make sure all known encoder implementations handle zero
1261 // target bitrate and remove this check.
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001262 if (!HasInternalSource() &&
1263 rate_settings.rate_control.bitrate.get_sum_bps() == 0) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001264 return;
1265 }
1266
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001267 if (rate_control_changed) {
1268 encoder_->SetRates(rate_settings.rate_control);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001269 frame_encode_metadata_writer_.OnSetRates(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001270 rate_settings.rate_control.bitrate,
1271 static_cast<uint32_t>(rate_settings.rate_control.framerate_fps + 0.5));
Erik Språng6a7baa72019-02-26 18:31:00 +01001272 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01001273}
1274
Sebastian Janssona3177052018-04-10 13:05:49 +02001275void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
1276 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -07001277 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -08001278
Per21d45d22016-10-30 21:37:57 +01001279 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -07001280 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -07001281 video_frame.is_texture() != last_frame_info_->is_texture) {
1282 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +01001283 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
1284 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +01001285 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
1286 << last_frame_info_->width << "x"
1287 << last_frame_info_->height
1288 << ", texture=" << last_frame_info_->is_texture << ".";
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001289 // Force full frame update, since resolution has changed.
1290 accumulated_update_rect_ =
1291 VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
perkjfa10b552016-10-02 23:45:26 -07001292 }
1293
Niels Möller4db138e2018-04-19 09:04:13 +02001294 // We have to create then encoder before the frame drop logic,
1295 // because the latter depends on encoder_->GetScalingSettings.
1296 // According to the testcase
1297 // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
1298 // from GetScalingSettings should enable or disable the frame drop.
1299
Erik Språnga8d48ab2019-02-08 14:17:40 +01001300 // Update input frame rate before we start using it. If we update it after
Erik Språngd7329ca2019-02-21 21:19:53 +01001301 // any potential frame drop we are going to artificially increase frame sizes.
1302 // Poll the rate before updating, otherwise we risk the rate being estimated
1303 // a little too high at the start of the call when then window is small.
Niels Möller6bb5ab92019-01-11 11:11:10 +01001304 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språngd7329ca2019-02-21 21:19:53 +01001305 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
Niels Möller6bb5ab92019-01-11 11:11:10 +01001306
Niels Möller4db138e2018-04-19 09:04:13 +02001307 int64_t now_ms = clock_->TimeInMilliseconds();
1308 if (pending_encoder_reconfiguration_) {
1309 ReconfigureEncoder();
1310 last_parameters_update_ms_.emplace(now_ms);
1311 } else if (!last_parameters_update_ms_ ||
1312 now_ms - *last_parameters_update_ms_ >=
Niels Möllerfe407b72019-09-10 10:48:48 +02001313 kParameterUpdateIntervalMs) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001314 if (last_encoder_rate_settings_) {
1315 // Clone rate settings before update, so that SetEncoderRates() will
1316 // actually detect the change between the input and
1317 // |last_encoder_rate_setings_|, triggering the call to SetRate() on the
1318 // encoder.
1319 EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_;
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001320 new_rate_settings.rate_control.framerate_fps =
1321 static_cast<double>(framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001322 SetEncoderRates(
1323 UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
1324 }
Niels Möller4db138e2018-04-19 09:04:13 +02001325 last_parameters_update_ms_.emplace(now_ms);
1326 }
1327
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001328 // Because pending frame will be dropped in any case, we need to
1329 // remember its updated region.
1330 if (pending_frame_) {
1331 encoder_stats_observer_->OnFrameDropped(
1332 VideoStreamEncoderObserver::DropReason::kEncoderQueue);
1333 accumulated_update_rect_.Union(pending_frame_->update_rect());
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001334 accumulated_update_rect_is_valid_ &= pending_frame_->has_update_rect();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001335 }
1336
Sebastian Janssona3177052018-04-10 13:05:49 +02001337 if (DropDueToSize(video_frame.size())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001338 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Åsa Persson45b176f2019-09-30 11:19:05 +02001339 int fps_count = GetConstAdaptCounter().FramerateCount(kQuality);
1340 int res_count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -08001341 AdaptDown(kQuality);
Åsa Persson45b176f2019-09-30 11:19:05 +02001342 if (degradation_preference_ == DegradationPreference::BALANCED &&
1343 GetConstAdaptCounter().FramerateCount(kQuality) > fps_count) {
1344 // Adapt framerate in same step as resolution.
1345 AdaptDown(kQuality);
1346 }
1347 if (GetConstAdaptCounter().ResolutionCount(kQuality) > res_count) {
Niels Möller213618e2018-07-24 09:29:58 +02001348 encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
Åsa Persson875841d2018-01-08 08:49:53 +01001349 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001350 ++initial_framedrop_;
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001351 // Storing references to a native buffer risks blocking frame capture.
1352 if (video_frame.video_frame_buffer()->type() !=
1353 VideoFrameBuffer::Type::kNative) {
1354 pending_frame_ = video_frame;
1355 pending_frame_post_time_us_ = time_when_posted_us;
1356 } else {
1357 // Ensure that any previously stored frame is dropped.
1358 pending_frame_.reset();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001359 accumulated_update_rect_.Union(video_frame.update_rect());
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001360 accumulated_update_rect_is_valid_ &= video_frame.has_update_rect();
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001361 }
kthelgason2bc68642017-02-07 07:02:22 -08001362 return;
1363 }
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001364 initial_framedrop_ = kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -08001365
Åsa Perssone644a032019-11-08 15:56:00 +01001366 if (!quality_rampup_done_ && TryQualityRampup(now_ms) &&
1367 GetConstAdaptCounter().ResolutionCount(kQuality) > 0 &&
1368 GetConstAdaptCounter().TotalCount(kCpu) == 0) {
1369 RTC_LOG(LS_INFO) << "Reset quality limitations.";
1370 last_adaptation_request_.reset();
1371 source_proxy_->ResetPixelFpsCount();
1372 adapt_counters_.clear();
1373 quality_rampup_done_ = true;
1374 }
1375
perkj26091b12016-09-01 01:17:40 -07001376 if (EncoderPaused()) {
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001377 // Storing references to a native buffer risks blocking frame capture.
1378 if (video_frame.video_frame_buffer()->type() !=
1379 VideoFrameBuffer::Type::kNative) {
1380 if (pending_frame_)
1381 TraceFrameDropStart();
1382 pending_frame_ = video_frame;
1383 pending_frame_post_time_us_ = time_when_posted_us;
1384 } else {
1385 // Ensure that any previously stored frame is dropped.
1386 pending_frame_.reset();
Sebastian Janssona3177052018-04-10 13:05:49 +02001387 TraceFrameDropStart();
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001388 accumulated_update_rect_.Union(video_frame.update_rect());
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001389 accumulated_update_rect_is_valid_ &= video_frame.has_update_rect();
Sebastian Jansson0d70e372018-04-17 13:57:13 +02001390 }
perkj26091b12016-09-01 01:17:40 -07001391 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001392 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001393
1394 pending_frame_.reset();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001395
1396 frame_dropper_.Leak(framerate_fps);
1397 // Frame dropping is enabled iff frame dropping is not force-disabled, and
1398 // rate controller is not trusted.
1399 const bool frame_dropping_enabled =
1400 !force_disable_frame_dropper_ &&
1401 !encoder_info_.has_trusted_rate_controller;
1402 frame_dropper_.Enable(frame_dropping_enabled);
1403 if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
Erik Språng4c6ca302019-04-08 15:14:01 +02001404 RTC_LOG(LS_VERBOSE)
1405 << "Drop Frame: "
1406 << "target bitrate "
1407 << (last_encoder_rate_settings_
1408 ? last_encoder_rate_settings_->encoder_target.bps()
1409 : 0)
1410 << ", input frame rate " << framerate_fps;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001411 OnDroppedFrame(
1412 EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001413 accumulated_update_rect_.Union(video_frame.update_rect());
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001414 accumulated_update_rect_is_valid_ &= video_frame.has_update_rect();
Niels Möller6bb5ab92019-01-11 11:11:10 +01001415 return;
1416 }
1417
Sebastian Janssona3177052018-04-10 13:05:49 +02001418 EncodeVideoFrame(video_frame, time_when_posted_us);
1419}
1420
1421void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
1422 int64_t time_when_posted_us) {
1423 RTC_DCHECK_RUN_ON(&encoder_queue_);
philipele8ed8302019-07-03 11:53:48 +02001424
1425 // If the encoder fail we can't continue to encode frames. When this happens
1426 // the WebrtcVideoSender is notified and the whole VideoSendStream is
1427 // recreated.
1428 if (encoder_failed_)
1429 return;
1430
perkj26091b12016-09-01 01:17:40 -07001431 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +00001432
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001433 // Encoder metadata needs to be updated before encode complete callback.
1434 VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
1435 if (info.implementation_name != encoder_info_.implementation_name) {
1436 encoder_stats_observer_->OnEncoderImplementationChanged(
1437 info.implementation_name);
1438 if (bitrate_adjuster_) {
1439 // Encoder implementation changed, reset overshoot detector states.
1440 bitrate_adjuster_->Reset();
1441 }
1442 }
1443
1444 if (bitrate_adjuster_) {
1445 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1446 if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
1447 bitrate_adjuster_->OnEncoderInfo(info);
1448 break;
1449 }
1450 }
1451 }
1452 encoder_info_ = info;
1453 last_encode_info_ms_ = clock_->TimeInMilliseconds();
1454
ilnik6b826ef2017-06-16 06:53:48 -07001455 VideoFrame out_frame(video_frame);
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001456
1457 const VideoFrameBuffer::Type buffer_type =
1458 out_frame.video_frame_buffer()->type();
1459 const bool is_buffer_type_supported =
1460 buffer_type == VideoFrameBuffer::Type::kI420 ||
1461 (buffer_type == VideoFrameBuffer::Type::kNative &&
1462 info.supports_native_handle);
1463
1464 if (!is_buffer_type_supported) {
1465 // This module only supports software encoding.
1466 rtc::scoped_refptr<I420BufferInterface> converted_buffer(
1467 out_frame.video_frame_buffer()->ToI420());
1468
1469 if (!converted_buffer) {
1470 RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
1471 return;
1472 }
1473
1474 VideoFrame::UpdateRect update_rect = out_frame.update_rect();
1475 if (!update_rect.IsEmpty() &&
1476 out_frame.video_frame_buffer()->GetI420() == nullptr) {
1477 // UpdatedRect is reset to full update if it's not empty, and buffer was
1478 // converted, therefore we can't guarantee that pixels outside of
1479 // UpdateRect didn't change comparing to the previous frame.
1480 update_rect =
1481 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
1482 }
1483
1484 out_frame.set_video_frame_buffer(converted_buffer);
1485 out_frame.set_update_rect(update_rect);
1486 }
1487
ilnik6b826ef2017-06-16 06:53:48 -07001488 // Crop frame if needed.
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001489 if ((crop_width_ > 0 || crop_height_ > 0) &&
1490 out_frame.video_frame_buffer()->type() !=
1491 VideoFrameBuffer::Type::kNative) {
Noah Richards51db4212019-06-12 06:59:12 -07001492 // If the frame can't be converted to I420, drop it.
1493 auto i420_buffer = video_frame.video_frame_buffer()->ToI420();
1494 if (!i420_buffer) {
1495 RTC_LOG(LS_ERROR) << "Frame conversion for crop failed, dropping frame.";
1496 return;
1497 }
ilnik6b826ef2017-06-16 06:53:48 -07001498 int cropped_width = video_frame.width() - crop_width_;
1499 int cropped_height = video_frame.height() - crop_height_;
1500 rtc::scoped_refptr<I420Buffer> cropped_buffer =
1501 I420Buffer::Create(cropped_width, cropped_height);
1502 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
1503 // happen after SinkWants signaled correctly from ReconfigureEncoder.
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001504 VideoFrame::UpdateRect update_rect = video_frame.update_rect();
ilnik6b826ef2017-06-16 06:53:48 -07001505 if (crop_width_ < 4 && crop_height_ < 4) {
Noah Richards51db4212019-06-12 06:59:12 -07001506 cropped_buffer->CropAndScaleFrom(*i420_buffer, crop_width_ / 2,
1507 crop_height_ / 2, cropped_width,
1508 cropped_height);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001509 update_rect.offset_x -= crop_width_ / 2;
1510 update_rect.offset_y -= crop_height_ / 2;
1511 update_rect.Intersect(
1512 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
1513
ilnik6b826ef2017-06-16 06:53:48 -07001514 } else {
Noah Richards51db4212019-06-12 06:59:12 -07001515 cropped_buffer->ScaleFrom(*i420_buffer);
Ilya Nikolaevskiy1c90cab2019-03-07 15:30:58 +01001516 if (!update_rect.IsEmpty()) {
1517 // Since we can't reason about pixels after scaling, we invalidate whole
1518 // picture, if anything changed.
1519 update_rect =
1520 VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
1521 }
ilnik6b826ef2017-06-16 06:53:48 -07001522 }
Ilya Nikolaevskiy4fc08552019-06-05 15:59:12 +02001523 out_frame.set_video_frame_buffer(cropped_buffer);
1524 out_frame.set_update_rect(update_rect);
ilnik6b826ef2017-06-16 06:53:48 -07001525 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001526 // Since accumulated_update_rect_ is constructed before cropping,
1527 // we can't trust it. If any changes were pending, we invalidate whole
1528 // frame here.
1529 if (!accumulated_update_rect_.IsEmpty()) {
1530 accumulated_update_rect_ =
1531 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001532 accumulated_update_rect_is_valid_ = false;
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001533 }
1534 }
1535
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001536 if (!accumulated_update_rect_is_valid_) {
1537 out_frame.clear_update_rect();
1538 } else if (!accumulated_update_rect_.IsEmpty() &&
1539 out_frame.has_update_rect()) {
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001540 accumulated_update_rect_.Union(out_frame.update_rect());
1541 accumulated_update_rect_.Intersect(
1542 VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
1543 out_frame.set_update_rect(accumulated_update_rect_);
1544 accumulated_update_rect_.MakeEmptyUpdate();
ilnik6b826ef2017-06-16 06:53:48 -07001545 }
Ilya Nikolaevskiy9560d7d2019-10-30 11:19:47 +01001546 accumulated_update_rect_is_valid_ = true;
ilnik6b826ef2017-06-16 06:53:48 -07001547
Magnus Jedvert26679d62015-04-07 14:07:41 +02001548 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +00001549 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +00001550
Niels Möller7dc26b72017-12-06 10:27:48 +01001551 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -07001552
Ilya Nikolaevskiyabd9e0f2019-09-25 16:05:47 +02001553 RTC_DCHECK_LE(send_codec_.width, out_frame.width());
1554 RTC_DCHECK_LE(send_codec_.height, out_frame.height());
1555 // Native frames should be scaled by the client.
1556 // For internal encoders we scale everything in one place here.
1557 RTC_DCHECK((out_frame.video_frame_buffer()->type() ==
1558 VideoFrameBuffer::Type::kNative) ||
1559 (send_codec_.width == out_frame.width() &&
1560 send_codec_.height == out_frame.height()));
Erik Språng6a7baa72019-02-26 18:31:00 +01001561
1562 TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
1563 out_frame.timestamp());
1564
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001565 frame_encode_metadata_writer_.OnEncodeStarted(out_frame);
Erik Språng6a7baa72019-02-26 18:31:00 +01001566
Niels Möllerc8d2e732019-03-06 12:00:33 +01001567 const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001568 was_encode_called_since_last_initialization_ = true;
Erik Språng6a7baa72019-02-26 18:31:00 +01001569
Erik Språngd7329ca2019-02-21 21:19:53 +01001570 if (encode_status < 0) {
philipele8ed8302019-07-03 11:53:48 +02001571 if (encode_status == WEBRTC_VIDEO_CODEC_ENCODER_FAILURE) {
1572 RTC_LOG(LS_ERROR) << "Encoder failed, failing encoder format: "
1573 << encoder_config_.video_format.ToString();
philipeld9cc8c02019-09-16 14:53:40 +02001574 if (settings_.encoder_switch_request_callback) {
philipele8ed8302019-07-03 11:53:48 +02001575 encoder_failed_ = true;
philipeld9cc8c02019-09-16 14:53:40 +02001576 settings_.encoder_switch_request_callback->RequestEncoderFallback();
philipele8ed8302019-07-03 11:53:48 +02001577 } else {
1578 RTC_LOG(LS_ERROR)
1579 << "Encoder failed but no encoder fallback callback is registered";
1580 }
1581 } else {
1582 RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
1583 << encode_status;
1584 }
1585
Erik Språngd7329ca2019-02-21 21:19:53 +01001586 return;
1587 }
1588
1589 for (auto& it : next_frame_types_) {
Niels Möller8f7ce222019-03-21 15:43:58 +01001590 it = VideoFrameType::kVideoFrameDelta;
Erik Språngd7329ca2019-02-21 21:19:53 +01001591 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001592}
niklase@google.com470e71d2011-07-07 08:21:25 +00001593
mflodmancc3d4422017-08-03 08:27:51 -07001594void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -07001595 if (!encoder_queue_.IsCurrent()) {
1596 encoder_queue_.PostTask([this] { SendKeyFrame(); });
1597 return;
1598 }
1599 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller1c9aa1e2018-02-16 10:27:23 +01001600 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
Erik Språngd7329ca2019-02-21 21:19:53 +01001601 RTC_DCHECK(!next_frame_types_.empty());
Sergey Silkine62a08a2019-05-13 13:45:39 +02001602
1603 // TODO(webrtc:10615): Map keyframe request to spatial layer.
1604 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1605 VideoFrameType::kVideoFrameKey);
1606
Erik Språngd7329ca2019-02-21 21:19:53 +01001607 if (HasInternalSource()) {
1608 // Try to request the frame if we have an external encoder with
1609 // internal source since AddVideoFrame never will be called.
Erik Språng6a7baa72019-02-26 18:31:00 +01001610
1611 // TODO(nisse): Used only with internal source. Delete as soon as
1612 // that feature is removed. The only implementation I've been able
1613 // to find ignores what's in the frame. With one exception: It seems
1614 // a few test cases, e.g.,
1615 // VideoSendStreamTest.VideoSendStreamStopSetEncoderRateToZero, set
1616 // internal_source to true and use FakeEncoder. And the latter will
1617 // happily encode this 1x1 frame and pass it on down the pipeline.
1618 if (encoder_->Encode(VideoFrame::Builder()
1619 .set_video_frame_buffer(I420Buffer::Create(1, 1))
1620 .set_rotation(kVideoRotation_0)
1621 .set_timestamp_us(0)
1622 .build(),
Erik Språng6a7baa72019-02-26 18:31:00 +01001623 &next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {
Erik Språngd7329ca2019-02-21 21:19:53 +01001624 // Try to remove just-performed keyframe request, if stream still exists.
Sergey Silkine62a08a2019-05-13 13:45:39 +02001625 std::fill(next_frame_types_.begin(), next_frame_types_.end(),
1626 VideoFrameType::kVideoFrameDelta);
Erik Språngd7329ca2019-02-21 21:19:53 +01001627 }
1628 }
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00001629}
1630
Elad Alonb6ef99b2019-04-10 16:37:07 +02001631void VideoStreamEncoder::OnLossNotification(
1632 const VideoEncoder::LossNotification& loss_notification) {
1633 if (!encoder_queue_.IsCurrent()) {
1634 encoder_queue_.PostTask(
1635 [this, loss_notification] { OnLossNotification(loss_notification); });
1636 return;
1637 }
1638
1639 RTC_DCHECK_RUN_ON(&encoder_queue_);
1640 if (encoder_) {
1641 encoder_->OnLossNotification(loss_notification);
1642 }
1643}
1644
mflodmancc3d4422017-08-03 08:27:51 -07001645EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001646 const EncodedImage& encoded_image,
1647 const CodecSpecificInfo* codec_specific_info,
1648 const RTPFragmentationHeader* fragmentation) {
Erik Språng6a7baa72019-02-26 18:31:00 +01001649 TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
1650 "timestamp", encoded_image.Timestamp());
1651 const size_t spatial_idx = encoded_image.SpatialIndex().value_or(0);
1652 EncodedImage image_copy(encoded_image);
1653
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +02001654 frame_encode_metadata_writer_.FillTimingInfo(spatial_idx, &image_copy);
Erik Språng6a7baa72019-02-26 18:31:00 +01001655
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001656 std::unique_ptr<RTPFragmentationHeader> fragmentation_copy =
1657 frame_encode_metadata_writer_.UpdateBitstream(codec_specific_info,
1658 fragmentation, &image_copy);
1659
Erik Språng6a7baa72019-02-26 18:31:00 +01001660 // Piggyback ALR experiment group id and simulcast id into the content type.
1661 const uint8_t experiment_id =
1662 experiment_groups_[videocontenttypehelpers::IsScreenshare(
1663 image_copy.content_type_)];
1664
1665 // TODO(ilnik): This will force content type extension to be present even
1666 // for realtime video. At the expense of miniscule overhead we will get
1667 // sliced receive statistics.
1668 RTC_CHECK(videocontenttypehelpers::SetExperimentId(&image_copy.content_type_,
1669 experiment_id));
1670 // We count simulcast streams from 1 on the wire. That's why we set simulcast
1671 // id in content type to +1 of that is actual simulcast index. This is because
1672 // value 0 on the wire is reserved for 'no simulcast stream specified'.
1673 RTC_CHECK(videocontenttypehelpers::SetSimulcastId(
1674 &image_copy.content_type_, static_cast<uint8_t>(spatial_idx + 1)));
1675
perkj26091b12016-09-01 01:17:40 -07001676 // Encoded is called on whatever thread the real encoder implementation run
1677 // on. In the case of hardware encoders, there might be several encoders
1678 // running in parallel on different threads.
Erik Språng6a7baa72019-02-26 18:31:00 +01001679 encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -07001680
philipelda5aa4d2019-04-26 13:37:37 +02001681 // The simulcast id is signaled in the SpatialIndex. This makes it impossible
1682 // to do simulcast for codecs that actually support spatial layers since we
1683 // can't distinguish between an actual spatial layer and a simulcast stream.
1684 // TODO(bugs.webrtc.org/10520): Signal the simulcast id explicitly.
1685 int simulcast_id = 0;
1686 if (codec_specific_info &&
1687 (codec_specific_info->codecType == kVideoCodecVP8 ||
1688 codec_specific_info->codecType == kVideoCodecH264 ||
1689 codec_specific_info->codecType == kVideoCodecGeneric)) {
1690 simulcast_id = encoded_image.SpatialIndex().value_or(0);
1691 }
1692
1693 std::unique_ptr<CodecSpecificInfo> codec_info_copy;
1694 {
1695 rtc::CritScope cs(&encoded_image_lock_);
1696
1697 if (codec_specific_info && codec_specific_info->generic_frame_info) {
1698 codec_info_copy =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001699 std::make_unique<CodecSpecificInfo>(*codec_specific_info);
philipelda5aa4d2019-04-26 13:37:37 +02001700 GenericFrameInfo& generic_info = *codec_info_copy->generic_frame_info;
1701 generic_info.frame_id = next_frame_id_++;
1702
1703 if (encoder_buffer_state_.size() <= static_cast<size_t>(simulcast_id)) {
1704 RTC_LOG(LS_ERROR) << "At most " << encoder_buffer_state_.size()
1705 << " simulcast streams supported.";
1706 } else {
1707 std::array<int64_t, kMaxEncoderBuffers>& state =
1708 encoder_buffer_state_[simulcast_id];
1709 for (const CodecBufferUsage& buffer : generic_info.encoder_buffers) {
1710 if (state.size() <= static_cast<size_t>(buffer.id)) {
1711 RTC_LOG(LS_ERROR)
1712 << "At most " << state.size() << " encoder buffers supported.";
1713 break;
1714 }
1715
1716 if (buffer.referenced) {
1717 int64_t diff = generic_info.frame_id - state[buffer.id];
1718 if (diff <= 0) {
1719 RTC_LOG(LS_ERROR) << "Invalid frame diff: " << diff << ".";
1720 } else if (absl::c_find(generic_info.frame_diffs, diff) ==
1721 generic_info.frame_diffs.end()) {
1722 generic_info.frame_diffs.push_back(diff);
1723 }
1724 }
1725
1726 if (buffer.updated)
1727 state[buffer.id] = generic_info.frame_id;
1728 }
1729 }
1730 }
1731 }
1732
1733 EncodedImageCallback::Result result = sink_->OnEncodedImage(
1734 image_copy, codec_info_copy ? codec_info_copy.get() : codec_specific_info,
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001735 fragmentation_copy ? fragmentation_copy.get() : fragmentation);
perkjbc75d972016-05-02 06:31:25 -07001736
Erik Språng7ca375c2019-02-06 16:20:17 +01001737 // We are only interested in propagating the meta-data about the image, not
1738 // encoded data itself, to the post encode function. Since we cannot be sure
1739 // the pointer will still be valid when run on the task queue, set it to null.
Erik Språng6a7baa72019-02-26 18:31:00 +01001740 image_copy.set_buffer(nullptr, 0);
Niels Möller83dbeac2017-12-14 16:39:44 +01001741
Erik Språng7ca375c2019-02-06 16:20:17 +01001742 int temporal_index = 0;
1743 if (codec_specific_info) {
1744 if (codec_specific_info->codecType == kVideoCodecVP9) {
1745 temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
1746 } else if (codec_specific_info->codecType == kVideoCodecVP8) {
1747 temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
1748 }
1749 }
1750 if (temporal_index == kNoTemporalIdx) {
1751 temporal_index = 0;
Niels Möller83dbeac2017-12-14 16:39:44 +01001752 }
1753
Erik Språng982dc792019-03-13 16:33:02 +01001754 RunPostEncode(image_copy, rtc::TimeMicros(), temporal_index);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001755
1756 if (result.error == Result::OK) {
1757 // In case of an internal encoder running on a separate thread, the
1758 // decision to drop a frame might be a frame late and signaled via
1759 // atomic flag. This is because we can't easily wait for the worker thread
1760 // without risking deadlocks, eg during shutdown when the worker thread
1761 // might be waiting for the internal encoder threads to stop.
1762 if (pending_frame_drops_.load() > 0) {
1763 int pending_drops = pending_frame_drops_.fetch_sub(1);
1764 RTC_DCHECK_GT(pending_drops, 0);
1765 result.drop_next_frame = true;
1766 }
1767 }
perkj803d97f2016-11-01 11:45:46 -07001768
Sergey Ulanov525df3f2016-08-02 17:46:41 -07001769 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +01001770}
1771
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001772void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
1773 switch (reason) {
1774 case DropReason::kDroppedByMediaOptimizations:
Niels Möller213618e2018-07-24 09:29:58 +02001775 encoder_stats_observer_->OnFrameDropped(
1776 VideoStreamEncoderObserver::DropReason::kMediaOptimization);
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001777 encoder_queue_.PostTask([this] {
1778 RTC_DCHECK_RUN_ON(&encoder_queue_);
1779 if (quality_scaler_)
Åsa Perssona945aee2018-04-24 16:53:25 +02001780 quality_scaler_->ReportDroppedFrameByMediaOpt();
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001781 });
1782 break;
1783 case DropReason::kDroppedByEncoder:
Niels Möller213618e2018-07-24 09:29:58 +02001784 encoder_stats_observer_->OnFrameDropped(
1785 VideoStreamEncoderObserver::DropReason::kEncoder);
Åsa Perssona945aee2018-04-24 16:53:25 +02001786 encoder_queue_.PostTask([this] {
1787 RTC_DCHECK_RUN_ON(&encoder_queue_);
1788 if (quality_scaler_)
1789 quality_scaler_->ReportDroppedFrameByEncoder();
1790 });
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +02001791 break;
1792 }
Jakob Ivarsson159b4172019-10-30 14:02:14 +01001793 sink_->OnDroppedFrame(reason);
kthelgason876222f2016-11-29 01:44:11 -08001794}
1795
Erik Språng610c7632019-03-06 15:37:33 +01001796void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate,
Florent Castellia8336d32019-09-09 13:36:55 +02001797 DataRate stable_target_bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +02001798 DataRate link_allocation,
mflodmancc3d4422017-08-03 08:27:51 -07001799 uint8_t fraction_lost,
1800 int64_t round_trip_time_ms) {
Sebastian Jansson5a000162019-04-12 11:21:32 +02001801 RTC_DCHECK_GE(link_allocation, target_bitrate);
perkj26091b12016-09-01 01:17:40 -07001802 if (!encoder_queue_.IsCurrent()) {
Florent Castellia8336d32019-09-09 13:36:55 +02001803 encoder_queue_.PostTask([this, target_bitrate, stable_target_bitrate,
1804 link_allocation, fraction_lost,
1805 round_trip_time_ms] {
1806 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
1807 fraction_lost, round_trip_time_ms);
Erik Språng610c7632019-03-06 15:37:33 +01001808 });
perkj26091b12016-09-01 01:17:40 -07001809 return;
1810 }
1811 RTC_DCHECK_RUN_ON(&encoder_queue_);
philipeld9cc8c02019-09-16 14:53:40 +02001812
1813 if (encoder_switch_experiment_.IsBitrateBelowThreshold(target_bitrate) &&
1814 settings_.encoder_switch_request_callback && !encoder_switch_requested_) {
1815 EncoderSwitchRequestCallback::Config conf;
1816 conf.codec_name = encoder_switch_experiment_.to_codec;
1817 conf.param = encoder_switch_experiment_.to_param;
1818 conf.value = encoder_switch_experiment_.to_value;
1819 settings_.encoder_switch_request_callback->RequestEncoderSwitch(conf);
1820
1821 encoder_switch_requested_ = true;
1822 }
1823
perkj26091b12016-09-01 01:17:40 -07001824 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
1825
Erik Språng610c7632019-03-06 15:37:33 +01001826 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps()
Florent Castellia8336d32019-09-09 13:36:55 +02001827 << " stable bitrate = " << stable_target_bitrate.bps()
Erik Språng4c6ca302019-04-08 15:14:01 +02001828 << " link allocation bitrate = " << link_allocation.bps()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001829 << " packet loss " << static_cast<int>(fraction_lost)
1830 << " rtt " << round_trip_time_ms;
Åsa Persson139f4dc2019-08-02 09:29:58 +02001831
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001832 // On significant changes to BWE at the start of the call,
1833 // enable frame drops to quickly react to jumps in available bandwidth.
1834 if (encoder_start_bitrate_bps_ != 0 &&
1835 !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
1836 initial_framedrop_on_bwe_enabled_ &&
Erik Språng610c7632019-03-06 15:37:33 +01001837 abs_diff(target_bitrate.bps(), encoder_start_bitrate_bps_) >=
Kári Tristan Helgason639602a2018-08-02 10:51:40 +02001838 kFramedropThreshold * encoder_start_bitrate_bps_) {
1839 // Reset initial framedrop feature when first real BW estimate arrives.
1840 // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
1841 // without an actual BW estimate.
1842 initial_framedrop_ = 0;
1843 has_seen_first_significant_bwe_change_ = true;
1844 }
Åsa Persson139f4dc2019-08-02 09:29:58 +02001845 if (set_start_bitrate_bps_ > 0 && !has_seen_first_bwe_drop_ &&
1846 quality_scaler_ && quality_scaler_settings_.InitialBitrateIntervalMs() &&
1847 quality_scaler_settings_.InitialBitrateFactor()) {
1848 int64_t diff_ms = clock_->TimeInMilliseconds() - set_start_bitrate_time_ms_;
1849 if (diff_ms < quality_scaler_settings_.InitialBitrateIntervalMs().value() &&
1850 (target_bitrate.bps() <
1851 (set_start_bitrate_bps_ *
1852 quality_scaler_settings_.InitialBitrateFactor().value()))) {
1853 RTC_LOG(LS_INFO) << "Reset initial_framedrop_. Start bitrate: "
1854 << set_start_bitrate_bps_
1855 << ", target bitrate: " << target_bitrate.bps();
1856 initial_framedrop_ = 0;
1857 has_seen_first_bwe_drop_ = true;
1858 }
1859 }
perkj26091b12016-09-01 01:17:40 -07001860
Elad Aloncde8ab22019-03-20 11:56:20 +01001861 if (encoder_) {
1862 encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f);
1863 encoder_->OnRttUpdate(round_trip_time_ms);
1864 }
1865
Niels Möller6bb5ab92019-01-11 11:11:10 +01001866 uint32_t framerate_fps = GetInputFramerateFps();
Erik Språng610c7632019-03-06 15:37:33 +01001867 frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps);
Erik Språng4c6ca302019-04-08 15:14:01 +02001868 const bool video_is_suspended = target_bitrate == DataRate::Zero();
1869 const bool video_suspension_changed = video_is_suspended != EncoderPaused();
1870
Florent Castellia8336d32019-09-09 13:36:55 +02001871 EncoderRateSettings new_rate_settings{
1872 VideoBitrateAllocation(), static_cast<double>(framerate_fps),
1873 link_allocation, target_bitrate, stable_target_bitrate};
Erik Språng4c6ca302019-04-08 15:14:01 +02001874 SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
perkj26091b12016-09-01 01:17:40 -07001875
Erik Språng610c7632019-03-06 15:37:33 +01001876 encoder_start_bitrate_bps_ = target_bitrate.bps() != 0
1877 ? target_bitrate.bps()
1878 : encoder_start_bitrate_bps_;
Peter Boströmd153a372015-11-10 15:27:12 +00001879
sprang552c7c72017-02-13 04:41:45 -08001880 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
1882 << (video_is_suspended ? "suspended" : "not suspended");
Niels Möller213618e2018-07-24 09:29:58 +02001883 encoder_stats_observer_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +02001884 }
Sebastian Janssona3177052018-04-10 13:05:49 +02001885 if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
1886 !DropDueToSize(pending_frame_->size())) {
1887 int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
1888 if (pending_time_us < kPendingFrameTimeoutMs * 1000)
1889 EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
1890 pending_frame_.reset();
1891 }
1892}
1893
1894bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
Sergey Silkin41c650b2019-10-14 13:12:19 +02001895 if (initial_framedrop_ >= kMaxInitialFramedrop ||
1896 encoder_start_bitrate_bps_ == 0) {
1897 return false;
1898 }
1899
1900 absl::optional<VideoEncoder::ResolutionBitrateLimits> encoder_bitrate_limits =
1901 GetEncoderBitrateLimits(encoder_->GetEncoderInfo(), pixel_count);
1902
1903 if (encoder_bitrate_limits.has_value()) {
1904 // Use bitrate limits provided by encoder.
1905 return encoder_start_bitrate_bps_ <
1906 static_cast<uint32_t>(encoder_bitrate_limits->min_start_bitrate_bps);
1907 }
1908
1909 if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
1910 return pixel_count > 320 * 240;
1911 } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
1912 return pixel_count > 640 * 480;
Sebastian Janssona3177052018-04-10 13:05:49 +02001913 }
1914 return false;
niklase@google.com470e71d2011-07-07 08:21:25 +00001915}
1916
Åsa Perssone644a032019-11-08 15:56:00 +01001917bool VideoStreamEncoder::TryQualityRampup(int64_t now_ms) {
1918 if (!quality_scaler_)
1919 return false;
1920
1921 uint32_t bw_kbps = last_encoder_rate_settings_
1922 ? last_encoder_rate_settings_->rate_control
1923 .bandwidth_allocation.kbps()
1924 : 0;
1925
1926 if (quality_rampup_experiment_.BwHigh(now_ms, bw_kbps)) {
1927 // Verify that encoder is at max bitrate and the QP is low.
1928 if (encoder_start_bitrate_bps_ == send_codec_.maxBitrate * 1000 &&
1929 quality_scaler_->QpFastFilterLow()) {
1930 return true;
1931 }
1932 }
1933 return false;
1934}
1935
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001936bool VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001937 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -07001938 AdaptationRequest adaptation_request = {
1939 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02001940 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07001941 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -07001942
sprangc5d62e22017-04-02 23:53:04 -07001943 bool downgrade_requested =
1944 last_adaptation_request_ &&
1945 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
1946
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001947 bool did_adapt = true;
1948
sprangc5d62e22017-04-02 23:53:04 -07001949 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001950 case DegradationPreference::BALANCED:
asaperssonf7e294d2017-06-13 23:25:22 -07001951 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001952 case DegradationPreference::MAINTAIN_FRAMERATE:
sprangc5d62e22017-04-02 23:53:04 -07001953 if (downgrade_requested &&
1954 adaptation_request.input_pixel_count_ >=
1955 last_adaptation_request_->input_pixel_count_) {
1956 // Don't request lower resolution if the current resolution is not
1957 // lower than the last time we asked for the resolution to be lowered.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001958 return true;
sprangc5d62e22017-04-02 23:53:04 -07001959 }
1960 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001961 case DegradationPreference::MAINTAIN_RESOLUTION:
sprangc5d62e22017-04-02 23:53:04 -07001962 if (adaptation_request.framerate_fps_ <= 0 ||
1963 (downgrade_requested &&
1964 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
1965 // If no input fps estimate available, can't determine how to scale down
1966 // framerate. Otherwise, don't request lower framerate if we don't have
1967 // a valid frame rate. Since framerate, unlike resolution, is a measure
1968 // we have to estimate, and can fluctuate naturally over time, don't
1969 // make the same kind of limitations as for resolution, but trust the
1970 // overuse detector to not trigger too often.
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001971 return true;
sprangc5d62e22017-04-02 23:53:04 -07001972 }
1973 break;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001974 case DegradationPreference::DISABLED:
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001975 return true;
sprang84a37592017-02-10 07:04:27 -08001976 }
sprangc5d62e22017-04-02 23:53:04 -07001977
sprangc5d62e22017-04-02 23:53:04 -07001978 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001979 case DegradationPreference::BALANCED: {
asaperssonf7e294d2017-06-13 23:25:22 -07001980 // Try scale down framerate, if lower.
Åsa Persson48284b82019-07-08 10:01:12 +02001981 int fps = balanced_settings_.MinFps(encoder_config_.codec_type,
1982 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07001983 if (source_proxy_->RestrictFramerate(fps)) {
1984 GetAdaptCounter().IncrementFramerate(reason);
Åsa Perssonf5e5d252019-08-16 17:24:59 +02001985 // Check if requested fps is higher (or close to) input fps.
1986 absl::optional<int> min_diff =
1987 balanced_settings_.MinFpsDiff(last_frame_info_->pixel_count());
1988 if (min_diff && adaptation_request.framerate_fps_ > 0) {
1989 int fps_diff = adaptation_request.framerate_fps_ - fps;
1990 if (fps_diff < min_diff.value()) {
1991 did_adapt = false;
1992 }
1993 }
asaperssonf7e294d2017-06-13 23:25:22 -07001994 break;
1995 }
1996 // Scale down resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01001997 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001998 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07001999 case DegradationPreference::MAINTAIN_FRAMERATE: {
asapersson13874762017-06-07 00:01:02 -07002000 // Scale down resolution.
Åsa Perssonc3ed6302017-11-16 14:04:52 +01002001 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -07002002 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -07002003 adaptation_request.input_pixel_count_,
Erik Språnge2fd86a2018-10-24 11:32:39 +02002004 encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
Åsa Perssonc3ed6302017-11-16 14:04:52 +01002005 &min_pixels_reached)) {
2006 if (min_pixels_reached)
Niels Möller213618e2018-07-24 09:29:58 +02002007 encoder_stats_observer_->OnMinPixelLimitReached();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02002008 return true;
asaperssond0de2952017-04-21 01:47:31 -07002009 }
asaperssonf7e294d2017-06-13 23:25:22 -07002010 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07002011 break;
Åsa Perssonc3ed6302017-11-16 14:04:52 +01002012 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002013 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07002014 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07002015 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
2016 adaptation_request.framerate_fps_);
2017 if (requested_framerate == -1)
Åsa Perssonf5e5d252019-08-16 17:24:59 +02002018 return true;
sprangfda496a2017-06-15 04:21:07 -07002019 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01002020 overuse_detector_->OnTargetFramerateUpdated(
2021 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07002022 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07002023 break;
sprangfda496a2017-06-15 04:21:07 -07002024 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002025 case DegradationPreference::DISABLED:
sprangc5d62e22017-04-02 23:53:04 -07002026 RTC_NOTREACHED();
2027 }
2028
asaperssond0de2952017-04-21 01:47:31 -07002029 last_adaptation_request_.emplace(adaptation_request);
2030
asapersson09f05612017-05-15 23:40:18 -07002031 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07002032
Mirko Bonadei675513b2017-11-09 11:09:25 +01002033 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
Åsa Perssonf5e5d252019-08-16 17:24:59 +02002034 return did_adapt;
perkj26091b12016-09-01 01:17:40 -07002035}
2036
mflodmancc3d4422017-08-03 08:27:51 -07002037void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07002038 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07002039
2040 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
2041 int num_downgrades = adapt_counter.TotalCount(reason);
2042 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07002043 return;
asapersson09f05612017-05-15 23:40:18 -07002044 RTC_DCHECK_GT(num_downgrades, 0);
2045
sprangc5d62e22017-04-02 23:53:04 -07002046 AdaptationRequest adaptation_request = {
2047 last_frame_info_->pixel_count(),
Niels Möller213618e2018-07-24 09:29:58 +02002048 encoder_stats_observer_->GetInputFrameRate(),
sprangc5d62e22017-04-02 23:53:04 -07002049 AdaptationRequest::Mode::kAdaptUp};
2050
2051 bool adapt_up_requested =
2052 last_adaptation_request_ &&
2053 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07002054
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002055 if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
asaperssonf7e294d2017-06-13 23:25:22 -07002056 if (adapt_up_requested &&
2057 adaptation_request.input_pixel_count_ <=
2058 last_adaptation_request_->input_pixel_count_) {
2059 // Don't request higher resolution if the current resolution is not
2060 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07002061 return;
asaperssonf7e294d2017-06-13 23:25:22 -07002062 }
sprangb1ca0732017-02-01 08:38:12 -08002063 }
sprangc5d62e22017-04-02 23:53:04 -07002064
sprangc5d62e22017-04-02 23:53:04 -07002065 switch (degradation_preference_) {
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002066 case DegradationPreference::BALANCED: {
Åsa Persson4869bd62019-08-23 16:20:06 +02002067 // Check if quality should be increased based on bitrate.
2068 if (reason == kQuality &&
2069 !balanced_settings_.CanAdaptUp(last_frame_info_->pixel_count(),
2070 encoder_start_bitrate_bps_)) {
Åsa Persson1b247f12019-08-14 17:26:39 +02002071 return;
2072 }
asaperssonf7e294d2017-06-13 23:25:22 -07002073 // Try scale up framerate, if higher.
Åsa Persson48284b82019-07-08 10:01:12 +02002074 int fps = balanced_settings_.MaxFps(encoder_config_.codec_type,
2075 last_frame_info_->pixel_count());
asaperssonf7e294d2017-06-13 23:25:22 -07002076 if (source_proxy_->IncreaseFramerate(fps)) {
2077 GetAdaptCounter().DecrementFramerate(reason, fps);
2078 // Reset framerate in case of fewer fps steps down than up.
2079 if (adapt_counter.FramerateCount() == 0 &&
2080 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002081 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07002082 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
2083 }
2084 break;
2085 }
Åsa Persson30ab0152019-08-27 12:22:33 +02002086 // Check if resolution should be increased based on bitrate.
2087 if (reason == kQuality &&
2088 !balanced_settings_.CanAdaptUpResolution(
2089 last_frame_info_->pixel_count(), encoder_start_bitrate_bps_)) {
2090 return;
2091 }
asaperssonf7e294d2017-06-13 23:25:22 -07002092 // Scale up resolution.
Karl Wiberg80ba3332018-02-05 10:33:35 +01002093 RTC_FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07002094 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002095 case DegradationPreference::MAINTAIN_FRAMERATE: {
Sergey Silkin41c650b2019-10-14 13:12:19 +02002096 // Check if resolution should be increased based on bitrate and
2097 // limits specified by encoder capabilities.
2098 if (reason == kQuality &&
2099 !CanAdaptUpResolution(last_frame_info_->pixel_count(),
2100 encoder_start_bitrate_bps_)) {
2101 return;
2102 }
2103
asapersson13874762017-06-07 00:01:02 -07002104 // Scale up resolution.
2105 int pixel_count = adaptation_request.input_pixel_count_;
2106 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002107 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07002108 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07002109 }
asapersson13874762017-06-07 00:01:02 -07002110 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
2111 return;
asaperssonf7e294d2017-06-13 23:25:22 -07002112 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07002113 break;
asapersson13874762017-06-07 00:01:02 -07002114 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002115 case DegradationPreference::MAINTAIN_RESOLUTION: {
asapersson13874762017-06-07 00:01:02 -07002116 // Scale up framerate.
2117 int fps = adaptation_request.framerate_fps_;
2118 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002119 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07002120 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07002121 }
sprangfda496a2017-06-15 04:21:07 -07002122
2123 const int requested_framerate =
2124 source_proxy_->RequestHigherFramerateThan(fps);
2125 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01002126 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07002127 return;
sprangfda496a2017-06-15 04:21:07 -07002128 }
Niels Möller7dc26b72017-12-06 10:27:48 +01002129 overuse_detector_->OnTargetFramerateUpdated(
2130 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07002131 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07002132 break;
asapersson13874762017-06-07 00:01:02 -07002133 }
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002134 case DegradationPreference::DISABLED:
asaperssonf7e294d2017-06-13 23:25:22 -07002135 return;
sprangc5d62e22017-04-02 23:53:04 -07002136 }
2137
asaperssond0de2952017-04-21 01:47:31 -07002138 last_adaptation_request_.emplace(adaptation_request);
2139
asapersson09f05612017-05-15 23:40:18 -07002140 UpdateAdaptationStats(reason);
2141
Mirko Bonadei675513b2017-11-09 11:09:25 +01002142 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07002143}
2144
Sergey Silkin41c650b2019-10-14 13:12:19 +02002145bool VideoStreamEncoder::CanAdaptUpResolution(int pixels,
2146 uint32_t bitrate_bps) const {
2147 absl::optional<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
2148 GetEncoderBitrateLimits(encoder_info_,
2149 source_proxy_->GetHigherResolutionThan(pixels));
2150 if (!bitrate_limits.has_value() || bitrate_bps == 0) {
2151 return true; // No limit configured or bitrate provided.
2152 }
2153 RTC_DCHECK_GE(bitrate_limits->frame_size_pixels, pixels);
2154 return bitrate_bps >=
2155 static_cast<uint32_t>(bitrate_limits->min_start_bitrate_bps);
2156}
2157
Niels Möller213618e2018-07-24 09:29:58 +02002158// TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
mflodmancc3d4422017-08-03 08:27:51 -07002159void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07002160 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07002161 case kCpu:
Niels Möller213618e2018-07-24 09:29:58 +02002162 encoder_stats_observer_->OnAdaptationChanged(
2163 VideoStreamEncoderObserver::AdaptationReason::kCpu,
2164 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asapersson09f05612017-05-15 23:40:18 -07002165 break;
2166 case kQuality:
Niels Möller213618e2018-07-24 09:29:58 +02002167 encoder_stats_observer_->OnAdaptationChanged(
2168 VideoStreamEncoderObserver::AdaptationReason::kQuality,
2169 GetActiveCounts(kCpu), GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07002170 break;
2171 }
perkj26091b12016-09-01 01:17:40 -07002172}
2173
Niels Möller213618e2018-07-24 09:29:58 +02002174VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
mflodmancc3d4422017-08-03 08:27:51 -07002175 AdaptReason reason) {
Niels Möller213618e2018-07-24 09:29:58 +02002176 VideoStreamEncoderObserver::AdaptationSteps counts =
mflodmancc3d4422017-08-03 08:27:51 -07002177 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07002178 switch (reason) {
2179 case kCpu:
2180 if (!IsFramerateScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002181 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002182 if (!IsResolutionScalingEnabled(degradation_preference_))
Niels Möller213618e2018-07-24 09:29:58 +02002183 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002184 break;
2185 case kQuality:
2186 if (!IsFramerateScalingEnabled(degradation_preference_) ||
2187 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002188 counts.num_framerate_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002189 }
2190 if (!IsResolutionScalingEnabled(degradation_preference_) ||
2191 !quality_scaler_) {
Niels Möller213618e2018-07-24 09:29:58 +02002192 counts.num_resolution_reductions = absl::nullopt;
asapersson09f05612017-05-15 23:40:18 -07002193 }
2194 break;
sprangc5d62e22017-04-02 23:53:04 -07002195 }
asapersson09f05612017-05-15 23:40:18 -07002196 return counts;
sprangc5d62e22017-04-02 23:53:04 -07002197}
2198
mflodmancc3d4422017-08-03 08:27:51 -07002199VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002200 return adapt_counters_[degradation_preference_];
2201}
2202
mflodmancc3d4422017-08-03 08:27:51 -07002203const VideoStreamEncoder::AdaptCounter&
2204VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002205 return adapt_counters_[degradation_preference_];
2206}
2207
Erik Språng7ca375c2019-02-06 16:20:17 +01002208void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
Niels Möller6bb5ab92019-01-11 11:11:10 +01002209 int64_t time_sent_us,
Erik Språng7ca375c2019-02-06 16:20:17 +01002210 int temporal_index) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002211 if (!encoder_queue_.IsCurrent()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01002212 encoder_queue_.PostTask(
2213 [this, encoded_image, time_sent_us, temporal_index] {
2214 RunPostEncode(encoded_image, time_sent_us, temporal_index);
2215 });
Niels Möller6bb5ab92019-01-11 11:11:10 +01002216 return;
2217 }
2218
2219 RTC_DCHECK_RUN_ON(&encoder_queue_);
Erik Språng7ca375c2019-02-06 16:20:17 +01002220
2221 absl::optional<int> encode_duration_us;
2222 if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
2223 encode_duration_us =
2224 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
2225 rtc::kNumMicrosecsPerMillisec *
2226 (encoded_image.timing_.encode_finish_ms -
2227 encoded_image.timing_.encode_start_ms);
2228 }
2229
2230 // Run post encode tasks, such as overuse detection and frame rate/drop
2231 // stats for internal encoders.
2232 const size_t frame_size = encoded_image.size();
Niels Möller87e2d782019-03-07 10:18:23 +01002233 const bool keyframe =
2234 encoded_image._frameType == VideoFrameType::kVideoFrameKey;
Erik Språng7ca375c2019-02-06 16:20:17 +01002235
2236 if (frame_size > 0) {
2237 frame_dropper_.Fill(frame_size, !keyframe);
Niels Möller6bb5ab92019-01-11 11:11:10 +01002238 }
2239
Erik Språngd7329ca2019-02-21 21:19:53 +01002240 if (HasInternalSource()) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01002241 // Update frame dropper after the fact for internal sources.
2242 input_framerate_.Update(1u, clock_->TimeInMilliseconds());
2243 frame_dropper_.Leak(GetInputFramerateFps());
2244 // Signal to encoder to drop next frame.
2245 if (frame_dropper_.DropFrame()) {
2246 pending_frame_drops_.fetch_add(1);
2247 }
2248 }
2249
Erik Språng7ca375c2019-02-06 16:20:17 +01002250 overuse_detector_->FrameSent(
2251 encoded_image.Timestamp(), time_sent_us,
2252 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
2253 encode_duration_us);
2254 if (quality_scaler_ && encoded_image.qp_ >= 0)
Sebastian Janssonb6789402019-03-01 15:40:49 +01002255 quality_scaler_->ReportQp(encoded_image.qp_, time_sent_us);
Erik Språng7ca375c2019-02-06 16:20:17 +01002256 if (bitrate_adjuster_) {
2257 bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
2258 }
Niels Möller6bb5ab92019-01-11 11:11:10 +01002259}
2260
Erik Språngd7329ca2019-02-21 21:19:53 +01002261bool VideoStreamEncoder::HasInternalSource() const {
2262 // TODO(sprang): Checking both info from encoder and from encoder factory
2263 // until we have deprecated and removed the encoder factory info.
2264 return codec_info_.has_internal_source || encoder_info_.has_internal_source;
2265}
2266
Erik Språng6a7baa72019-02-26 18:31:00 +01002267void VideoStreamEncoder::ReleaseEncoder() {
2268 if (!encoder_ || !encoder_initialized_) {
2269 return;
2270 }
2271 encoder_->Release();
2272 encoder_initialized_ = false;
2273 TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
2274}
2275
asapersson09f05612017-05-15 23:40:18 -07002276// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07002277VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07002278 fps_counters_.resize(kScaleReasonSize);
2279 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07002280 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07002281}
2282
mflodmancc3d4422017-08-03 08:27:51 -07002283VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07002284
mflodmancc3d4422017-08-03 08:27:51 -07002285std::string VideoStreamEncoder::AdaptCounter::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002286 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002287 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
2288 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
Jonas Olsson84df1c72018-09-14 16:59:32 +02002289 return ss.Release();
asapersson09f05612017-05-15 23:40:18 -07002290}
2291
Niels Möller213618e2018-07-24 09:29:58 +02002292VideoStreamEncoderObserver::AdaptationSteps
2293VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
2294 VideoStreamEncoderObserver::AdaptationSteps counts;
2295 counts.num_framerate_reductions = fps_counters_[reason];
2296 counts.num_resolution_reductions = resolution_counters_[reason];
asapersson09f05612017-05-15 23:40:18 -07002297 return counts;
2298}
2299
mflodmancc3d4422017-08-03 08:27:51 -07002300void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002301 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07002302}
2303
mflodmancc3d4422017-08-03 08:27:51 -07002304void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002305 ++(resolution_counters_[reason]);
2306}
2307
mflodmancc3d4422017-08-03 08:27:51 -07002308void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002309 if (fps_counters_[reason] == 0) {
2310 // Balanced mode: Adapt up is in a different order, switch reason.
2311 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
2312 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
2313 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
2314 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
2315 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
2316 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2317 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
2318 MoveCount(&resolution_counters_, reason);
2319 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
2320 }
2321 --(fps_counters_[reason]);
2322 RTC_DCHECK_GE(fps_counters_[reason], 0);
2323}
2324
mflodmancc3d4422017-08-03 08:27:51 -07002325void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002326 if (resolution_counters_[reason] == 0) {
2327 // Balanced mode: Adapt up is in a different order, switch reason.
2328 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
2329 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
2330 MoveCount(&fps_counters_, reason);
2331 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
2332 }
2333 --(resolution_counters_[reason]);
2334 RTC_DCHECK_GE(resolution_counters_[reason], 0);
2335}
2336
mflodmancc3d4422017-08-03 08:27:51 -07002337void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
2338 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07002339 DecrementFramerate(reason);
2340 // Reset if at max fps (i.e. in case of fewer steps up than down).
2341 if (cur_fps == std::numeric_limits<int>::max())
Steve Antonbd631a02019-03-28 10:51:27 -07002342 absl::c_fill(fps_counters_, 0);
asapersson09f05612017-05-15 23:40:18 -07002343}
2344
mflodmancc3d4422017-08-03 08:27:51 -07002345int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07002346 return Count(fps_counters_);
2347}
2348
mflodmancc3d4422017-08-03 08:27:51 -07002349int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07002350 return Count(resolution_counters_);
2351}
2352
mflodmancc3d4422017-08-03 08:27:51 -07002353int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002354 return fps_counters_[reason];
2355}
2356
mflodmancc3d4422017-08-03 08:27:51 -07002357int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002358 return resolution_counters_[reason];
2359}
2360
mflodmancc3d4422017-08-03 08:27:51 -07002361int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07002362 return FramerateCount(reason) + ResolutionCount(reason);
2363}
2364
mflodmancc3d4422017-08-03 08:27:51 -07002365int VideoStreamEncoder::AdaptCounter::Count(
2366 const std::vector<int>& counters) const {
Steve Antonbd631a02019-03-28 10:51:27 -07002367 return absl::c_accumulate(counters, 0);
asapersson09f05612017-05-15 23:40:18 -07002368}
2369
mflodmancc3d4422017-08-03 08:27:51 -07002370void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
2371 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07002372 int to_reason = (from_reason + 1) % kScaleReasonSize;
2373 ++((*counters)[to_reason]);
2374 --((*counters)[from_reason]);
2375}
2376
mflodmancc3d4422017-08-03 08:27:51 -07002377std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07002378 const std::vector<int>& counters) const {
Jonas Olsson366a50c2018-09-06 13:41:30 +02002379 rtc::StringBuilder ss;
asapersson09f05612017-05-15 23:40:18 -07002380 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
2381 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07002382 }
Jonas Olsson84df1c72018-09-14 16:59:32 +02002383 return ss.Release();
sprangc5d62e22017-04-02 23:53:04 -07002384}
2385
philipeld9cc8c02019-09-16 14:53:40 +02002386bool VideoStreamEncoder::EncoderSwitchExperiment::IsBitrateBelowThreshold(
2387 const DataRate& target_bitrate) {
2388 DataRate rate =
2389 DataRate::kbps(bitrate_filter.Apply(1.0, target_bitrate.kbps()));
2390 return current_thresholds.bitrate && rate < *current_thresholds.bitrate;
2391}
2392
2393bool VideoStreamEncoder::EncoderSwitchExperiment::IsPixelCountBelowThreshold(
2394 int pixel_count) const {
2395 return current_thresholds.pixel_count &&
2396 pixel_count < *current_thresholds.pixel_count;
2397}
2398
2399void VideoStreamEncoder::EncoderSwitchExperiment::SetCodec(
2400 VideoCodecType codec) {
2401 auto it = codec_thresholds.find(codec);
2402 if (it == codec_thresholds.end()) {
2403 current_thresholds = {};
2404 } else {
2405 current_thresholds = it->second;
2406 }
2407}
2408
2409VideoStreamEncoder::EncoderSwitchExperiment
2410VideoStreamEncoder::ParseEncoderSwitchFieldTrial() const {
2411 EncoderSwitchExperiment result;
2412
2413 // Each "codec threshold" have the format
2414 // "<codec name>;<bitrate kbps>;<pixel count>", and are separated by the "|"
2415 // character.
2416 webrtc::FieldTrialOptional<std::string> codec_thresholds_string{
2417 "codec_thresholds"};
2418 webrtc::FieldTrialOptional<std::string> to_codec{"to_codec"};
2419 webrtc::FieldTrialOptional<std::string> to_param{"to_param"};
2420 webrtc::FieldTrialOptional<std::string> to_value{"to_value"};
2421 webrtc::FieldTrialOptional<double> window{"window"};
2422
2423 webrtc::ParseFieldTrial(
2424 {&codec_thresholds_string, &to_codec, &to_param, &to_value, &window},
2425 webrtc::field_trial::FindFullName(
2426 "WebRTC-NetworkCondition-EncoderSwitch"));
2427
2428 if (!codec_thresholds_string || !to_codec || !window) {
2429 return {};
2430 }
2431
2432 result.bitrate_filter.Reset(1.0 - 1.0 / *window);
2433 result.to_codec = *to_codec;
2434 result.to_param = to_param.GetOptional();
2435 result.to_value = to_value.GetOptional();
2436
2437 std::vector<std::string> codecs_thresholds;
2438 if (rtc::split(*codec_thresholds_string, '|', &codecs_thresholds) == 0) {
2439 return {};
2440 }
2441
2442 for (const std::string& codec_threshold : codecs_thresholds) {
2443 std::vector<std::string> thresholds_split;
2444 if (rtc::split(codec_threshold, ';', &thresholds_split) != 3) {
2445 return {};
2446 }
2447
2448 VideoCodecType codec = PayloadStringToCodecType(thresholds_split[0]);
2449 int bitrate_kbps;
2450 rtc::FromString(thresholds_split[1], &bitrate_kbps);
2451 int pixel_count;
2452 rtc::FromString(thresholds_split[2], &pixel_count);
2453
2454 if (bitrate_kbps > 0) {
2455 result.codec_thresholds[codec].bitrate = DataRate::kbps(bitrate_kbps);
2456 }
2457
2458 if (pixel_count > 0) {
2459 result.codec_thresholds[codec].pixel_count = pixel_count;
2460 }
2461
2462 if (!result.codec_thresholds[codec].bitrate &&
2463 !result.codec_thresholds[codec].pixel_count) {
2464 return {};
2465 }
2466 }
2467
2468 rtc::StringBuilder ss;
2469 ss << "Successfully parsed WebRTC-NetworkCondition-EncoderSwitch field "
2470 "trial."
2471 << " to_codec:" << result.to_codec
2472 << " to_param:" << result.to_param.value_or("<none>")
2473 << " to_value:" << result.to_value.value_or("<none>")
2474 << " codec_thresholds:";
2475
2476 for (auto kv : result.codec_thresholds) {
2477 std::string codec_name = CodecTypeToPayloadString(kv.first);
2478 std::string bitrate = kv.second.bitrate
2479 ? std::to_string(kv.second.bitrate->kbps())
2480 : "<none>";
2481 std::string pixels = kv.second.pixel_count
2482 ? std::to_string(*kv.second.pixel_count)
2483 : "<none>";
2484 ss << " (" << codec_name << ":" << bitrate << ":" << pixels << ")";
2485 }
2486
2487 RTC_LOG(LS_INFO) << ss.str();
2488
2489 return result;
2490}
2491
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00002492} // namespace webrtc