blob: 97f3bb7f4cce9246d0761279e4440b3d47f6569f [file] [log] [blame]
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +02001/*
2 * Copyright 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10#include "video/video_send_stream_impl.h"
11
Yves Gerey3e707812018-11-28 16:47:49 +010012#include <stdio.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020013
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020014#include <algorithm>
Yves Gerey3e707812018-11-28 16:47:49 +010015#include <cstdint>
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020016#include <string>
17#include <utility>
18
Steve Antonbd631a02019-03-28 10:51:27 -070019#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080020#include "api/crypto/crypto_options.h"
21#include "api/rtp_parameters.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010022#include "api/scoped_refptr.h"
Yves Gerey3e707812018-11-28 16:47:49 +010023#include "api/video_codecs/video_codec.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020024#include "call/rtp_transport_controller_send_interface.h"
Yves Gerey3e707812018-11-28 16:47:49 +010025#include "call/video_send_stream.h"
Yves Gerey3e707812018-11-28 16:47:49 +010026#include "modules/pacing/paced_sender.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/atomic_ops.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020028#include "rtc_base/checks.h"
29#include "rtc_base/experiments/alr_experiment.h"
Ying Wang8c5520c2019-09-03 15:25:21 +000030#include "rtc_base/experiments/field_trial_parser.h"
Elad Alon80f53b72019-10-11 16:19:43 +020031#include "rtc_base/experiments/min_video_bitrate_experiment.h"
Erik Språngcd76eab2019-01-21 18:06:46 +010032#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020033#include "rtc_base/logging.h"
34#include "rtc_base/numerics/safe_conversions.h"
Sebastian Janssonb55015e2019-04-09 13:44:04 +020035#include "rtc_base/synchronization/sequence_checker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010036#include "rtc_base/thread_checker.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020037#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010038#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020039#include "system_wrappers/include/field_trial.h"
40
41namespace webrtc {
42namespace internal {
43namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020044
Erik Språng4e193e42018-09-14 19:01:58 +020045// Max positive size difference to treat allocations as "similar".
46static constexpr int kMaxVbaSizeDifferencePercent = 10;
47// Max time we will throttle similar video bitrate allocations.
48static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
49
Sebastian Janssonecb68972019-01-18 10:30:54 +010050constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds<2>();
51
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020052bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
53 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070054 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
55 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
56 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020057}
58
Erik Språngb57ab382018-09-13 10:52:38 +020059// Calculate max padding bitrate for a multi layer codec.
60int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010061 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020062 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020063 bool pad_to_min_bitrate,
64 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020065 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020066
67 // Filter out only the active streams;
68 std::vector<VideoStream> active_streams;
69 for (const VideoStream& stream : streams) {
70 if (stream.active)
71 active_streams.emplace_back(stream);
72 }
73
74 if (active_streams.size() > 1) {
75 if (alr_probing) {
76 // With alr probing, just pad to the min bitrate of the lowest stream,
77 // probing will handle the rest of the rampup.
78 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
79 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010080 // Without alr probing, pad up to start bitrate of the
81 // highest active stream.
82 const double hysteresis_factor =
83 RateControlSettings::ParseFromFieldTrials()
84 .GetSimulcastHysteresisFactor(content_type);
85 const size_t top_active_stream_idx = active_streams.size() - 1;
86 pad_up_to_bitrate_bps = std::min(
87 static_cast<int>(
88 hysteresis_factor *
89 active_streams[top_active_stream_idx].min_bitrate_bps +
90 0.5),
91 active_streams[top_active_stream_idx].target_bitrate_bps);
92
93 // Add target_bitrate_bps of the lower active streams.
94 for (size_t i = 0; i < top_active_stream_idx; ++i) {
Erik Språngb57ab382018-09-13 10:52:38 +020095 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
Rasmus Brandtc402dbe2019-02-04 11:09:46 +010096 }
Erik Språngb57ab382018-09-13 10:52:38 +020097 }
98 } else if (!active_streams.empty() && pad_to_min_bitrate) {
99 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200100 }
101
102 pad_up_to_bitrate_bps =
103 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
104
105 return pad_up_to_bitrate_bps;
106}
107
Benjamin Wright192eeec2018-10-17 17:27:25 -0700108RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
109 const VideoSendStream::Config* config) {
110 RtpSenderFrameEncryptionConfig frame_encryption_config;
111 frame_encryption_config.frame_encryptor = config->frame_encryptor;
112 frame_encryption_config.crypto_options = config->crypto_options;
113 return frame_encryption_config;
114}
115
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200116RtpSenderObservers CreateObservers(CallStats* call_stats,
Elad Alon14d1c9d2019-04-08 14:16:17 +0200117 EncoderRtcpFeedback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200118 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200119 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200120 RtpSenderObservers observers;
121 observers.rtcp_rtt_stats = call_stats;
122 observers.intra_frame_callback = encoder_feedback;
Elad Alon0a8562e2019-04-09 11:55:13 +0200123 observers.rtcp_loss_notification_observer = encoder_feedback;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200124 observers.rtcp_stats = stats_proxy;
Henrik Boström87e3f9d2019-05-27 10:44:24 +0200125 observers.report_block_data_observer = stats_proxy;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200126 observers.rtp_stats = stats_proxy;
127 observers.bitrate_observer = stats_proxy;
128 observers.frame_count_observer = stats_proxy;
129 observers.rtcp_type_observer = stats_proxy;
130 observers.send_delay_observer = stats_proxy;
131 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200132 return observers;
133}
Erik Språngb57ab382018-09-13 10:52:38 +0200134
135absl::optional<AlrExperimentSettings> GetAlrSettings(
136 VideoEncoderConfig::ContentType content_type) {
137 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
138 return AlrExperimentSettings::CreateFromFieldTrial(
139 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
140 }
141 return AlrExperimentSettings::CreateFromFieldTrial(
142 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
143}
Erik Språng4e193e42018-09-14 19:01:58 +0200144
145bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
146 const VideoBitrateAllocation& rhs) {
147 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
148 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
149 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
150 return false;
151 }
152 }
153 }
154 return true;
155}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200156} // namespace
157
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100158PacingConfig::PacingConfig()
159 : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
160 max_pacing_delay("max_delay",
161 TimeDelta::ms(PacedSender::kMaxQueueLengthMs)) {
162 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
163 field_trial::FindFullName("WebRTC-Video-Pacing"));
164}
165PacingConfig::PacingConfig(const PacingConfig&) = default;
166PacingConfig::~PacingConfig() = default;
167
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200168VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100169 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200170 SendStatisticsProxy* stats_proxy,
171 rtc::TaskQueue* worker_queue,
172 CallStats* call_stats,
173 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200174 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200175 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200176 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200177 RtcEventLog* event_log,
178 const VideoSendStream::Config* config,
179 int initial_encoder_max_bitrate,
180 double initial_encoder_bitrate_priority,
181 std::map<uint32_t, RtpState> suspended_ssrcs,
182 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
183 VideoEncoderConfig::ContentType content_type,
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800184 std::unique_ptr<FecController> fec_controller)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100185 : clock_(clock),
186 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200187 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100188 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200189 stats_proxy_(stats_proxy),
190 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200191 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100192 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200193 call_stats_(call_stats),
194 transport_(transport),
195 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200196 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200197 max_padding_bitrate_(0),
198 encoder_min_bitrate_bps_(0),
199 encoder_target_rate_bps_(0),
200 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
201 has_packet_feedback_(false),
202 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100203 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200204 bandwidth_observer_(transport->GetBandwidthObserver()),
Benjamin Wright192eeec2018-10-17 17:27:25 -0700205 rtp_video_sender_(transport_->CreateRtpVideoSender(
Benjamin Wright192eeec2018-10-17 17:27:25 -0700206 suspended_ssrcs,
207 suspended_payload_states,
208 config_->rtp,
Jiawei Ou55718122018-11-09 13:17:39 -0800209 config_->rtcp_report_interval_ms,
Benjamin Wright192eeec2018-10-17 17:27:25 -0700210 config_->send_transport,
211 CreateObservers(call_stats,
212 &encoder_feedback_,
213 stats_proxy_,
214 send_delay_stats),
215 event_log,
216 std::move(fec_controller),
217 CreateFrameEncryptionConfig(config_))),
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800218 weak_ptr_factory_(this) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200219 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200220 RTC_DCHECK_RUN_ON(worker_queue_);
221 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
222 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200223
Elad Alonb6ef99b2019-04-10 16:37:07 +0200224 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
225
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800226 RTC_DCHECK(!config_->rtp.ssrcs.empty());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200227 RTC_DCHECK(call_stats_);
228 RTC_DCHECK(transport_);
229 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
230
231 if (initial_encoder_max_bitrate > 0) {
232 encoder_max_bitrate_bps_ =
233 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
234 } else {
235 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
236 // have any way to handle unset values in downstream code, such as the
237 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
238 // behaviour that is not safe. Converting to 10 Mbps should be safe for
239 // reasonable use cases as it allows adding the max of multiple streams
240 // without wrappping around.
241 const int kFallbackMaxBitrateBps = 10000000;
242 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
243 << initial_encoder_max_bitrate << " which is <= 0!";
244 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
245 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
246 }
247
248 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
249 // If send-side BWE is enabled, check if we should apply updated probing and
250 // pacing settings.
251 if (TransportSeqNumExtensionConfigured(*config_)) {
252 has_packet_feedback_ = true;
253
Erik Språngb57ab382018-09-13 10:52:38 +0200254 absl::optional<AlrExperimentSettings> alr_settings =
255 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200256 if (alr_settings) {
257 transport->EnablePeriodicAlrProbing(true);
258 transport->SetPacingFactor(alr_settings->pacing_factor);
259 configured_pacing_factor_ = alr_settings->pacing_factor;
260 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
261 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100262 RateControlSettings rate_control_settings =
263 RateControlSettings::ParseFromFieldTrials();
264
265 transport->EnablePeriodicAlrProbing(
266 rate_control_settings.UseAlrProbing());
267 const double pacing_factor =
268 rate_control_settings.GetPacingFactor().value_or(
269 pacing_config_.pacing_factor);
270 transport->SetPacingFactor(pacing_factor);
271 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100272 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200273 }
274 }
275
276 if (config_->periodic_alr_bandwidth_probing) {
277 transport->EnablePeriodicAlrProbing(true);
278 }
279
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200280 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
281 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
282
283 video_stream_encoder_->SetStartBitrate(
284 bitrate_allocator_->GetStartBitrate(this));
285
286 // Only request rotation at the source when we positively know that the remote
287 // side doesn't support the rotation extension. This allows us to prepare the
288 // encoder in the expectation that rotation is supported - which is the common
289 // case.
Steve Antonbd631a02019-03-28 10:51:27 -0700290 bool rotation_applied = absl::c_none_of(
291 config_->rtp.extensions, [](const RtpExtension& extension) {
292 return extension.uri == RtpExtension::kVideoRotationUri;
293 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200294
295 video_stream_encoder_->SetSink(this, rotation_applied);
296}
297
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200298VideoSendStreamImpl::~VideoSendStreamImpl() {
299 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200300 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200301 << "VideoSendStreamImpl::Stop not called";
302 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200303 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200304}
305
306void VideoSendStreamImpl::RegisterProcessThread(
307 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200308 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200309}
310
311void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200312 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200313}
314
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100315void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200316 // Runs on a network thread.
317 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200318 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200319}
320
321void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
322 const std::vector<bool> active_layers) {
323 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200324 RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200325 bool previously_active = rtp_video_sender_->IsActive();
326 rtp_video_sender_->SetActiveModules(active_layers);
327 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200328 // Payload router switched from active to inactive.
329 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200330 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200331 // Payload router switched from inactive to active.
332 StartupVideoSendStream();
333 }
334}
335
336void VideoSendStreamImpl::Start() {
337 RTC_DCHECK_RUN_ON(worker_queue_);
338 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200339 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200340 return;
341 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200342 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200343 StartupVideoSendStream();
344}
345
346void VideoSendStreamImpl::StartupVideoSendStream() {
347 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100348 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200349 // Start monitoring encoder activity.
350 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100351 RTC_DCHECK(!check_encoder_activity_task_.Running());
352
353 activity_ = false;
354 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100355 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
356 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100357 RTC_DCHECK_RUN_ON(worker_queue_);
358 if (!activity_) {
359 if (!timed_out_) {
360 SignalEncoderTimedOut();
361 }
362 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200363 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100364 } else if (timed_out_) {
365 SignalEncoderActive();
366 timed_out_ = false;
367 }
368 activity_ = false;
369 return kEncoderTimeOut;
370 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200371 }
372
373 video_stream_encoder_->SendKeyFrame();
374}
375
376void VideoSendStreamImpl::Stop() {
377 RTC_DCHECK_RUN_ON(worker_queue_);
378 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
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::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200382 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200383 StopVideoSendStream();
384}
385
386void VideoSendStreamImpl::StopVideoSendStream() {
387 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100388 check_encoder_activity_task_.Stop();
Florent Castellia8336d32019-09-09 13:36:55 +0200389 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
390 DataRate::Zero(), 0, 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200391 stats_proxy_->OnSetEncoderTargetRate(0);
392}
393
394void VideoSendStreamImpl::SignalEncoderTimedOut() {
395 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100396 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200397 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
398 // if a camera stops producing frames.
399 if (encoder_target_rate_bps_ > 0) {
400 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
401 bitrate_allocator_->RemoveObserver(this);
402 }
403}
404
405void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200406 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200407 if (!worker_queue_->IsCurrent()) {
408 auto ptr = weak_ptr_;
409 worker_queue_->PostTask([=] {
410 if (!ptr.get())
411 return;
412 ptr->OnBitrateAllocationUpdated(allocation);
413 });
414 return;
415 }
416
417 RTC_DCHECK_RUN_ON(worker_queue_);
418
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100419 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200420 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200421 if (video_bitrate_allocation_context_) {
422 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
423 // the previously sent allocation and the same streams are still enabled,
424 // it is considered "similar". We do not want send similar allocations
425 // more once per kMaxVbaThrottleTimeMs.
426 const VideoBitrateAllocation& last =
427 video_bitrate_allocation_context_->last_sent_allocation;
428 const bool is_similar =
429 allocation.get_sum_bps() >= last.get_sum_bps() &&
430 allocation.get_sum_bps() <
431 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
432 100 &&
433 SameStreamsEnabled(allocation, last);
434 if (is_similar &&
435 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
436 kMaxVbaThrottleTimeMs) {
437 // This allocation is too similar, cache it and return.
438 video_bitrate_allocation_context_->throttled_allocation = allocation;
439 return;
440 }
441 } else {
442 video_bitrate_allocation_context_.emplace();
443 }
444
445 video_bitrate_allocation_context_->last_sent_allocation = allocation;
446 video_bitrate_allocation_context_->throttled_allocation.reset();
447 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
448
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200449 // Send bitrate allocation metadata only if encoder is not paused.
450 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
451 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200452}
453
454void VideoSendStreamImpl::SignalEncoderActive() {
455 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200456 if (rtp_video_sender_->IsActive()) {
457 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
458 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
459 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100460}
461
462MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
463 return MediaStreamAllocationConfig{
464 static_cast<uint32_t>(encoder_min_bitrate_bps_),
465 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200466 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100467 /* priority_bitrate */ 0,
468 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100469 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200470}
471
472void VideoSendStreamImpl::OnEncoderConfigurationChanged(
473 std::vector<VideoStream> streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100474 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200475 int min_transmit_bitrate_bps) {
476 if (!worker_queue_->IsCurrent()) {
477 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Mirko Bonadei80a86872019-02-04 15:01:43 +0100478 worker_queue_->PostTask([send_stream, streams, content_type,
479 min_transmit_bitrate_bps]() mutable {
480 if (send_stream) {
481 send_stream->OnEncoderConfigurationChanged(
482 std::move(streams), content_type, min_transmit_bitrate_bps);
483 }
484 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200485 return;
486 }
487 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
488 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
489 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
490 RTC_DCHECK_RUN_ON(worker_queue_);
491
Elad Alon80f53b72019-10-11 16:19:43 +0200492 const VideoCodecType codec_type =
493 PayloadStringToCodecType(config_->rtp.payload_name);
494
495 const absl::optional<DataRate> experimental_min_bitrate =
496 GetExperimentalMinVideoBitrate(codec_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200497 encoder_min_bitrate_bps_ =
Elad Alonc67a4d62019-10-11 16:54:18 +0200498 experimental_min_bitrate
499 ? experimental_min_bitrate->bps()
500 : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
501
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200502 encoder_max_bitrate_bps_ = 0;
503 double stream_bitrate_priority_sum = 0;
504 for (const auto& stream : streams) {
505 // We don't want to allocate more bitrate than needed to inactive streams.
506 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
507 if (stream.bitrate_priority) {
508 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
509 stream_bitrate_priority_sum += *stream.bitrate_priority;
510 }
511 }
512 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
513 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
514 encoder_max_bitrate_bps_ =
515 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
516 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500517
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100518 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
“Michael277a6562018-06-01 14:09:19 -0500519 if (codec_type == kVideoCodecVP9) {
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100520 max_padding_bitrate_ = has_alr_probing_ ? streams[0].min_bitrate_bps
521 : streams[0].target_bitrate_bps;
“Michael277a6562018-06-01 14:09:19 -0500522 } else {
523 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100524 streams, content_type, min_transmit_bitrate_bps,
525 config_->suspend_below_min_bitrate, has_alr_probing_);
“Michael277a6562018-06-01 14:09:19 -0500526 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200527
528 // Clear stats for disabled layers.
529 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
530 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
531 }
532
533 const size_t num_temporal_layers =
534 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200535
536 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
537 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200538
Stefan Holmer9416ef82018-07-19 10:34:38 +0200539 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200540 // The send stream is started already. Update the allocator with new bitrate
541 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100542 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200543 }
544}
545
546EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
547 const EncodedImage& encoded_image,
548 const CodecSpecificInfo* codec_specific_info,
549 const RTPFragmentationHeader* fragmentation) {
550 // Encoded is called on whatever thread the real encoder implementation run
551 // on. In the case of hardware encoders, there might be several encoders
552 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100553
554 // Indicate that there still is activity going on.
555 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200556
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200557 auto enable_padding_task = [this]() {
558 if (disable_padding_) {
559 RTC_DCHECK_RUN_ON(worker_queue_);
560 disable_padding_ = false;
561 // To ensure that padding bitrate is propagated to the bitrate allocator.
562 SignalEncoderActive();
563 }
564 };
565 if (!worker_queue_->IsCurrent()) {
566 worker_queue_->PostTask(enable_padding_task);
567 } else {
568 enable_padding_task();
569 }
570
Niels Möller46879152019-01-07 15:54:47 +0100571 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800572 result = rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info,
573 fragmentation);
Erik Språng4e193e42018-09-14 19:01:58 +0200574 // Check if there's a throttled VideoBitrateAllocation that we should try
575 // sending.
576 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
577 auto update_task = [send_stream]() {
578 if (send_stream) {
579 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
580 auto& context = send_stream->video_bitrate_allocation_context_;
581 if (context && context->throttled_allocation) {
582 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
583 }
584 }
585 };
586 if (!worker_queue_->IsCurrent()) {
587 worker_queue_->PostTask(update_task);
588 } else {
589 update_task();
590 }
591
592 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200593}
594
Jakob Ivarsson159b4172019-10-30 14:02:14 +0100595void VideoSendStreamImpl::OnDroppedFrame(
596 EncodedImageCallback::DropReason reason) {
597 activity_ = true;
598}
599
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200600std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200601 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200602}
603
604std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
605 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200606 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200607}
608
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200609uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200610 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200611 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200612 << "VideoSendStream::Start has not been called.";
613
Florent Castellia8336d32019-09-09 13:36:55 +0200614 // When the BWE algorithm doesn't pass a stable estimate, we'll use the
615 // unstable one instead.
616 if (update.stable_target_bitrate.IsZero()) {
617 update.stable_target_bitrate = update.target_bitrate;
618 }
619
Sebastian Jansson82ed2e82019-10-15 15:58:37 +0200620 rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200621 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100622 const uint32_t protection_bitrate_bps =
623 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200624 DataRate link_allocation = DataRate::Zero();
625 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
626 link_allocation =
627 DataRate::bps(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100628 }
Florent Castellia8336d32019-09-09 13:36:55 +0200629 DataRate overhead =
630 update.target_bitrate - DataRate::bps(encoder_target_rate_bps_);
631 DataRate encoder_stable_target_rate = update.stable_target_bitrate;
632 if (encoder_stable_target_rate > overhead) {
633 encoder_stable_target_rate = encoder_stable_target_rate - overhead;
634 } else {
635 encoder_stable_target_rate = DataRate::bps(encoder_target_rate_bps_);
636 }
637
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200638 encoder_target_rate_bps_ =
639 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200640
Florent Castellia8336d32019-09-09 13:36:55 +0200641 encoder_stable_target_rate = std::min(DataRate::bps(encoder_max_bitrate_bps_),
642 encoder_stable_target_rate);
643
Erik Språng4c6ca302019-04-08 15:14:01 +0200644 DataRate encoder_target_rate = DataRate::bps(encoder_target_rate_bps_);
645 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100646 video_stream_encoder_->OnBitrateUpdated(
Florent Castellia8336d32019-09-09 13:36:55 +0200647 encoder_target_rate, encoder_stable_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100648 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
649 update.round_trip_time.ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200650 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100651 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200652}
653
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200654} // namespace internal
655} // namespace webrtc