blob: 0b3d08114b55a73bba15ad3e0a3985271424697b [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>
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020013#include <algorithm>
Yves Gerey3e707812018-11-28 16:47:49 +010014#include <cstdint>
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020015#include <string>
16#include <utility>
17
Steve Antonbd631a02019-03-28 10:51:27 -070018#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "api/crypto/crypto_options.h"
20#include "api/rtp_parameters.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010021#include "api/scoped_refptr.h"
Yves Gerey3e707812018-11-28 16:47:49 +010022#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020023#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 16:47:49 +010024#include "call/video_send_stream.h"
Yves Gerey3e707812018-11-28 16:47:49 +010025#include "modules/pacing/paced_sender.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/atomic_ops.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020027#include "rtc_base/checks.h"
28#include "rtc_base/experiments/alr_experiment.h"
Erik Språngcd76eab2019-01-21 18:06:46 +010029#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020030#include "rtc_base/logging.h"
31#include "rtc_base/numerics/safe_conversions.h"
Sebastian Janssonb55015e2019-04-09 13:44:04 +020032#include "rtc_base/synchronization/sequence_checker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010033#include "rtc_base/thread_checker.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020034#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010035#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020036#include "system_wrappers/include/field_trial.h"
37
38namespace webrtc {
39namespace internal {
40namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020041
Erik Språng4e193e42018-09-14 19:01:58 +020042// Max positive size difference to treat allocations as "similar".
43static constexpr int kMaxVbaSizeDifferencePercent = 10;
44// Max time we will throttle similar video bitrate allocations.
45static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
46
Sebastian Janssonecb68972019-01-18 10:30:54 +010047constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds<2>();
48
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020049bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
50 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070051 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
52 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
53 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020054}
55
56const char kForcedFallbackFieldTrial[] =
57 "WebRTC-VP8-Forced-Fallback-Encoder-v2";
58
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020059absl::optional<int> GetFallbackMinBpsFromFieldTrial() {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020060 if (!webrtc::field_trial::IsEnabled(kForcedFallbackFieldTrial))
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020061 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020062
63 std::string group =
64 webrtc::field_trial::FindFullName(kForcedFallbackFieldTrial);
65 if (group.empty())
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020066 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020067
68 int min_pixels;
69 int max_pixels;
70 int min_bps;
71 if (sscanf(group.c_str(), "Enabled-%d,%d,%d", &min_pixels, &max_pixels,
72 &min_bps) != 3) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020073 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020074 }
75
76 if (min_bps <= 0)
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020077 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020078
79 return min_bps;
80}
81
82int GetEncoderMinBitrateBps() {
83 const int kDefaultEncoderMinBitrateBps = 30000;
84 return GetFallbackMinBpsFromFieldTrial().value_or(
85 kDefaultEncoderMinBitrateBps);
86}
87
Erik Språngb57ab382018-09-13 10:52:38 +020088// Calculate max padding bitrate for a multi layer codec.
89int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010090 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020091 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020092 bool pad_to_min_bitrate,
93 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020094 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020095
96 // Filter out only the active streams;
97 std::vector<VideoStream> active_streams;
98 for (const VideoStream& stream : streams) {
99 if (stream.active)
100 active_streams.emplace_back(stream);
101 }
102
103 if (active_streams.size() > 1) {
104 if (alr_probing) {
105 // With alr probing, just pad to the min bitrate of the lowest stream,
106 // probing will handle the rest of the rampup.
107 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
108 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100109 // Without alr probing, pad up to start bitrate of the
110 // highest active stream.
111 const double hysteresis_factor =
112 RateControlSettings::ParseFromFieldTrials()
113 .GetSimulcastHysteresisFactor(content_type);
114 const size_t top_active_stream_idx = active_streams.size() - 1;
115 pad_up_to_bitrate_bps = std::min(
116 static_cast<int>(
117 hysteresis_factor *
118 active_streams[top_active_stream_idx].min_bitrate_bps +
119 0.5),
120 active_streams[top_active_stream_idx].target_bitrate_bps);
121
122 // Add target_bitrate_bps of the lower active streams.
123 for (size_t i = 0; i < top_active_stream_idx; ++i) {
Erik Språngb57ab382018-09-13 10:52:38 +0200124 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100125 }
Erik Språngb57ab382018-09-13 10:52:38 +0200126 }
127 } else if (!active_streams.empty() && pad_to_min_bitrate) {
128 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200129 }
130
131 pad_up_to_bitrate_bps =
132 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
133
134 return pad_up_to_bitrate_bps;
135}
136
Benjamin Wright192eeec2018-10-17 17:27:25 -0700137RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
138 const VideoSendStream::Config* config) {
139 RtpSenderFrameEncryptionConfig frame_encryption_config;
140 frame_encryption_config.frame_encryptor = config->frame_encryptor;
141 frame_encryption_config.crypto_options = config->crypto_options;
142 return frame_encryption_config;
143}
144
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200145RtpSenderObservers CreateObservers(CallStats* call_stats,
Elad Alon14d1c9d2019-04-08 14:16:17 +0200146 EncoderRtcpFeedback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200147 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200148 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200149 RtpSenderObservers observers;
150 observers.rtcp_rtt_stats = call_stats;
151 observers.intra_frame_callback = encoder_feedback;
Elad Alon0a8562e2019-04-09 11:55:13 +0200152 observers.rtcp_loss_notification_observer = encoder_feedback;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200153 observers.rtcp_stats = stats_proxy;
154 observers.rtp_stats = stats_proxy;
155 observers.bitrate_observer = stats_proxy;
156 observers.frame_count_observer = stats_proxy;
157 observers.rtcp_type_observer = stats_proxy;
158 observers.send_delay_observer = stats_proxy;
159 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200160 return observers;
161}
Erik Språngb57ab382018-09-13 10:52:38 +0200162
163absl::optional<AlrExperimentSettings> GetAlrSettings(
164 VideoEncoderConfig::ContentType content_type) {
165 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
166 return AlrExperimentSettings::CreateFromFieldTrial(
167 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
168 }
169 return AlrExperimentSettings::CreateFromFieldTrial(
170 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
171}
Erik Språng4e193e42018-09-14 19:01:58 +0200172
173bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
174 const VideoBitrateAllocation& rhs) {
175 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
176 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
177 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
178 return false;
179 }
180 }
181 }
182 return true;
183}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200184} // namespace
185
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100186PacingConfig::PacingConfig()
187 : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
188 max_pacing_delay("max_delay",
189 TimeDelta::ms(PacedSender::kMaxQueueLengthMs)) {
190 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
191 field_trial::FindFullName("WebRTC-Video-Pacing"));
192}
193PacingConfig::PacingConfig(const PacingConfig&) = default;
194PacingConfig::~PacingConfig() = default;
195
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200196VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100197 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200198 SendStatisticsProxy* stats_proxy,
199 rtc::TaskQueue* worker_queue,
200 CallStats* call_stats,
201 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200202 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200203 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200204 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200205 RtcEventLog* event_log,
206 const VideoSendStream::Config* config,
207 int initial_encoder_max_bitrate,
208 double initial_encoder_bitrate_priority,
209 std::map<uint32_t, RtpState> suspended_ssrcs,
210 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
211 VideoEncoderConfig::ContentType content_type,
Niels Möller46879152019-01-07 15:54:47 +0100212 std::unique_ptr<FecController> fec_controller,
213 MediaTransportInterface* media_transport)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100214 : clock_(clock),
215 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200216 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100217 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200218 stats_proxy_(stats_proxy),
219 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200220 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100221 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200222 call_stats_(call_stats),
223 transport_(transport),
224 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200225 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200226 max_padding_bitrate_(0),
227 encoder_min_bitrate_bps_(0),
228 encoder_target_rate_bps_(0),
229 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
230 has_packet_feedback_(false),
231 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100232 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200233 bandwidth_observer_(transport->GetBandwidthObserver()),
Benjamin Wright192eeec2018-10-17 17:27:25 -0700234 rtp_video_sender_(transport_->CreateRtpVideoSender(
Benjamin Wright192eeec2018-10-17 17:27:25 -0700235 suspended_ssrcs,
236 suspended_payload_states,
237 config_->rtp,
Jiawei Ou55718122018-11-09 13:17:39 -0800238 config_->rtcp_report_interval_ms,
Benjamin Wright192eeec2018-10-17 17:27:25 -0700239 config_->send_transport,
240 CreateObservers(call_stats,
241 &encoder_feedback_,
242 stats_proxy_,
243 send_delay_stats),
244 event_log,
245 std::move(fec_controller),
246 CreateFrameEncryptionConfig(config_))),
Niels Möller46879152019-01-07 15:54:47 +0100247 weak_ptr_factory_(this),
248 media_transport_(media_transport) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200249 RTC_DCHECK_RUN_ON(worker_queue_);
250 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
251 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200252
Elad Alonb6ef99b2019-04-10 16:37:07 +0200253 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
254
Niels Möller46879152019-01-07 15:54:47 +0100255 if (media_transport_) {
256 // The configured ssrc is interpreted as a channel id, so there must be
257 // exactly one.
258 RTC_DCHECK_EQ(config_->rtp.ssrcs.size(), 1);
Niels Möllerfa89d842019-01-30 16:33:45 +0100259 media_transport_->SetKeyFrameRequestCallback(&encoder_feedback_);
Niels Möller46879152019-01-07 15:54:47 +0100260 } else {
261 RTC_DCHECK(!config_->rtp.ssrcs.empty());
262 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200263 RTC_DCHECK(call_stats_);
264 RTC_DCHECK(transport_);
265 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
266
267 if (initial_encoder_max_bitrate > 0) {
268 encoder_max_bitrate_bps_ =
269 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
270 } else {
271 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
272 // have any way to handle unset values in downstream code, such as the
273 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
274 // behaviour that is not safe. Converting to 10 Mbps should be safe for
275 // reasonable use cases as it allows adding the max of multiple streams
276 // without wrappping around.
277 const int kFallbackMaxBitrateBps = 10000000;
278 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
279 << initial_encoder_max_bitrate << " which is <= 0!";
280 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
281 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
282 }
283
284 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
285 // If send-side BWE is enabled, check if we should apply updated probing and
286 // pacing settings.
287 if (TransportSeqNumExtensionConfigured(*config_)) {
288 has_packet_feedback_ = true;
289
Erik Språngb57ab382018-09-13 10:52:38 +0200290 absl::optional<AlrExperimentSettings> alr_settings =
291 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200292 if (alr_settings) {
293 transport->EnablePeriodicAlrProbing(true);
294 transport->SetPacingFactor(alr_settings->pacing_factor);
295 configured_pacing_factor_ = alr_settings->pacing_factor;
296 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
297 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100298 RateControlSettings rate_control_settings =
299 RateControlSettings::ParseFromFieldTrials();
300
301 transport->EnablePeriodicAlrProbing(
302 rate_control_settings.UseAlrProbing());
303 const double pacing_factor =
304 rate_control_settings.GetPacingFactor().value_or(
305 pacing_config_.pacing_factor);
306 transport->SetPacingFactor(pacing_factor);
307 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100308 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200309 }
310 }
311
312 if (config_->periodic_alr_bandwidth_probing) {
313 transport->EnablePeriodicAlrProbing(true);
314 }
315
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200316 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
317 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
318
319 video_stream_encoder_->SetStartBitrate(
320 bitrate_allocator_->GetStartBitrate(this));
321
322 // Only request rotation at the source when we positively know that the remote
323 // side doesn't support the rotation extension. This allows us to prepare the
324 // encoder in the expectation that rotation is supported - which is the common
325 // case.
Steve Antonbd631a02019-03-28 10:51:27 -0700326 bool rotation_applied = absl::c_none_of(
327 config_->rtp.extensions, [](const RtpExtension& extension) {
328 return extension.uri == RtpExtension::kVideoRotationUri;
329 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200330
331 video_stream_encoder_->SetSink(this, rotation_applied);
332}
333
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200334VideoSendStreamImpl::~VideoSendStreamImpl() {
335 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200336 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200337 << "VideoSendStreamImpl::Stop not called";
338 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200339 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Niels Möllerfa89d842019-01-30 16:33:45 +0100340 if (media_transport_) {
341 media_transport_->SetKeyFrameRequestCallback(nullptr);
342 }
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200343}
344
345void VideoSendStreamImpl::RegisterProcessThread(
346 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200347 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200348}
349
350void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200351 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200352}
353
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100354void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200355 // Runs on a network thread.
356 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200357 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200358}
359
360void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
361 const std::vector<bool> active_layers) {
362 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200363 RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200364 bool previously_active = rtp_video_sender_->IsActive();
365 rtp_video_sender_->SetActiveModules(active_layers);
366 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200367 // Payload router switched from active to inactive.
368 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200369 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200370 // Payload router switched from inactive to active.
371 StartupVideoSendStream();
372 }
373}
374
375void VideoSendStreamImpl::Start() {
376 RTC_DCHECK_RUN_ON(worker_queue_);
377 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200378 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200379 return;
380 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200381 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200382 StartupVideoSendStream();
383}
384
385void VideoSendStreamImpl::StartupVideoSendStream() {
386 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100387 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200388 // Start monitoring encoder activity.
389 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100390 RTC_DCHECK(!check_encoder_activity_task_.Running());
391
392 activity_ = false;
393 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100394 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
395 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100396 RTC_DCHECK_RUN_ON(worker_queue_);
397 if (!activity_) {
398 if (!timed_out_) {
399 SignalEncoderTimedOut();
400 }
401 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200402 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100403 } else if (timed_out_) {
404 SignalEncoderActive();
405 timed_out_ = false;
406 }
407 activity_ = false;
408 return kEncoderTimeOut;
409 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200410 }
411
412 video_stream_encoder_->SendKeyFrame();
413}
414
415void VideoSendStreamImpl::Stop() {
416 RTC_DCHECK_RUN_ON(worker_queue_);
417 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200418 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200419 return;
420 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200421 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200422 StopVideoSendStream();
423}
424
425void VideoSendStreamImpl::StopVideoSendStream() {
426 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100427 check_encoder_activity_task_.Stop();
Erik Språng610c7632019-03-06 15:37:33 +0100428 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), 0,
429 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200430 stats_proxy_->OnSetEncoderTargetRate(0);
431}
432
433void VideoSendStreamImpl::SignalEncoderTimedOut() {
434 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100435 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200436 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
437 // if a camera stops producing frames.
438 if (encoder_target_rate_bps_ > 0) {
439 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
440 bitrate_allocator_->RemoveObserver(this);
441 }
442}
443
444void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200445 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200446 if (!worker_queue_->IsCurrent()) {
447 auto ptr = weak_ptr_;
448 worker_queue_->PostTask([=] {
449 if (!ptr.get())
450 return;
451 ptr->OnBitrateAllocationUpdated(allocation);
452 });
453 return;
454 }
455
456 RTC_DCHECK_RUN_ON(worker_queue_);
457
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100458 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200459 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200460 if (video_bitrate_allocation_context_) {
461 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
462 // the previously sent allocation and the same streams are still enabled,
463 // it is considered "similar". We do not want send similar allocations
464 // more once per kMaxVbaThrottleTimeMs.
465 const VideoBitrateAllocation& last =
466 video_bitrate_allocation_context_->last_sent_allocation;
467 const bool is_similar =
468 allocation.get_sum_bps() >= last.get_sum_bps() &&
469 allocation.get_sum_bps() <
470 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
471 100 &&
472 SameStreamsEnabled(allocation, last);
473 if (is_similar &&
474 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
475 kMaxVbaThrottleTimeMs) {
476 // This allocation is too similar, cache it and return.
477 video_bitrate_allocation_context_->throttled_allocation = allocation;
478 return;
479 }
480 } else {
481 video_bitrate_allocation_context_.emplace();
482 }
483
484 video_bitrate_allocation_context_->last_sent_allocation = allocation;
485 video_bitrate_allocation_context_->throttled_allocation.reset();
486 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
487
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200488 // Send bitrate allocation metadata only if encoder is not paused.
489 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
490 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200491}
492
493void VideoSendStreamImpl::SignalEncoderActive() {
494 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200495 if (rtp_video_sender_->IsActive()) {
496 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
497 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
498 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100499}
500
501MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
502 return MediaStreamAllocationConfig{
503 static_cast<uint32_t>(encoder_min_bitrate_bps_),
504 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200505 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100506 /* priority_bitrate */ 0,
507 !config_->suspend_below_min_bitrate,
508 config_->track_id,
509 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200510}
511
512void VideoSendStreamImpl::OnEncoderConfigurationChanged(
513 std::vector<VideoStream> streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100514 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200515 int min_transmit_bitrate_bps) {
516 if (!worker_queue_->IsCurrent()) {
517 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Mirko Bonadei80a86872019-02-04 15:01:43 +0100518 worker_queue_->PostTask([send_stream, streams, content_type,
519 min_transmit_bitrate_bps]() mutable {
520 if (send_stream) {
521 send_stream->OnEncoderConfigurationChanged(
522 std::move(streams), content_type, min_transmit_bitrate_bps);
523 }
524 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200525 return;
526 }
527 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
528 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
529 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
530 RTC_DCHECK_RUN_ON(worker_queue_);
531
532 encoder_min_bitrate_bps_ =
533 std::max(streams[0].min_bitrate_bps, GetEncoderMinBitrateBps());
534 encoder_max_bitrate_bps_ = 0;
535 double stream_bitrate_priority_sum = 0;
536 for (const auto& stream : streams) {
537 // We don't want to allocate more bitrate than needed to inactive streams.
538 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
539 if (stream.bitrate_priority) {
540 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
541 stream_bitrate_priority_sum += *stream.bitrate_priority;
542 }
543 }
544 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
545 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
546 encoder_max_bitrate_bps_ =
547 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
548 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500549
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100550 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
“Michael277a6562018-06-01 14:09:19 -0500551 const VideoCodecType codec_type =
552 PayloadStringToCodecType(config_->rtp.payload_name);
553 if (codec_type == kVideoCodecVP9) {
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100554 max_padding_bitrate_ = has_alr_probing_ ? streams[0].min_bitrate_bps
555 : streams[0].target_bitrate_bps;
“Michael277a6562018-06-01 14:09:19 -0500556 } else {
557 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100558 streams, content_type, min_transmit_bitrate_bps,
559 config_->suspend_below_min_bitrate, has_alr_probing_);
“Michael277a6562018-06-01 14:09:19 -0500560 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200561
562 // Clear stats for disabled layers.
563 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
564 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
565 }
566
567 const size_t num_temporal_layers =
568 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200569
570 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
571 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200572
Stefan Holmer9416ef82018-07-19 10:34:38 +0200573 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200574 // The send stream is started already. Update the allocator with new bitrate
575 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100576 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200577 }
578}
579
580EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
581 const EncodedImage& encoded_image,
582 const CodecSpecificInfo* codec_specific_info,
583 const RTPFragmentationHeader* fragmentation) {
584 // Encoded is called on whatever thread the real encoder implementation run
585 // on. In the case of hardware encoders, there might be several encoders
586 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100587
588 // Indicate that there still is activity going on.
589 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200590
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200591 auto enable_padding_task = [this]() {
592 if (disable_padding_) {
593 RTC_DCHECK_RUN_ON(worker_queue_);
594 disable_padding_ = false;
595 // To ensure that padding bitrate is propagated to the bitrate allocator.
596 SignalEncoderActive();
597 }
598 };
599 if (!worker_queue_->IsCurrent()) {
600 worker_queue_->PostTask(enable_padding_task);
601 } else {
602 enable_padding_task();
603 }
604
Niels Möller46879152019-01-07 15:54:47 +0100605 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
606 if (media_transport_) {
607 int64_t frame_id;
608 {
609 // TODO(nisse): Responsibility for allocation of frame ids should move to
610 // VideoStreamEncoder.
611 rtc::CritScope cs(&media_transport_id_lock_);
612 frame_id = media_transport_frame_id_++;
613 }
614 // TODO(nisse): Responsibility for reference meta data should be moved
615 // upstream, ideally close to the encoders, but probably VideoStreamEncoder
616 // will need to do some translation to produce reference info using frame
617 // ids.
618 std::vector<int64_t> referenced_frame_ids;
Niels Möller8f7ce222019-03-21 15:43:58 +0100619 if (encoded_image._frameType != VideoFrameType::kVideoFrameKey) {
Niels Möller46879152019-01-07 15:54:47 +0100620 RTC_DCHECK_GT(frame_id, 0);
621 referenced_frame_ids.push_back(frame_id - 1);
622 }
623 media_transport_->SendVideoFrame(
624 config_->rtp.ssrcs[0], webrtc::MediaTransportEncodedVideoFrame(
625 frame_id, referenced_frame_ids,
626 config_->rtp.payload_type, encoded_image));
627 } else {
628 result = rtp_video_sender_->OnEncodedImage(
629 encoded_image, codec_specific_info, fragmentation);
630 }
Erik Språng4e193e42018-09-14 19:01:58 +0200631 // Check if there's a throttled VideoBitrateAllocation that we should try
632 // sending.
633 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
634 auto update_task = [send_stream]() {
635 if (send_stream) {
636 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
637 auto& context = send_stream->video_bitrate_allocation_context_;
638 if (context && context->throttled_allocation) {
639 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
640 }
641 }
642 };
643 if (!worker_queue_->IsCurrent()) {
644 worker_queue_->PostTask(update_task);
645 } else {
646 update_task();
647 }
648
649 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200650}
651
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200652std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200653 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200654}
655
656std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
657 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200658 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200659}
660
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200661uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200662 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200663 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200664 << "VideoSendStream::Start has not been called.";
665
Sebastian Jansson13e59032018-11-21 19:13:07 +0100666 rtp_video_sender_->OnBitrateUpdated(
667 update.target_bitrate.bps(),
668 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
669 update.round_trip_time.ms(), stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200670 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100671 const uint32_t protection_bitrate_bps =
672 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200673 DataRate link_allocation = DataRate::Zero();
674 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
675 link_allocation =
676 DataRate::bps(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100677 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200678 encoder_target_rate_bps_ =
679 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200680
681 DataRate encoder_target_rate = DataRate::bps(encoder_target_rate_bps_);
682 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100683 video_stream_encoder_->OnBitrateUpdated(
Erik Språng4c6ca302019-04-08 15:14:01 +0200684 encoder_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100685 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
686 update.round_trip_time.ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200687 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100688 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200689}
690
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200691} // namespace internal
692} // namespace webrtc