blob: f34388e56aeb93fff58c3ebb77ea91235be32c0e [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"
Per Kjellander828ef912022-10-10 12:53:41 +020024#include "api/task_queue/pending_task_safety_flag.h"
25#include "api/task_queue/task_queue_base.h"
Yves Gerey3e707812018-11-28 16:47:49 +010026#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020027#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 16:47:49 +010028#include "call/video_send_stream.h"
Erik Språngf3f3a612022-05-13 15:55:29 +020029#include "modules/pacing/pacing_controller.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020030#include "rtc_base/checks.h"
31#include "rtc_base/experiments/alr_experiment.h"
Ying Wang8c5520c2019-09-03 15:25:21 +000032#include "rtc_base/experiments/field_trial_parser.h"
Elad Alon80f53b72019-10-11 16:19:43 +020033#include "rtc_base/experiments/min_video_bitrate_experiment.h"
Erik Språngcd76eab2019-01-21 18:06:46 +010034#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020035#include "rtc_base/logging.h"
36#include "rtc_base/numerics/safe_conversions.h"
37#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ång0c1a9342022-07-27 16:49:25 +020052constexpr double kVideoHysteresis = 1.2;
53constexpr double kScreenshareHysteresis = 1.35;
54
Erik Språng9d69cbe2020-10-22 17:44:42 +020055// When send-side BWE is used a stricter 1.1x pacing factor is used, rather than
56// the 2.5x which is used with receive-side BWE. Provides a more careful
57// bandwidth rampup with less risk of overshoots causing adverse effects like
58// packet loss. Not used for receive side BWE, since there we lack the probing
59// feature and so may result in too slow initial rampup.
60static constexpr double kStrictPacingMultiplier = 1.1;
61
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020062bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
63 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070064 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
65 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
66 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020067}
68
Erik Språngb57ab382018-09-13 10:52:38 +020069// Calculate max padding bitrate for a multi layer codec.
70int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020071 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010072 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020073 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020074 bool pad_to_min_bitrate,
75 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020076 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020077
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020078 RTC_DCHECK(!is_svc || streams.size() <= 1) << "Only one stream is allowed in "
79 "SVC mode.";
80
Erik Språngb57ab382018-09-13 10:52:38 +020081 // Filter out only the active streams;
82 std::vector<VideoStream> active_streams;
83 for (const VideoStream& stream : streams) {
84 if (stream.active)
85 active_streams.emplace_back(stream);
86 }
87
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020088 if (active_streams.size() > 1 || (!active_streams.empty() && is_svc)) {
89 // Simulcast or SVC is used.
90 // if SVC is used, stream bitrates should already encode svc bitrates:
91 // min_bitrate = min bitrate of a lowest svc layer.
92 // target_bitrate = sum of target bitrates of lower layers + min bitrate
93 // of the last one (as used in the calculations below).
94 // max_bitrate = sum of all active layers' max_bitrate.
Erik Språngb57ab382018-09-13 10:52:38 +020095 if (alr_probing) {
96 // With alr probing, just pad to the min bitrate of the lowest stream,
97 // probing will handle the rest of the rampup.
98 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
99 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100100 // Without alr probing, pad up to start bitrate of the
101 // highest active stream.
102 const double hysteresis_factor =
Erik Språng0c1a9342022-07-27 16:49:25 +0200103 content_type == VideoEncoderConfig::ContentType::kScreen
104 ? kScreenshareHysteresis
105 : kVideoHysteresis;
Erik Språng576db1b2020-06-08 13:32:20 +0200106 if (is_svc) {
107 // For SVC, since there is only one "stream", the padding bitrate
108 // needed to enable the top spatial layer is stored in the
Artem Titovab30d722021-07-27 16:22:11 +0200109 // `target_bitrate_bps` field.
Erik Språng576db1b2020-06-08 13:32:20 +0200110 // TODO(sprang): This behavior needs to die.
111 pad_up_to_bitrate_bps = static_cast<int>(
112 hysteresis_factor * active_streams[0].target_bitrate_bps + 0.5);
113 } else {
114 const size_t top_active_stream_idx = active_streams.size() - 1;
115 pad_up_to_bitrate_bps = std::min(
116 static_cast<int>(
117 hysteresis_factor *
118 active_streams[top_active_stream_idx].min_bitrate_bps +
119 0.5),
120 active_streams[top_active_stream_idx].target_bitrate_bps);
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100121
Erik Språng576db1b2020-06-08 13:32:20 +0200122 // Add target_bitrate_bps of the lower active streams.
123 for (size_t i = 0; i < top_active_stream_idx; ++i) {
124 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
125 }
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100126 }
Erik Språngb57ab382018-09-13 10:52:38 +0200127 }
128 } else if (!active_streams.empty() && pad_to_min_bitrate) {
129 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200130 }
131
132 pad_up_to_bitrate_bps =
133 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
134
135 return pad_up_to_bitrate_bps;
136}
137
Erik Språngb57ab382018-09-13 10:52:38 +0200138absl::optional<AlrExperimentSettings> GetAlrSettings(
139 VideoEncoderConfig::ContentType content_type) {
140 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
141 return AlrExperimentSettings::CreateFromFieldTrial(
142 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
143 }
144 return AlrExperimentSettings::CreateFromFieldTrial(
145 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
146}
Erik Språng4e193e42018-09-14 19:01:58 +0200147
148bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
149 const VideoBitrateAllocation& rhs) {
150 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
151 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
152 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
153 return false;
154 }
155 }
156 }
157 return true;
158}
Tommie902f282021-06-03 12:02:02 +0200159
160// Returns an optional that has value iff TransportSeqNumExtensionConfigured
161// is `true` for the given video send stream config.
162absl::optional<float> GetConfiguredPacingFactor(
163 const VideoSendStream::Config& config,
164 VideoEncoderConfig::ContentType content_type,
165 const PacingConfig& default_pacing_config) {
166 if (!TransportSeqNumExtensionConfigured(config))
167 return absl::nullopt;
168
169 absl::optional<AlrExperimentSettings> alr_settings =
170 GetAlrSettings(content_type);
171 if (alr_settings)
172 return alr_settings->pacing_factor;
173
174 RateControlSettings rate_control_settings =
175 RateControlSettings::ParseFromFieldTrials();
176 return rate_control_settings.GetPacingFactor().value_or(
177 default_pacing_config.pacing_factor);
178}
179
Tommifa3ce632021-06-03 12:06:02 +0200180uint32_t GetInitialEncoderMaxBitrate(int initial_encoder_max_bitrate) {
181 if (initial_encoder_max_bitrate > 0)
182 return rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
183
184 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
185 // have any way to handle unset values in downstream code, such as the
186 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
187 // behaviour that is not safe. Converting to 10 Mbps should be safe for
188 // reasonable use cases as it allows adding the max of multiple streams
189 // without wrappping around.
190 const int kFallbackMaxBitrateBps = 10000000;
191 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
192 << initial_encoder_max_bitrate << " which is <= 0!";
193 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
194 return kFallbackMaxBitrateBps;
195}
196
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200197} // namespace
198
Jonas Orelande62c2f22022-03-29 11:04:48 +0200199PacingConfig::PacingConfig(const FieldTrialsView& field_trials)
Erik Språng9d69cbe2020-10-22 17:44:42 +0200200 : pacing_factor("factor", kStrictPacingMultiplier),
Erik Språngf3f3a612022-05-13 15:55:29 +0200201 max_pacing_delay("max_delay", PacingController::kMaxExpectedQueueLength) {
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100202 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
Jonas Oreland8ca06132022-03-14 12:52:48 +0100203 field_trials.Lookup("WebRTC-Video-Pacing"));
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100204}
205PacingConfig::PacingConfig(const PacingConfig&) = default;
206PacingConfig::~PacingConfig() = default;
207
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200208VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100209 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200210 SendStatisticsProxy* stats_proxy,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200211 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200212 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200213 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200214 const VideoSendStream::Config* config,
215 int initial_encoder_max_bitrate,
216 double initial_encoder_bitrate_priority,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200217 VideoEncoderConfig::ContentType content_type,
Jonas Oreland8ca06132022-03-14 12:52:48 +0100218 RtpVideoSenderInterface* rtp_video_sender,
Jonas Orelande62c2f22022-03-29 11:04:48 +0200219 const FieldTrialsView& field_trials)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100220 : clock_(clock),
221 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200222 GetAlrSettings(content_type)),
Jonas Oreland8ca06132022-03-14 12:52:48 +0100223 pacing_config_(PacingConfig(field_trials)),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200224 stats_proxy_(stats_proxy),
225 config_(config),
Per Kjellander828ef912022-10-10 12:53:41 +0200226 rtp_transport_queue_(transport->GetWorkerQueue()),
Erik Språngcd76eab2019-01-21 18:06:46 +0100227 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200228 transport_(transport),
229 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200230 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200231 max_padding_bitrate_(0),
232 encoder_min_bitrate_bps_(0),
Tommifa3ce632021-06-03 12:06:02 +0200233 encoder_max_bitrate_bps_(
234 GetInitialEncoderMaxBitrate(initial_encoder_max_bitrate)),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200235 encoder_target_rate_bps_(0),
236 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200237 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200238 bandwidth_observer_(transport->GetBandwidthObserver()),
Tommi1050fbc2021-06-03 17:58:28 +0200239 rtp_video_sender_(rtp_video_sender),
Tommie902f282021-06-03 12:02:02 +0200240 configured_pacing_factor_(
241 GetConfiguredPacingFactor(*config_, content_type, pacing_config_)) {
Tommifa3ce632021-06-03 12:06:02 +0200242 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
243 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800244 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200245 RTC_DCHECK(transport_);
246 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
Tommi1050fbc2021-06-03 17:58:28 +0200247 RTC_LOG(LS_INFO) << "VideoSendStreamImpl: " << config_->ToString();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200248
249 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
Tommifa3ce632021-06-03 12:06:02 +0200250
Tommi1050fbc2021-06-03 17:58:28 +0200251 // Only request rotation at the source when we positively know that the remote
252 // side doesn't support the rotation extension. This allows us to prepare the
253 // encoder in the expectation that rotation is supported - which is the common
254 // case.
255 bool rotation_applied = absl::c_none_of(
256 config_->rtp.extensions, [](const RtpExtension& extension) {
257 return extension.uri == RtpExtension::kVideoRotationUri;
258 });
259
260 video_stream_encoder_->SetSink(this, rotation_applied);
Tommifa3ce632021-06-03 12:06:02 +0200261
262 absl::optional<bool> enable_alr_bw_probing;
263
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200264 // If send-side BWE is enabled, check if we should apply updated probing and
265 // pacing settings.
Tommi1050fbc2021-06-03 17:58:28 +0200266 if (configured_pacing_factor_) {
Erik Språngb57ab382018-09-13 10:52:38 +0200267 absl::optional<AlrExperimentSettings> alr_settings =
268 GetAlrSettings(content_type);
Tommifa3ce632021-06-03 12:06:02 +0200269 int queue_time_limit_ms;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200270 if (alr_settings) {
Tommifa3ce632021-06-03 12:06:02 +0200271 enable_alr_bw_probing = true;
272 queue_time_limit_ms = alr_settings->max_paced_queue_time;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200273 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100274 RateControlSettings rate_control_settings =
275 RateControlSettings::ParseFromFieldTrials();
Tommifa3ce632021-06-03 12:06:02 +0200276 enable_alr_bw_probing = rate_control_settings.UseAlrProbing();
277 queue_time_limit_ms = pacing_config_.max_pacing_delay.Get().ms();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200278 }
Tommie902f282021-06-03 12:02:02 +0200279
Tommifa3ce632021-06-03 12:06:02 +0200280 transport->SetQueueTimeLimit(queue_time_limit_ms);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200281 }
282
283 if (config_->periodic_alr_bandwidth_probing) {
Tommifa3ce632021-06-03 12:06:02 +0200284 enable_alr_bw_probing = config_->periodic_alr_bandwidth_probing;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200285 }
286
Tommifa3ce632021-06-03 12:06:02 +0200287 if (enable_alr_bw_probing) {
288 transport->EnablePeriodicAlrProbing(*enable_alr_bw_probing);
289 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200290
Per Kjellander828ef912022-10-10 12:53:41 +0200291 rtp_transport_queue_->RunOrPost(SafeTask(transport_queue_safety_, [this] {
Tommi1050fbc2021-06-03 17:58:28 +0200292 if (configured_pacing_factor_)
293 transport_->SetPacingFactor(*configured_pacing_factor_);
294
295 video_stream_encoder_->SetStartBitrate(
296 bitrate_allocator_->GetStartBitrate(this));
297 }));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200298}
299
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200300VideoSendStreamImpl::~VideoSendStreamImpl() {
Tommi1050fbc2021-06-03 17:58:28 +0200301 RTC_DCHECK_RUN_ON(&thread_checker_);
302 RTC_LOG(LS_INFO) << "~VideoSendStreamImpl: " << config_->ToString();
Per Kjellander12046bf2022-11-14 14:27:30 +0100303 // TODO(webrtc:14502): Change `transport_queue_safety_` to be of type
304 // ScopedTaskSafety if experiment WebRTC-SendPacketsOnWorkerThread succeed.
305 if (rtp_transport_queue_->IsCurrent()) {
306 transport_queue_safety_->SetNotAlive();
307 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200308}
309
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100310void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Per Kjellander828ef912022-10-10 12:53:41 +0200311 // Runs on a worker thread.
Stefan Holmer9416ef82018-07-19 10:34:38 +0200312 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200313}
314
Per Kjellander59ade012022-12-02 08:09:37 +0000315void VideoSendStreamImpl::StartPerRtpStream(
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200316 const std::vector<bool> active_layers) {
Tommifa3ce632021-06-03 12:06:02 +0200317 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200318 bool previously_active = rtp_video_sender_->IsActive();
319 rtp_video_sender_->SetActiveModules(active_layers);
320 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200321 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200322 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200323 StartupVideoSendStream();
324 }
325}
326
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200327void VideoSendStreamImpl::StartupVideoSendStream() {
Tommifa3ce632021-06-03 12:06:02 +0200328 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Tommi1050fbc2021-06-03 17:58:28 +0200329 transport_queue_safety_->SetAlive();
330
Sebastian Jansson464a5572019-02-12 13:32:32 +0100331 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200332 // Start monitoring encoder activity.
333 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100334 RTC_DCHECK(!check_encoder_activity_task_.Running());
335
336 activity_ = false;
337 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100338 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
Per Kjellander828ef912022-10-10 12:53:41 +0200339 rtp_transport_queue_->TaskQueueForDelayedTasks(), kEncoderTimeOut,
340 [this] {
Tommifa3ce632021-06-03 12:06:02 +0200341 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100342 if (!activity_) {
343 if (!timed_out_) {
344 SignalEncoderTimedOut();
345 }
346 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200347 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100348 } else if (timed_out_) {
349 SignalEncoderActive();
350 timed_out_ = false;
351 }
352 activity_ = false;
353 return kEncoderTimeOut;
354 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200355 }
356
357 video_stream_encoder_->SendKeyFrame();
358}
359
360void VideoSendStreamImpl::Stop() {
Tommifa3ce632021-06-03 12:06:02 +0200361 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Evan Shrubsole0db33962020-11-25 14:54:58 +0100362 RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200363 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200364 return;
Tommi1050fbc2021-06-03 17:58:28 +0200365
366 RTC_DCHECK(transport_queue_safety_->alive());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200367 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Per Kjellander59ade012022-12-02 08:09:37 +0000368 rtp_video_sender_->Stop();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200369 StopVideoSendStream();
370}
371
372void VideoSendStreamImpl::StopVideoSendStream() {
Danil Chapovalov6e7c2682022-07-25 15:58:28 +0200373 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200374 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100375 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200376 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100377 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200378 stats_proxy_->OnSetEncoderTargetRate(0);
Tommi1050fbc2021-06-03 17:58:28 +0200379 transport_queue_safety_->SetNotAlive();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200380}
381
382void VideoSendStreamImpl::SignalEncoderTimedOut() {
Tommifa3ce632021-06-03 12:06:02 +0200383 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100384 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200385 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
386 // if a camera stops producing frames.
387 if (encoder_target_rate_bps_ > 0) {
388 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
389 bitrate_allocator_->RemoveObserver(this);
390 }
391}
392
393void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200394 const VideoBitrateAllocation& allocation) {
Per Kjellander828ef912022-10-10 12:53:41 +0200395 // OnBitrateAllocationUpdated is invoked from the encoder task queue or
396 // the rtp_transport_queue_.
397 auto task = [=] {
398 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
399 if (encoder_target_rate_bps_ == 0) {
400 return;
401 }
402 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språng4e193e42018-09-14 19:01:58 +0200403 if (video_bitrate_allocation_context_) {
Per Kjellander828ef912022-10-10 12:53:41 +0200404 // If new allocation is within kMaxVbaSizeDifferencePercent larger
405 // than the previously sent allocation and the same streams are still
406 // enabled, it is considered "similar". We do not want send similar
407 // allocations more once per kMaxVbaThrottleTimeMs.
Erik Språng4e193e42018-09-14 19:01:58 +0200408 const VideoBitrateAllocation& last =
409 video_bitrate_allocation_context_->last_sent_allocation;
410 const bool is_similar =
411 allocation.get_sum_bps() >= last.get_sum_bps() &&
412 allocation.get_sum_bps() <
413 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
414 100 &&
415 SameStreamsEnabled(allocation, last);
416 if (is_similar &&
417 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
418 kMaxVbaThrottleTimeMs) {
419 // This allocation is too similar, cache it and return.
420 video_bitrate_allocation_context_->throttled_allocation = allocation;
421 return;
422 }
423 } else {
424 video_bitrate_allocation_context_.emplace();
425 }
426
427 video_bitrate_allocation_context_->last_sent_allocation = allocation;
428 video_bitrate_allocation_context_->throttled_allocation.reset();
429 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
430
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200431 // Send bitrate allocation metadata only if encoder is not paused.
432 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
Per Kjellander828ef912022-10-10 12:53:41 +0200433 };
434 if (!rtp_transport_queue_->IsCurrent()) {
435 rtp_transport_queue_->TaskQueueForPost()->PostTask(
436 SafeTask(transport_queue_safety_, std::move(task)));
437 } else {
438 task();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200439 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200440}
441
Per Kjellandera9434842020-10-15 17:53:22 +0200442void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
443 VideoLayersAllocation allocation) {
Per Kjellanderda06e8f2021-01-07 19:37:00 +0100444 // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
445 // order to not race with OnEncodedImage callbacks.
Per Kjellanderaf704182020-10-16 10:30:40 +0200446 rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
Per Kjellandera9434842020-10-15 17:53:22 +0200447}
448
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200449void VideoSendStreamImpl::SignalEncoderActive() {
Tommifa3ce632021-06-03 12:06:02 +0200450 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200451 if (rtp_video_sender_->IsActive()) {
452 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
453 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
454 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100455}
456
457MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
458 return MediaStreamAllocationConfig{
459 static_cast<uint32_t>(encoder_min_bitrate_bps_),
460 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200461 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100462 /* priority_bitrate */ 0,
463 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100464 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200465}
466
467void VideoSendStreamImpl::OnEncoderConfigurationChanged(
468 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200469 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100470 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200471 int min_transmit_bitrate_bps) {
Per Kjellander828ef912022-10-10 12:53:41 +0200472 // Currently called on the encoder TQ
473 RTC_DCHECK(!rtp_transport_queue_->IsCurrent());
474 auto closure = [this, streams = std::move(streams), is_svc, content_type,
475 min_transmit_bitrate_bps]() mutable {
476 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
477 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
478 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200479
Per Kjellander828ef912022-10-10 12:53:41 +0200480 const VideoCodecType codec_type =
481 PayloadStringToCodecType(config_->rtp.payload_name);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200482
Per Kjellander828ef912022-10-10 12:53:41 +0200483 const absl::optional<DataRate> experimental_min_bitrate =
484 GetExperimentalMinVideoBitrate(codec_type);
485 encoder_min_bitrate_bps_ =
486 experimental_min_bitrate
487 ? experimental_min_bitrate->bps()
488 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
Elad Alon80f53b72019-10-11 16:19:43 +0200489
Per Kjellander828ef912022-10-10 12:53:41 +0200490 encoder_max_bitrate_bps_ = 0;
491 double stream_bitrate_priority_sum = 0;
492 for (const auto& stream : streams) {
493 // We don't want to allocate more bitrate than needed to inactive streams.
494 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
495 if (stream.bitrate_priority) {
496 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
497 stream_bitrate_priority_sum += *stream.bitrate_priority;
498 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200499 }
Per Kjellander828ef912022-10-10 12:53:41 +0200500 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
501 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
502 encoder_max_bitrate_bps_ =
503 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
504 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500505
Per Kjellander828ef912022-10-10 12:53:41 +0200506 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
507 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
508 streams, is_svc, content_type, min_transmit_bitrate_bps,
509 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200510
Per Kjellander828ef912022-10-10 12:53:41 +0200511 // Clear stats for disabled layers.
512 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
513 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
514 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200515
Per Kjellander828ef912022-10-10 12:53:41 +0200516 const size_t num_temporal_layers =
517 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200518
Per Kjellander828ef912022-10-10 12:53:41 +0200519 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
520 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200521
Per Kjellander828ef912022-10-10 12:53:41 +0200522 if (rtp_video_sender_->IsActive()) {
523 // The send stream is started already. Update the allocator with new
524 // bitrate limits.
525 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
526 }
527 };
528
529 rtp_transport_queue_->TaskQueueForPost()->PostTask(
530 SafeTask(transport_queue_safety_, std::move(closure)));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200531}
532
533EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
534 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +0200535 const CodecSpecificInfo* codec_specific_info) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200536 // Encoded is called on whatever thread the real encoder implementation run
537 // on. In the case of hardware encoders, there might be several encoders
538 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100539
540 // Indicate that there still is activity going on.
541 activity_ = true;
Per Kjellander828ef912022-10-10 12:53:41 +0200542 RTC_DCHECK(!rtp_transport_queue_->IsCurrent());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200543
Per Kjellander828ef912022-10-10 12:53:41 +0200544 auto task_to_run_on_worker = [this]() {
545 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200546 if (disable_padding_) {
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200547 disable_padding_ = false;
548 // To ensure that padding bitrate is propagated to the bitrate allocator.
549 SignalEncoderActive();
550 }
Per Kjellander828ef912022-10-10 12:53:41 +0200551 // Check if there's a throttled VideoBitrateAllocation that we should try
552 // sending.
Tommi1050fbc2021-06-03 17:58:28 +0200553 auto& context = video_bitrate_allocation_context_;
554 if (context && context->throttled_allocation) {
555 OnBitrateAllocationUpdated(*context->throttled_allocation);
Erik Språng4e193e42018-09-14 19:01:58 +0200556 }
557 };
Per Kjellander828ef912022-10-10 12:53:41 +0200558 rtp_transport_queue_->TaskQueueForPost()->PostTask(
559 SafeTask(transport_queue_safety_, std::move(task_to_run_on_worker)));
Erik Språng4e193e42018-09-14 19:01:58 +0200560
Per Kjellander828ef912022-10-10 12:53:41 +0200561 return rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200562}
563
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100564void VideoSendStreamImpl::OnDroppedFrame(
565 EncodedImageCallback::DropReason reason) {
566 activity_ = true;
567}
568
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200569std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200570 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200571}
572
573std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
574 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200575 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200576}
577
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200578uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Tommifa3ce632021-06-03 12:06:02 +0200579 RTC_DCHECK_RUN_ON(rtp_transport_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200580 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200581 << "VideoSendStream::Start has not been called.";
582
Florent Castellia8336d32019-09-09 13:36:55 +0200583 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
584 // unstable one instead.
585 if (update.stable_target_bitrate.IsZero()) {
586 update.stable_target_bitrate = update.target_bitrate;
587 }
588
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200589 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200590 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100591 const uint32_t protection_bitrate_bps =
592 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200593 DataRate link_allocation = DataRate::Zero();
594 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
595 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100596 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100597 }
Florent Castellia8336d32019-09-09 13:36:55 +0200598 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100599 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200600 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
601 if (encoder_stable_target_rate > overhead) {
602 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
603 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100604 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200605 }
606
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200607 encoder_target_rate_bps_ =
608 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200609
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100610 encoder_stable_target_rate =
611 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
612 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200613
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100614 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200615 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100616 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200617 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100618 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100619 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200620 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100621 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200622}
623
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200624} // namespace internal
625} // namespace webrtc