blob: 11494dadd7e2bf3c859fd7fbc96796abe209b39b [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"
36#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010037#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020038#include "system_wrappers/include/field_trial.h"
39
40namespace webrtc {
41namespace internal {
42namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020043
Erik Språng4e193e42018-09-14 19:01:58 +020044// Max positive size difference to treat allocations as "similar".
45static constexpr int kMaxVbaSizeDifferencePercent = 10;
46// Max time we will throttle similar video bitrate allocations.
47static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
48
Danil Chapovalov0c626af2020-02-10 11:16:00 +010049constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds(2);
Sebastian Janssonecb68972019-01-18 10:30:54 +010050
Erik Språng9d69cbe2020-10-22 17:44:42 +020051// When send-side BWE is used a stricter 1.1x pacing factor is used, rather than
52// the 2.5x which is used with receive-side BWE. Provides a more careful
53// bandwidth rampup with less risk of overshoots causing adverse effects like
54// packet loss. Not used for receive side BWE, since there we lack the probing
55// feature and so may result in too slow initial rampup.
56static constexpr double kStrictPacingMultiplier = 1.1;
57
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020058bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
59 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070060 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
61 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
62 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020063}
64
Erik Språngb57ab382018-09-13 10:52:38 +020065// Calculate max padding bitrate for a multi layer codec.
66int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020067 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010068 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020069 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020070 bool pad_to_min_bitrate,
71 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020072 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020073
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020074 RTC_DCHECK(!is_svc || streams.size() <= 1) << "Only one stream is allowed in "
75 "SVC mode.";
76
Erik Språngb57ab382018-09-13 10:52:38 +020077 // Filter out only the active streams;
78 std::vector<VideoStream> active_streams;
79 for (const VideoStream& stream : streams) {
80 if (stream.active)
81 active_streams.emplace_back(stream);
82 }
83
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020084 if (active_streams.size() > 1 || (!active_streams.empty() && is_svc)) {
85 // Simulcast or SVC is used.
86 // if SVC is used, stream bitrates should already encode svc bitrates:
87 // min_bitrate = min bitrate of a lowest svc layer.
88 // target_bitrate = sum of target bitrates of lower layers + min bitrate
89 // of the last one (as used in the calculations below).
90 // max_bitrate = sum of all active layers' max_bitrate.
Erik Språngb57ab382018-09-13 10:52:38 +020091 if (alr_probing) {
92 // With alr probing, just pad to the min bitrate of the lowest stream,
93 // probing will handle the rest of the rampup.
94 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
95 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010096 // Without alr probing, pad up to start bitrate of the
97 // highest active stream.
98 const double hysteresis_factor =
99 RateControlSettings::ParseFromFieldTrials()
100 .GetSimulcastHysteresisFactor(content_type);
Erik Språng576db1b2020-06-08 13:32:20 +0200101 if (is_svc) {
102 // For SVC, since there is only one "stream", the padding bitrate
103 // needed to enable the top spatial layer is stored in the
104 // |target_bitrate_bps| field.
105 // TODO(sprang): This behavior needs to die.
106 pad_up_to_bitrate_bps = static_cast<int>(
107 hysteresis_factor * active_streams[0].target_bitrate_bps + 0.5);
108 } else {
109 const size_t top_active_stream_idx = active_streams.size() - 1;
110 pad_up_to_bitrate_bps = std::min(
111 static_cast<int>(
112 hysteresis_factor *
113 active_streams[top_active_stream_idx].min_bitrate_bps +
114 0.5),
115 active_streams[top_active_stream_idx].target_bitrate_bps);
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100116
Erik Språng576db1b2020-06-08 13:32:20 +0200117 // Add target_bitrate_bps of the lower active streams.
118 for (size_t i = 0; i < top_active_stream_idx; ++i) {
119 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
120 }
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100121 }
Erik Språngb57ab382018-09-13 10:52:38 +0200122 }
123 } else if (!active_streams.empty() && pad_to_min_bitrate) {
124 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200125 }
126
127 pad_up_to_bitrate_bps =
128 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
129
130 return pad_up_to_bitrate_bps;
131}
132
Benjamin Wright192eeec2018-10-17 17:27:25 -0700133RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
134 const VideoSendStream::Config* config) {
135 RtpSenderFrameEncryptionConfig frame_encryption_config;
136 frame_encryption_config.frame_encryptor = config->frame_encryptor;
137 frame_encryption_config.crypto_options = config->crypto_options;
138 return frame_encryption_config;
139}
140
Tommi8ae18ad2020-05-03 22:45:02 +0200141RtpSenderObservers CreateObservers(RtcpRttStats* call_stats,
Elad Alon14d1c9d2019-04-08 14:16:17 +0200142 EncoderRtcpFeedback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200143 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200144 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200145 RtpSenderObservers observers;
146 observers.rtcp_rtt_stats = call_stats;
147 observers.intra_frame_callback = encoder_feedback;
Elad Alon0a8562e2019-04-09 11:55:13 +0200148 observers.rtcp_loss_notification_observer = encoder_feedback;
Henrik Boström87e3f9d2019-05-27 10:44:24 +0200149 observers.report_block_data_observer = stats_proxy;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200150 observers.rtp_stats = stats_proxy;
151 observers.bitrate_observer = stats_proxy;
152 observers.frame_count_observer = stats_proxy;
153 observers.rtcp_type_observer = stats_proxy;
154 observers.send_delay_observer = stats_proxy;
155 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200156 return observers;
157}
Erik Språngb57ab382018-09-13 10:52:38 +0200158
159absl::optional<AlrExperimentSettings> GetAlrSettings(
160 VideoEncoderConfig::ContentType content_type) {
161 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
162 return AlrExperimentSettings::CreateFromFieldTrial(
163 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
164 }
165 return AlrExperimentSettings::CreateFromFieldTrial(
166 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
167}
Erik Språng4e193e42018-09-14 19:01:58 +0200168
169bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
170 const VideoBitrateAllocation& rhs) {
171 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
172 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
173 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
174 return false;
175 }
176 }
177 }
178 return true;
179}
Tommie902f282021-06-03 12:02:02 +0200180
181// Returns an optional that has value iff TransportSeqNumExtensionConfigured
182// is `true` for the given video send stream config.
183absl::optional<float> GetConfiguredPacingFactor(
184 const VideoSendStream::Config& config,
185 VideoEncoderConfig::ContentType content_type,
186 const PacingConfig& default_pacing_config) {
187 if (!TransportSeqNumExtensionConfigured(config))
188 return absl::nullopt;
189
190 absl::optional<AlrExperimentSettings> alr_settings =
191 GetAlrSettings(content_type);
192 if (alr_settings)
193 return alr_settings->pacing_factor;
194
195 RateControlSettings rate_control_settings =
196 RateControlSettings::ParseFromFieldTrials();
197 return rate_control_settings.GetPacingFactor().value_or(
198 default_pacing_config.pacing_factor);
199}
200
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200201} // namespace
202
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100203PacingConfig::PacingConfig()
Erik Språng9d69cbe2020-10-22 17:44:42 +0200204 : pacing_factor("factor", kStrictPacingMultiplier),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100205 max_pacing_delay("max_delay",
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100206 TimeDelta::Millis(PacedSender::kMaxQueueLengthMs)) {
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100207 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
208 field_trial::FindFullName("WebRTC-Video-Pacing"));
209}
210PacingConfig::PacingConfig(const PacingConfig&) = default;
211PacingConfig::~PacingConfig() = default;
212
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200213VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100214 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200215 SendStatisticsProxy* stats_proxy,
216 rtc::TaskQueue* worker_queue,
Tommi8ae18ad2020-05-03 22:45:02 +0200217 RtcpRttStats* call_stats,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200218 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200219 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200220 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200221 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200222 RtcEventLog* event_log,
223 const VideoSendStream::Config* config,
224 int initial_encoder_max_bitrate,
225 double initial_encoder_bitrate_priority,
226 std::map<uint32_t, RtpState> suspended_ssrcs,
227 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
228 VideoEncoderConfig::ContentType content_type,
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800229 std::unique_ptr<FecController> fec_controller)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100230 : clock_(clock),
231 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200232 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100233 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200234 stats_proxy_(stats_proxy),
235 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200236 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100237 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200238 transport_(transport),
239 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200240 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200241 max_padding_bitrate_(0),
242 encoder_min_bitrate_bps_(0),
243 encoder_target_rate_bps_(0),
244 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200245 video_stream_encoder_(video_stream_encoder),
Tommi28e96532021-06-03 11:52:15 +0200246 encoder_feedback_(
247 clock,
248 config_->rtp.ssrcs,
249 video_stream_encoder,
250 [this](uint32_t ssrc, const std::vector<uint16_t>& seq_nums) {
251 return rtp_video_sender_->GetSentRtpPacketInfos(ssrc, seq_nums);
252 }),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200253 bandwidth_observer_(transport->GetBandwidthObserver()),
Marina Cioceae77912b2020-02-27 16:16:55 +0100254 rtp_video_sender_(
255 transport_->CreateRtpVideoSender(suspended_ssrcs,
256 suspended_payload_states,
257 config_->rtp,
258 config_->rtcp_report_interval_ms,
259 config_->send_transport,
260 CreateObservers(call_stats,
261 &encoder_feedback_,
262 stats_proxy_,
263 send_delay_stats),
264 event_log,
265 std::move(fec_controller),
266 CreateFrameEncryptionConfig(config_),
267 config->frame_transformer)),
Tommie902f282021-06-03 12:02:02 +0200268 weak_ptr_factory_(this),
269 configured_pacing_factor_(
270 GetConfiguredPacingFactor(*config_, content_type, pacing_config_)) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200271 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200272 RTC_DCHECK_RUN_ON(worker_queue_);
273 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
274 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200275
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800276 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200277 RTC_DCHECK(transport_);
278 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
279
280 if (initial_encoder_max_bitrate > 0) {
281 encoder_max_bitrate_bps_ =
282 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
283 } else {
284 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
285 // have any way to handle unset values in downstream code, such as the
286 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
287 // behaviour that is not safe. Converting to 10 Mbps should be safe for
288 // reasonable use cases as it allows adding the max of multiple streams
289 // without wrappping around.
290 const int kFallbackMaxBitrateBps = 10000000;
291 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
292 << initial_encoder_max_bitrate << " which is <= 0!";
293 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
294 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
295 }
296
297 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
298 // If send-side BWE is enabled, check if we should apply updated probing and
299 // pacing settings.
Tommie902f282021-06-03 12:02:02 +0200300 if (configured_pacing_factor_.has_value()) {
Erik Språngb57ab382018-09-13 10:52:38 +0200301 absl::optional<AlrExperimentSettings> alr_settings =
302 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200303 if (alr_settings) {
304 transport->EnablePeriodicAlrProbing(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200305 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
306 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100307 RateControlSettings rate_control_settings =
308 RateControlSettings::ParseFromFieldTrials();
309
310 transport->EnablePeriodicAlrProbing(
311 rate_control_settings.UseAlrProbing());
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100312 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200313 }
Tommie902f282021-06-03 12:02:02 +0200314
315 transport->SetPacingFactor(*configured_pacing_factor_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200316 }
317
318 if (config_->periodic_alr_bandwidth_probing) {
319 transport->EnablePeriodicAlrProbing(true);
320 }
321
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200322 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
323 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
324
325 video_stream_encoder_->SetStartBitrate(
326 bitrate_allocator_->GetStartBitrate(this));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200327}
328
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200329VideoSendStreamImpl::~VideoSendStreamImpl() {
330 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200331 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200332 << "VideoSendStreamImpl::Stop not called";
333 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200334 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200335}
336
337void VideoSendStreamImpl::RegisterProcessThread(
338 ProcessThread* module_process_thread) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200339 // Called on libjingle's worker thread (not worker_queue_), as part of the
340 // initialization steps. That's also the correct thread/queue for setting the
341 // state for |video_stream_encoder_|.
342
343 // Only request rotation at the source when we positively know that the remote
344 // side doesn't support the rotation extension. This allows us to prepare the
345 // encoder in the expectation that rotation is supported - which is the common
346 // case.
347 bool rotation_applied = absl::c_none_of(
348 config_->rtp.extensions, [](const RtpExtension& extension) {
349 return extension.uri == RtpExtension::kVideoRotationUri;
350 });
351
352 video_stream_encoder_->SetSink(this, rotation_applied);
353
Stefan Holmer9416ef82018-07-19 10:34:38 +0200354 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200355}
356
357void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200358 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200359}
360
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100361void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200362 // Runs on a network thread.
363 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200364 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200365}
366
367void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
368 const std::vector<bool> active_layers) {
369 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200370 bool previously_active = rtp_video_sender_->IsActive();
371 rtp_video_sender_->SetActiveModules(active_layers);
372 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200373 // Payload router switched from active to inactive.
374 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200375 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200376 // Payload router switched from inactive to active.
377 StartupVideoSendStream();
378 }
379}
380
381void VideoSendStreamImpl::Start() {
382 RTC_DCHECK_RUN_ON(worker_queue_);
383 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200384 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200385 return;
386 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200387 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200388 StartupVideoSendStream();
389}
390
391void VideoSendStreamImpl::StartupVideoSendStream() {
392 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100393 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200394 // Start monitoring encoder activity.
395 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100396 RTC_DCHECK(!check_encoder_activity_task_.Running());
397
398 activity_ = false;
399 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100400 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
401 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100402 RTC_DCHECK_RUN_ON(worker_queue_);
403 if (!activity_) {
404 if (!timed_out_) {
405 SignalEncoderTimedOut();
406 }
407 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200408 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100409 } else if (timed_out_) {
410 SignalEncoderActive();
411 timed_out_ = false;
412 }
413 activity_ = false;
414 return kEncoderTimeOut;
415 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200416 }
417
418 video_stream_encoder_->SendKeyFrame();
419}
420
421void VideoSendStreamImpl::Stop() {
422 RTC_DCHECK_RUN_ON(worker_queue_);
Evan Shrubsole0db33962020-11-25 14:54:58 +0100423 RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200424 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200425 return;
426 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200427 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200428 StopVideoSendStream();
429}
430
431void VideoSendStreamImpl::StopVideoSendStream() {
432 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100433 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200434 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100435 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200436 stats_proxy_->OnSetEncoderTargetRate(0);
437}
438
439void VideoSendStreamImpl::SignalEncoderTimedOut() {
440 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100441 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200442 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
443 // if a camera stops producing frames.
444 if (encoder_target_rate_bps_ > 0) {
445 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
446 bitrate_allocator_->RemoveObserver(this);
447 }
448}
449
450void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200451 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200452 if (!worker_queue_->IsCurrent()) {
453 auto ptr = weak_ptr_;
454 worker_queue_->PostTask([=] {
455 if (!ptr.get())
456 return;
457 ptr->OnBitrateAllocationUpdated(allocation);
458 });
459 return;
460 }
461
462 RTC_DCHECK_RUN_ON(worker_queue_);
463
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100464 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200465 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200466 if (video_bitrate_allocation_context_) {
467 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
468 // the previously sent allocation and the same streams are still enabled,
469 // it is considered "similar". We do not want send similar allocations
470 // more once per kMaxVbaThrottleTimeMs.
471 const VideoBitrateAllocation& last =
472 video_bitrate_allocation_context_->last_sent_allocation;
473 const bool is_similar =
474 allocation.get_sum_bps() >= last.get_sum_bps() &&
475 allocation.get_sum_bps() <
476 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
477 100 &&
478 SameStreamsEnabled(allocation, last);
479 if (is_similar &&
480 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
481 kMaxVbaThrottleTimeMs) {
482 // This allocation is too similar, cache it and return.
483 video_bitrate_allocation_context_->throttled_allocation = allocation;
484 return;
485 }
486 } else {
487 video_bitrate_allocation_context_.emplace();
488 }
489
490 video_bitrate_allocation_context_->last_sent_allocation = allocation;
491 video_bitrate_allocation_context_->throttled_allocation.reset();
492 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
493
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200494 // Send bitrate allocation metadata only if encoder is not paused.
495 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
496 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200497}
498
Per Kjellandera9434842020-10-15 17:53:22 +0200499void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
500 VideoLayersAllocation allocation) {
Per Kjellanderda06e8f2021-01-07 19:37:00 +0100501 // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
502 // order to not race with OnEncodedImage callbacks.
Per Kjellanderaf704182020-10-16 10:30:40 +0200503 rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
Per Kjellandera9434842020-10-15 17:53:22 +0200504}
505
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200506void VideoSendStreamImpl::SignalEncoderActive() {
507 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200508 if (rtp_video_sender_->IsActive()) {
509 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
510 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
511 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100512}
513
514MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
515 return MediaStreamAllocationConfig{
516 static_cast<uint32_t>(encoder_min_bitrate_bps_),
517 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200518 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100519 /* priority_bitrate */ 0,
520 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100521 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200522}
523
524void VideoSendStreamImpl::OnEncoderConfigurationChanged(
525 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200526 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100527 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200528 int min_transmit_bitrate_bps) {
529 if (!worker_queue_->IsCurrent()) {
530 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200531 worker_queue_->PostTask([send_stream, streams, is_svc, content_type,
Mirko Bonadei80a86872019-02-04 15:01:43 +0100532 min_transmit_bitrate_bps]() mutable {
533 if (send_stream) {
534 send_stream->OnEncoderConfigurationChanged(
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200535 std::move(streams), is_svc, content_type, min_transmit_bitrate_bps);
Mirko Bonadei80a86872019-02-04 15:01:43 +0100536 }
537 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200538 return;
539 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200540
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200541 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
542 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200543 RTC_DCHECK_RUN_ON(worker_queue_);
544
Elad Alon80f53b72019-10-11 16:19:43 +0200545 const VideoCodecType codec_type =
546 PayloadStringToCodecType(config_->rtp.payload_name);
547
548 const absl::optional<DataRate> experimental_min_bitrate =
549 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200550 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200551 experimental_min_bitrate
552 ? experimental_min_bitrate->bps()
553 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
554
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200555 encoder_max_bitrate_bps_ = 0;
556 double stream_bitrate_priority_sum = 0;
557 for (const auto& stream : streams) {
558 // We don't want to allocate more bitrate than needed to inactive streams.
559 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
560 if (stream.bitrate_priority) {
561 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
562 stream_bitrate_priority_sum += *stream.bitrate_priority;
563 }
564 }
565 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
566 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
567 encoder_max_bitrate_bps_ =
568 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
569 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500570
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100571 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200572 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
573 streams, is_svc, content_type, min_transmit_bitrate_bps,
574 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200575
576 // Clear stats for disabled layers.
577 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
578 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
579 }
580
581 const size_t num_temporal_layers =
582 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200583
584 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
585 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200586
Stefan Holmer9416ef82018-07-19 10:34:38 +0200587 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200588 // The send stream is started already. Update the allocator with new bitrate
589 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100590 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200591 }
592}
593
594EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
595 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +0200596 const CodecSpecificInfo* codec_specific_info) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200597 // Encoded is called on whatever thread the real encoder implementation run
598 // on. In the case of hardware encoders, there might be several encoders
599 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100600
601 // Indicate that there still is activity going on.
602 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200603
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200604 auto enable_padding_task = [this]() {
605 if (disable_padding_) {
606 RTC_DCHECK_RUN_ON(worker_queue_);
607 disable_padding_ = false;
608 // To ensure that padding bitrate is propagated to the bitrate allocator.
609 SignalEncoderActive();
610 }
611 };
612 if (!worker_queue_->IsCurrent()) {
613 worker_queue_->PostTask(enable_padding_task);
614 } else {
615 enable_padding_task();
616 }
617
Niels Möller46879152019-01-07 15:54:47 +0100618 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200619 result =
620 rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
Erik Språng4e193e42018-09-14 19:01:58 +0200621 // Check if there's a throttled VideoBitrateAllocation that we should try
622 // sending.
623 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
624 auto update_task = [send_stream]() {
625 if (send_stream) {
626 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
627 auto& context = send_stream->video_bitrate_allocation_context_;
628 if (context && context->throttled_allocation) {
629 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
630 }
631 }
632 };
633 if (!worker_queue_->IsCurrent()) {
634 worker_queue_->PostTask(update_task);
635 } else {
636 update_task();
637 }
638
639 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200640}
641
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100642void VideoSendStreamImpl::OnDroppedFrame(
643 EncodedImageCallback::DropReason reason) {
644 activity_ = true;
645}
646
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200647std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200648 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200649}
650
651std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
652 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200653 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200654}
655
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200656uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200657 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200658 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200659 << "VideoSendStream::Start has not been called.";
660
Florent Castellia8336d32019-09-09 13:36:55 +0200661 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
662 // unstable one instead.
663 if (update.stable_target_bitrate.IsZero()) {
664 update.stable_target_bitrate = update.target_bitrate;
665 }
666
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200667 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200668 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100669 const uint32_t protection_bitrate_bps =
670 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200671 DataRate link_allocation = DataRate::Zero();
672 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
673 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100674 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100675 }
Florent Castellia8336d32019-09-09 13:36:55 +0200676 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100677 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200678 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
679 if (encoder_stable_target_rate > overhead) {
680 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
681 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100682 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200683 }
684
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200685 encoder_target_rate_bps_ =
686 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200687
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100688 encoder_stable_target_rate =
689 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
690 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200691
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100692 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200693 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100694 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200695 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100696 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100697 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200698 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100699 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200700}
701
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200702} // namespace internal
703} // namespace webrtc