blob: bfd621689257f67f2d7fd5ec66a4eb44a5523628 [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
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200126RtpSenderObservers CreateObservers(CallStats* 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,
182 CallStats* call_stats,
183 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 call_stats_(call_stats),
204 transport_(transport),
205 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200206 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200207 max_padding_bitrate_(0),
208 encoder_min_bitrate_bps_(0),
209 encoder_target_rate_bps_(0),
210 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
211 has_packet_feedback_(false),
212 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100213 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200214 bandwidth_observer_(transport->GetBandwidthObserver()),
Marina Cioceae77912b2020-02-27 16:16:55 +0100215 rtp_video_sender_(
216 transport_->CreateRtpVideoSender(suspended_ssrcs,
217 suspended_payload_states,
218 config_->rtp,
219 config_->rtcp_report_interval_ms,
220 config_->send_transport,
221 CreateObservers(call_stats,
222 &encoder_feedback_,
223 stats_proxy_,
224 send_delay_stats),
225 event_log,
226 std::move(fec_controller),
227 CreateFrameEncryptionConfig(config_),
228 config->frame_transformer)),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800229 weak_ptr_factory_(this) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200230 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200231 RTC_DCHECK_RUN_ON(worker_queue_);
232 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
233 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200234
Elad Alonb6ef99b2019-04-10 16:37:07 +0200235 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
236
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800237 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200238 RTC_DCHECK(call_stats_);
239 RTC_DCHECK(transport_);
240 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
241
242 if (initial_encoder_max_bitrate > 0) {
243 encoder_max_bitrate_bps_ =
244 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
245 } else {
246 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
247 // have any way to handle unset values in downstream code, such as the
248 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
249 // behaviour that is not safe. Converting to 10 Mbps should be safe for
250 // reasonable use cases as it allows adding the max of multiple streams
251 // without wrappping around.
252 const int kFallbackMaxBitrateBps = 10000000;
253 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
254 << initial_encoder_max_bitrate << " which is <= 0!";
255 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
256 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
257 }
258
259 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
260 // If send-side BWE is enabled, check if we should apply updated probing and
261 // pacing settings.
262 if (TransportSeqNumExtensionConfigured(*config_)) {
263 has_packet_feedback_ = true;
264
Erik Språngb57ab382018-09-13 10:52:38 +0200265 absl::optional<AlrExperimentSettings> alr_settings =
266 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200267 if (alr_settings) {
268 transport->EnablePeriodicAlrProbing(true);
269 transport->SetPacingFactor(alr_settings->pacing_factor);
270 configured_pacing_factor_ = alr_settings->pacing_factor;
271 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
272 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100273 RateControlSettings rate_control_settings =
274 RateControlSettings::ParseFromFieldTrials();
275
276 transport->EnablePeriodicAlrProbing(
277 rate_control_settings.UseAlrProbing());
278 const double pacing_factor =
279 rate_control_settings.GetPacingFactor().value_or(
280 pacing_config_.pacing_factor);
281 transport->SetPacingFactor(pacing_factor);
282 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100283 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200284 }
285 }
286
287 if (config_->periodic_alr_bandwidth_probing) {
288 transport->EnablePeriodicAlrProbing(true);
289 }
290
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200291 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
292 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
293
294 video_stream_encoder_->SetStartBitrate(
295 bitrate_allocator_->GetStartBitrate(this));
296
297 // Only request rotation at the source when we positively know that the remote
298 // side doesn't support the rotation extension. This allows us to prepare the
299 // encoder in the expectation that rotation is supported - which is the common
300 // case.
Steve Antonbd631a02019-03-28 10:51:27 -0700301 bool rotation_applied = absl::c_none_of(
302 config_->rtp.extensions, [](const RtpExtension& extension) {
303 return extension.uri == RtpExtension::kVideoRotationUri;
304 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200305
306 video_stream_encoder_->SetSink(this, rotation_applied);
307}
308
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200309VideoSendStreamImpl::~VideoSendStreamImpl() {
310 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200311 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200312 << "VideoSendStreamImpl::Stop not called";
313 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200314 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200315}
316
317void VideoSendStreamImpl::RegisterProcessThread(
318 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200319 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200320}
321
322void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200323 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200324}
325
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100326void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200327 // Runs on a network thread.
328 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200329 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200330}
331
332void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
333 const std::vector<bool> active_layers) {
334 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200335 bool previously_active = rtp_video_sender_->IsActive();
336 rtp_video_sender_->SetActiveModules(active_layers);
337 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200338 // Payload router switched from active to inactive.
339 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200340 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200341 // Payload router switched from inactive to active.
342 StartupVideoSendStream();
343 }
344}
345
346void VideoSendStreamImpl::Start() {
347 RTC_DCHECK_RUN_ON(worker_queue_);
348 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200349 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200350 return;
351 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200352 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200353 StartupVideoSendStream();
354}
355
356void VideoSendStreamImpl::StartupVideoSendStream() {
357 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100358 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200359 // Start monitoring encoder activity.
360 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100361 RTC_DCHECK(!check_encoder_activity_task_.Running());
362
363 activity_ = false;
364 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100365 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
366 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100367 RTC_DCHECK_RUN_ON(worker_queue_);
368 if (!activity_) {
369 if (!timed_out_) {
370 SignalEncoderTimedOut();
371 }
372 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200373 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100374 } else if (timed_out_) {
375 SignalEncoderActive();
376 timed_out_ = false;
377 }
378 activity_ = false;
379 return kEncoderTimeOut;
380 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200381 }
382
383 video_stream_encoder_->SendKeyFrame();
384}
385
386void VideoSendStreamImpl::Stop() {
387 RTC_DCHECK_RUN_ON(worker_queue_);
388 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200389 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200390 return;
391 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200392 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200393 StopVideoSendStream();
394}
395
396void VideoSendStreamImpl::StopVideoSendStream() {
397 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100398 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200399 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100400 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200401 stats_proxy_->OnSetEncoderTargetRate(0);
402}
403
404void VideoSendStreamImpl::SignalEncoderTimedOut() {
405 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100406 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200407 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
408 // if a camera stops producing frames.
409 if (encoder_target_rate_bps_ > 0) {
410 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
411 bitrate_allocator_->RemoveObserver(this);
412 }
413}
414
415void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200416 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200417 if (!worker_queue_->IsCurrent()) {
418 auto ptr = weak_ptr_;
419 worker_queue_->PostTask([=] {
420 if (!ptr.get())
421 return;
422 ptr->OnBitrateAllocationUpdated(allocation);
423 });
424 return;
425 }
426
427 RTC_DCHECK_RUN_ON(worker_queue_);
428
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100429 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200430 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200431 if (video_bitrate_allocation_context_) {
432 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
433 // the previously sent allocation and the same streams are still enabled,
434 // it is considered "similar". We do not want send similar allocations
435 // more once per kMaxVbaThrottleTimeMs.
436 const VideoBitrateAllocation& last =
437 video_bitrate_allocation_context_->last_sent_allocation;
438 const bool is_similar =
439 allocation.get_sum_bps() >= last.get_sum_bps() &&
440 allocation.get_sum_bps() <
441 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
442 100 &&
443 SameStreamsEnabled(allocation, last);
444 if (is_similar &&
445 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
446 kMaxVbaThrottleTimeMs) {
447 // This allocation is too similar, cache it and return.
448 video_bitrate_allocation_context_->throttled_allocation = allocation;
449 return;
450 }
451 } else {
452 video_bitrate_allocation_context_.emplace();
453 }
454
455 video_bitrate_allocation_context_->last_sent_allocation = allocation;
456 video_bitrate_allocation_context_->throttled_allocation.reset();
457 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
458
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200459 // Send bitrate allocation metadata only if encoder is not paused.
460 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
461 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200462}
463
464void VideoSendStreamImpl::SignalEncoderActive() {
465 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200466 if (rtp_video_sender_->IsActive()) {
467 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
468 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
469 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100470}
471
472MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
473 return MediaStreamAllocationConfig{
474 static_cast<uint32_t>(encoder_min_bitrate_bps_),
475 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200476 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100477 /* priority_bitrate */ 0,
478 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100479 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200480}
481
482void VideoSendStreamImpl::OnEncoderConfigurationChanged(
483 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200484 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100485 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200486 int min_transmit_bitrate_bps) {
487 if (!worker_queue_->IsCurrent()) {
488 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200489 worker_queue_->PostTask([send_stream, streams, is_svc, content_type,
Mirko Bonadei80a86872019-02-04 15:01:43 +0100490 min_transmit_bitrate_bps]() mutable {
491 if (send_stream) {
492 send_stream->OnEncoderConfigurationChanged(
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200493 std::move(streams), is_svc, content_type, min_transmit_bitrate_bps);
Mirko Bonadei80a86872019-02-04 15:01:43 +0100494 }
495 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200496 return;
497 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200498
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200499 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
500 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200501 RTC_DCHECK_RUN_ON(worker_queue_);
502
Elad Alon80f53b72019-10-11 16:19:43 +0200503 const VideoCodecType codec_type =
504 PayloadStringToCodecType(config_->rtp.payload_name);
505
506 const absl::optional<DataRate> experimental_min_bitrate =
507 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200508 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200509 experimental_min_bitrate
510 ? experimental_min_bitrate->bps()
511 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
512
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200513 encoder_max_bitrate_bps_ = 0;
514 double stream_bitrate_priority_sum = 0;
515 for (const auto& stream : streams) {
516 // We don't want to allocate more bitrate than needed to inactive streams.
517 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
518 if (stream.bitrate_priority) {
519 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
520 stream_bitrate_priority_sum += *stream.bitrate_priority;
521 }
522 }
523 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
524 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
525 encoder_max_bitrate_bps_ =
526 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
527 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500528
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100529 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200530 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
531 streams, is_svc, content_type, min_transmit_bitrate_bps,
532 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200533
534 // Clear stats for disabled layers.
535 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
536 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
537 }
538
539 const size_t num_temporal_layers =
540 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200541
542 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
543 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200544
Stefan Holmer9416ef82018-07-19 10:34:38 +0200545 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200546 // The send stream is started already. Update the allocator with new bitrate
547 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100548 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200549 }
550}
551
552EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
553 const EncodedImage& encoded_image,
554 const CodecSpecificInfo* codec_specific_info,
555 const RTPFragmentationHeader* fragmentation) {
556 // Encoded is called on whatever thread the real encoder implementation run
557 // on. In the case of hardware encoders, there might be several encoders
558 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100559
560 // Indicate that there still is activity going on.
561 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200562
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200563 auto enable_padding_task = [this]() {
564 if (disable_padding_) {
565 RTC_DCHECK_RUN_ON(worker_queue_);
566 disable_padding_ = false;
567 // To ensure that padding bitrate is propagated to the bitrate allocator.
568 SignalEncoderActive();
569 }
570 };
571 if (!worker_queue_->IsCurrent()) {
572 worker_queue_->PostTask(enable_padding_task);
573 } else {
574 enable_padding_task();
575 }
576
Niels Möller46879152019-01-07 15:54:47 +0100577 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800578 result = rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info,
579 fragmentation);
Erik Språng4e193e42018-09-14 19:01:58 +0200580 // Check if there's a throttled VideoBitrateAllocation that we should try
581 // sending.
582 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
583 auto update_task = [send_stream]() {
584 if (send_stream) {
585 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
586 auto& context = send_stream->video_bitrate_allocation_context_;
587 if (context && context->throttled_allocation) {
588 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
589 }
590 }
591 };
592 if (!worker_queue_->IsCurrent()) {
593 worker_queue_->PostTask(update_task);
594 } else {
595 update_task();
596 }
597
598 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200599}
600
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100601void VideoSendStreamImpl::OnDroppedFrame(
602 EncodedImageCallback::DropReason reason) {
603 activity_ = true;
604}
605
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200606std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200607 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200608}
609
610std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
611 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200612 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200613}
614
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200615uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200616 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200617 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200618 << "VideoSendStream::Start has not been called.";
619
Florent Castellia8336d32019-09-09 13:36:55 +0200620 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
621 // unstable one instead.
622 if (update.stable_target_bitrate.IsZero()) {
623 update.stable_target_bitrate = update.target_bitrate;
624 }
625
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200626 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200627 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100628 const uint32_t protection_bitrate_bps =
629 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200630 DataRate link_allocation = DataRate::Zero();
631 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
632 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100633 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100634 }
Florent Castellia8336d32019-09-09 13:36:55 +0200635 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100636 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200637 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
638 if (encoder_stable_target_rate > overhead) {
639 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
640 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100641 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200642 }
643
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200644 encoder_target_rate_bps_ =
645 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200646
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100647 encoder_stable_target_rate =
648 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
649 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200650
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100651 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200652 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100653 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200654 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100655 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100656 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200657 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100658 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200659}
660
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200661} // namespace internal
662} // namespace webrtc