blob: 2032c4cb58712bf8e9a3bd47ae4f01519e45007a [file] [log] [blame]
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +02001/*
2 * Copyright 2018 The WebRTC project authors. All Rights Reserved.
3 *
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#include "video/video_send_stream_impl.h"
11
Yves Gerey3e707812018-11-28 16:47:49 +010012#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020013
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020014#include <algorithm>
Yves Gerey3e707812018-11-28 16:47:49 +010015#include <cstdint>
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020016#include <string>
17#include <utility>
18
Steve Antonbd631a02019-03-28 10:51:27 -070019#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080020#include "api/crypto/crypto_options.h"
21#include "api/rtp_parameters.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010022#include "api/scoped_refptr.h"
Artem Titovd15a5752021-02-10 14:31:24 +010023#include "api/sequence_checker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010024#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020025#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 16:47:49 +010026#include "call/video_send_stream.h"
Erik Språngf3f3a612022-05-13 15:55:29 +020027#include "modules/pacing/pacing_controller.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020028#include "rtc_base/checks.h"
29#include "rtc_base/experiments/alr_experiment.h"
Ying Wang8c5520c2019-09-03 15:25:21 +000030#include "rtc_base/experiments/field_trial_parser.h"
Elad Alon80f53b72019-10-11 16:19:43 +020031#include "rtc_base/experiments/min_video_bitrate_experiment.h"
Erik Språngcd76eab2019-01-21 18:06:46 +010032#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020033#include "rtc_base/logging.h"
34#include "rtc_base/numerics/safe_conversions.h"
35#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010036#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020037#include "system_wrappers/include/field_trial.h"
38
39namespace webrtc {
40namespace internal {
41namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020042
Erik Språng4e193e42018-09-14 19:01:58 +020043// Max positive size difference to treat allocations as "similar".
44static constexpr int kMaxVbaSizeDifferencePercent = 10;
45// Max time we will throttle similar video bitrate allocations.
46static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
47
Danil Chapovalov0c626af2020-02-10 11:16:00 +010048constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds(2);
Sebastian Janssonecb68972019-01-18 10:30:54 +010049
Erik Språng9d69cbe2020-10-22 17:44:42 +020050// When send-side BWE is used a stricter 1.1x pacing factor is used, rather than
51// the 2.5x which is used with receive-side BWE. Provides a more careful
52// bandwidth rampup with less risk of overshoots causing adverse effects like
53// packet loss. Not used for receive side BWE, since there we lack the probing
54// feature and so may result in too slow initial rampup.
55static constexpr double kStrictPacingMultiplier = 1.1;
56
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020057bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
58 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070059 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
60 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
61 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020062}
63
Erik Språngb57ab382018-09-13 10:52:38 +020064// Calculate max padding bitrate for a multi layer codec.
65int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020066 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010067 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020068 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020069 bool pad_to_min_bitrate,
70 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020071 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020072
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020073 RTC_DCHECK(!is_svc || streams.size() <= 1) << "Only one stream is allowed in "
74 "SVC mode.";
75
Erik Språngb57ab382018-09-13 10:52:38 +020076 // Filter out only the active streams;
77 std::vector<VideoStream> active_streams;
78 for (const VideoStream& stream : streams) {
79 if (stream.active)
80 active_streams.emplace_back(stream);
81 }
82
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020083 if (active_streams.size() > 1 || (!active_streams.empty() && is_svc)) {
84 // Simulcast or SVC is used.
85 // if SVC is used, stream bitrates should already encode svc bitrates:
86 // min_bitrate = min bitrate of a lowest svc layer.
87 // target_bitrate = sum of target bitrates of lower layers + min bitrate
88 // of the last one (as used in the calculations below).
89 // max_bitrate = sum of all active layers' max_bitrate.
Erik Språngb57ab382018-09-13 10:52:38 +020090 if (alr_probing) {
91 // With alr probing, just pad to the min bitrate of the lowest stream,
92 // probing will handle the rest of the rampup.
93 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
94 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010095 // Without alr probing, pad up to start bitrate of the
96 // highest active stream.
97 const double hysteresis_factor =
98 RateControlSettings::ParseFromFieldTrials()
99 .GetSimulcastHysteresisFactor(content_type);
Erik Språng576db1b2020-06-08 13:32:20 +0200100 if (is_svc) {
101 // For SVC, since there is only one "stream", the padding bitrate
102 // needed to enable the top spatial layer is stored in the
Artem Titovab30d722021-07-27 16:22:11 +0200103 // `target_bitrate_bps` field.
Erik Språng576db1b2020-06-08 13:32:20 +0200104 // TODO(sprang): This behavior needs to die.
105 pad_up_to_bitrate_bps = static_cast<int>(
106 hysteresis_factor * active_streams[0].target_bitrate_bps + 0.5);
107 } else {
108 const size_t top_active_stream_idx = active_streams.size() - 1;
109 pad_up_to_bitrate_bps = std::min(
110 static_cast<int>(
111 hysteresis_factor *
112 active_streams[top_active_stream_idx].min_bitrate_bps +
113 0.5),
114 active_streams[top_active_stream_idx].target_bitrate_bps);
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100115
Erik Språng576db1b2020-06-08 13:32:20 +0200116 // Add target_bitrate_bps of the lower active streams.
117 for (size_t i = 0; i < top_active_stream_idx; ++i) {
118 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
119 }
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100120 }
Erik Språngb57ab382018-09-13 10:52:38 +0200121 }
122 } else if (!active_streams.empty() && pad_to_min_bitrate) {
123 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200124 }
125
126 pad_up_to_bitrate_bps =
127 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
128
129 return pad_up_to_bitrate_bps;
130}
131
Erik Språngb57ab382018-09-13 10:52:38 +0200132absl::optional<AlrExperimentSettings> GetAlrSettings(
133 VideoEncoderConfig::ContentType content_type) {
134 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
135 return AlrExperimentSettings::CreateFromFieldTrial(
136 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
137 }
138 return AlrExperimentSettings::CreateFromFieldTrial(
139 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
140}
Erik Språng4e193e42018-09-14 19:01:58 +0200141
142bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
143 const VideoBitrateAllocation& rhs) {
144 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
145 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
146 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
147 return false;
148 }
149 }
150 }
151 return true;
152}
Tommie902f282021-06-03 12:02:02 +0200153
154// Returns an optional that has value iff TransportSeqNumExtensionConfigured
155// is `true` for the given video send stream config.
156absl::optional<float> GetConfiguredPacingFactor(
157 const VideoSendStream::Config& config,
158 VideoEncoderConfig::ContentType content_type,
159 const PacingConfig& default_pacing_config) {
160 if (!TransportSeqNumExtensionConfigured(config))
161 return absl::nullopt;
162
163 absl::optional<AlrExperimentSettings> alr_settings =
164 GetAlrSettings(content_type);
165 if (alr_settings)
166 return alr_settings->pacing_factor;
167
168 RateControlSettings rate_control_settings =
169 RateControlSettings::ParseFromFieldTrials();
170 return rate_control_settings.GetPacingFactor().value_or(
171 default_pacing_config.pacing_factor);
172}
173
Tommifa3ce632021-06-03 12:06:02 +0200174uint32_t GetInitialEncoderMaxBitrate(int initial_encoder_max_bitrate) {
175 if (initial_encoder_max_bitrate > 0)
176 return rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
177
178 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
179 // have any way to handle unset values in downstream code, such as the
180 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
181 // behaviour that is not safe. Converting to 10 Mbps should be safe for
182 // reasonable use cases as it allows adding the max of multiple streams
183 // without wrappping around.
184 const int kFallbackMaxBitrateBps = 10000000;
185 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
186 << initial_encoder_max_bitrate << " which is <= 0!";
187 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
188 return kFallbackMaxBitrateBps;
189}
190
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200191} // namespace
192
Jonas Orelande62c2f22022-03-29 11:04:48 +0200193PacingConfig::PacingConfig(const FieldTrialsView& field_trials)
Erik Språng9d69cbe2020-10-22 17:44:42 +0200194 : pacing_factor("factor", kStrictPacingMultiplier),
Erik Språngf3f3a612022-05-13 15:55:29 +0200195 max_pacing_delay("max_delay", PacingController::kMaxExpectedQueueLength) {
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100196 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
Jonas Oreland8ca06132022-03-14 12:52:48 +0100197 field_trials.Lookup("WebRTC-Video-Pacing"));
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100198}
199PacingConfig::PacingConfig(const PacingConfig&) = default;
200PacingConfig::~PacingConfig() = default;
201
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200202VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100203 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200204 SendStatisticsProxy* stats_proxy,
Danil Chapovalov03f8b8a2022-07-18 13:11:42 +0200205 TaskQueueBase* rtp_transport_queue,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200206 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200207 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200208 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200209 const VideoSendStream::Config* config,
210 int initial_encoder_max_bitrate,
211 double initial_encoder_bitrate_priority,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200212 VideoEncoderConfig::ContentType content_type,
Jonas Oreland8ca06132022-03-14 12:52:48 +0100213 RtpVideoSenderInterface* rtp_video_sender,
Jonas Orelande62c2f22022-03-29 11:04:48 +0200214 const FieldTrialsView& field_trials)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100215 : clock_(clock),
216 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200217 GetAlrSettings(content_type)),
Jonas Oreland8ca06132022-03-14 12:52:48 +0100218 pacing_config_(PacingConfig(field_trials)),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200219 stats_proxy_(stats_proxy),
220 config_(config),
Tommifa3ce632021-06-03 12:06:02 +0200221 rtp_transport_queue_(rtp_transport_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100222 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200223 transport_(transport),
224 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200225 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200226 max_padding_bitrate_(0),
227 encoder_min_bitrate_bps_(0),
Tommifa3ce632021-06-03 12:06:02 +0200228 encoder_max_bitrate_bps_(
229 GetInitialEncoderMaxBitrate(initial_encoder_max_bitrate)),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200230 encoder_target_rate_bps_(0),
231 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200232 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200233 bandwidth_observer_(transport->GetBandwidthObserver()),
Tommi1050fbc2021-06-03 17:58:28 +0200234 rtp_video_sender_(rtp_video_sender),
Tommie902f282021-06-03 12:02:02 +0200235 configured_pacing_factor_(
236 GetConfiguredPacingFactor(*config_, content_type, pacing_config_)) {
Tommifa3ce632021-06-03 12:06:02 +0200237 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
238 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800239 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200240 RTC_DCHECK(transport_);
241 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
Tommi1050fbc2021-06-03 17:58:28 +0200242 RTC_LOG(LS_INFO) << "VideoSendStreamImpl: " << config_->ToString();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200243
244 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
Tommifa3ce632021-06-03 12:06:02 +0200245
Tommi1050fbc2021-06-03 17:58:28 +0200246 // Only request rotation at the source when we positively know that the remote
247 // side doesn't support the rotation extension. This allows us to prepare the
248 // encoder in the expectation that rotation is supported - which is the common
249 // case.
250 bool rotation_applied = absl::c_none_of(
251 config_->rtp.extensions, [](const RtpExtension& extension) {
252 return extension.uri == RtpExtension::kVideoRotationUri;
253 });
254
255 video_stream_encoder_->SetSink(this, rotation_applied);
Tommifa3ce632021-06-03 12:06:02 +0200256
257 absl::optional<bool> enable_alr_bw_probing;
258
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200259 // If send-side BWE is enabled, check if we should apply updated probing and
260 // pacing settings.
Tommi1050fbc2021-06-03 17:58:28 +0200261 if (configured_pacing_factor_) {
Erik Språngb57ab382018-09-13 10:52:38 +0200262 absl::optional<AlrExperimentSettings> alr_settings =
263 GetAlrSettings(content_type);
Tommifa3ce632021-06-03 12:06:02 +0200264 int queue_time_limit_ms;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200265 if (alr_settings) {
Tommifa3ce632021-06-03 12:06:02 +0200266 enable_alr_bw_probing = true;
267 queue_time_limit_ms = alr_settings->max_paced_queue_time;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200268 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100269 RateControlSettings rate_control_settings =
270 RateControlSettings::ParseFromFieldTrials();
Tommifa3ce632021-06-03 12:06:02 +0200271 enable_alr_bw_probing = rate_control_settings.UseAlrProbing();
272 queue_time_limit_ms = pacing_config_.max_pacing_delay.Get().ms();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200273 }
Tommie902f282021-06-03 12:02:02 +0200274
Tommifa3ce632021-06-03 12:06:02 +0200275 transport->SetQueueTimeLimit(queue_time_limit_ms);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200276 }
277
278 if (config_->periodic_alr_bandwidth_probing) {
Tommifa3ce632021-06-03 12:06:02 +0200279 enable_alr_bw_probing = config_->periodic_alr_bandwidth_probing;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200280 }
281
Tommifa3ce632021-06-03 12:06:02 +0200282 if (enable_alr_bw_probing) {
283 transport->EnablePeriodicAlrProbing(*enable_alr_bw_probing);
284 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200285
Danil Chapovalov95eeaa72022-07-06 10:14:29 +0200286 rtp_transport_queue_->PostTask(SafeTask(transport_queue_safety_, [this] {
Tommi1050fbc2021-06-03 17:58:28 +0200287 if (configured_pacing_factor_)
288 transport_->SetPacingFactor(*configured_pacing_factor_);
289
290 video_stream_encoder_->SetStartBitrate(
291 bitrate_allocator_->GetStartBitrate(this));
292 }));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200293}
294
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200295VideoSendStreamImpl::~VideoSendStreamImpl() {
Tommi1050fbc2021-06-03 17:58:28 +0200296 RTC_DCHECK_RUN_ON(&thread_checker_);
297 RTC_LOG(LS_INFO) << "~VideoSendStreamImpl: " << config_->ToString();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200298}
299
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100300void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200301 // Runs on a network thread.
Tommifa3ce632021-06-03 12:06:02 +0200302 RTC_DCHECK(!rtp_transport_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200303 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200304}
305
306void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
307 const std::vector<bool> active_layers) {
Tommifa3ce632021-06-03 12:06:02 +0200308 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200309 bool previously_active = rtp_video_sender_->IsActive();
310 rtp_video_sender_->SetActiveModules(active_layers);
311 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200312 // Payload router switched from active to inactive.
313 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200314 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200315 // Payload router switched from inactive to active.
316 StartupVideoSendStream();
317 }
318}
319
320void VideoSendStreamImpl::Start() {
Tommifa3ce632021-06-03 12:06:02 +0200321 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200322 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200323 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200324 return;
Tommi1050fbc2021-06-03 17:58:28 +0200325
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200326 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200327 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200328 StartupVideoSendStream();
329}
330
331void VideoSendStreamImpl::StartupVideoSendStream() {
Tommifa3ce632021-06-03 12:06:02 +0200332 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Tommi1050fbc2021-06-03 17:58:28 +0200333
334 transport_queue_safety_->SetAlive();
335
Sebastian Jansson464a5572019-02-12 13:32:32 +0100336 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200337 // Start monitoring encoder activity.
338 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100339 RTC_DCHECK(!check_encoder_activity_task_.Running());
340
341 activity_ = false;
342 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100343 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
Danil Chapovalov03f8b8a2022-07-18 13:11:42 +0200344 rtp_transport_queue_, kEncoderTimeOut, [this] {
Tommifa3ce632021-06-03 12:06:02 +0200345 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100346 if (!activity_) {
347 if (!timed_out_) {
348 SignalEncoderTimedOut();
349 }
350 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200351 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100352 } else if (timed_out_) {
353 SignalEncoderActive();
354 timed_out_ = false;
355 }
356 activity_ = false;
357 return kEncoderTimeOut;
358 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200359 }
360
361 video_stream_encoder_->SendKeyFrame();
362}
363
364void VideoSendStreamImpl::Stop() {
Tommifa3ce632021-06-03 12:06:02 +0200365 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Evan Shrubsole0db33962020-11-25 14:54:58 +0100366 RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200367 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200368 return;
Tommi1050fbc2021-06-03 17:58:28 +0200369
370 RTC_DCHECK(transport_queue_safety_->alive());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200371 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200372 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200373 StopVideoSendStream();
374}
375
Tommi1050fbc2021-06-03 17:58:28 +0200376// RTC_RUN_ON(rtp_transport_queue_)
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200377void VideoSendStreamImpl::StopVideoSendStream() {
378 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100379 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200380 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100381 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200382 stats_proxy_->OnSetEncoderTargetRate(0);
Tommi1050fbc2021-06-03 17:58:28 +0200383 transport_queue_safety_->SetNotAlive();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200384}
385
386void VideoSendStreamImpl::SignalEncoderTimedOut() {
Tommifa3ce632021-06-03 12:06:02 +0200387 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100388 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200389 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
390 // if a camera stops producing frames.
391 if (encoder_target_rate_bps_ > 0) {
392 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
393 bitrate_allocator_->RemoveObserver(this);
394 }
395}
396
397void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200398 const VideoBitrateAllocation& allocation) {
Tommifa3ce632021-06-03 12:06:02 +0200399 if (!rtp_transport_queue_->IsCurrent()) {
Danil Chapovalov95eeaa72022-07-06 10:14:29 +0200400 rtp_transport_queue_->PostTask(SafeTask(transport_queue_safety_, [=] {
Tommi1050fbc2021-06-03 17:58:28 +0200401 OnBitrateAllocationUpdated(allocation);
402 }));
Erik Språng4e193e42018-09-14 19:01:58 +0200403 return;
404 }
405
Tommifa3ce632021-06-03 12:06:02 +0200406 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Erik Språng4e193e42018-09-14 19:01:58 +0200407
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100408 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200409 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200410 if (video_bitrate_allocation_context_) {
411 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
412 // the previously sent allocation and the same streams are still enabled,
413 // it is considered "similar". We do not want send similar allocations
414 // more once per kMaxVbaThrottleTimeMs.
415 const VideoBitrateAllocation& last =
416 video_bitrate_allocation_context_->last_sent_allocation;
417 const bool is_similar =
418 allocation.get_sum_bps() >= last.get_sum_bps() &&
419 allocation.get_sum_bps() <
420 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
421 100 &&
422 SameStreamsEnabled(allocation, last);
423 if (is_similar &&
424 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
425 kMaxVbaThrottleTimeMs) {
426 // This allocation is too similar, cache it and return.
427 video_bitrate_allocation_context_->throttled_allocation = allocation;
428 return;
429 }
430 } else {
431 video_bitrate_allocation_context_.emplace();
432 }
433
434 video_bitrate_allocation_context_->last_sent_allocation = allocation;
435 video_bitrate_allocation_context_->throttled_allocation.reset();
436 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
437
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200438 // Send bitrate allocation metadata only if encoder is not paused.
439 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
440 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200441}
442
Per Kjellandera9434842020-10-15 17:53:22 +0200443void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
444 VideoLayersAllocation allocation) {
Per Kjellanderda06e8f2021-01-07 19:37:00 +0100445 // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
446 // order to not race with OnEncodedImage callbacks.
Per Kjellanderaf704182020-10-16 10:30:40 +0200447 rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
Per Kjellandera9434842020-10-15 17:53:22 +0200448}
449
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200450void VideoSendStreamImpl::SignalEncoderActive() {
Tommifa3ce632021-06-03 12:06:02 +0200451 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200452 if (rtp_video_sender_->IsActive()) {
453 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
454 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
455 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100456}
457
458MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
459 return MediaStreamAllocationConfig{
460 static_cast<uint32_t>(encoder_min_bitrate_bps_),
461 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200462 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100463 /* priority_bitrate */ 0,
464 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100465 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200466}
467
468void VideoSendStreamImpl::OnEncoderConfigurationChanged(
469 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200470 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100471 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200472 int min_transmit_bitrate_bps) {
Tommifa3ce632021-06-03 12:06:02 +0200473 if (!rtp_transport_queue_->IsCurrent()) {
Danil Chapovalov95eeaa72022-07-06 10:14:29 +0200474 rtp_transport_queue_->PostTask(SafeTask(
Tommi1050fbc2021-06-03 17:58:28 +0200475 transport_queue_safety_,
476 [this, streams = std::move(streams), is_svc, content_type,
477 min_transmit_bitrate_bps]() mutable {
478 OnEncoderConfigurationChanged(std::move(streams), is_svc,
479 content_type, min_transmit_bitrate_bps);
480 }));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200481 return;
482 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200483
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200484 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
485 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Tommifa3ce632021-06-03 12:06:02 +0200486 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200487
Elad Alon80f53b72019-10-11 16:19:43 +0200488 const VideoCodecType codec_type =
489 PayloadStringToCodecType(config_->rtp.payload_name);
490
491 const absl::optional<DataRate> experimental_min_bitrate =
492 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200493 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200494 experimental_min_bitrate
495 ? experimental_min_bitrate->bps()
496 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
497
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200498 encoder_max_bitrate_bps_ = 0;
499 double stream_bitrate_priority_sum = 0;
500 for (const auto& stream : streams) {
501 // We don't want to allocate more bitrate than needed to inactive streams.
502 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
503 if (stream.bitrate_priority) {
504 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
505 stream_bitrate_priority_sum += *stream.bitrate_priority;
506 }
507 }
508 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
509 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
510 encoder_max_bitrate_bps_ =
511 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
512 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500513
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100514 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200515 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
516 streams, is_svc, content_type, min_transmit_bitrate_bps,
517 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200518
519 // Clear stats for disabled layers.
520 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
521 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
522 }
523
524 const size_t num_temporal_layers =
525 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200526
527 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
528 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200529
Jakob Ivarssonf9d5e552021-06-16 16:03:16 +0000530 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200531 // The send stream is started already. Update the allocator with new bitrate
532 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100533 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200534 }
535}
536
537EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
538 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +0200539 const CodecSpecificInfo* codec_specific_info) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200540 // Encoded is called on whatever thread the real encoder implementation run
541 // on. In the case of hardware encoders, there might be several encoders
542 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100543
544 // Indicate that there still is activity going on.
545 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200546
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200547 auto enable_padding_task = [this]() {
548 if (disable_padding_) {
Tommifa3ce632021-06-03 12:06:02 +0200549 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200550 disable_padding_ = false;
551 // To ensure that padding bitrate is propagated to the bitrate allocator.
552 SignalEncoderActive();
553 }
554 };
Tommifa3ce632021-06-03 12:06:02 +0200555 if (!rtp_transport_queue_->IsCurrent()) {
Tommi1050fbc2021-06-03 17:58:28 +0200556 rtp_transport_queue_->PostTask(
Danil Chapovalov95eeaa72022-07-06 10:14:29 +0200557 SafeTask(transport_queue_safety_, std::move(enable_padding_task)));
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200558 } else {
559 enable_padding_task();
560 }
561
Niels Möller46879152019-01-07 15:54:47 +0100562 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200563 result =
564 rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
Erik Språng4e193e42018-09-14 19:01:58 +0200565 // Check if there's a throttled VideoBitrateAllocation that we should try
566 // sending.
Tommi1050fbc2021-06-03 17:58:28 +0200567 auto update_task = [this]() {
568 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
569 auto& context = video_bitrate_allocation_context_;
570 if (context && context->throttled_allocation) {
571 OnBitrateAllocationUpdated(*context->throttled_allocation);
Erik Språng4e193e42018-09-14 19:01:58 +0200572 }
573 };
Tommifa3ce632021-06-03 12:06:02 +0200574 if (!rtp_transport_queue_->IsCurrent()) {
Tommi1050fbc2021-06-03 17:58:28 +0200575 rtp_transport_queue_->PostTask(
Danil Chapovalov95eeaa72022-07-06 10:14:29 +0200576 SafeTask(transport_queue_safety_, std::move(update_task)));
Erik Språng4e193e42018-09-14 19:01:58 +0200577 } else {
578 update_task();
579 }
580
581 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200582}
583
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100584void VideoSendStreamImpl::OnDroppedFrame(
585 EncodedImageCallback::DropReason reason) {
586 activity_ = true;
587}
588
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200589std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200590 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200591}
592
593std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
594 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200595 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200596}
597
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200598uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Tommifa3ce632021-06-03 12:06:02 +0200599 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200600 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200601 << "VideoSendStream::Start has not been called.";
602
Florent Castellia8336d32019-09-09 13:36:55 +0200603 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
604 // unstable one instead.
605 if (update.stable_target_bitrate.IsZero()) {
606 update.stable_target_bitrate = update.target_bitrate;
607 }
608
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200609 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200610 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100611 const uint32_t protection_bitrate_bps =
612 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200613 DataRate link_allocation = DataRate::Zero();
614 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
615 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100616 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100617 }
Florent Castellia8336d32019-09-09 13:36:55 +0200618 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100619 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200620 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
621 if (encoder_stable_target_rate > overhead) {
622 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
623 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100624 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200625 }
626
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200627 encoder_target_rate_bps_ =
628 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200629
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100630 encoder_stable_target_rate =
631 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
632 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200633
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100634 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200635 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100636 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200637 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100638 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100639 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200640 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100641 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200642}
643
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200644} // namespace internal
645} // namespace webrtc