blob: 03c9613ab4e8558a8ec0714245f7abda91e96e84 [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"
Yves Gerey3e707812018-11-28 16:47:49 +010023#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020024#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 16:47:49 +010025#include "call/video_send_stream.h"
Yves Gerey3e707812018-11-28 16:47:49 +010026#include "modules/pacing/paced_sender.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/atomic_ops.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020028#include "rtc_base/checks.h"
29#include "rtc_base/experiments/alr_experiment.h"
Ying Wang8c5520c2019-09-03 15:25:21 +000030#include "rtc_base/experiments/field_trial_parser.h"
Elad Alon80f53b72019-10-11 16:19:43 +020031#include "rtc_base/experiments/min_video_bitrate_experiment.h"
Erik Språngcd76eab2019-01-21 18:06:46 +010032#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020033#include "rtc_base/logging.h"
34#include "rtc_base/numerics/safe_conversions.h"
Sebastian Janssonb55015e2019-04-09 13:44:04 +020035#include "rtc_base/synchronization/sequence_checker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010036#include "rtc_base/thread_checker.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020037#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010038#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020039#include "system_wrappers/include/field_trial.h"
40
41namespace webrtc {
42namespace internal {
43namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020044
Erik Språng4e193e42018-09-14 19:01:58 +020045// Max positive size difference to treat allocations as "similar".
46static constexpr int kMaxVbaSizeDifferencePercent = 10;
47// Max time we will throttle similar video bitrate allocations.
48static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
49
Danil Chapovalov0c626af2020-02-10 11:16:00 +010050constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds(2);
Sebastian Janssonecb68972019-01-18 10:30:54 +010051
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020052bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
53 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070054 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
55 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
56 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020057}
58
Erik Språngb57ab382018-09-13 10:52:38 +020059// Calculate max padding bitrate for a multi layer codec.
60int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020061 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010062 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020063 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020064 bool pad_to_min_bitrate,
65 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020066 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020067
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020068 RTC_DCHECK(!is_svc || streams.size() <= 1) << "Only one stream is allowed in "
69 "SVC mode.";
70
Erik Språngb57ab382018-09-13 10:52:38 +020071 // Filter out only the active streams;
72 std::vector<VideoStream> active_streams;
73 for (const VideoStream& stream : streams) {
74 if (stream.active)
75 active_streams.emplace_back(stream);
76 }
77
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +020078 if (active_streams.size() > 1 || (!active_streams.empty() && is_svc)) {
79 // Simulcast or SVC is used.
80 // if SVC is used, stream bitrates should already encode svc bitrates:
81 // min_bitrate = min bitrate of a lowest svc layer.
82 // target_bitrate = sum of target bitrates of lower layers + min bitrate
83 // of the last one (as used in the calculations below).
84 // max_bitrate = sum of all active layers' max_bitrate.
Erik Språngb57ab382018-09-13 10:52:38 +020085 if (alr_probing) {
86 // With alr probing, just pad to the min bitrate of the lowest stream,
87 // probing will handle the rest of the rampup.
88 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
89 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010090 // Without alr probing, pad up to start bitrate of the
91 // highest active stream.
92 const double hysteresis_factor =
93 RateControlSettings::ParseFromFieldTrials()
94 .GetSimulcastHysteresisFactor(content_type);
95 const size_t top_active_stream_idx = active_streams.size() - 1;
96 pad_up_to_bitrate_bps = std::min(
97 static_cast<int>(
98 hysteresis_factor *
99 active_streams[top_active_stream_idx].min_bitrate_bps +
100 0.5),
101 active_streams[top_active_stream_idx].target_bitrate_bps);
102
103 // Add target_bitrate_bps of the lower active streams.
104 for (size_t i = 0; i < top_active_stream_idx; ++i) {
Erik Språngb57ab382018-09-13 10:52:38 +0200105 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100106 }
Erik Språngb57ab382018-09-13 10:52:38 +0200107 }
108 } else if (!active_streams.empty() && pad_to_min_bitrate) {
109 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200110 }
111
112 pad_up_to_bitrate_bps =
113 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
114
115 return pad_up_to_bitrate_bps;
116}
117
Benjamin Wright192eeec2018-10-17 17:27:25 -0700118RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
119 const VideoSendStream::Config* config) {
120 RtpSenderFrameEncryptionConfig frame_encryption_config;
121 frame_encryption_config.frame_encryptor = config->frame_encryptor;
122 frame_encryption_config.crypto_options = config->crypto_options;
123 return frame_encryption_config;
124}
125
Tommi8ae18ad2020-05-03 22:45:02 +0200126RtpSenderObservers CreateObservers(RtcpRttStats* call_stats,
Elad Alon14d1c9d2019-04-08 14:16:17 +0200127 EncoderRtcpFeedback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200128 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200129 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200130 RtpSenderObservers observers;
131 observers.rtcp_rtt_stats = call_stats;
132 observers.intra_frame_callback = encoder_feedback;
Elad Alon0a8562e2019-04-09 11:55:13 +0200133 observers.rtcp_loss_notification_observer = encoder_feedback;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200134 observers.rtcp_stats = stats_proxy;
Henrik Boström87e3f9d2019-05-27 10:44:24 +0200135 observers.report_block_data_observer = stats_proxy;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200136 observers.rtp_stats = stats_proxy;
137 observers.bitrate_observer = stats_proxy;
138 observers.frame_count_observer = stats_proxy;
139 observers.rtcp_type_observer = stats_proxy;
140 observers.send_delay_observer = stats_proxy;
141 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200142 return observers;
143}
Erik Språngb57ab382018-09-13 10:52:38 +0200144
145absl::optional<AlrExperimentSettings> GetAlrSettings(
146 VideoEncoderConfig::ContentType content_type) {
147 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
148 return AlrExperimentSettings::CreateFromFieldTrial(
149 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
150 }
151 return AlrExperimentSettings::CreateFromFieldTrial(
152 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
153}
Erik Språng4e193e42018-09-14 19:01:58 +0200154
155bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
156 const VideoBitrateAllocation& rhs) {
157 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
158 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
159 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
160 return false;
161 }
162 }
163 }
164 return true;
165}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200166} // namespace
167
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100168PacingConfig::PacingConfig()
169 : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
170 max_pacing_delay("max_delay",
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100171 TimeDelta::Millis(PacedSender::kMaxQueueLengthMs)) {
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100172 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
173 field_trial::FindFullName("WebRTC-Video-Pacing"));
174}
175PacingConfig::PacingConfig(const PacingConfig&) = default;
176PacingConfig::~PacingConfig() = default;
177
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200178VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100179 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200180 SendStatisticsProxy* stats_proxy,
181 rtc::TaskQueue* worker_queue,
Tommi8ae18ad2020-05-03 22:45:02 +0200182 RtcpRttStats* call_stats,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200183 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200184 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200185 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200186 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200187 RtcEventLog* event_log,
188 const VideoSendStream::Config* config,
189 int initial_encoder_max_bitrate,
190 double initial_encoder_bitrate_priority,
191 std::map<uint32_t, RtpState> suspended_ssrcs,
192 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
193 VideoEncoderConfig::ContentType content_type,
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800194 std::unique_ptr<FecController> fec_controller)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100195 : clock_(clock),
196 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200197 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100198 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200199 stats_proxy_(stats_proxy),
200 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200201 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100202 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200203 transport_(transport),
204 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200205 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200206 max_padding_bitrate_(0),
207 encoder_min_bitrate_bps_(0),
208 encoder_target_rate_bps_(0),
209 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
210 has_packet_feedback_(false),
211 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100212 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200213 bandwidth_observer_(transport->GetBandwidthObserver()),
Marina Cioceae77912b2020-02-27 16:16:55 +0100214 rtp_video_sender_(
215 transport_->CreateRtpVideoSender(suspended_ssrcs,
216 suspended_payload_states,
217 config_->rtp,
218 config_->rtcp_report_interval_ms,
219 config_->send_transport,
220 CreateObservers(call_stats,
221 &encoder_feedback_,
222 stats_proxy_,
223 send_delay_stats),
224 event_log,
225 std::move(fec_controller),
226 CreateFrameEncryptionConfig(config_),
227 config->frame_transformer)),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800228 weak_ptr_factory_(this) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200229 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200230 RTC_DCHECK_RUN_ON(worker_queue_);
231 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
232 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200233
Elad Alonb6ef99b2019-04-10 16:37:07 +0200234 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
235
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800236 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200237 RTC_DCHECK(transport_);
238 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
239
240 if (initial_encoder_max_bitrate > 0) {
241 encoder_max_bitrate_bps_ =
242 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
243 } else {
244 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
245 // have any way to handle unset values in downstream code, such as the
246 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
247 // behaviour that is not safe. Converting to 10 Mbps should be safe for
248 // reasonable use cases as it allows adding the max of multiple streams
249 // without wrappping around.
250 const int kFallbackMaxBitrateBps = 10000000;
251 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
252 << initial_encoder_max_bitrate << " which is <= 0!";
253 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
254 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
255 }
256
257 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
258 // If send-side BWE is enabled, check if we should apply updated probing and
259 // pacing settings.
260 if (TransportSeqNumExtensionConfigured(*config_)) {
261 has_packet_feedback_ = true;
262
Erik Språngb57ab382018-09-13 10:52:38 +0200263 absl::optional<AlrExperimentSettings> alr_settings =
264 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200265 if (alr_settings) {
266 transport->EnablePeriodicAlrProbing(true);
267 transport->SetPacingFactor(alr_settings->pacing_factor);
268 configured_pacing_factor_ = alr_settings->pacing_factor;
269 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
270 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100271 RateControlSettings rate_control_settings =
272 RateControlSettings::ParseFromFieldTrials();
273
274 transport->EnablePeriodicAlrProbing(
275 rate_control_settings.UseAlrProbing());
276 const double pacing_factor =
277 rate_control_settings.GetPacingFactor().value_or(
278 pacing_config_.pacing_factor);
279 transport->SetPacingFactor(pacing_factor);
280 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100281 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200282 }
283 }
284
285 if (config_->periodic_alr_bandwidth_probing) {
286 transport->EnablePeriodicAlrProbing(true);
287 }
288
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200289 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
290 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
291
292 video_stream_encoder_->SetStartBitrate(
293 bitrate_allocator_->GetStartBitrate(this));
294
295 // Only request rotation at the source when we positively know that the remote
296 // side doesn't support the rotation extension. This allows us to prepare the
297 // encoder in the expectation that rotation is supported - which is the common
298 // case.
Steve Antonbd631a02019-03-28 10:51:27 -0700299 bool rotation_applied = absl::c_none_of(
300 config_->rtp.extensions, [](const RtpExtension& extension) {
301 return extension.uri == RtpExtension::kVideoRotationUri;
302 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200303
304 video_stream_encoder_->SetSink(this, rotation_applied);
305}
306
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200307VideoSendStreamImpl::~VideoSendStreamImpl() {
308 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200309 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200310 << "VideoSendStreamImpl::Stop not called";
311 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200312 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200313}
314
315void VideoSendStreamImpl::RegisterProcessThread(
316 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200317 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200318}
319
320void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200321 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200322}
323
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100324void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200325 // Runs on a network thread.
326 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200327 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200328}
329
330void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
331 const std::vector<bool> active_layers) {
332 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200333 bool previously_active = rtp_video_sender_->IsActive();
334 rtp_video_sender_->SetActiveModules(active_layers);
335 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200336 // Payload router switched from active to inactive.
337 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200338 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200339 // Payload router switched from inactive to active.
340 StartupVideoSendStream();
341 }
342}
343
344void VideoSendStreamImpl::Start() {
345 RTC_DCHECK_RUN_ON(worker_queue_);
346 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200347 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200348 return;
349 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200350 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200351 StartupVideoSendStream();
352}
353
354void VideoSendStreamImpl::StartupVideoSendStream() {
355 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100356 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200357 // Start monitoring encoder activity.
358 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100359 RTC_DCHECK(!check_encoder_activity_task_.Running());
360
361 activity_ = false;
362 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100363 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
364 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100365 RTC_DCHECK_RUN_ON(worker_queue_);
366 if (!activity_) {
367 if (!timed_out_) {
368 SignalEncoderTimedOut();
369 }
370 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200371 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100372 } else if (timed_out_) {
373 SignalEncoderActive();
374 timed_out_ = false;
375 }
376 activity_ = false;
377 return kEncoderTimeOut;
378 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200379 }
380
381 video_stream_encoder_->SendKeyFrame();
382}
383
384void VideoSendStreamImpl::Stop() {
385 RTC_DCHECK_RUN_ON(worker_queue_);
386 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200387 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200388 return;
389 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200390 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200391 StopVideoSendStream();
392}
393
394void VideoSendStreamImpl::StopVideoSendStream() {
395 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100396 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200397 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100398 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200399 stats_proxy_->OnSetEncoderTargetRate(0);
400}
401
402void VideoSendStreamImpl::SignalEncoderTimedOut() {
403 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100404 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200405 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
406 // if a camera stops producing frames.
407 if (encoder_target_rate_bps_ > 0) {
408 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
409 bitrate_allocator_->RemoveObserver(this);
410 }
411}
412
413void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200414 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200415 if (!worker_queue_->IsCurrent()) {
416 auto ptr = weak_ptr_;
417 worker_queue_->PostTask([=] {
418 if (!ptr.get())
419 return;
420 ptr->OnBitrateAllocationUpdated(allocation);
421 });
422 return;
423 }
424
425 RTC_DCHECK_RUN_ON(worker_queue_);
426
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100427 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200428 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200429 if (video_bitrate_allocation_context_) {
430 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
431 // the previously sent allocation and the same streams are still enabled,
432 // it is considered "similar". We do not want send similar allocations
433 // more once per kMaxVbaThrottleTimeMs.
434 const VideoBitrateAllocation& last =
435 video_bitrate_allocation_context_->last_sent_allocation;
436 const bool is_similar =
437 allocation.get_sum_bps() >= last.get_sum_bps() &&
438 allocation.get_sum_bps() <
439 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
440 100 &&
441 SameStreamsEnabled(allocation, last);
442 if (is_similar &&
443 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
444 kMaxVbaThrottleTimeMs) {
445 // This allocation is too similar, cache it and return.
446 video_bitrate_allocation_context_->throttled_allocation = allocation;
447 return;
448 }
449 } else {
450 video_bitrate_allocation_context_.emplace();
451 }
452
453 video_bitrate_allocation_context_->last_sent_allocation = allocation;
454 video_bitrate_allocation_context_->throttled_allocation.reset();
455 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
456
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200457 // Send bitrate allocation metadata only if encoder is not paused.
458 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
459 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200460}
461
462void VideoSendStreamImpl::SignalEncoderActive() {
463 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200464 if (rtp_video_sender_->IsActive()) {
465 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
466 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
467 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100468}
469
470MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
471 return MediaStreamAllocationConfig{
472 static_cast<uint32_t>(encoder_min_bitrate_bps_),
473 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200474 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100475 /* priority_bitrate */ 0,
476 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100477 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200478}
479
480void VideoSendStreamImpl::OnEncoderConfigurationChanged(
481 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200482 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100483 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200484 int min_transmit_bitrate_bps) {
485 if (!worker_queue_->IsCurrent()) {
486 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200487 worker_queue_->PostTask([send_stream, streams, is_svc, content_type,
Mirko Bonadei80a86872019-02-04 15:01:43 +0100488 min_transmit_bitrate_bps]() mutable {
489 if (send_stream) {
490 send_stream->OnEncoderConfigurationChanged(
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200491 std::move(streams), is_svc, content_type, min_transmit_bitrate_bps);
Mirko Bonadei80a86872019-02-04 15:01:43 +0100492 }
493 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200494 return;
495 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200496
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200497 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
498 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200499 RTC_DCHECK_RUN_ON(worker_queue_);
500
Elad Alon80f53b72019-10-11 16:19:43 +0200501 const VideoCodecType codec_type =
502 PayloadStringToCodecType(config_->rtp.payload_name);
503
504 const absl::optional<DataRate> experimental_min_bitrate =
505 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200506 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200507 experimental_min_bitrate
508 ? experimental_min_bitrate->bps()
509 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
510
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200511 encoder_max_bitrate_bps_ = 0;
512 double stream_bitrate_priority_sum = 0;
513 for (const auto& stream : streams) {
514 // We don't want to allocate more bitrate than needed to inactive streams.
515 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
516 if (stream.bitrate_priority) {
517 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
518 stream_bitrate_priority_sum += *stream.bitrate_priority;
519 }
520 }
521 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
522 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
523 encoder_max_bitrate_bps_ =
524 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
525 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500526
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100527 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200528 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
529 streams, is_svc, content_type, min_transmit_bitrate_bps,
530 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200531
532 // Clear stats for disabled layers.
533 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
534 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
535 }
536
537 const size_t num_temporal_layers =
538 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200539
540 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
541 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200542
Stefan Holmer9416ef82018-07-19 10:34:38 +0200543 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200544 // The send stream is started already. Update the allocator with new bitrate
545 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100546 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200547 }
548}
549
550EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
551 const EncodedImage& encoded_image,
552 const CodecSpecificInfo* codec_specific_info,
553 const RTPFragmentationHeader* fragmentation) {
554 // Encoded is called on whatever thread the real encoder implementation run
555 // on. In the case of hardware encoders, there might be several encoders
556 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100557
558 // Indicate that there still is activity going on.
559 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200560
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200561 auto enable_padding_task = [this]() {
562 if (disable_padding_) {
563 RTC_DCHECK_RUN_ON(worker_queue_);
564 disable_padding_ = false;
565 // To ensure that padding bitrate is propagated to the bitrate allocator.
566 SignalEncoderActive();
567 }
568 };
569 if (!worker_queue_->IsCurrent()) {
570 worker_queue_->PostTask(enable_padding_task);
571 } else {
572 enable_padding_task();
573 }
574
Niels Möller46879152019-01-07 15:54:47 +0100575 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800576 result = rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info,
577 fragmentation);
Erik Språng4e193e42018-09-14 19:01:58 +0200578 // Check if there's a throttled VideoBitrateAllocation that we should try
579 // sending.
580 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
581 auto update_task = [send_stream]() {
582 if (send_stream) {
583 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
584 auto& context = send_stream->video_bitrate_allocation_context_;
585 if (context && context->throttled_allocation) {
586 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
587 }
588 }
589 };
590 if (!worker_queue_->IsCurrent()) {
591 worker_queue_->PostTask(update_task);
592 } else {
593 update_task();
594 }
595
596 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200597}
598
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100599void VideoSendStreamImpl::OnDroppedFrame(
600 EncodedImageCallback::DropReason reason) {
601 activity_ = true;
602}
603
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200604std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200605 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200606}
607
608std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
609 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200610 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200611}
612
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200613uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200614 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200615 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200616 << "VideoSendStream::Start has not been called.";
617
Florent Castellia8336d32019-09-09 13:36:55 +0200618 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
619 // unstable one instead.
620 if (update.stable_target_bitrate.IsZero()) {
621 update.stable_target_bitrate = update.target_bitrate;
622 }
623
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200624 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200625 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100626 const uint32_t protection_bitrate_bps =
627 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200628 DataRate link_allocation = DataRate::Zero();
629 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
630 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100631 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100632 }
Florent Castellia8336d32019-09-09 13:36:55 +0200633 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100634 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200635 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
636 if (encoder_stable_target_rate > overhead) {
637 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
638 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100639 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200640 }
641
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200642 encoder_target_rate_bps_ =
643 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200644
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100645 encoder_stable_target_rate =
646 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
647 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200648
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100649 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200650 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100651 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200652 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100653 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100654 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200655 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100656 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200657}
658
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200659} // namespace internal
660} // namespace webrtc