blob: 266d27fc0a99e720a7ba76fa45b656d6dfb1da5e [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 Anton10542f22019-01-11 09:11:00 -080018#include "api/crypto/crypto_options.h"
19#include "api/rtp_parameters.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010020#include "api/scoped_refptr.h"
Yves Gerey3e707812018-11-28 16:47:49 +010021#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020022#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 16:47:49 +010023#include "call/video_send_stream.h"
24#include "common_types.h" // NOLINT(build/include)
25#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"
Yves Gerey3e707812018-11-28 16:47:49 +010032#include "rtc_base/sequenced_task_checker.h"
33#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/time_utils.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020035#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010036#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020037#include "system_wrappers/include/field_trial.h"
38
39namespace webrtc {
40namespace internal {
41namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020042
Erik Språng4e193e42018-09-14 19:01:58 +020043// 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 10:30:54 +010048constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds<2>();
49
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020050bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
51 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
52 return std::find_if(
53 extensions.begin(), extensions.end(), [](const RtpExtension& ext) {
54 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
55 }) != extensions.end();
56}
57
58const char kForcedFallbackFieldTrial[] =
59 "WebRTC-VP8-Forced-Fallback-Encoder-v2";
60
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020061absl::optional<int> GetFallbackMinBpsFromFieldTrial() {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020062 if (!webrtc::field_trial::IsEnabled(kForcedFallbackFieldTrial))
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020063 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020064
65 std::string group =
66 webrtc::field_trial::FindFullName(kForcedFallbackFieldTrial);
67 if (group.empty())
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020068 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020069
70 int min_pixels;
71 int max_pixels;
72 int min_bps;
73 if (sscanf(group.c_str(), "Enabled-%d,%d,%d", &min_pixels, &max_pixels,
74 &min_bps) != 3) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020075 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020076 }
77
78 if (min_bps <= 0)
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020079 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020080
81 return min_bps;
82}
83
84int GetEncoderMinBitrateBps() {
85 const int kDefaultEncoderMinBitrateBps = 30000;
86 return GetFallbackMinBpsFromFieldTrial().value_or(
87 kDefaultEncoderMinBitrateBps);
88}
89
Erik Språngb57ab382018-09-13 10:52:38 +020090// Calculate max padding bitrate for a multi layer codec.
91int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010092 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020093 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020094 bool pad_to_min_bitrate,
95 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020096 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020097
98 // Filter out only the active streams;
99 std::vector<VideoStream> active_streams;
100 for (const VideoStream& stream : streams) {
101 if (stream.active)
102 active_streams.emplace_back(stream);
103 }
104
105 if (active_streams.size() > 1) {
106 if (alr_probing) {
107 // With alr probing, just pad to the min bitrate of the lowest stream,
108 // probing will handle the rest of the rampup.
109 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
110 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100111 // Without alr probing, pad up to start bitrate of the
112 // highest active stream.
113 const double hysteresis_factor =
114 RateControlSettings::ParseFromFieldTrials()
115 .GetSimulcastHysteresisFactor(content_type);
116 const size_t top_active_stream_idx = active_streams.size() - 1;
117 pad_up_to_bitrate_bps = std::min(
118 static_cast<int>(
119 hysteresis_factor *
120 active_streams[top_active_stream_idx].min_bitrate_bps +
121 0.5),
122 active_streams[top_active_stream_idx].target_bitrate_bps);
123
124 // Add target_bitrate_bps of the lower active streams.
125 for (size_t i = 0; i < top_active_stream_idx; ++i) {
Erik Språngb57ab382018-09-13 10:52:38 +0200126 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100127 }
Erik Språngb57ab382018-09-13 10:52:38 +0200128 }
129 } else if (!active_streams.empty() && pad_to_min_bitrate) {
130 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200131 }
132
133 pad_up_to_bitrate_bps =
134 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
135
136 return pad_up_to_bitrate_bps;
137}
138
Benjamin Wright192eeec2018-10-17 17:27:25 -0700139RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
140 const VideoSendStream::Config* config) {
141 RtpSenderFrameEncryptionConfig frame_encryption_config;
142 frame_encryption_config.frame_encryptor = config->frame_encryptor;
143 frame_encryption_config.crypto_options = config->crypto_options;
144 return frame_encryption_config;
145}
146
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200147RtpSenderObservers CreateObservers(CallStats* call_stats,
Niels Möllerfa89d842019-01-30 16:33:45 +0100148 EncoderKeyFrameCallback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200149 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200150 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200151 RtpSenderObservers observers;
152 observers.rtcp_rtt_stats = call_stats;
153 observers.intra_frame_callback = encoder_feedback;
154 observers.rtcp_stats = stats_proxy;
155 observers.rtp_stats = stats_proxy;
156 observers.bitrate_observer = stats_proxy;
157 observers.frame_count_observer = stats_proxy;
158 observers.rtcp_type_observer = stats_proxy;
159 observers.send_delay_observer = stats_proxy;
160 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200161 return observers;
162}
Erik Språngb57ab382018-09-13 10:52:38 +0200163
164absl::optional<AlrExperimentSettings> GetAlrSettings(
165 VideoEncoderConfig::ContentType content_type) {
166 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
167 return AlrExperimentSettings::CreateFromFieldTrial(
168 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
169 }
170 return AlrExperimentSettings::CreateFromFieldTrial(
171 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
172}
Erik Språng4e193e42018-09-14 19:01:58 +0200173
174bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
175 const VideoBitrateAllocation& rhs) {
176 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
177 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
178 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
179 return false;
180 }
181 }
182 }
183 return true;
184}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200185} // namespace
186
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100187PacingConfig::PacingConfig()
188 : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
189 max_pacing_delay("max_delay",
190 TimeDelta::ms(PacedSender::kMaxQueueLengthMs)) {
191 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
192 field_trial::FindFullName("WebRTC-Video-Pacing"));
193}
194PacingConfig::PacingConfig(const PacingConfig&) = default;
195PacingConfig::~PacingConfig() = default;
196
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200197VideoSendStreamImpl::VideoSendStreamImpl(
198 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)
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200214 : has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200215 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100216 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200217 stats_proxy_(stats_proxy),
218 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200219 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100220 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200221 call_stats_(call_stats),
222 transport_(transport),
223 bitrate_allocator_(bitrate_allocator),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200224 max_padding_bitrate_(0),
225 encoder_min_bitrate_bps_(0),
226 encoder_target_rate_bps_(0),
227 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
228 has_packet_feedback_(false),
229 video_stream_encoder_(video_stream_encoder),
230 encoder_feedback_(Clock::GetRealTimeClock(),
231 config_->rtp.ssrcs,
232 video_stream_encoder),
233 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
Niels Möller46879152019-01-07 15:54:47 +0100253 if (media_transport_) {
254 // The configured ssrc is interpreted as a channel id, so there must be
255 // exactly one.
256 RTC_DCHECK_EQ(config_->rtp.ssrcs.size(), 1);
Niels Möllerfa89d842019-01-30 16:33:45 +0100257 media_transport_->SetKeyFrameRequestCallback(&encoder_feedback_);
Niels Möller46879152019-01-07 15:54:47 +0100258 } else {
259 RTC_DCHECK(!config_->rtp.ssrcs.empty());
260 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200261 RTC_DCHECK(call_stats_);
262 RTC_DCHECK(transport_);
263 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
264
265 if (initial_encoder_max_bitrate > 0) {
266 encoder_max_bitrate_bps_ =
267 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
268 } else {
269 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
270 // have any way to handle unset values in downstream code, such as the
271 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
272 // behaviour that is not safe. Converting to 10 Mbps should be safe for
273 // reasonable use cases as it allows adding the max of multiple streams
274 // without wrappping around.
275 const int kFallbackMaxBitrateBps = 10000000;
276 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
277 << initial_encoder_max_bitrate << " which is <= 0!";
278 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
279 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
280 }
281
282 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
283 // If send-side BWE is enabled, check if we should apply updated probing and
284 // pacing settings.
285 if (TransportSeqNumExtensionConfigured(*config_)) {
286 has_packet_feedback_ = true;
287
Erik Språngb57ab382018-09-13 10:52:38 +0200288 absl::optional<AlrExperimentSettings> alr_settings =
289 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200290 if (alr_settings) {
291 transport->EnablePeriodicAlrProbing(true);
292 transport->SetPacingFactor(alr_settings->pacing_factor);
293 configured_pacing_factor_ = alr_settings->pacing_factor;
294 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
295 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100296 RateControlSettings rate_control_settings =
297 RateControlSettings::ParseFromFieldTrials();
298
299 transport->EnablePeriodicAlrProbing(
300 rate_control_settings.UseAlrProbing());
301 const double pacing_factor =
302 rate_control_settings.GetPacingFactor().value_or(
303 pacing_config_.pacing_factor);
304 transport->SetPacingFactor(pacing_factor);
305 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100306 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200307 }
308 }
309
310 if (config_->periodic_alr_bandwidth_probing) {
311 transport->EnablePeriodicAlrProbing(true);
312 }
313
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200314 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
315 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
316
317 video_stream_encoder_->SetStartBitrate(
318 bitrate_allocator_->GetStartBitrate(this));
319
320 // Only request rotation at the source when we positively know that the remote
321 // side doesn't support the rotation extension. This allows us to prepare the
322 // encoder in the expectation that rotation is supported - which is the common
323 // case.
324 bool rotation_applied =
325 std::find_if(config_->rtp.extensions.begin(),
326 config_->rtp.extensions.end(),
327 [](const RtpExtension& extension) {
328 return extension.uri == RtpExtension::kVideoRotationUri;
329 }) == config_->rtp.extensions.end();
330
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
354bool VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
355 // 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 return true;
359}
360
361void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
362 const std::vector<bool> active_layers) {
363 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200364 RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200365 bool previously_active = rtp_video_sender_->IsActive();
366 rtp_video_sender_->SetActiveModules(active_layers);
367 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200368 // Payload router switched from active to inactive.
369 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200370 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200371 // Payload router switched from inactive to active.
372 StartupVideoSendStream();
373 }
374}
375
376void VideoSendStreamImpl::Start() {
377 RTC_DCHECK_RUN_ON(worker_queue_);
378 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200379 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200380 return;
381 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200382 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200383 StartupVideoSendStream();
384}
385
386void VideoSendStreamImpl::StartupVideoSendStream() {
387 RTC_DCHECK_RUN_ON(worker_queue_);
388 bitrate_allocator_->AddObserver(
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200389 this,
390 MediaStreamAllocationConfig{
391 static_cast<uint32_t>(encoder_min_bitrate_bps_),
392 encoder_max_bitrate_bps_, static_cast<uint32_t>(max_padding_bitrate_),
393 !config_->suspend_below_min_bitrate, config_->track_id,
Sebastian Jansson79f0d4d2019-01-23 09:41:43 +0100394 encoder_bitrate_priority_});
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200395 // Start monitoring encoder activity.
396 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100397 RTC_DCHECK(!check_encoder_activity_task_.Running());
398
399 activity_ = false;
400 timed_out_ = false;
401 check_encoder_activity_task_ =
402 RepeatingTaskHandle::DelayedStart(kEncoderTimeOut, [this] {
403 RTC_DCHECK_RUN_ON(worker_queue_);
404 if (!activity_) {
405 if (!timed_out_) {
406 SignalEncoderTimedOut();
407 }
408 timed_out_ = true;
409 } else if (timed_out_) {
410 SignalEncoderActive();
411 timed_out_ = false;
412 }
413 activity_ = false;
414 return kEncoderTimeOut;
415 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200416 }
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 10:34:38 +0200424 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200425 return;
426 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200427 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200428 StopVideoSendStream();
429}
430
431void VideoSendStreamImpl::StopVideoSendStream() {
432 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100433 check_encoder_activity_task_.Stop();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200434 video_stream_encoder_->OnBitrateUpdated(0, 0, 0);
435 stats_proxy_->OnSetEncoderTargetRate(0);
436}
437
438void VideoSendStreamImpl::SignalEncoderTimedOut() {
439 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100440 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200441 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
442 // if a camera stops producing frames.
443 if (encoder_target_rate_bps_ > 0) {
444 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
445 bitrate_allocator_->RemoveObserver(this);
446 }
447}
448
449void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200450 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200451 if (!worker_queue_->IsCurrent()) {
452 auto ptr = weak_ptr_;
453 worker_queue_->PostTask([=] {
454 if (!ptr.get())
455 return;
456 ptr->OnBitrateAllocationUpdated(allocation);
457 });
458 return;
459 }
460
461 RTC_DCHECK_RUN_ON(worker_queue_);
462
463 int64_t now_ms = rtc::TimeMillis();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200464 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200465 if (video_bitrate_allocation_context_) {
466 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
467 // the previously sent allocation and the same streams are still enabled,
468 // it is considered "similar". We do not want send similar allocations
469 // more once per kMaxVbaThrottleTimeMs.
470 const VideoBitrateAllocation& last =
471 video_bitrate_allocation_context_->last_sent_allocation;
472 const bool is_similar =
473 allocation.get_sum_bps() >= last.get_sum_bps() &&
474 allocation.get_sum_bps() <
475 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
476 100 &&
477 SameStreamsEnabled(allocation, last);
478 if (is_similar &&
479 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
480 kMaxVbaThrottleTimeMs) {
481 // This allocation is too similar, cache it and return.
482 video_bitrate_allocation_context_->throttled_allocation = allocation;
483 return;
484 }
485 } else {
486 video_bitrate_allocation_context_.emplace();
487 }
488
489 video_bitrate_allocation_context_->last_sent_allocation = allocation;
490 video_bitrate_allocation_context_->throttled_allocation.reset();
491 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
492
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200493 // Send bitrate allocation metadata only if encoder is not paused.
494 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
495 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200496}
497
498void VideoSendStreamImpl::SignalEncoderActive() {
499 RTC_DCHECK_RUN_ON(worker_queue_);
500 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
501 bitrate_allocator_->AddObserver(
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200502 this,
503 MediaStreamAllocationConfig{
504 static_cast<uint32_t>(encoder_min_bitrate_bps_),
505 encoder_max_bitrate_bps_, static_cast<uint32_t>(max_padding_bitrate_),
506 !config_->suspend_below_min_bitrate, config_->track_id,
Sebastian Jansson79f0d4d2019-01-23 09:41:43 +0100507 encoder_bitrate_priority_});
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200508}
509
510void VideoSendStreamImpl::OnEncoderConfigurationChanged(
511 std::vector<VideoStream> streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100512 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200513 int min_transmit_bitrate_bps) {
514 if (!worker_queue_->IsCurrent()) {
515 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100516 worker_queue_->PostTask(
517 [send_stream, streams, content_type, min_transmit_bitrate_bps]() {
518 if (send_stream) {
519 send_stream->OnEncoderConfigurationChanged(
520 std::move(streams), content_type, min_transmit_bitrate_bps);
521 }
522 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200523 return;
524 }
525 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
526 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
527 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
528 RTC_DCHECK_RUN_ON(worker_queue_);
529
530 encoder_min_bitrate_bps_ =
531 std::max(streams[0].min_bitrate_bps, GetEncoderMinBitrateBps());
532 encoder_max_bitrate_bps_ = 0;
533 double stream_bitrate_priority_sum = 0;
534 for (const auto& stream : streams) {
535 // We don't want to allocate more bitrate than needed to inactive streams.
536 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
537 if (stream.bitrate_priority) {
538 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
539 stream_bitrate_priority_sum += *stream.bitrate_priority;
540 }
541 }
542 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
543 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
544 encoder_max_bitrate_bps_ =
545 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
546 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500547
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100548 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
“Michael277a6562018-06-01 14:09:19 -0500549 const VideoCodecType codec_type =
550 PayloadStringToCodecType(config_->rtp.payload_name);
551 if (codec_type == kVideoCodecVP9) {
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100552 max_padding_bitrate_ = has_alr_probing_ ? streams[0].min_bitrate_bps
553 : streams[0].target_bitrate_bps;
“Michael277a6562018-06-01 14:09:19 -0500554 } else {
555 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100556 streams, content_type, min_transmit_bitrate_bps,
557 config_->suspend_below_min_bitrate, has_alr_probing_);
“Michael277a6562018-06-01 14:09:19 -0500558 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200559
560 // Clear stats for disabled layers.
561 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
562 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
563 }
564
565 const size_t num_temporal_layers =
566 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200567
568 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
569 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200570
Stefan Holmer9416ef82018-07-19 10:34:38 +0200571 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200572 // The send stream is started already. Update the allocator with new bitrate
573 // limits.
574 bitrate_allocator_->AddObserver(
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200575 this, MediaStreamAllocationConfig{
576 static_cast<uint32_t>(encoder_min_bitrate_bps_),
577 encoder_max_bitrate_bps_,
578 static_cast<uint32_t>(max_padding_bitrate_),
579 !config_->suspend_below_min_bitrate, config_->track_id,
Sebastian Jansson79f0d4d2019-01-23 09:41:43 +0100580 encoder_bitrate_priority_});
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200581 }
582}
583
584EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
585 const EncodedImage& encoded_image,
586 const CodecSpecificInfo* codec_specific_info,
587 const RTPFragmentationHeader* fragmentation) {
588 // Encoded is called on whatever thread the real encoder implementation run
589 // on. In the case of hardware encoders, there might be several encoders
590 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100591
592 // Indicate that there still is activity going on.
593 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200594
Niels Möller46879152019-01-07 15:54:47 +0100595 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
596 if (media_transport_) {
597 int64_t frame_id;
598 {
599 // TODO(nisse): Responsibility for allocation of frame ids should move to
600 // VideoStreamEncoder.
601 rtc::CritScope cs(&media_transport_id_lock_);
602 frame_id = media_transport_frame_id_++;
603 }
604 // TODO(nisse): Responsibility for reference meta data should be moved
605 // upstream, ideally close to the encoders, but probably VideoStreamEncoder
606 // will need to do some translation to produce reference info using frame
607 // ids.
608 std::vector<int64_t> referenced_frame_ids;
609 if (encoded_image._frameType != kVideoFrameKey) {
610 RTC_DCHECK_GT(frame_id, 0);
611 referenced_frame_ids.push_back(frame_id - 1);
612 }
613 media_transport_->SendVideoFrame(
614 config_->rtp.ssrcs[0], webrtc::MediaTransportEncodedVideoFrame(
615 frame_id, referenced_frame_ids,
616 config_->rtp.payload_type, encoded_image));
617 } else {
618 result = rtp_video_sender_->OnEncodedImage(
619 encoded_image, codec_specific_info, fragmentation);
620 }
Erik Språng4e193e42018-09-14 19:01:58 +0200621 // Check if there's a throttled VideoBitrateAllocation that we should try
622 // sending.
623 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
624 auto update_task = [send_stream]() {
625 if (send_stream) {
626 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
627 auto& context = send_stream->video_bitrate_allocation_context_;
628 if (context && context->throttled_allocation) {
629 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
630 }
631 }
632 };
633 if (!worker_queue_->IsCurrent()) {
634 worker_queue_->PostTask(update_task);
635 } else {
636 update_task();
637 }
638
639 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200640}
641
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200642std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200643 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200644}
645
646std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
647 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200648 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200649}
650
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200651uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200652 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200653 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200654 << "VideoSendStream::Start has not been called.";
655
Sebastian Jansson13e59032018-11-21 19:13:07 +0100656 rtp_video_sender_->OnBitrateUpdated(
657 update.target_bitrate.bps(),
658 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
659 update.round_trip_time.ms(), stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200660 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200661 encoder_target_rate_bps_ =
662 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100663 video_stream_encoder_->OnBitrateUpdated(
664 encoder_target_rate_bps_,
665 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
666 update.round_trip_time.ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200667 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200668 return rtp_video_sender_->GetProtectionBitrateBps();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200669}
670
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200671} // namespace internal
672} // namespace webrtc