blob: 76caeecdca8d19379fb802dc2c8489127aa7627f [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"
Erik Språngcd76eab2019-01-21 18:06:46 +010031#include "rtc_base/experiments/rate_control_settings.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020032#include "rtc_base/logging.h"
33#include "rtc_base/numerics/safe_conversions.h"
Sebastian Janssonb55015e2019-04-09 13:44:04 +020034#include "rtc_base/synchronization/sequence_checker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010035#include "rtc_base/thread_checker.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020036#include "rtc_base/trace_event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010037#include "system_wrappers/include/clock.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020038#include "system_wrappers/include/field_trial.h"
39
40namespace webrtc {
41namespace internal {
42namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020043
Erik Språng4e193e42018-09-14 19:01:58 +020044// Max positive size difference to treat allocations as "similar".
45static constexpr int kMaxVbaSizeDifferencePercent = 10;
46// Max time we will throttle similar video bitrate allocations.
47static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
48
Sebastian Janssonecb68972019-01-18 10:30:54 +010049constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds<2>();
50
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020051bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
52 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
Steve Antonbd631a02019-03-28 10:51:27 -070053 return absl::c_any_of(extensions, [](const RtpExtension& ext) {
54 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
55 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020056}
57
58const char kForcedFallbackFieldTrial[] =
59 "WebRTC-VP8-Forced-Fallback-Encoder-v2";
60
Ying Wang8c5520c2019-09-03 15:25:21 +000061const int kDefaultEncoderMinBitrateBps = 30000;
62const char kMinVideoBitrateExperiment[] = "WebRTC-Video-MinVideoBitrate";
63
64struct MinVideoBitrateConfig {
65 webrtc::FieldTrialParameter<webrtc::DataRate> min_video_bitrate;
66
67 MinVideoBitrateConfig()
68 : min_video_bitrate("br",
69 webrtc::DataRate::bps(kDefaultEncoderMinBitrateBps)) {
70 webrtc::ParseFieldTrial(
71 {&min_video_bitrate},
72 webrtc::field_trial::FindFullName(kMinVideoBitrateExperiment));
73 }
74};
75
Åsa Persson59830872019-06-28 17:01:08 +020076absl::optional<int> GetFallbackMinBpsFromFieldTrial(VideoCodecType type) {
77 if (type != kVideoCodecVP8)
78 return absl::nullopt;
79
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020080 if (!webrtc::field_trial::IsEnabled(kForcedFallbackFieldTrial))
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020081 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020082
83 std::string group =
84 webrtc::field_trial::FindFullName(kForcedFallbackFieldTrial);
85 if (group.empty())
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020086 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020087
88 int min_pixels;
89 int max_pixels;
90 int min_bps;
91 if (sscanf(group.c_str(), "Enabled-%d,%d,%d", &min_pixels, &max_pixels,
92 &min_bps) != 3) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020093 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020094 }
95
96 if (min_bps <= 0)
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020097 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020098
99 return min_bps;
100}
101
Åsa Persson59830872019-06-28 17:01:08 +0200102int GetEncoderMinBitrateBps(VideoCodecType type) {
Ying Wang8c5520c2019-09-03 15:25:21 +0000103 if (GetFallbackMinBpsFromFieldTrial(type).has_value()) {
104 return GetFallbackMinBpsFromFieldTrial(type).value();
105 }
106 if (webrtc::field_trial::IsEnabled(kMinVideoBitrateExperiment)) {
107 return MinVideoBitrateConfig().min_video_bitrate->bps();
108 }
109 return kDefaultEncoderMinBitrateBps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200110}
111
Erik Språngb57ab382018-09-13 10:52:38 +0200112// Calculate max padding bitrate for a multi layer codec.
113int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100114 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200115 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +0200116 bool pad_to_min_bitrate,
117 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200118 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +0200119
120 // Filter out only the active streams;
121 std::vector<VideoStream> active_streams;
122 for (const VideoStream& stream : streams) {
123 if (stream.active)
124 active_streams.emplace_back(stream);
125 }
126
127 if (active_streams.size() > 1) {
128 if (alr_probing) {
129 // With alr probing, just pad to the min bitrate of the lowest stream,
130 // probing will handle the rest of the rampup.
131 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
132 } else {
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100133 // Without alr probing, pad up to start bitrate of the
134 // highest active stream.
135 const double hysteresis_factor =
136 RateControlSettings::ParseFromFieldTrials()
137 .GetSimulcastHysteresisFactor(content_type);
138 const size_t top_active_stream_idx = active_streams.size() - 1;
139 pad_up_to_bitrate_bps = std::min(
140 static_cast<int>(
141 hysteresis_factor *
142 active_streams[top_active_stream_idx].min_bitrate_bps +
143 0.5),
144 active_streams[top_active_stream_idx].target_bitrate_bps);
145
146 // Add target_bitrate_bps of the lower active streams.
147 for (size_t i = 0; i < top_active_stream_idx; ++i) {
Erik Språngb57ab382018-09-13 10:52:38 +0200148 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100149 }
Erik Språngb57ab382018-09-13 10:52:38 +0200150 }
151 } else if (!active_streams.empty() && pad_to_min_bitrate) {
152 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200153 }
154
155 pad_up_to_bitrate_bps =
156 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
157
158 return pad_up_to_bitrate_bps;
159}
160
Benjamin Wright192eeec2018-10-17 17:27:25 -0700161RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
162 const VideoSendStream::Config* config) {
163 RtpSenderFrameEncryptionConfig frame_encryption_config;
164 frame_encryption_config.frame_encryptor = config->frame_encryptor;
165 frame_encryption_config.crypto_options = config->crypto_options;
166 return frame_encryption_config;
167}
168
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200169RtpSenderObservers CreateObservers(CallStats* call_stats,
Elad Alon14d1c9d2019-04-08 14:16:17 +0200170 EncoderRtcpFeedback* encoder_feedback,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200171 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200172 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200173 RtpSenderObservers observers;
174 observers.rtcp_rtt_stats = call_stats;
175 observers.intra_frame_callback = encoder_feedback;
Elad Alon0a8562e2019-04-09 11:55:13 +0200176 observers.rtcp_loss_notification_observer = encoder_feedback;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200177 observers.rtcp_stats = stats_proxy;
Henrik Boström87e3f9d2019-05-27 10:44:24 +0200178 observers.report_block_data_observer = stats_proxy;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200179 observers.rtp_stats = stats_proxy;
180 observers.bitrate_observer = stats_proxy;
181 observers.frame_count_observer = stats_proxy;
182 observers.rtcp_type_observer = stats_proxy;
183 observers.send_delay_observer = stats_proxy;
184 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200185 return observers;
186}
Erik Språngb57ab382018-09-13 10:52:38 +0200187
188absl::optional<AlrExperimentSettings> GetAlrSettings(
189 VideoEncoderConfig::ContentType content_type) {
190 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
191 return AlrExperimentSettings::CreateFromFieldTrial(
192 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
193 }
194 return AlrExperimentSettings::CreateFromFieldTrial(
195 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
196}
Erik Språng4e193e42018-09-14 19:01:58 +0200197
198bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
199 const VideoBitrateAllocation& rhs) {
200 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
201 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
202 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
203 return false;
204 }
205 }
206 }
207 return true;
208}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200209} // namespace
210
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100211PacingConfig::PacingConfig()
212 : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
213 max_pacing_delay("max_delay",
214 TimeDelta::ms(PacedSender::kMaxQueueLengthMs)) {
215 ParseFieldTrial({&pacing_factor, &max_pacing_delay},
216 field_trial::FindFullName("WebRTC-Video-Pacing"));
217}
218PacingConfig::PacingConfig(const PacingConfig&) = default;
219PacingConfig::~PacingConfig() = default;
220
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200221VideoSendStreamImpl::VideoSendStreamImpl(
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100222 Clock* clock,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200223 SendStatisticsProxy* stats_proxy,
224 rtc::TaskQueue* worker_queue,
225 CallStats* call_stats,
226 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200227 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200228 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200229 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200230 RtcEventLog* event_log,
231 const VideoSendStream::Config* config,
232 int initial_encoder_max_bitrate,
233 double initial_encoder_bitrate_priority,
234 std::map<uint32_t, RtpState> suspended_ssrcs,
235 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
236 VideoEncoderConfig::ContentType content_type,
Niels Möller46879152019-01-07 15:54:47 +0100237 std::unique_ptr<FecController> fec_controller,
238 MediaTransportInterface* media_transport)
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100239 : clock_(clock),
240 has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200241 GetAlrSettings(content_type)),
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100242 pacing_config_(PacingConfig()),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200243 stats_proxy_(stats_proxy),
244 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200245 worker_queue_(worker_queue),
Erik Språngcd76eab2019-01-21 18:06:46 +0100246 timed_out_(false),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200247 call_stats_(call_stats),
248 transport_(transport),
249 bitrate_allocator_(bitrate_allocator),
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200250 disable_padding_(true),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200251 max_padding_bitrate_(0),
252 encoder_min_bitrate_bps_(0),
253 encoder_target_rate_bps_(0),
254 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
255 has_packet_feedback_(false),
256 video_stream_encoder_(video_stream_encoder),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100257 encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200258 bandwidth_observer_(transport->GetBandwidthObserver()),
Benjamin Wright192eeec2018-10-17 17:27:25 -0700259 rtp_video_sender_(transport_->CreateRtpVideoSender(
Benjamin Wright192eeec2018-10-17 17:27:25 -0700260 suspended_ssrcs,
261 suspended_payload_states,
262 config_->rtp,
Jiawei Ou55718122018-11-09 13:17:39 -0800263 config_->rtcp_report_interval_ms,
Benjamin Wright192eeec2018-10-17 17:27:25 -0700264 config_->send_transport,
265 CreateObservers(call_stats,
266 &encoder_feedback_,
267 stats_proxy_,
268 send_delay_stats),
269 event_log,
270 std::move(fec_controller),
271 CreateFrameEncryptionConfig(config_))),
Niels Möller46879152019-01-07 15:54:47 +0100272 weak_ptr_factory_(this),
273 media_transport_(media_transport) {
Elad Alon8f01c4e2019-06-28 15:19:43 +0200274 video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200275 RTC_DCHECK_RUN_ON(worker_queue_);
276 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
277 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200278
Elad Alonb6ef99b2019-04-10 16:37:07 +0200279 encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
280
Niels Möller46879152019-01-07 15:54:47 +0100281 if (media_transport_) {
282 // The configured ssrc is interpreted as a channel id, so there must be
283 // exactly one.
284 RTC_DCHECK_EQ(config_->rtp.ssrcs.size(), 1);
Niels Möllerfa89d842019-01-30 16:33:45 +0100285 media_transport_->SetKeyFrameRequestCallback(&encoder_feedback_);
Niels Möller46879152019-01-07 15:54:47 +0100286 } else {
287 RTC_DCHECK(!config_->rtp.ssrcs.empty());
288 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200289 RTC_DCHECK(call_stats_);
290 RTC_DCHECK(transport_);
291 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
292
293 if (initial_encoder_max_bitrate > 0) {
294 encoder_max_bitrate_bps_ =
295 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
296 } else {
297 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
298 // have any way to handle unset values in downstream code, such as the
299 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
300 // behaviour that is not safe. Converting to 10 Mbps should be safe for
301 // reasonable use cases as it allows adding the max of multiple streams
302 // without wrappping around.
303 const int kFallbackMaxBitrateBps = 10000000;
304 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
305 << initial_encoder_max_bitrate << " which is <= 0!";
306 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
307 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
308 }
309
310 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
311 // If send-side BWE is enabled, check if we should apply updated probing and
312 // pacing settings.
313 if (TransportSeqNumExtensionConfigured(*config_)) {
314 has_packet_feedback_ = true;
315
Erik Språngb57ab382018-09-13 10:52:38 +0200316 absl::optional<AlrExperimentSettings> alr_settings =
317 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200318 if (alr_settings) {
319 transport->EnablePeriodicAlrProbing(true);
320 transport->SetPacingFactor(alr_settings->pacing_factor);
321 configured_pacing_factor_ = alr_settings->pacing_factor;
322 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
323 } else {
Erik Språngcd76eab2019-01-21 18:06:46 +0100324 RateControlSettings rate_control_settings =
325 RateControlSettings::ParseFromFieldTrials();
326
327 transport->EnablePeriodicAlrProbing(
328 rate_control_settings.UseAlrProbing());
329 const double pacing_factor =
330 rate_control_settings.GetPacingFactor().value_or(
331 pacing_config_.pacing_factor);
332 transport->SetPacingFactor(pacing_factor);
333 configured_pacing_factor_ = pacing_factor;
Christoffer Rodbro196c5ba2018-11-27 11:56:25 +0100334 transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200335 }
336 }
337
338 if (config_->periodic_alr_bandwidth_probing) {
339 transport->EnablePeriodicAlrProbing(true);
340 }
341
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200342 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
343 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
344
345 video_stream_encoder_->SetStartBitrate(
346 bitrate_allocator_->GetStartBitrate(this));
347
348 // Only request rotation at the source when we positively know that the remote
349 // side doesn't support the rotation extension. This allows us to prepare the
350 // encoder in the expectation that rotation is supported - which is the common
351 // case.
Steve Antonbd631a02019-03-28 10:51:27 -0700352 bool rotation_applied = absl::c_none_of(
353 config_->rtp.extensions, [](const RtpExtension& extension) {
354 return extension.uri == RtpExtension::kVideoRotationUri;
355 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200356
357 video_stream_encoder_->SetSink(this, rotation_applied);
358}
359
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200360VideoSendStreamImpl::~VideoSendStreamImpl() {
361 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200362 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200363 << "VideoSendStreamImpl::Stop not called";
364 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200365 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Niels Möllerfa89d842019-01-30 16:33:45 +0100366 if (media_transport_) {
367 media_transport_->SetKeyFrameRequestCallback(nullptr);
368 }
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200369}
370
371void VideoSendStreamImpl::RegisterProcessThread(
372 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200373 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200374}
375
376void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200377 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200378}
379
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100380void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200381 // Runs on a network thread.
382 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200383 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200384}
385
386void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
387 const std::vector<bool> active_layers) {
388 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200389 RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200390 bool previously_active = rtp_video_sender_->IsActive();
391 rtp_video_sender_->SetActiveModules(active_layers);
392 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200393 // Payload router switched from active to inactive.
394 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200395 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200396 // Payload router switched from inactive to active.
397 StartupVideoSendStream();
398 }
399}
400
401void VideoSendStreamImpl::Start() {
402 RTC_DCHECK_RUN_ON(worker_queue_);
403 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200404 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200405 return;
406 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200407 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200408 StartupVideoSendStream();
409}
410
411void VideoSendStreamImpl::StartupVideoSendStream() {
412 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson464a5572019-02-12 13:32:32 +0100413 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200414 // Start monitoring encoder activity.
415 {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100416 RTC_DCHECK(!check_encoder_activity_task_.Running());
417
418 activity_ = false;
419 timed_out_ = false;
Sebastian Janssoncda86dd2019-03-11 17:26:36 +0100420 check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
421 worker_queue_->Get(), kEncoderTimeOut, [this] {
Sebastian Janssonecb68972019-01-18 10:30:54 +0100422 RTC_DCHECK_RUN_ON(worker_queue_);
423 if (!activity_) {
424 if (!timed_out_) {
425 SignalEncoderTimedOut();
426 }
427 timed_out_ = true;
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200428 disable_padding_ = true;
Sebastian Janssonecb68972019-01-18 10:30:54 +0100429 } else if (timed_out_) {
430 SignalEncoderActive();
431 timed_out_ = false;
432 }
433 activity_ = false;
434 return kEncoderTimeOut;
435 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200436 }
437
438 video_stream_encoder_->SendKeyFrame();
439}
440
441void VideoSendStreamImpl::Stop() {
442 RTC_DCHECK_RUN_ON(worker_queue_);
443 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200444 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200445 return;
446 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200447 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200448 StopVideoSendStream();
449}
450
451void VideoSendStreamImpl::StopVideoSendStream() {
452 bitrate_allocator_->RemoveObserver(this);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100453 check_encoder_activity_task_.Stop();
Erik Språng610c7632019-03-06 15:37:33 +0100454 video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), 0,
455 0);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200456 stats_proxy_->OnSetEncoderTargetRate(0);
457}
458
459void VideoSendStreamImpl::SignalEncoderTimedOut() {
460 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Janssonecb68972019-01-18 10:30:54 +0100461 // If the encoder has not produced anything the last kEncoderTimeOut and it
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200462 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
463 // if a camera stops producing frames.
464 if (encoder_target_rate_bps_ > 0) {
465 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
466 bitrate_allocator_->RemoveObserver(this);
467 }
468}
469
470void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200471 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200472 if (!worker_queue_->IsCurrent()) {
473 auto ptr = weak_ptr_;
474 worker_queue_->PostTask([=] {
475 if (!ptr.get())
476 return;
477 ptr->OnBitrateAllocationUpdated(allocation);
478 });
479 return;
480 }
481
482 RTC_DCHECK_RUN_ON(worker_queue_);
483
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100484 int64_t now_ms = clock_->TimeInMilliseconds();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200485 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200486 if (video_bitrate_allocation_context_) {
487 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
488 // the previously sent allocation and the same streams are still enabled,
489 // it is considered "similar". We do not want send similar allocations
490 // more once per kMaxVbaThrottleTimeMs.
491 const VideoBitrateAllocation& last =
492 video_bitrate_allocation_context_->last_sent_allocation;
493 const bool is_similar =
494 allocation.get_sum_bps() >= last.get_sum_bps() &&
495 allocation.get_sum_bps() <
496 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
497 100 &&
498 SameStreamsEnabled(allocation, last);
499 if (is_similar &&
500 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
501 kMaxVbaThrottleTimeMs) {
502 // This allocation is too similar, cache it and return.
503 video_bitrate_allocation_context_->throttled_allocation = allocation;
504 return;
505 }
506 } else {
507 video_bitrate_allocation_context_.emplace();
508 }
509
510 video_bitrate_allocation_context_->last_sent_allocation = allocation;
511 video_bitrate_allocation_context_->throttled_allocation.reset();
512 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
513
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200514 // Send bitrate allocation metadata only if encoder is not paused.
515 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
516 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200517}
518
519void VideoSendStreamImpl::SignalEncoderActive() {
520 RTC_DCHECK_RUN_ON(worker_queue_);
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200521 if (rtp_video_sender_->IsActive()) {
522 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
523 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
524 }
Sebastian Jansson464a5572019-02-12 13:32:32 +0100525}
526
527MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
528 return MediaStreamAllocationConfig{
529 static_cast<uint32_t>(encoder_min_bitrate_bps_),
530 encoder_max_bitrate_bps_,
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200531 static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
Sebastian Jansson464a5572019-02-12 13:32:32 +0100532 /* priority_bitrate */ 0,
533 !config_->suspend_below_min_bitrate,
Sebastian Jansson464a5572019-02-12 13:32:32 +0100534 encoder_bitrate_priority_};
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200535}
536
537void VideoSendStreamImpl::OnEncoderConfigurationChanged(
538 std::vector<VideoStream> streams,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100539 VideoEncoderConfig::ContentType content_type,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200540 int min_transmit_bitrate_bps) {
541 if (!worker_queue_->IsCurrent()) {
542 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
Mirko Bonadei80a86872019-02-04 15:01:43 +0100543 worker_queue_->PostTask([send_stream, streams, content_type,
544 min_transmit_bitrate_bps]() mutable {
545 if (send_stream) {
546 send_stream->OnEncoderConfigurationChanged(
547 std::move(streams), content_type, min_transmit_bitrate_bps);
548 }
549 });
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200550 return;
551 }
552 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
553 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
554 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
555 RTC_DCHECK_RUN_ON(worker_queue_);
556
557 encoder_min_bitrate_bps_ =
Åsa Persson59830872019-06-28 17:01:08 +0200558 std::max(streams[0].min_bitrate_bps,
559 GetEncoderMinBitrateBps(
560 PayloadStringToCodecType(config_->rtp.payload_name)));
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200561 encoder_max_bitrate_bps_ = 0;
562 double stream_bitrate_priority_sum = 0;
563 for (const auto& stream : streams) {
564 // We don't want to allocate more bitrate than needed to inactive streams.
565 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
566 if (stream.bitrate_priority) {
567 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
568 stream_bitrate_priority_sum += *stream.bitrate_priority;
569 }
570 }
571 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
572 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
573 encoder_max_bitrate_bps_ =
574 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
575 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500576
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100577 // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
“Michael277a6562018-06-01 14:09:19 -0500578 const VideoCodecType codec_type =
579 PayloadStringToCodecType(config_->rtp.payload_name);
580 if (codec_type == kVideoCodecVP9) {
Sergey Silkin8b9b5f92018-12-10 09:28:53 +0100581 max_padding_bitrate_ = has_alr_probing_ ? streams[0].min_bitrate_bps
582 : streams[0].target_bitrate_bps;
“Michael277a6562018-06-01 14:09:19 -0500583 } else {
584 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
Rasmus Brandtc402dbe2019-02-04 11:09:46 +0100585 streams, content_type, min_transmit_bitrate_bps,
586 config_->suspend_below_min_bitrate, has_alr_probing_);
“Michael277a6562018-06-01 14:09:19 -0500587 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200588
589 // Clear stats for disabled layers.
590 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
591 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
592 }
593
594 const size_t num_temporal_layers =
595 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200596
597 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
598 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200599
Stefan Holmer9416ef82018-07-19 10:34:38 +0200600 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200601 // The send stream is started already. Update the allocator with new bitrate
602 // limits.
Sebastian Jansson464a5572019-02-12 13:32:32 +0100603 bitrate_allocator_->AddObserver(this, GetAllocationConfig());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200604 }
605}
606
607EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
608 const EncodedImage& encoded_image,
609 const CodecSpecificInfo* codec_specific_info,
610 const RTPFragmentationHeader* fragmentation) {
611 // Encoded is called on whatever thread the real encoder implementation run
612 // on. In the case of hardware encoders, there might be several encoders
613 // running in parallel on different threads.
Sebastian Janssonecb68972019-01-18 10:30:54 +0100614
615 // Indicate that there still is activity going on.
616 activity_ = true;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200617
Ilya Nikolaevskiyaa9aa572019-04-11 09:20:24 +0200618 auto enable_padding_task = [this]() {
619 if (disable_padding_) {
620 RTC_DCHECK_RUN_ON(worker_queue_);
621 disable_padding_ = false;
622 // To ensure that padding bitrate is propagated to the bitrate allocator.
623 SignalEncoderActive();
624 }
625 };
626 if (!worker_queue_->IsCurrent()) {
627 worker_queue_->PostTask(enable_padding_task);
628 } else {
629 enable_padding_task();
630 }
631
Niels Möller46879152019-01-07 15:54:47 +0100632 EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
633 if (media_transport_) {
634 int64_t frame_id;
635 {
636 // TODO(nisse): Responsibility for allocation of frame ids should move to
637 // VideoStreamEncoder.
638 rtc::CritScope cs(&media_transport_id_lock_);
639 frame_id = media_transport_frame_id_++;
640 }
641 // TODO(nisse): Responsibility for reference meta data should be moved
642 // upstream, ideally close to the encoders, but probably VideoStreamEncoder
643 // will need to do some translation to produce reference info using frame
644 // ids.
645 std::vector<int64_t> referenced_frame_ids;
Niels Möller8f7ce222019-03-21 15:43:58 +0100646 if (encoded_image._frameType != VideoFrameType::kVideoFrameKey) {
Niels Möller46879152019-01-07 15:54:47 +0100647 RTC_DCHECK_GT(frame_id, 0);
648 referenced_frame_ids.push_back(frame_id - 1);
649 }
650 media_transport_->SendVideoFrame(
651 config_->rtp.ssrcs[0], webrtc::MediaTransportEncodedVideoFrame(
652 frame_id, referenced_frame_ids,
653 config_->rtp.payload_type, encoded_image));
654 } else {
655 result = rtp_video_sender_->OnEncodedImage(
656 encoded_image, codec_specific_info, fragmentation);
657 }
Erik Språng4e193e42018-09-14 19:01:58 +0200658 // Check if there's a throttled VideoBitrateAllocation that we should try
659 // sending.
660 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
661 auto update_task = [send_stream]() {
662 if (send_stream) {
663 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
664 auto& context = send_stream->video_bitrate_allocation_context_;
665 if (context && context->throttled_allocation) {
666 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
667 }
668 }
669 };
670 if (!worker_queue_->IsCurrent()) {
671 worker_queue_->PostTask(update_task);
672 } else {
673 update_task();
674 }
675
676 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200677}
678
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200679std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200680 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200681}
682
683std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
684 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200685 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200686}
687
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200688uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200689 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200690 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200691 << "VideoSendStream::Start has not been called.";
692
Sebastian Jansson13e59032018-11-21 19:13:07 +0100693 rtp_video_sender_->OnBitrateUpdated(
694 update.target_bitrate.bps(),
695 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
696 update.round_trip_time.ms(), stats_proxy_->GetSendFrameRate());
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200697 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Erik Språng26111642019-03-26 11:09:04 +0100698 const uint32_t protection_bitrate_bps =
699 rtp_video_sender_->GetProtectionBitrateBps();
Erik Språng4c6ca302019-04-08 15:14:01 +0200700 DataRate link_allocation = DataRate::Zero();
701 if (encoder_target_rate_bps_ > protection_bitrate_bps) {
702 link_allocation =
703 DataRate::bps(encoder_target_rate_bps_ - protection_bitrate_bps);
Erik Språng610c7632019-03-06 15:37:33 +0100704 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200705 encoder_target_rate_bps_ =
706 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
Erik Språng4c6ca302019-04-08 15:14:01 +0200707
708 DataRate encoder_target_rate = DataRate::bps(encoder_target_rate_bps_);
709 link_allocation = std::max(encoder_target_rate, link_allocation);
Sebastian Jansson13e59032018-11-21 19:13:07 +0100710 video_stream_encoder_->OnBitrateUpdated(
Erik Språng4c6ca302019-04-08 15:14:01 +0200711 encoder_target_rate, link_allocation,
Sebastian Jansson13e59032018-11-21 19:13:07 +0100712 rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
713 update.round_trip_time.ms());
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200714 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Erik Språng26111642019-03-26 11:09:04 +0100715 return protection_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200716}
717
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200718} // namespace internal
719} // namespace webrtc