blob: 8f369d103d95942c23612a423db479e38d569e4f [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}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200180} // namespace
181
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100182PacingConfig::PacingConfig()
Erik Språng9d69cbe2020-10-22 17:44:42 +0200183 : pacing_factor("factor", kStrictPacingMultiplier),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100184 max_pacing_delay("max_delay",
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100185 TimeDelta::Millis(PacedSender::kMaxQueueLengthMs)) {
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100186 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
187 field_trial::FindFullName("WebRTC-Video-Pacing"));
188}
189PacingConfig::PacingConfig(const PacingConfig&) = default;
190PacingConfig::~PacingConfig() = default;
191
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200192VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100193 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200194 SendStatisticsProxy* stats_proxy,
195 rtc::TaskQueue* worker_queue,
Tommi8ae18ad2020-05-03 22:45:02 +0200196 RtcpRttStats* call_stats,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200197 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200198 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200199 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200200 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200201 RtcEventLog* event_log,
202 const VideoSendStream::Config* config,
203 int initial_encoder_max_bitrate,
204 double initial_encoder_bitrate_priority,
205 std::map<uint32_t, RtpState> suspended_ssrcs,
206 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
207 VideoEncoderConfig::ContentType content_type,
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800208 std::unique_ptr<FecController> fec_controller)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100209 : clock_(clock),
210 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200211 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100212 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200213 stats_proxy_(stats_proxy),
214 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200215 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100216 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200217 transport_(transport),
218 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200219 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200220 max_padding_bitrate_(0),
221 encoder_min_bitrate_bps_(0),
222 encoder_target_rate_bps_(0),
223 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
224 has_packet_feedback_(false),
225 video_stream_encoder_(video_stream_encoder),
Tommi28e96532021-06-03 11:52:15 +0200226 encoder_feedback_(
227 clock,
228 config_->rtp.ssrcs,
229 video_stream_encoder,
230 [this](uint32_t ssrc, const std::vector<uint16_t>& seq_nums) {
231 return rtp_video_sender_->GetSentRtpPacketInfos(ssrc, seq_nums);
232 }),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200233 bandwidth_observer_(transport->GetBandwidthObserver()),
Marina Cioceae77912b2020-02-27 16:16:55 +0100234 rtp_video_sender_(
235 transport_->CreateRtpVideoSender(suspended_ssrcs,
236 suspended_payload_states,
237 config_->rtp,
238 config_->rtcp_report_interval_ms,
239 config_->send_transport,
240 CreateObservers(call_stats,
241 &encoder_feedback_,
242 stats_proxy_,
243 send_delay_stats),
244 event_log,
245 std::move(fec_controller),
246 CreateFrameEncryptionConfig(config_),
247 config->frame_transformer)),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800248 weak_ptr_factory_(this) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200249 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200250 RTC_DCHECK_RUN_ON(worker_queue_);
251 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
252 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200253
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800254 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200255 RTC_DCHECK(transport_);
256 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
257
258 if (initial_encoder_max_bitrate > 0) {
259 encoder_max_bitrate_bps_ =
260 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
261 } else {
262 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
263 // have any way to handle unset values in downstream code, such as the
264 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
265 // behaviour that is not safe. Converting to 10 Mbps should be safe for
266 // reasonable use cases as it allows adding the max of multiple streams
267 // without wrappping around.
268 const int kFallbackMaxBitrateBps = 10000000;
269 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
270 << initial_encoder_max_bitrate << " which is <= 0!";
271 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
272 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
273 }
274
275 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
276 // If send-side BWE is enabled, check if we should apply updated probing and
277 // pacing settings.
278 if (TransportSeqNumExtensionConfigured(*config_)) {
279 has_packet_feedback_ = true;
280
Erik Språngb57ab382018-09-13 10:52:38 +0200281 absl::optional<AlrExperimentSettings> alr_settings =
282 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200283 if (alr_settings) {
284 transport->EnablePeriodicAlrProbing(true);
285 transport->SetPacingFactor(alr_settings->pacing_factor);
286 configured_pacing_factor_ = alr_settings->pacing_factor;
287 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
288 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100289 RateControlSettings rate_control_settings =
290 RateControlSettings::ParseFromFieldTrials();
291
292 transport->EnablePeriodicAlrProbing(
293 rate_control_settings.UseAlrProbing());
294 const double pacing_factor =
295 rate_control_settings.GetPacingFactor().value_or(
296 pacing_config_.pacing_factor);
297 transport->SetPacingFactor(pacing_factor);
298 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100299 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200300 }
301 }
302
303 if (config_->periodic_alr_bandwidth_probing) {
304 transport->EnablePeriodicAlrProbing(true);
305 }
306
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200307 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
308 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
309
310 video_stream_encoder_->SetStartBitrate(
311 bitrate_allocator_->GetStartBitrate(this));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200312}
313
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200314VideoSendStreamImpl::~VideoSendStreamImpl() {
315 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200316 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200317 << "VideoSendStreamImpl::Stop not called";
318 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200319 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200320}
321
322void VideoSendStreamImpl::RegisterProcessThread(
323 ProcessThread* module_process_thread) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200324 // Called on libjingle's worker thread (not worker_queue_), as part of the
325 // initialization steps. That's also the correct thread/queue for setting the
326 // state for |video_stream_encoder_|.
327
328 // Only request rotation at the source when we positively know that the remote
329 // side doesn't support the rotation extension. This allows us to prepare the
330 // encoder in the expectation that rotation is supported - which is the common
331 // case.
332 bool rotation_applied = absl::c_none_of(
333 config_->rtp.extensions, [](const RtpExtension& extension) {
334 return extension.uri == RtpExtension::kVideoRotationUri;
335 });
336
337 video_stream_encoder_->SetSink(this, rotation_applied);
338
Stefan Holmer9416ef82018-07-19 10:34:38 +0200339 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200340}
341
342void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200343 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200344}
345
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100346void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200347 // Runs on a network thread.
348 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200349 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200350}
351
352void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
353 const std::vector<bool> active_layers) {
354 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200355 bool previously_active = rtp_video_sender_->IsActive();
356 rtp_video_sender_->SetActiveModules(active_layers);
357 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200358 // Payload router switched from active to inactive.
359 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200360 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200361 // Payload router switched from inactive to active.
362 StartupVideoSendStream();
363 }
364}
365
366void VideoSendStreamImpl::Start() {
367 RTC_DCHECK_RUN_ON(worker_queue_);
368 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200369 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200370 return;
371 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200372 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200373 StartupVideoSendStream();
374}
375
376void VideoSendStreamImpl::StartupVideoSendStream() {
377 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100378 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200379 // Start monitoring encoder activity.
380 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100381 RTC_DCHECK(!check_encoder_activity_task_.Running());
382
383 activity_ = false;
384 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100385 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
386 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100387 RTC_DCHECK_RUN_ON(worker_queue_);
388 if (!activity_) {
389 if (!timed_out_) {
390 SignalEncoderTimedOut();
391 }
392 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200393 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100394 } else if (timed_out_) {
395 SignalEncoderActive();
396 timed_out_ = false;
397 }
398 activity_ = false;
399 return kEncoderTimeOut;
400 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200401 }
402
403 video_stream_encoder_->SendKeyFrame();
404}
405
406void VideoSendStreamImpl::Stop() {
407 RTC_DCHECK_RUN_ON(worker_queue_);
Evan Shrubsole0db33962020-11-25 14:54:58 +0100408 RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200409 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200410 return;
411 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200412 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200413 StopVideoSendStream();
414}
415
416void VideoSendStreamImpl::StopVideoSendStream() {
417 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100418 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200419 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100420 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200421 stats_proxy_->OnSetEncoderTargetRate(0);
422}
423
424void VideoSendStreamImpl::SignalEncoderTimedOut() {
425 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100426 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200427 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
428 // if a camera stops producing frames.
429 if (encoder_target_rate_bps_ > 0) {
430 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
431 bitrate_allocator_->RemoveObserver(this);
432 }
433}
434
435void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200436 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200437 if (!worker_queue_->IsCurrent()) {
438 auto ptr = weak_ptr_;
439 worker_queue_->PostTask([=] {
440 if (!ptr.get())
441 return;
442 ptr->OnBitrateAllocationUpdated(allocation);
443 });
444 return;
445 }
446
447 RTC_DCHECK_RUN_ON(worker_queue_);
448
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100449 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200450 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200451 if (video_bitrate_allocation_context_) {
452 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
453 // the previously sent allocation and the same streams are still enabled,
454 // it is considered "similar". We do not want send similar allocations
455 // more once per kMaxVbaThrottleTimeMs.
456 const VideoBitrateAllocation& last =
457 video_bitrate_allocation_context_->last_sent_allocation;
458 const bool is_similar =
459 allocation.get_sum_bps() >= last.get_sum_bps() &&
460 allocation.get_sum_bps() <
461 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
462 100 &&
463 SameStreamsEnabled(allocation, last);
464 if (is_similar &&
465 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
466 kMaxVbaThrottleTimeMs) {
467 // This allocation is too similar, cache it and return.
468 video_bitrate_allocation_context_->throttled_allocation = allocation;
469 return;
470 }
471 } else {
472 video_bitrate_allocation_context_.emplace();
473 }
474
475 video_bitrate_allocation_context_->last_sent_allocation = allocation;
476 video_bitrate_allocation_context_->throttled_allocation.reset();
477 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
478
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200479 // Send bitrate allocation metadata only if encoder is not paused.
480 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
481 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200482}
483
Per Kjellandera9434842020-10-15 17:53:22 +0200484void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
485 VideoLayersAllocation allocation) {
Per Kjellanderda06e8f2021-01-07 19:37:00 +0100486 // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
487 // order to not race with OnEncodedImage callbacks.
Per Kjellanderaf704182020-10-16 10:30:40 +0200488 rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
Per Kjellandera9434842020-10-15 17:53:22 +0200489}
490
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200491void VideoSendStreamImpl::SignalEncoderActive() {
492 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200493 if (rtp_video_sender_->IsActive()) {
494 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
495 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
496 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100497}
498
499MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
500 return MediaStreamAllocationConfig{
501 static_cast<uint32_t>(encoder_min_bitrate_bps_),
502 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200503 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100504 /* priority_bitrate */ 0,
505 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100506 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200507}
508
509void VideoSendStreamImpl::OnEncoderConfigurationChanged(
510 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200511 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100512 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200513 int min_transmit_bitrate_bps) {
514 if (!worker_queue_->IsCurrent()) {
515 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200516 worker_queue_->PostTask([send_stream, streams, is_svc, content_type,
Mirko Bonadei80a86872019-02-04 15:01:43 +0100517 min_transmit_bitrate_bps]() mutable {
518 if (send_stream) {
519 send_stream->OnEncoderConfigurationChanged(
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200520 std::move(streams), is_svc, content_type, min_transmit_bitrate_bps);
Mirko Bonadei80a86872019-02-04 15:01:43 +0100521 }
522 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200523 return;
524 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200525
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200526 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
527 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200528 RTC_DCHECK_RUN_ON(worker_queue_);
529
Elad Alon80f53b72019-10-11 16:19:43 +0200530 const VideoCodecType codec_type =
531 PayloadStringToCodecType(config_->rtp.payload_name);
532
533 const absl::optional<DataRate> experimental_min_bitrate =
534 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200535 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200536 experimental_min_bitrate
537 ? experimental_min_bitrate->bps()
538 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
539
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200540 encoder_max_bitrate_bps_ = 0;
541 double stream_bitrate_priority_sum = 0;
542 for (const auto& stream : streams) {
543 // We don't want to allocate more bitrate than needed to inactive streams.
544 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
545 if (stream.bitrate_priority) {
546 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
547 stream_bitrate_priority_sum += *stream.bitrate_priority;
548 }
549 }
550 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
551 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
552 encoder_max_bitrate_bps_ =
553 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
554 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500555
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100556 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200557 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
558 streams, is_svc, content_type, min_transmit_bitrate_bps,
559 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200560
561 // Clear stats for disabled layers.
562 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
563 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
564 }
565
566 const size_t num_temporal_layers =
567 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200568
569 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
570 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200571
Stefan Holmer9416ef82018-07-19 10:34:38 +0200572 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200573 // The send stream is started already. Update the allocator with new bitrate
574 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100575 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200576 }
577}
578
579EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
580 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +0200581 const CodecSpecificInfo* codec_specific_info) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200582 // Encoded is called on whatever thread the real encoder implementation run
583 // on. In the case of hardware encoders, there might be several encoders
584 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100585
586 // Indicate that there still is activity going on.
587 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200588
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200589 auto enable_padding_task = [this]() {
590 if (disable_padding_) {
591 RTC_DCHECK_RUN_ON(worker_queue_);
592 disable_padding_ = false;
593 // To ensure that padding bitrate is propagated to the bitrate allocator.
594 SignalEncoderActive();
595 }
596 };
597 if (!worker_queue_->IsCurrent()) {
598 worker_queue_->PostTask(enable_padding_task);
599 } else {
600 enable_padding_task();
601 }
602
Niels Möller46879152019-01-07 15:54:47 +0100603 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200604 result =
605 rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
Erik Språng4e193e42018-09-14 19:01:58 +0200606 // Check if there's a throttled VideoBitrateAllocation that we should try
607 // sending.
608 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
609 auto update_task = [send_stream]() {
610 if (send_stream) {
611 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
612 auto& context = send_stream->video_bitrate_allocation_context_;
613 if (context && context->throttled_allocation) {
614 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
615 }
616 }
617 };
618 if (!worker_queue_->IsCurrent()) {
619 worker_queue_->PostTask(update_task);
620 } else {
621 update_task();
622 }
623
624 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200625}
626
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100627void VideoSendStreamImpl::OnDroppedFrame(
628 EncodedImageCallback::DropReason reason) {
629 activity_ = true;
630}
631
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200632std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200633 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200634}
635
636std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
637 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200638 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200639}
640
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200641uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200642 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200643 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200644 << "VideoSendStream::Start has not been called.";
645
Florent Castellia8336d32019-09-09 13:36:55 +0200646 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
647 // unstable one instead.
648 if (update.stable_target_bitrate.IsZero()) {
649 update.stable_target_bitrate = update.target_bitrate;
650 }
651
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200652 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200653 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100654 const uint32_t protection_bitrate_bps =
655 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200656 DataRate link_allocation = DataRate::Zero();
657 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
658 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100659 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100660 }
Florent Castellia8336d32019-09-09 13:36:55 +0200661 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100662 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200663 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
664 if (encoder_stable_target_rate > overhead) {
665 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
666 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100667 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200668 }
669
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200670 encoder_target_rate_bps_ =
671 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200672
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100673 encoder_stable_target_rate =
674 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
675 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200676
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100677 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200678 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100679 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200680 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100681 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100682 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200683 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100684 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200685}
686
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200687} // namespace internal
688} // namespace webrtc