blob: 50bbb1f9785afae90f778d7218dee8f37fdbb0e3 [file] [log] [blame]
Sebastian Jansson8e0b15b2018-04-18 17:19:221/*
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 15:47:4912#include <stdio.h>
Jonas Olssona4d87372019-07-05 17:08:3313
Sebastian Jansson8e0b15b2018-04-18 17:19:2214#include <algorithm>
Yves Gerey3e707812018-11-28 15:47:4915#include <cstdint>
Sebastian Jansson8e0b15b2018-04-18 17:19:2216#include <string>
17#include <utility>
18
Steve Antonbd631a02019-03-28 17:51:2719#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 17:11:0020#include "api/crypto/crypto_options.h"
21#include "api/rtp_parameters.h"
Mirko Bonadeid9708072019-01-25 19:26:4822#include "api/scoped_refptr.h"
Yves Gerey3e707812018-11-28 15:47:4923#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 17:19:2224#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 15:47:4925#include "call/video_send_stream.h"
Yves Gerey3e707812018-11-28 15:47:4926#include "modules/pacing/paced_sender.h"
Steve Anton10542f22019-01-11 17:11:0027#include "rtc_base/atomic_ops.h"
Sebastian Jansson8e0b15b2018-04-18 17:19:2228#include "rtc_base/checks.h"
29#include "rtc_base/experiments/alr_experiment.h"
Erik Språngcd76eab2019-01-21 17:06:4630#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 17:19:2231#include "rtc_base/logging.h"
32#include "rtc_base/numerics/safe_conversions.h"
Sebastian Janssonb55015e2019-04-09 11:44:0433#include "rtc_base/synchronization/sequence_checker.h"
Yves Gerey3e707812018-11-28 15:47:4934#include "rtc_base/thread_checker.h"
Sebastian Jansson8e0b15b2018-04-18 17:19:2235#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 15:47:4936#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 17:19:2237#include "system_wrappers/include/field_trial.h"
38
39namespace webrtc {
40namespace internal {
41namespace {
Sebastian Jansson8e0b15b2018-04-18 17:19:2242
Erik Språng4e193e42018-09-14 17:01:5843// Max positive size difference to treat allocations as "similar".
44static constexpr int kMaxVbaSizeDifferencePercent = 10;
45// Max time we will throttle similar video bitrate allocations.
46static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
47
Sebastian Janssonecb68972019-01-18 09:30:5448constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds<2>();
49
Sebastian Jansson8e0b15b2018-04-18 17:19:2250bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
51 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 17:51:2752 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
53 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
54 });
Sebastian Jansson8e0b15b2018-04-18 17:19:2255}
56
57const char kForcedFallbackFieldTrial[] =
58 "WebRTC-VP8-Forced-Fallback-Encoder-v2";
59
Åsa Persson59830872019-06-28 15:01:0860absl::optional<int> GetFallbackMinBpsFromFieldTrial(VideoCodecType type) {
61 if (type != kVideoCodecVP8)
62 return absl::nullopt;
63
Sebastian Jansson8e0b15b2018-04-18 17:19:2264 if (!webrtc::field_trial::IsEnabled(kForcedFallbackFieldTrial))
Danil Chapovalovb9b146c2018-06-15 10:28:0765 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 17:19:2266
67 std::string group =
68 webrtc::field_trial::FindFullName(kForcedFallbackFieldTrial);
69 if (group.empty())
Danil Chapovalovb9b146c2018-06-15 10:28:0770 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 17:19:2271
72 int min_pixels;
73 int max_pixels;
74 int min_bps;
75 if (sscanf(group.c_str(), "Enabled-%d,%d,%d", &min_pixels, &max_pixels,
76 &min_bps) != 3) {
Danil Chapovalovb9b146c2018-06-15 10:28:0777 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 17:19:2278 }
79
80 if (min_bps <= 0)
Danil Chapovalovb9b146c2018-06-15 10:28:0781 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 17:19:2282
83 return min_bps;
84}
85
Åsa Persson59830872019-06-28 15:01:0886int GetEncoderMinBitrateBps(VideoCodecType type) {
Alessio Bazzica1d2149c2019-09-03 15:12:1487 const int kDefaultEncoderMinBitrateBps = 30000;
88 return GetFallbackMinBpsFromFieldTrial(type).value_or(
89 kDefaultEncoderMinBitrateBps);
Sebastian Jansson8e0b15b2018-04-18 17:19:2290}
91
Erik Språngb57ab382018-09-13 08:52:3892// Calculate max padding bitrate for a multi layer codec.
93int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Rasmus Brandtc402dbe2019-02-04 10:09:4694 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 17:19:2295 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 08:52:3896 bool pad_to_min_bitrate,
97 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 17:19:2298 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 08:52:3899
100 // Filter out only the active streams;
101 std::vector<VideoStream> active_streams;
102 for (const VideoStream& stream : streams) {
103 if (stream.active)
104 active_streams.emplace_back(stream);
105 }
106
107 if (active_streams.size() > 1) {
108 if (alr_probing) {
109 // With alr probing, just pad to the min bitrate of the lowest stream,
110 // probing will handle the rest of the rampup.
111 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
112 } else {
Rasmus Brandtc402dbe2019-02-04 10:09:46113 // Without alr probing, pad up to start bitrate of the
114 // highest active stream.
115 const double hysteresis_factor =
116 RateControlSettings::ParseFromFieldTrials()
117 .GetSimulcastHysteresisFactor(content_type);
118 const size_t top_active_stream_idx = active_streams.size() - 1;
119 pad_up_to_bitrate_bps = std::min(
120 static_cast<int>(
121 hysteresis_factor *
122 active_streams[top_active_stream_idx].min_bitrate_bps +
123 0.5),
124 active_streams[top_active_stream_idx].target_bitrate_bps);
125
126 // Add target_bitrate_bps of the lower active streams.
127 for (size_t i = 0; i < top_active_stream_idx; ++i) {
Erik Språngb57ab382018-09-13 08:52:38128 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
Rasmus Brandtc402dbe2019-02-04 10:09:46129 }
Erik Språngb57ab382018-09-13 08:52:38130 }
131 } else if (!active_streams.empty() && pad_to_min_bitrate) {
132 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 17:19:22133 }
134
135 pad_up_to_bitrate_bps =
136 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
137
138 return pad_up_to_bitrate_bps;
139}
140
Benjamin Wright192eeec2018-10-18 00:27:25141RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
142 const VideoSendStream::Config* config) {
143 RtpSenderFrameEncryptionConfig frame_encryption_config;
144 frame_encryption_config.frame_encryptor = config->frame_encryptor;
145 frame_encryption_config.crypto_options = config->crypto_options;
146 return frame_encryption_config;
147}
148
Stefan Holmerdbdb3a02018-07-17 14:03:46149RtpSenderObservers CreateObservers(CallStats* call_stats,
Elad Alon14d1c9d2019-04-08 12:16:17150 EncoderRtcpFeedback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 14:03:46151 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 13:21:55152 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 14:03:46153 RtpSenderObservers observers;
154 observers.rtcp_rtt_stats = call_stats;
155 observers.intra_frame_callback = encoder_feedback;
Elad Alon0a8562e2019-04-09 09:55:13156 observers.rtcp_loss_notification_observer = encoder_feedback;
Stefan Holmerdbdb3a02018-07-17 14:03:46157 observers.rtcp_stats = stats_proxy;
Henrik Boström87e3f9d2019-05-27 08:44:24158 observers.report_block_data_observer = stats_proxy;
Stefan Holmerdbdb3a02018-07-17 14:03:46159 observers.rtp_stats = stats_proxy;
160 observers.bitrate_observer = stats_proxy;
161 observers.frame_count_observer = stats_proxy;
162 observers.rtcp_type_observer = stats_proxy;
163 observers.send_delay_observer = stats_proxy;
164 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 14:03:46165 return observers;
166}
Erik Språngb57ab382018-09-13 08:52:38167
168absl::optional<AlrExperimentSettings> GetAlrSettings(
169 VideoEncoderConfig::ContentType content_type) {
170 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
171 return AlrExperimentSettings::CreateFromFieldTrial(
172 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
173 }
174 return AlrExperimentSettings::CreateFromFieldTrial(
175 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
176}
Erik Språng4e193e42018-09-14 17:01:58177
178bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
179 const VideoBitrateAllocation& rhs) {
180 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
181 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
182 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
183 return false;
184 }
185 }
186 }
187 return true;
188}
Sebastian Jansson8e0b15b2018-04-18 17:19:22189} // namespace
190
Christoffer Rodbro196c5ba2018-11-27 10:56:25191PacingConfig::PacingConfig()
192 : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
193 max_pacing_delay("max_delay",
194 TimeDelta::ms(PacedSender::kMaxQueueLengthMs)) {
195 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
196 field_trial::FindFullName("WebRTC-Video-Pacing"));
197}
198PacingConfig::PacingConfig(const PacingConfig&) = default;
199PacingConfig::~PacingConfig() = default;
200
Sebastian Jansson8e0b15b2018-04-18 17:19:22201VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 17:30:41202 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 17:19:22203 SendStatisticsProxy* stats_proxy,
204 rtc::TaskQueue* worker_queue,
205 CallStats* call_stats,
206 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 15:09:15207 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 17:19:22208 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 15:09:15209 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 17:19:22210 RtcEventLog* event_log,
211 const VideoSendStream::Config* config,
212 int initial_encoder_max_bitrate,
213 double initial_encoder_bitrate_priority,
214 std::map<uint32_t, RtpState> suspended_ssrcs,
215 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
216 VideoEncoderConfig::ContentType content_type,
Niels Möller46879152019-01-07 14:54:47217 std::unique_ptr<FecController> fec_controller,
218 MediaTransportInterface* media_transport)
Sebastian Jansson572c60f2019-03-04 17:30:41219 : clock_(clock),
220 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 08:52:38221 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 10:56:25222 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 17:19:22223 stats_proxy_(stats_proxy),
224 config_(config),
Sebastian Jansson8e0b15b2018-04-18 17:19:22225 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 17:06:46226 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 17:19:22227 call_stats_(call_stats),
228 transport_(transport),
229 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 07:20:24230 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 17:19:22231 max_padding_bitrate_(0),
232 encoder_min_bitrate_bps_(0),
233 encoder_target_rate_bps_(0),
234 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
235 has_packet_feedback_(false),
236 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson572c60f2019-03-04 17:30:41237 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 17:19:22238 bandwidth_observer_(transport->GetBandwidthObserver()),
Benjamin Wright192eeec2018-10-18 00:27:25239 rtp_video_sender_(transport_->CreateRtpVideoSender(
Benjamin Wright192eeec2018-10-18 00:27:25240 suspended_ssrcs,
241 suspended_payload_states,
242 config_->rtp,
Jiawei Ou55718122018-11-09 21:17:39243 config_->rtcp_report_interval_ms,
Benjamin Wright192eeec2018-10-18 00:27:25244 config_->send_transport,
245 CreateObservers(call_stats,
246 &encoder_feedback_,
247 stats_proxy_,
248 send_delay_stats),
249 event_log,
250 std::move(fec_controller),
251 CreateFrameEncryptionConfig(config_))),
Niels Möller46879152019-01-07 14:54:47252 weak_ptr_factory_(this),
253 media_transport_(media_transport) {
Elad Alon8f01c4e2019-06-28 13:19:43254 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 17:19:22255 RTC_DCHECK_RUN_ON(worker_queue_);
256 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
257 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 17:19:22258
Elad Alonb6ef99b2019-04-10 14:37:07259 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
260
Niels Möller46879152019-01-07 14:54:47261 if (media_transport_) {
262 // The configured ssrc is interpreted as a channel id, so there must be
263 // exactly one.
264 RTC_DCHECK_EQ(config_->rtp.ssrcs.size(), 1);
Niels Möllerfa89d842019-01-30 15:33:45265 media_transport_->SetKeyFrameRequestCallback(&encoder_feedback_);
Niels Möller46879152019-01-07 14:54:47266 } else {
267 RTC_DCHECK(!config_->rtp.ssrcs.empty());
268 }
Sebastian Jansson8e0b15b2018-04-18 17:19:22269 RTC_DCHECK(call_stats_);
270 RTC_DCHECK(transport_);
271 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
272
273 if (initial_encoder_max_bitrate > 0) {
274 encoder_max_bitrate_bps_ =
275 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
276 } else {
277 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
278 // have any way to handle unset values in downstream code, such as the
279 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
280 // behaviour that is not safe. Converting to 10 Mbps should be safe for
281 // reasonable use cases as it allows adding the max of multiple streams
282 // without wrappping around.
283 const int kFallbackMaxBitrateBps = 10000000;
284 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
285 << initial_encoder_max_bitrate << " which is <= 0!";
286 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
287 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
288 }
289
290 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
291 // If send-side BWE is enabled, check if we should apply updated probing and
292 // pacing settings.
293 if (TransportSeqNumExtensionConfigured(*config_)) {
294 has_packet_feedback_ = true;
295
Erik Språngb57ab382018-09-13 08:52:38296 absl::optional<AlrExperimentSettings> alr_settings =
297 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 17:19:22298 if (alr_settings) {
299 transport->EnablePeriodicAlrProbing(true);
300 transport->SetPacingFactor(alr_settings->pacing_factor);
301 configured_pacing_factor_ = alr_settings->pacing_factor;
302 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
303 } else {
Erik Språngcd76eab2019-01-21 17:06:46304 RateControlSettings rate_control_settings =
305 RateControlSettings::ParseFromFieldTrials();
306
307 transport->EnablePeriodicAlrProbing(
308 rate_control_settings.UseAlrProbing());
309 const double pacing_factor =
310 rate_control_settings.GetPacingFactor().value_or(
311 pacing_config_.pacing_factor);
312 transport->SetPacingFactor(pacing_factor);
313 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 10:56:25314 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 17:19:22315 }
316 }
317
318 if (config_->periodic_alr_bandwidth_probing) {
319 transport->EnablePeriodicAlrProbing(true);
320 }
321
Sebastian Jansson8e0b15b2018-04-18 17:19:22322 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
323 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
324
325 video_stream_encoder_->SetStartBitrate(
326 bitrate_allocator_->GetStartBitrate(this));
327
328 // Only request rotation at the source when we positively know that the remote
329 // side doesn't support the rotation extension. This allows us to prepare the
330 // encoder in the expectation that rotation is supported - which is the common
331 // case.
Steve Antonbd631a02019-03-28 17:51:27332 bool rotation_applied = absl::c_none_of(
333 config_->rtp.extensions, [](const RtpExtension& extension) {
334 return extension.uri == RtpExtension::kVideoRotationUri;
335 });
Sebastian Jansson8e0b15b2018-04-18 17:19:22336
337 video_stream_encoder_->SetSink(this, rotation_applied);
338}
339
Sebastian Jansson8e0b15b2018-04-18 17:19:22340VideoSendStreamImpl::~VideoSendStreamImpl() {
341 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 08:34:38342 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 17:19:22343 << "VideoSendStreamImpl::Stop not called";
344 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 08:34:38345 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Niels Möllerfa89d842019-01-30 15:33:45346 if (media_transport_) {
347 media_transport_->SetKeyFrameRequestCallback(nullptr);
348 }
Stefan Holmerdbdb3a02018-07-17 14:03:46349}
350
351void VideoSendStreamImpl::RegisterProcessThread(
352 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 08:34:38353 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 14:03:46354}
355
356void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 08:34:38357 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 17:19:22358}
359
Niels Möller8fb1a6a2019-03-05 13:29:42360void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 17:19:22361 // Runs on a network thread.
362 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 08:34:38363 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 17:19:22364}
365
366void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
367 const std::vector<bool> active_layers) {
368 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8e0b15b2018-04-18 17:19:22369 RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
Stefan Holmer9416ef82018-07-19 08:34:38370 bool previously_active = rtp_video_sender_->IsActive();
371 rtp_video_sender_->SetActiveModules(active_layers);
372 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 17:19:22373 // Payload router switched from active to inactive.
374 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 08:34:38375 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 17:19:22376 // Payload router switched from inactive to active.
377 StartupVideoSendStream();
378 }
379}
380
381void VideoSendStreamImpl::Start() {
382 RTC_DCHECK_RUN_ON(worker_queue_);
383 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 08:34:38384 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 17:19:22385 return;
386 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 08:34:38387 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 17:19:22388 StartupVideoSendStream();
389}
390
391void VideoSendStreamImpl::StartupVideoSendStream() {
392 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 12:32:32393 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 17:19:22394 // Start monitoring encoder activity.
395 {
Sebastian Janssonecb68972019-01-18 09:30:54396 RTC_DCHECK(!check_encoder_activity_task_.Running());
397
398 activity_ = false;
399 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 16:26:36400 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
401 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 09:30:54402 RTC_DCHECK_RUN_ON(worker_queue_);
403 if (!activity_) {
404 if (!timed_out_) {
405 SignalEncoderTimedOut();
406 }
407 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 07:20:24408 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 09:30:54409 } else if (timed_out_) {
410 SignalEncoderActive();
411 timed_out_ = false;
412 }
413 activity_ = false;
414 return kEncoderTimeOut;
415 });
Sebastian Jansson8e0b15b2018-04-18 17:19:22416 }
417
418 video_stream_encoder_->SendKeyFrame();
419}
420
421void VideoSendStreamImpl::Stop() {
422 RTC_DCHECK_RUN_ON(worker_queue_);
423 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
Stefan Holmer9416ef82018-07-19 08:34:38424 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 17:19:22425 return;
426 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 08:34:38427 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 17:19:22428 StopVideoSendStream();
429}
430
431void VideoSendStreamImpl::StopVideoSendStream() {
432 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 09:30:54433 check_encoder_activity_task_.Stop();
Erik Språng610c7632019-03-06 14:37:33434 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), 0,
435 0);
Sebastian Jansson8e0b15b2018-04-18 17:19:22436 stats_proxy_->OnSetEncoderTargetRate(0);
437}
438
439void VideoSendStreamImpl::SignalEncoderTimedOut() {
440 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 09:30:54441 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 17:19:22442 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
443 // if a camera stops producing frames.
444 if (encoder_target_rate_bps_ > 0) {
445 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
446 bitrate_allocator_->RemoveObserver(this);
447 }
448}
449
450void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 10:32:22451 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 17:01:58452 if (!worker_queue_->IsCurrent()) {
453 auto ptr = weak_ptr_;
454 worker_queue_->PostTask([=] {
455 if (!ptr.get())
456 return;
457 ptr->OnBitrateAllocationUpdated(allocation);
458 });
459 return;
460 }
461
462 RTC_DCHECK_RUN_ON(worker_queue_);
463
Sebastian Jansson572c60f2019-03-04 17:30:41464 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 10:37:51465 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 17:01:58466 if (video_bitrate_allocation_context_) {
467 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
468 // the previously sent allocation and the same streams are still enabled,
469 // it is considered "similar". We do not want send similar allocations
470 // more once per kMaxVbaThrottleTimeMs.
471 const VideoBitrateAllocation& last =
472 video_bitrate_allocation_context_->last_sent_allocation;
473 const bool is_similar =
474 allocation.get_sum_bps() >= last.get_sum_bps() &&
475 allocation.get_sum_bps() <
476 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
477 100 &&
478 SameStreamsEnabled(allocation, last);
479 if (is_similar &&
480 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
481 kMaxVbaThrottleTimeMs) {
482 // This allocation is too similar, cache it and return.
483 video_bitrate_allocation_context_->throttled_allocation = allocation;
484 return;
485 }
486 } else {
487 video_bitrate_allocation_context_.emplace();
488 }
489
490 video_bitrate_allocation_context_->last_sent_allocation = allocation;
491 video_bitrate_allocation_context_->throttled_allocation.reset();
492 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
493
Erik Språngf4ef2dd2018-09-11 10:37:51494 // Send bitrate allocation metadata only if encoder is not paused.
495 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
496 }
Sebastian Jansson8e0b15b2018-04-18 17:19:22497}
498
499void VideoSendStreamImpl::SignalEncoderActive() {
500 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 07:20:24501 if (rtp_video_sender_->IsActive()) {
502 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
503 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
504 }
Sebastian Jansson464a5572019-02-12 12:32:32505}
506
507MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
508 return MediaStreamAllocationConfig{
509 static_cast<uint32_t>(encoder_min_bitrate_bps_),
510 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 07:20:24511 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 12:32:32512 /* priority_bitrate */ 0,
513 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 12:32:32514 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 17:19:22515}
516
517void VideoSendStreamImpl::OnEncoderConfigurationChanged(
518 std::vector<VideoStream> streams,
Rasmus Brandtc402dbe2019-02-04 10:09:46519 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 17:19:22520 int min_transmit_bitrate_bps) {
521 if (!worker_queue_->IsCurrent()) {
522 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Mirko Bonadei80a86872019-02-04 14:01:43523 worker_queue_->PostTask([send_stream, streams, content_type,
524 min_transmit_bitrate_bps]() mutable {
525 if (send_stream) {
526 send_stream->OnEncoderConfigurationChanged(
527 std::move(streams), content_type, min_transmit_bitrate_bps);
528 }
529 });
Sebastian Jansson8e0b15b2018-04-18 17:19:22530 return;
531 }
532 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
533 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
534 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
535 RTC_DCHECK_RUN_ON(worker_queue_);
536
537 encoder_min_bitrate_bps_ =
Åsa Persson59830872019-06-28 15:01:08538 std::max(streams[0].min_bitrate_bps,
539 GetEncoderMinBitrateBps(
540 PayloadStringToCodecType(config_->rtp.payload_name)));
Sebastian Jansson8e0b15b2018-04-18 17:19:22541 encoder_max_bitrate_bps_ = 0;
542 double stream_bitrate_priority_sum = 0;
543 for (const auto& stream : streams) {
544 // We don't want to allocate more bitrate than needed to inactive streams.
545 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
546 if (stream.bitrate_priority) {
547 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
548 stream_bitrate_priority_sum += *stream.bitrate_priority;
549 }
550 }
551 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
552 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
553 encoder_max_bitrate_bps_ =
554 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
555 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 19:09:19556
Rasmus Brandtc402dbe2019-02-04 10:09:46557 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
“Michael277a6562018-06-01 19:09:19558 const VideoCodecType codec_type =
559 PayloadStringToCodecType(config_->rtp.payload_name);
560 if (codec_type == kVideoCodecVP9) {
Sergey Silkin8b9b5f92018-12-10 08:28:53561 max_padding_bitrate_ = has_alr_probing_ ? streams[0].min_bitrate_bps
562 : streams[0].target_bitrate_bps;
“Michael277a6562018-06-01 19:09:19563 } else {
564 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
Rasmus Brandtc402dbe2019-02-04 10:09:46565 streams, content_type, min_transmit_bitrate_bps,
566 config_->suspend_below_min_bitrate, has_alr_probing_);
“Michael277a6562018-06-01 19:09:19567 }
Sebastian Jansson8e0b15b2018-04-18 17:19:22568
569 // Clear stats for disabled layers.
570 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
571 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
572 }
573
574 const size_t num_temporal_layers =
575 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 13:21:55576
577 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
578 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 17:19:22579
Stefan Holmer9416ef82018-07-19 08:34:38580 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 17:19:22581 // The send stream is started already. Update the allocator with new bitrate
582 // limits.
Sebastian Jansson464a5572019-02-12 12:32:32583 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 17:19:22584 }
585}
586
587EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
588 const EncodedImage& encoded_image,
589 const CodecSpecificInfo* codec_specific_info,
590 const RTPFragmentationHeader* fragmentation) {
591 // Encoded is called on whatever thread the real encoder implementation run
592 // on. In the case of hardware encoders, there might be several encoders
593 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 09:30:54594
595 // Indicate that there still is activity going on.
596 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 17:19:22597
Ilya Nikolaevskiyaa9aa572019-04-11 07:20:24598 auto enable_padding_task = [this]() {
599 if (disable_padding_) {
600 RTC_DCHECK_RUN_ON(worker_queue_);
601 disable_padding_ = false;
602 // To ensure that padding bitrate is propagated to the bitrate allocator.
603 SignalEncoderActive();
604 }
605 };
606 if (!worker_queue_->IsCurrent()) {
607 worker_queue_->PostTask(enable_padding_task);
608 } else {
609 enable_padding_task();
610 }
611
Niels Möller46879152019-01-07 14:54:47612 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
613 if (media_transport_) {
614 int64_t frame_id;
615 {
616 // TODO(nisse): Responsibility for allocation of frame ids should move to
617 // VideoStreamEncoder.
618 rtc::CritScope cs(&media_transport_id_lock_);
619 frame_id = media_transport_frame_id_++;
620 }
621 // TODO(nisse): Responsibility for reference meta data should be moved
622 // upstream, ideally close to the encoders, but probably VideoStreamEncoder
623 // will need to do some translation to produce reference info using frame
624 // ids.
625 std::vector<int64_t> referenced_frame_ids;
Niels Möller8f7ce222019-03-21 14:43:58626 if (encoded_image._frameType != VideoFrameType::kVideoFrameKey) {
Niels Möller46879152019-01-07 14:54:47627 RTC_DCHECK_GT(frame_id, 0);
628 referenced_frame_ids.push_back(frame_id - 1);
629 }
630 media_transport_->SendVideoFrame(
631 config_->rtp.ssrcs[0], webrtc::MediaTransportEncodedVideoFrame(
632 frame_id, referenced_frame_ids,
633 config_->rtp.payload_type, encoded_image));
634 } else {
635 result = rtp_video_sender_->OnEncodedImage(
636 encoded_image, codec_specific_info, fragmentation);
637 }
Erik Språng4e193e42018-09-14 17:01:58638 // Check if there's a throttled VideoBitrateAllocation that we should try
639 // sending.
640 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
641 auto update_task = [send_stream]() {
642 if (send_stream) {
643 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
644 auto& context = send_stream->video_bitrate_allocation_context_;
645 if (context && context->throttled_allocation) {
646 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
647 }
648 }
649 };
650 if (!worker_queue_->IsCurrent()) {
651 worker_queue_->PostTask(update_task);
652 } else {
653 update_task();
654 }
655
656 return result;
Sebastian Jansson8e0b15b2018-04-18 17:19:22657}
658
Sebastian Jansson8e0b15b2018-04-18 17:19:22659std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 08:34:38660 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 17:19:22661}
662
663std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
664 const {
Stefan Holmer9416ef82018-07-19 08:34:38665 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 17:19:22666}
667
Sebastian Janssonc0e4d452018-10-25 13:08:32668uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 17:19:22669 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 08:34:38670 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 17:19:22671 << "VideoSendStream::Start has not been called.";
672
Sebastian Jansson13e59032018-11-21 18:13:07673 rtp_video_sender_->OnBitrateUpdated(
674 update.target_bitrate.bps(),
675 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
676 update.round_trip_time.ms(), stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 13:21:55677 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 10:09:04678 const uint32_t protection_bitrate_bps =
679 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 13:14:01680 DataRate link_allocation = DataRate::Zero();
681 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
682 link_allocation =
683 DataRate::bps(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 14:37:33684 }
Sebastian Jansson8e0b15b2018-04-18 17:19:22685 encoder_target_rate_bps_ =
686 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 13:14:01687
688 DataRate encoder_target_rate = DataRate::bps(encoder_target_rate_bps_);
689 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 18:13:07690 video_stream_encoder_->OnBitrateUpdated(
Erik Språng4c6ca302019-04-08 13:14:01691 encoder_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 18:13:07692 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
693 update.round_trip_time.ms());
Sebastian Jansson8e0b15b2018-04-18 17:19:22694 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 10:09:04695 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 17:19:22696}
697
Sebastian Jansson8e0b15b2018-04-18 17:19:22698} // namespace internal
699} // namespace webrtc