blob: 687121ae2bebabb2380dab83b0d1c18e1dfb1842 [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"
Yves Gerey3e707812018-11-28 16:47:49 +010027#include "modules/pacing/paced_sender.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "rtc_base/atomic_ops.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020029#include "rtc_base/checks.h"
30#include "rtc_base/experiments/alr_experiment.h"
Ying Wang8c5520c2019-09-03 15:25:21 +000031#include "rtc_base/experiments/field_trial_parser.h"
Elad Alon80f53b72019-10-11 16:19:43 +020032#include "rtc_base/experiments/min_video_bitrate_experiment.h"
Erik Språngcd76eab2019-01-21 18:06:46 +010033#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020034#include "rtc_base/logging.h"
35#include "rtc_base/numerics/safe_conversions.h"
Tommi1050fbc2021-06-03 17:58:28 +020036#include "rtc_base/task_utils/to_queued_task.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020037#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010038#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020039#include "system_wrappers/include/field_trial.h"
40
41namespace webrtc {
42namespace internal {
43namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020044
Erik Språng4e193e42018-09-14 19:01:58 +020045// Max positive size difference to treat allocations as "similar".
46static constexpr int kMaxVbaSizeDifferencePercent = 10;
47// Max time we will throttle similar video bitrate allocations.
48static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
49
Danil Chapovalov0c626af2020-02-10 11:16:00 +010050constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds(2);
Sebastian Janssonecb68972019-01-18 10:30:54 +010051
Erik Språng9d69cbe2020-10-22 17:44:42 +020052// When send-side BWE is used a stricter 1.1x pacing factor is used, rather than
53// the 2.5x which is used with receive-side BWE. Provides a more careful
54// bandwidth rampup with less risk of overshoots causing adverse effects like
55// packet loss. Not used for receive side BWE, since there we lack the probing
56// feature and so may result in too slow initial rampup.
57static constexpr double kStrictPacingMultiplier = 1.1;
58
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020059bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
60 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070061 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
62 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
63 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020064}
65
Erik Språngb57ab382018-09-13 10:52:38 +020066// Calculate max padding bitrate for a multi layer codec.
67int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020068 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010069 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020070 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020071 bool pad_to_min_bitrate,
72 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020073 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020074
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020075 RTC_DCHECK(!is_svc || streams.size() <= 1) << "Only one stream is allowed in "
76 "SVC mode.";
77
Erik Språngb57ab382018-09-13 10:52:38 +020078 // Filter out only the active streams;
79 std::vector<VideoStream> active_streams;
80 for (const VideoStream& stream : streams) {
81 if (stream.active)
82 active_streams.emplace_back(stream);
83 }
84
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020085 if (active_streams.size() > 1 || (!active_streams.empty() && is_svc)) {
86 // Simulcast or SVC is used.
87 // if SVC is used, stream bitrates should already encode svc bitrates:
88 // min_bitrate = min bitrate of a lowest svc layer.
89 // target_bitrate = sum of target bitrates of lower layers + min bitrate
90 // of the last one (as used in the calculations below).
91 // max_bitrate = sum of all active layers' max_bitrate.
Erik Språngb57ab382018-09-13 10:52:38 +020092 if (alr_probing) {
93 // With alr probing, just pad to the min bitrate of the lowest stream,
94 // probing will handle the rest of the rampup.
95 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
96 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010097 // Without alr probing, pad up to start bitrate of the
98 // highest active stream.
99 const double hysteresis_factor =
100 RateControlSettings::ParseFromFieldTrials()
101 .GetSimulcastHysteresisFactor(content_type);
Erik Språng576db1b2020-06-08 13:32:20 +0200102 if (is_svc) {
103 // For SVC, since there is only one "stream", the padding bitrate
104 // needed to enable the top spatial layer is stored in the
105 // |target_bitrate_bps| field.
106 // TODO(sprang): This behavior needs to die.
107 pad_up_to_bitrate_bps = static_cast<int>(
108 hysteresis_factor * active_streams[0].target_bitrate_bps + 0.5);
109 } else {
110 const size_t top_active_stream_idx = active_streams.size() - 1;
111 pad_up_to_bitrate_bps = std::min(
112 static_cast<int>(
113 hysteresis_factor *
114 active_streams[top_active_stream_idx].min_bitrate_bps +
115 0.5),
116 active_streams[top_active_stream_idx].target_bitrate_bps);
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100117
Erik Språng576db1b2020-06-08 13:32:20 +0200118 // Add target_bitrate_bps of the lower active streams.
119 for (size_t i = 0; i < top_active_stream_idx; ++i) {
120 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
121 }
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100122 }
Erik Språngb57ab382018-09-13 10:52:38 +0200123 }
124 } else if (!active_streams.empty() && pad_to_min_bitrate) {
125 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200126 }
127
128 pad_up_to_bitrate_bps =
129 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
130
131 return pad_up_to_bitrate_bps;
132}
133
Erik Språngb57ab382018-09-13 10:52:38 +0200134absl::optional<AlrExperimentSettings> GetAlrSettings(
135 VideoEncoderConfig::ContentType content_type) {
136 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
137 return AlrExperimentSettings::CreateFromFieldTrial(
138 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
139 }
140 return AlrExperimentSettings::CreateFromFieldTrial(
141 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
142}
Erik Språng4e193e42018-09-14 19:01:58 +0200143
144bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
145 const VideoBitrateAllocation& rhs) {
146 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
147 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
148 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
149 return false;
150 }
151 }
152 }
153 return true;
154}
Tommie902f282021-06-03 12:02:02 +0200155
156// Returns an optional that has value iff TransportSeqNumExtensionConfigured
157// is `true` for the given video send stream config.
158absl::optional<float> GetConfiguredPacingFactor(
159 const VideoSendStream::Config& config,
160 VideoEncoderConfig::ContentType content_type,
161 const PacingConfig& default_pacing_config) {
162 if (!TransportSeqNumExtensionConfigured(config))
163 return absl::nullopt;
164
165 absl::optional<AlrExperimentSettings> alr_settings =
166 GetAlrSettings(content_type);
167 if (alr_settings)
168 return alr_settings->pacing_factor;
169
170 RateControlSettings rate_control_settings =
171 RateControlSettings::ParseFromFieldTrials();
172 return rate_control_settings.GetPacingFactor().value_or(
173 default_pacing_config.pacing_factor);
174}
175
Tommifa3ce632021-06-03 12:06:02 +0200176uint32_t GetInitialEncoderMaxBitrate(int initial_encoder_max_bitrate) {
177 if (initial_encoder_max_bitrate > 0)
178 return rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
179
180 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
181 // have any way to handle unset values in downstream code, such as the
182 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
183 // behaviour that is not safe. Converting to 10 Mbps should be safe for
184 // reasonable use cases as it allows adding the max of multiple streams
185 // without wrappping around.
186 const int kFallbackMaxBitrateBps = 10000000;
187 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
188 << initial_encoder_max_bitrate << " which is <= 0!";
189 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
190 return kFallbackMaxBitrateBps;
191}
192
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200193} // namespace
194
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100195PacingConfig::PacingConfig()
Erik Språng9d69cbe2020-10-22 17:44:42 +0200196 : pacing_factor("factor", kStrictPacingMultiplier),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100197 max_pacing_delay("max_delay",
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100198 TimeDelta::Millis(PacedSender::kMaxQueueLengthMs)) {
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100199 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
200 field_trial::FindFullName("WebRTC-Video-Pacing"));
201}
202PacingConfig::PacingConfig(const PacingConfig&) = default;
203PacingConfig::~PacingConfig() = default;
204
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200205VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100206 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200207 SendStatisticsProxy* stats_proxy,
Tommifa3ce632021-06-03 12:06:02 +0200208 rtc::TaskQueue* rtp_transport_queue,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200209 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200210 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200211 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200212 const VideoSendStream::Config* config,
213 int initial_encoder_max_bitrate,
214 double initial_encoder_bitrate_priority,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200215 VideoEncoderConfig::ContentType content_type,
Tommi1050fbc2021-06-03 17:58:28 +0200216 RtpVideoSenderInterface* rtp_video_sender)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100217 : clock_(clock),
218 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200219 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100220 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200221 stats_proxy_(stats_proxy),
222 config_(config),
Tommifa3ce632021-06-03 12:06:02 +0200223 rtp_transport_queue_(rtp_transport_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100224 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200225 transport_(transport),
226 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200227 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200228 max_padding_bitrate_(0),
229 encoder_min_bitrate_bps_(0),
Tommifa3ce632021-06-03 12:06:02 +0200230 encoder_max_bitrate_bps_(
231 GetInitialEncoderMaxBitrate(initial_encoder_max_bitrate)),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200232 encoder_target_rate_bps_(0),
233 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200234 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200235 bandwidth_observer_(transport->GetBandwidthObserver()),
Tommi1050fbc2021-06-03 17:58:28 +0200236 rtp_video_sender_(rtp_video_sender),
Tommie902f282021-06-03 12:02:02 +0200237 configured_pacing_factor_(
238 GetConfiguredPacingFactor(*config_, content_type, pacing_config_)) {
Tommifa3ce632021-06-03 12:06:02 +0200239 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
240 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800241 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200242 RTC_DCHECK(transport_);
243 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
Tommi1050fbc2021-06-03 17:58:28 +0200244 RTC_LOG(LS_INFO) << "VideoSendStreamImpl: " << config_->ToString();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200245
246 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
Tommifa3ce632021-06-03 12:06:02 +0200247
Tommi1050fbc2021-06-03 17:58:28 +0200248 // Only request rotation at the source when we positively know that the remote
249 // side doesn't support the rotation extension. This allows us to prepare the
250 // encoder in the expectation that rotation is supported - which is the common
251 // case.
252 bool rotation_applied = absl::c_none_of(
253 config_->rtp.extensions, [](const RtpExtension& extension) {
254 return extension.uri == RtpExtension::kVideoRotationUri;
255 });
256
257 video_stream_encoder_->SetSink(this, rotation_applied);
Tommifa3ce632021-06-03 12:06:02 +0200258
259 absl::optional<bool> enable_alr_bw_probing;
260
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200261 // If send-side BWE is enabled, check if we should apply updated probing and
262 // pacing settings.
Tommi1050fbc2021-06-03 17:58:28 +0200263 if (configured_pacing_factor_) {
Erik Språngb57ab382018-09-13 10:52:38 +0200264 absl::optional<AlrExperimentSettings> alr_settings =
265 GetAlrSettings(content_type);
Tommifa3ce632021-06-03 12:06:02 +0200266 int queue_time_limit_ms;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200267 if (alr_settings) {
Tommifa3ce632021-06-03 12:06:02 +0200268 enable_alr_bw_probing = true;
269 queue_time_limit_ms = alr_settings->max_paced_queue_time;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200270 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100271 RateControlSettings rate_control_settings =
272 RateControlSettings::ParseFromFieldTrials();
Tommifa3ce632021-06-03 12:06:02 +0200273 enable_alr_bw_probing = rate_control_settings.UseAlrProbing();
274 queue_time_limit_ms = pacing_config_.max_pacing_delay.Get().ms();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200275 }
Tommie902f282021-06-03 12:02:02 +0200276
Tommifa3ce632021-06-03 12:06:02 +0200277 transport->SetQueueTimeLimit(queue_time_limit_ms);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200278 }
279
280 if (config_->periodic_alr_bandwidth_probing) {
Tommifa3ce632021-06-03 12:06:02 +0200281 enable_alr_bw_probing = config_->periodic_alr_bandwidth_probing;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200282 }
283
Tommifa3ce632021-06-03 12:06:02 +0200284 if (enable_alr_bw_probing) {
285 transport->EnablePeriodicAlrProbing(*enable_alr_bw_probing);
286 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200287
Tommi1050fbc2021-06-03 17:58:28 +0200288 rtp_transport_queue_->PostTask(ToQueuedTask(transport_queue_safety_, [this] {
289 if (configured_pacing_factor_)
290 transport_->SetPacingFactor(*configured_pacing_factor_);
291
292 video_stream_encoder_->SetStartBitrate(
293 bitrate_allocator_->GetStartBitrate(this));
294 }));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200295}
296
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200297VideoSendStreamImpl::~VideoSendStreamImpl() {
Tommi1050fbc2021-06-03 17:58:28 +0200298 RTC_DCHECK_RUN_ON(&thread_checker_);
299 RTC_LOG(LS_INFO) << "~VideoSendStreamImpl: " << config_->ToString();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200300}
301
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100302void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200303 // Runs on a network thread.
Tommifa3ce632021-06-03 12:06:02 +0200304 RTC_DCHECK(!rtp_transport_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200305 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200306}
307
308void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
309 const std::vector<bool> active_layers) {
Tommifa3ce632021-06-03 12:06:02 +0200310 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200311 bool previously_active = rtp_video_sender_->IsActive();
312 rtp_video_sender_->SetActiveModules(active_layers);
313 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200314 // Payload router switched from active to inactive.
315 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200316 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200317 // Payload router switched from inactive to active.
318 StartupVideoSendStream();
319 }
320}
321
322void VideoSendStreamImpl::Start() {
Tommifa3ce632021-06-03 12:06:02 +0200323 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200324 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200325 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200326 return;
Tommi1050fbc2021-06-03 17:58:28 +0200327
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200328 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200329 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200330 StartupVideoSendStream();
331}
332
333void VideoSendStreamImpl::StartupVideoSendStream() {
Tommifa3ce632021-06-03 12:06:02 +0200334 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Tommi1050fbc2021-06-03 17:58:28 +0200335
336 transport_queue_safety_->SetAlive();
337
Sebastian Jansson464a5572019-02-12 13:32:32 +0100338 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200339 // Start monitoring encoder activity.
340 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100341 RTC_DCHECK(!check_encoder_activity_task_.Running());
342
343 activity_ = false;
344 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100345 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
Tommifa3ce632021-06-03 12:06:02 +0200346 rtp_transport_queue_->Get(), kEncoderTimeOut, [this] {
347 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100348 if (!activity_) {
349 if (!timed_out_) {
350 SignalEncoderTimedOut();
351 }
352 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200353 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100354 } else if (timed_out_) {
355 SignalEncoderActive();
356 timed_out_ = false;
357 }
358 activity_ = false;
359 return kEncoderTimeOut;
360 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200361 }
362
363 video_stream_encoder_->SendKeyFrame();
364}
365
366void VideoSendStreamImpl::Stop() {
Tommi1050fbc2021-06-03 17:58:28 +0200367 if (!rtp_transport_queue_->IsCurrent()) {
368 rtp_transport_queue_->PostTask(
369 ToQueuedTask(transport_queue_safety_, [this] { Stop(); }));
370 return;
371 }
Tommifa3ce632021-06-03 12:06:02 +0200372 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Evan Shrubsole0db33962020-11-25 14:54:58 +0100373 RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200374 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200375 return;
Tommi1050fbc2021-06-03 17:58:28 +0200376
377 RTC_DCHECK(transport_queue_safety_->alive());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200378 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200379 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200380 StopVideoSendStream();
381}
382
Tommi1050fbc2021-06-03 17:58:28 +0200383// RTC_RUN_ON(rtp_transport_queue_)
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200384void VideoSendStreamImpl::StopVideoSendStream() {
385 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100386 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200387 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100388 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200389 stats_proxy_->OnSetEncoderTargetRate(0);
Tommi1050fbc2021-06-03 17:58:28 +0200390 transport_queue_safety_->SetNotAlive();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200391}
392
393void VideoSendStreamImpl::SignalEncoderTimedOut() {
Tommifa3ce632021-06-03 12:06:02 +0200394 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100395 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200396 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
397 // if a camera stops producing frames.
398 if (encoder_target_rate_bps_ > 0) {
399 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
400 bitrate_allocator_->RemoveObserver(this);
401 }
402}
403
404void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200405 const VideoBitrateAllocation& allocation) {
Tommifa3ce632021-06-03 12:06:02 +0200406 if (!rtp_transport_queue_->IsCurrent()) {
Tommi1050fbc2021-06-03 17:58:28 +0200407 rtp_transport_queue_->PostTask(ToQueuedTask(transport_queue_safety_, [=] {
408 OnBitrateAllocationUpdated(allocation);
409 }));
Erik Språng4e193e42018-09-14 19:01:58 +0200410 return;
411 }
412
Tommifa3ce632021-06-03 12:06:02 +0200413 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Erik Språng4e193e42018-09-14 19:01:58 +0200414
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100415 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200416 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200417 if (video_bitrate_allocation_context_) {
418 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
419 // the previously sent allocation and the same streams are still enabled,
420 // it is considered "similar". We do not want send similar allocations
421 // more once per kMaxVbaThrottleTimeMs.
422 const VideoBitrateAllocation& last =
423 video_bitrate_allocation_context_->last_sent_allocation;
424 const bool is_similar =
425 allocation.get_sum_bps() >= last.get_sum_bps() &&
426 allocation.get_sum_bps() <
427 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
428 100 &&
429 SameStreamsEnabled(allocation, last);
430 if (is_similar &&
431 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
432 kMaxVbaThrottleTimeMs) {
433 // This allocation is too similar, cache it and return.
434 video_bitrate_allocation_context_->throttled_allocation = allocation;
435 return;
436 }
437 } else {
438 video_bitrate_allocation_context_.emplace();
439 }
440
441 video_bitrate_allocation_context_->last_sent_allocation = allocation;
442 video_bitrate_allocation_context_->throttled_allocation.reset();
443 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
444
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200445 // Send bitrate allocation metadata only if encoder is not paused.
446 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
447 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200448}
449
Per Kjellandera9434842020-10-15 17:53:22 +0200450void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
451 VideoLayersAllocation allocation) {
Per Kjellanderda06e8f2021-01-07 19:37:00 +0100452 // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
453 // order to not race with OnEncodedImage callbacks.
Per Kjellanderaf704182020-10-16 10:30:40 +0200454 rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
Per Kjellandera9434842020-10-15 17:53:22 +0200455}
456
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200457void VideoSendStreamImpl::SignalEncoderActive() {
Tommifa3ce632021-06-03 12:06:02 +0200458 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200459 if (rtp_video_sender_->IsActive()) {
460 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
461 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
462 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100463}
464
465MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
466 return MediaStreamAllocationConfig{
467 static_cast<uint32_t>(encoder_min_bitrate_bps_),
468 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200469 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100470 /* priority_bitrate */ 0,
471 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100472 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200473}
474
475void VideoSendStreamImpl::OnEncoderConfigurationChanged(
476 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200477 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100478 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200479 int min_transmit_bitrate_bps) {
Tommifa3ce632021-06-03 12:06:02 +0200480 if (!rtp_transport_queue_->IsCurrent()) {
Tommi1050fbc2021-06-03 17:58:28 +0200481 rtp_transport_queue_->PostTask(ToQueuedTask(
482 transport_queue_safety_,
483 [this, streams = std::move(streams), is_svc, content_type,
484 min_transmit_bitrate_bps]() mutable {
485 OnEncoderConfigurationChanged(std::move(streams), is_svc,
486 content_type, min_transmit_bitrate_bps);
487 }));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200488 return;
489 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200490
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200491 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
492 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Tommifa3ce632021-06-03 12:06:02 +0200493 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200494
Elad Alon80f53b72019-10-11 16:19:43 +0200495 const VideoCodecType codec_type =
496 PayloadStringToCodecType(config_->rtp.payload_name);
497
498 const absl::optional<DataRate> experimental_min_bitrate =
499 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200500 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200501 experimental_min_bitrate
502 ? experimental_min_bitrate->bps()
503 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
504
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200505 encoder_max_bitrate_bps_ = 0;
506 double stream_bitrate_priority_sum = 0;
507 for (const auto& stream : streams) {
508 // We don't want to allocate more bitrate than needed to inactive streams.
509 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
510 if (stream.bitrate_priority) {
511 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
512 stream_bitrate_priority_sum += *stream.bitrate_priority;
513 }
514 }
515 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
516 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
517 encoder_max_bitrate_bps_ =
518 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
519 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500520
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100521 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200522 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
523 streams, is_svc, content_type, min_transmit_bitrate_bps,
524 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200525
526 // Clear stats for disabled layers.
527 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
528 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
529 }
530
531 const size_t num_temporal_layers =
532 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200533
534 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
535 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200536
Stefan Holmer9416ef82018-07-19 10:34:38 +0200537 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200538 // The send stream is started already. Update the allocator with new bitrate
539 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100540 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200541 }
542}
543
544EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
545 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +0200546 const CodecSpecificInfo* codec_specific_info) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200547 // Encoded is called on whatever thread the real encoder implementation run
548 // on. In the case of hardware encoders, there might be several encoders
549 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100550
551 // Indicate that there still is activity going on.
552 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200553
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200554 auto enable_padding_task = [this]() {
555 if (disable_padding_) {
Tommifa3ce632021-06-03 12:06:02 +0200556 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200557 disable_padding_ = false;
558 // To ensure that padding bitrate is propagated to the bitrate allocator.
559 SignalEncoderActive();
560 }
561 };
Tommifa3ce632021-06-03 12:06:02 +0200562 if (!rtp_transport_queue_->IsCurrent()) {
Tommi1050fbc2021-06-03 17:58:28 +0200563 rtp_transport_queue_->PostTask(
564 ToQueuedTask(transport_queue_safety_, std::move(enable_padding_task)));
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200565 } else {
566 enable_padding_task();
567 }
568
Niels Möller46879152019-01-07 15:54:47 +0100569 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200570 result =
571 rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
Erik Språng4e193e42018-09-14 19:01:58 +0200572 // Check if there's a throttled VideoBitrateAllocation that we should try
573 // sending.
Tommi1050fbc2021-06-03 17:58:28 +0200574 auto update_task = [this]() {
575 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
576 auto& context = video_bitrate_allocation_context_;
577 if (context && context->throttled_allocation) {
578 OnBitrateAllocationUpdated(*context->throttled_allocation);
Erik Språng4e193e42018-09-14 19:01:58 +0200579 }
580 };
Tommifa3ce632021-06-03 12:06:02 +0200581 if (!rtp_transport_queue_->IsCurrent()) {
Tommi1050fbc2021-06-03 17:58:28 +0200582 rtp_transport_queue_->PostTask(
583 ToQueuedTask(transport_queue_safety_, std::move(update_task)));
Erik Språng4e193e42018-09-14 19:01:58 +0200584 } else {
585 update_task();
586 }
587
588 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200589}
590
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100591void VideoSendStreamImpl::OnDroppedFrame(
592 EncodedImageCallback::DropReason reason) {
593 activity_ = true;
594}
595
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200596std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200597 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200598}
599
600std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
601 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200602 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200603}
604
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200605uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Tommifa3ce632021-06-03 12:06:02 +0200606 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200607 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200608 << "VideoSendStream::Start has not been called.";
609
Florent Castellia8336d32019-09-09 13:36:55 +0200610 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
611 // unstable one instead.
612 if (update.stable_target_bitrate.IsZero()) {
613 update.stable_target_bitrate = update.target_bitrate;
614 }
615
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200616 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200617 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100618 const uint32_t protection_bitrate_bps =
619 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200620 DataRate link_allocation = DataRate::Zero();
621 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
622 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100623 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100624 }
Florent Castellia8336d32019-09-09 13:36:55 +0200625 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100626 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200627 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
628 if (encoder_stable_target_rate > overhead) {
629 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
630 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100631 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200632 }
633
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200634 encoder_target_rate_bps_ =
635 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200636
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100637 encoder_stable_target_rate =
638 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
639 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200640
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100641 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200642 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100643 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200644 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100645 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100646 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200647 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100648 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200649}
650
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200651} // namespace internal
652} // namespace webrtc