blob: ebd4445004debd600bf24c64e7c6fbc08776b441 [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),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100226 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200227 bandwidth_observer_(transport->GetBandwidthObserver()),
Marina Cioceae77912b2020-02-27 16:16:55 +0100228 rtp_video_sender_(
229 transport_->CreateRtpVideoSender(suspended_ssrcs,
230 suspended_payload_states,
231 config_->rtp,
232 config_->rtcp_report_interval_ms,
233 config_->send_transport,
234 CreateObservers(call_stats,
235 &encoder_feedback_,
236 stats_proxy_,
237 send_delay_stats),
238 event_log,
239 std::move(fec_controller),
240 CreateFrameEncryptionConfig(config_),
241 config->frame_transformer)),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800242 weak_ptr_factory_(this) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200243 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200244 RTC_DCHECK_RUN_ON(worker_queue_);
245 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
246 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200247
Elad Alonb6ef99b2019-04-10 16:37:07 +0200248 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
249
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800250 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200251 RTC_DCHECK(transport_);
252 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
253
254 if (initial_encoder_max_bitrate > 0) {
255 encoder_max_bitrate_bps_ =
256 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
257 } else {
258 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
259 // have any way to handle unset values in downstream code, such as the
260 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
261 // behaviour that is not safe. Converting to 10 Mbps should be safe for
262 // reasonable use cases as it allows adding the max of multiple streams
263 // without wrappping around.
264 const int kFallbackMaxBitrateBps = 10000000;
265 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
266 << initial_encoder_max_bitrate << " which is <= 0!";
267 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
268 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
269 }
270
271 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
272 // If send-side BWE is enabled, check if we should apply updated probing and
273 // pacing settings.
274 if (TransportSeqNumExtensionConfigured(*config_)) {
275 has_packet_feedback_ = true;
276
Erik Språngb57ab382018-09-13 10:52:38 +0200277 absl::optional<AlrExperimentSettings> alr_settings =
278 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200279 if (alr_settings) {
280 transport->EnablePeriodicAlrProbing(true);
281 transport->SetPacingFactor(alr_settings->pacing_factor);
282 configured_pacing_factor_ = alr_settings->pacing_factor;
283 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
284 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100285 RateControlSettings rate_control_settings =
286 RateControlSettings::ParseFromFieldTrials();
287
288 transport->EnablePeriodicAlrProbing(
289 rate_control_settings.UseAlrProbing());
290 const double pacing_factor =
291 rate_control_settings.GetPacingFactor().value_or(
292 pacing_config_.pacing_factor);
293 transport->SetPacingFactor(pacing_factor);
294 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100295 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200296 }
297 }
298
299 if (config_->periodic_alr_bandwidth_probing) {
300 transport->EnablePeriodicAlrProbing(true);
301 }
302
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200303 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
304 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
305
306 video_stream_encoder_->SetStartBitrate(
307 bitrate_allocator_->GetStartBitrate(this));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200308}
309
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200310VideoSendStreamImpl::~VideoSendStreamImpl() {
311 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200312 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200313 << "VideoSendStreamImpl::Stop not called";
314 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200315 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200316}
317
318void VideoSendStreamImpl::RegisterProcessThread(
319 ProcessThread* module_process_thread) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200320 // Called on libjingle's worker thread (not worker_queue_), as part of the
321 // initialization steps. That's also the correct thread/queue for setting the
322 // state for |video_stream_encoder_|.
323
324 // Only request rotation at the source when we positively know that the remote
325 // side doesn't support the rotation extension. This allows us to prepare the
326 // encoder in the expectation that rotation is supported - which is the common
327 // case.
328 bool rotation_applied = absl::c_none_of(
329 config_->rtp.extensions, [](const RtpExtension& extension) {
330 return extension.uri == RtpExtension::kVideoRotationUri;
331 });
332
333 video_stream_encoder_->SetSink(this, rotation_applied);
334
Stefan Holmer9416ef82018-07-19 10:34:38 +0200335 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200336}
337
338void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200339 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200340}
341
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100342void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200343 // Runs on a network thread.
344 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200345 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200346}
347
348void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
349 const std::vector<bool> active_layers) {
350 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200351 bool previously_active = rtp_video_sender_->IsActive();
352 rtp_video_sender_->SetActiveModules(active_layers);
353 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200354 // Payload router switched from active to inactive.
355 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200356 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200357 // Payload router switched from inactive to active.
358 StartupVideoSendStream();
359 }
360}
361
362void VideoSendStreamImpl::Start() {
363 RTC_DCHECK_RUN_ON(worker_queue_);
364 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200365 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200366 return;
367 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200368 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200369 StartupVideoSendStream();
370}
371
372void VideoSendStreamImpl::StartupVideoSendStream() {
373 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100374 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200375 // Start monitoring encoder activity.
376 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100377 RTC_DCHECK(!check_encoder_activity_task_.Running());
378
379 activity_ = false;
380 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100381 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
382 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100383 RTC_DCHECK_RUN_ON(worker_queue_);
384 if (!activity_) {
385 if (!timed_out_) {
386 SignalEncoderTimedOut();
387 }
388 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200389 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100390 } else if (timed_out_) {
391 SignalEncoderActive();
392 timed_out_ = false;
393 }
394 activity_ = false;
395 return kEncoderTimeOut;
396 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200397 }
398
399 video_stream_encoder_->SendKeyFrame();
400}
401
402void VideoSendStreamImpl::Stop() {
403 RTC_DCHECK_RUN_ON(worker_queue_);
Evan Shrubsole0db33962020-11-25 14:54:58 +0100404 RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200405 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200406 return;
407 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200408 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200409 StopVideoSendStream();
410}
411
412void VideoSendStreamImpl::StopVideoSendStream() {
413 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100414 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200415 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
Ying Wang9b881ab2020-02-07 14:29:32 +0100416 DataRate::Zero(), 0, 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200417 stats_proxy_->OnSetEncoderTargetRate(0);
418}
419
420void VideoSendStreamImpl::SignalEncoderTimedOut() {
421 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100422 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200423 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
424 // if a camera stops producing frames.
425 if (encoder_target_rate_bps_ > 0) {
426 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
427 bitrate_allocator_->RemoveObserver(this);
428 }
429}
430
431void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200432 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200433 if (!worker_queue_->IsCurrent()) {
434 auto ptr = weak_ptr_;
435 worker_queue_->PostTask([=] {
436 if (!ptr.get())
437 return;
438 ptr->OnBitrateAllocationUpdated(allocation);
439 });
440 return;
441 }
442
443 RTC_DCHECK_RUN_ON(worker_queue_);
444
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100445 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200446 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200447 if (video_bitrate_allocation_context_) {
448 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
449 // the previously sent allocation and the same streams are still enabled,
450 // it is considered "similar". We do not want send similar allocations
451 // more once per kMaxVbaThrottleTimeMs.
452 const VideoBitrateAllocation& last =
453 video_bitrate_allocation_context_->last_sent_allocation;
454 const bool is_similar =
455 allocation.get_sum_bps() >= last.get_sum_bps() &&
456 allocation.get_sum_bps() <
457 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
458 100 &&
459 SameStreamsEnabled(allocation, last);
460 if (is_similar &&
461 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
462 kMaxVbaThrottleTimeMs) {
463 // This allocation is too similar, cache it and return.
464 video_bitrate_allocation_context_->throttled_allocation = allocation;
465 return;
466 }
467 } else {
468 video_bitrate_allocation_context_.emplace();
469 }
470
471 video_bitrate_allocation_context_->last_sent_allocation = allocation;
472 video_bitrate_allocation_context_->throttled_allocation.reset();
473 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
474
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200475 // Send bitrate allocation metadata only if encoder is not paused.
476 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
477 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200478}
479
Per Kjellandera9434842020-10-15 17:53:22 +0200480void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
481 VideoLayersAllocation allocation) {
Per Kjellanderda06e8f2021-01-07 19:37:00 +0100482 // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
483 // order to not race with OnEncodedImage callbacks.
Per Kjellanderaf704182020-10-16 10:30:40 +0200484 rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
Per Kjellandera9434842020-10-15 17:53:22 +0200485}
486
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200487void VideoSendStreamImpl::SignalEncoderActive() {
488 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200489 if (rtp_video_sender_->IsActive()) {
490 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
491 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
492 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100493}
494
495MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
496 return MediaStreamAllocationConfig{
497 static_cast<uint32_t>(encoder_min_bitrate_bps_),
498 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200499 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100500 /* priority_bitrate */ 0,
501 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100502 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200503}
504
505void VideoSendStreamImpl::OnEncoderConfigurationChanged(
506 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200507 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100508 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200509 int min_transmit_bitrate_bps) {
510 if (!worker_queue_->IsCurrent()) {
511 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200512 worker_queue_->PostTask([send_stream, streams, is_svc, content_type,
Mirko Bonadei80a86872019-02-04 15:01:43 +0100513 min_transmit_bitrate_bps]() mutable {
514 if (send_stream) {
515 send_stream->OnEncoderConfigurationChanged(
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200516 std::move(streams), is_svc, content_type, min_transmit_bitrate_bps);
Mirko Bonadei80a86872019-02-04 15:01:43 +0100517 }
518 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200519 return;
520 }
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200521
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200522 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
523 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200524 RTC_DCHECK_RUN_ON(worker_queue_);
525
Elad Alon80f53b72019-10-11 16:19:43 +0200526 const VideoCodecType codec_type =
527 PayloadStringToCodecType(config_->rtp.payload_name);
528
529 const absl::optional<DataRate> experimental_min_bitrate =
530 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200531 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200532 experimental_min_bitrate
533 ? experimental_min_bitrate->bps()
534 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
535
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200536 encoder_max_bitrate_bps_ = 0;
537 double stream_bitrate_priority_sum = 0;
538 for (const auto& stream : streams) {
539 // We don't want to allocate more bitrate than needed to inactive streams.
540 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
541 if (stream.bitrate_priority) {
542 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
543 stream_bitrate_priority_sum += *stream.bitrate_priority;
544 }
545 }
546 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
547 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
548 encoder_max_bitrate_bps_ =
549 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
550 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500551
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100552 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +0200553 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
554 streams, is_svc, content_type, min_transmit_bitrate_bps,
555 config_->suspend_below_min_bitrate, has_alr_probing_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200556
557 // Clear stats for disabled layers.
558 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
559 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
560 }
561
562 const size_t num_temporal_layers =
563 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200564
565 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
566 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200567
Stefan Holmer9416ef82018-07-19 10:34:38 +0200568 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200569 // The send stream is started already. Update the allocator with new bitrate
570 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100571 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200572 }
573}
574
575EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
576 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +0200577 const CodecSpecificInfo* codec_specific_info) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200578 // Encoded is called on whatever thread the real encoder implementation run
579 // on. In the case of hardware encoders, there might be several encoders
580 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100581
582 // Indicate that there still is activity going on.
583 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200584
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200585 auto enable_padding_task = [this]() {
586 if (disable_padding_) {
587 RTC_DCHECK_RUN_ON(worker_queue_);
588 disable_padding_ = false;
589 // To ensure that padding bitrate is propagated to the bitrate allocator.
590 SignalEncoderActive();
591 }
592 };
593 if (!worker_queue_->IsCurrent()) {
594 worker_queue_->PostTask(enable_padding_task);
595 } else {
596 enable_padding_task();
597 }
598
Niels Möller46879152019-01-07 15:54:47 +0100599 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200600 result =
601 rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
Erik Språng4e193e42018-09-14 19:01:58 +0200602 // Check if there's a throttled VideoBitrateAllocation that we should try
603 // sending.
604 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
605 auto update_task = [send_stream]() {
606 if (send_stream) {
607 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
608 auto& context = send_stream->video_bitrate_allocation_context_;
609 if (context && context->throttled_allocation) {
610 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
611 }
612 }
613 };
614 if (!worker_queue_->IsCurrent()) {
615 worker_queue_->PostTask(update_task);
616 } else {
617 update_task();
618 }
619
620 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200621}
622
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100623void VideoSendStreamImpl::OnDroppedFrame(
624 EncodedImageCallback::DropReason reason) {
625 activity_ = true;
626}
627
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200628std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200629 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200630}
631
632std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
633 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200634 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200635}
636
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200637uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200638 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200639 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200640 << "VideoSendStream::Start has not been called.";
641
Florent Castellia8336d32019-09-09 13:36:55 +0200642 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
643 // unstable one instead.
644 if (update.stable_target_bitrate.IsZero()) {
645 update.stable_target_bitrate = update.target_bitrate;
646 }
647
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200648 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200649 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100650 const uint32_t protection_bitrate_bps =
651 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200652 DataRate link_allocation = DataRate::Zero();
653 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
654 link_allocation =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100655 DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100656 }
Florent Castellia8336d32019-09-09 13:36:55 +0200657 DataRate overhead =
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100658 update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200659 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
660 if (encoder_stable_target_rate > overhead) {
661 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
662 } else {
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100663 encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Florent Castellia8336d32019-09-09 13:36:55 +0200664 }
665
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200666 encoder_target_rate_bps_ =
667 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200668
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100669 encoder_stable_target_rate =
670 std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
671 encoder_stable_target_rate);
Florent Castellia8336d32019-09-09 13:36:55 +0200672
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100673 DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200674 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100675 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200676 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100677 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
Ying Wang9b881ab2020-02-07 14:29:32 +0100678 update.round_trip_time.ms(), update.cwnd_reduce_ratio);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200679 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100680 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200681}
682
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200683} // namespace internal
684} // namespace webrtc