blob: 1cb4dbc6f2a5f4d9c4b847c56e7f707c31ce2d58 [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
12#include <algorithm>
13#include <string>
14#include <utility>
15
16#include "call/rtp_transport_controller_send_interface.h"
17#include "modules/pacing/packet_router.h"
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020018#include "modules/rtp_rtcp/source/rtp_sender.h"
19#include "rtc_base/checks.h"
20#include "rtc_base/experiments/alr_experiment.h"
21#include "rtc_base/file.h"
22#include "rtc_base/location.h"
23#include "rtc_base/logging.h"
24#include "rtc_base/numerics/safe_conversions.h"
25#include "rtc_base/trace_event.h"
26#include "system_wrappers/include/field_trial.h"
27
28namespace webrtc {
29namespace internal {
30namespace {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020031
Erik Språng4e193e42018-09-14 19:01:58 +020032// Max positive size difference to treat allocations as "similar".
33static constexpr int kMaxVbaSizeDifferencePercent = 10;
34// Max time we will throttle similar video bitrate allocations.
35static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
36
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020037bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
38 const std::vector<RtpExtension>& extensions = config.rtp.extensions;
39 return std::find_if(
40 extensions.begin(), extensions.end(), [](const RtpExtension& ext) {
41 return ext.uri == RtpExtension::kTransportSequenceNumberUri;
42 }) != extensions.end();
43}
44
45const char kForcedFallbackFieldTrial[] =
46 "WebRTC-VP8-Forced-Fallback-Encoder-v2";
47
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020048absl::optional<int> GetFallbackMinBpsFromFieldTrial() {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020049 if (!webrtc::field_trial::IsEnabled(kForcedFallbackFieldTrial))
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020050 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020051
52 std::string group =
53 webrtc::field_trial::FindFullName(kForcedFallbackFieldTrial);
54 if (group.empty())
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020055 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020056
57 int min_pixels;
58 int max_pixels;
59 int min_bps;
60 if (sscanf(group.c_str(), "Enabled-%d,%d,%d", &min_pixels, &max_pixels,
61 &min_bps) != 3) {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020062 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020063 }
64
65 if (min_bps <= 0)
Danil Chapovalovb9b146c2018-06-15 12:28:07 +020066 return absl::nullopt;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020067
68 return min_bps;
69}
70
71int GetEncoderMinBitrateBps() {
72 const int kDefaultEncoderMinBitrateBps = 30000;
73 return GetFallbackMinBpsFromFieldTrial().value_or(
74 kDefaultEncoderMinBitrateBps);
75}
76
Erik Språngb57ab382018-09-13 10:52:38 +020077// Calculate max padding bitrate for a multi layer codec.
78int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020079 int min_transmit_bitrate_bps,
Erik Språngb57ab382018-09-13 10:52:38 +020080 bool pad_to_min_bitrate,
81 bool alr_probing) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +020082 int pad_up_to_bitrate_bps = 0;
Erik Språngb57ab382018-09-13 10:52:38 +020083
84 // Filter out only the active streams;
85 std::vector<VideoStream> active_streams;
86 for (const VideoStream& stream : streams) {
87 if (stream.active)
88 active_streams.emplace_back(stream);
89 }
90
91 if (active_streams.size() > 1) {
92 if (alr_probing) {
93 // With alr probing, just pad to the min bitrate of the lowest stream,
94 // probing will handle the rest of the rampup.
95 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
96 } else {
97 // Pad to min bitrate of the highest layer.
98 pad_up_to_bitrate_bps =
99 active_streams[active_streams.size() - 1].min_bitrate_bps;
100 // Add target_bitrate_bps of the lower layers.
101 for (size_t i = 0; i < active_streams.size() - 1; ++i)
102 pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
103 }
104 } else if (!active_streams.empty() && pad_to_min_bitrate) {
105 pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200106 }
107
108 pad_up_to_bitrate_bps =
109 std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
110
111 return pad_up_to_bitrate_bps;
112}
113
Benjamin Wright192eeec2018-10-17 17:27:25 -0700114RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
115 const VideoSendStream::Config* config) {
116 RtpSenderFrameEncryptionConfig frame_encryption_config;
117 frame_encryption_config.frame_encryptor = config->frame_encryptor;
118 frame_encryption_config.crypto_options = config->crypto_options;
119 return frame_encryption_config;
120}
121
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200122RtpSenderObservers CreateObservers(CallStats* call_stats,
123 EncoderRtcpFeedback* encoder_feedback,
124 SendStatisticsProxy* stats_proxy,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200125 SendDelayStats* send_delay_stats) {
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200126 RtpSenderObservers observers;
127 observers.rtcp_rtt_stats = call_stats;
128 observers.intra_frame_callback = encoder_feedback;
129 observers.rtcp_stats = stats_proxy;
130 observers.rtp_stats = stats_proxy;
131 observers.bitrate_observer = stats_proxy;
132 observers.frame_count_observer = stats_proxy;
133 observers.rtcp_type_observer = stats_proxy;
134 observers.send_delay_observer = stats_proxy;
135 observers.send_packet_observer = send_delay_stats;
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200136 return observers;
137}
Erik Språngb57ab382018-09-13 10:52:38 +0200138
139absl::optional<AlrExperimentSettings> GetAlrSettings(
140 VideoEncoderConfig::ContentType content_type) {
141 if (content_type == VideoEncoderConfig::ContentType::kScreen) {
142 return AlrExperimentSettings::CreateFromFieldTrial(
143 AlrExperimentSettings::kScreenshareProbingBweExperimentName);
144 }
145 return AlrExperimentSettings::CreateFromFieldTrial(
146 AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
147}
Erik Språng4e193e42018-09-14 19:01:58 +0200148
149bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
150 const VideoBitrateAllocation& rhs) {
151 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
152 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
153 if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
154 return false;
155 }
156 }
157 }
158 return true;
159}
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200160} // namespace
161
162// CheckEncoderActivityTask is used for tracking when the encoder last produced
163// and encoded video frame. If the encoder has not produced anything the last
164// kEncoderTimeOutMs we also want to stop sending padding.
165class VideoSendStreamImpl::CheckEncoderActivityTask : public rtc::QueuedTask {
166 public:
167 static const int kEncoderTimeOutMs = 2000;
168 explicit CheckEncoderActivityTask(
169 const rtc::WeakPtr<VideoSendStreamImpl>& send_stream)
170 : activity_(0), send_stream_(std::move(send_stream)), timed_out_(false) {}
171
172 void Stop() {
173 RTC_CHECK(task_checker_.CalledSequentially());
174 send_stream_.reset();
175 }
176
177 void UpdateEncoderActivity() {
178 // UpdateEncoderActivity is called from VideoSendStreamImpl::Encoded on
179 // whatever thread the real encoder implementation run on. In the case of
180 // hardware encoders, there might be several encoders
181 // running in parallel on different threads.
182 rtc::AtomicOps::ReleaseStore(&activity_, 1);
183 }
184
185 private:
186 bool Run() override {
187 RTC_CHECK(task_checker_.CalledSequentially());
188 if (!send_stream_)
189 return true;
190 if (!rtc::AtomicOps::AcquireLoad(&activity_)) {
191 if (!timed_out_) {
192 send_stream_->SignalEncoderTimedOut();
193 }
194 timed_out_ = true;
195 } else if (timed_out_) {
196 send_stream_->SignalEncoderActive();
197 timed_out_ = false;
198 }
199 rtc::AtomicOps::ReleaseStore(&activity_, 0);
200
201 rtc::TaskQueue::Current()->PostDelayedTask(
202 std::unique_ptr<rtc::QueuedTask>(this), kEncoderTimeOutMs);
203 // Return false to prevent this task from being deleted. Ownership has been
204 // transferred to the task queue when PostDelayedTask was called.
205 return false;
206 }
207 volatile int activity_;
208
209 rtc::SequencedTaskChecker task_checker_;
210 rtc::WeakPtr<VideoSendStreamImpl> send_stream_;
211 bool timed_out_;
212};
213
214VideoSendStreamImpl::VideoSendStreamImpl(
215 SendStatisticsProxy* stats_proxy,
216 rtc::TaskQueue* worker_queue,
217 CallStats* call_stats,
218 RtpTransportControllerSendInterface* transport,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200219 BitrateAllocatorInterface* bitrate_allocator,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200220 SendDelayStats* send_delay_stats,
Sebastian Jansson652dc912018-04-19 17:09:15 +0200221 VideoStreamEncoderInterface* video_stream_encoder,
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200222 RtcEventLog* event_log,
223 const VideoSendStream::Config* config,
224 int initial_encoder_max_bitrate,
225 double initial_encoder_bitrate_priority,
226 std::map<uint32_t, RtpState> suspended_ssrcs,
227 std::map<uint32_t, RtpPayloadState> suspended_payload_states,
228 VideoEncoderConfig::ContentType content_type,
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200229 std::unique_ptr<FecController> fec_controller)
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200230 : has_alr_probing_(config->periodic_alr_bandwidth_probing ||
Erik Språngb57ab382018-09-13 10:52:38 +0200231 GetAlrSettings(content_type)),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200232 stats_proxy_(stats_proxy),
233 config_(config),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200234 worker_queue_(worker_queue),
235 check_encoder_activity_task_(nullptr),
236 call_stats_(call_stats),
237 transport_(transport),
238 bitrate_allocator_(bitrate_allocator),
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200239 max_padding_bitrate_(0),
240 encoder_min_bitrate_bps_(0),
241 encoder_target_rate_bps_(0),
242 encoder_bitrate_priority_(initial_encoder_bitrate_priority),
243 has_packet_feedback_(false),
244 video_stream_encoder_(video_stream_encoder),
245 encoder_feedback_(Clock::GetRealTimeClock(),
246 config_->rtp.ssrcs,
247 video_stream_encoder),
248 bandwidth_observer_(transport->GetBandwidthObserver()),
Benjamin Wright192eeec2018-10-17 17:27:25 -0700249 rtp_video_sender_(transport_->CreateRtpVideoSender(
250 config_->rtp.ssrcs,
251 suspended_ssrcs,
252 suspended_payload_states,
253 config_->rtp,
Jiawei Ou55718122018-11-09 13:17:39 -0800254 config_->rtcp_report_interval_ms,
Benjamin Wright192eeec2018-10-17 17:27:25 -0700255 config_->send_transport,
256 CreateObservers(call_stats,
257 &encoder_feedback_,
258 stats_proxy_,
259 send_delay_stats),
260 event_log,
261 std::move(fec_controller),
262 CreateFrameEncryptionConfig(config_))),
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200263 weak_ptr_factory_(this) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200264 RTC_DCHECK_RUN_ON(worker_queue_);
265 RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
266 weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200267
268 RTC_DCHECK(!config_->rtp.ssrcs.empty());
269 RTC_DCHECK(call_stats_);
270 RTC_DCHECK(transport_);
271 RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
272
273 if (initial_encoder_max_bitrate > 0) {
274 encoder_max_bitrate_bps_ =
275 rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
276 } else {
277 // TODO(srte): Make sure max bitrate is not set to negative values. We don't
278 // have any way to handle unset values in downstream code, such as the
279 // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
280 // behaviour that is not safe. Converting to 10 Mbps should be safe for
281 // reasonable use cases as it allows adding the max of multiple streams
282 // without wrappping around.
283 const int kFallbackMaxBitrateBps = 10000000;
284 RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
285 << initial_encoder_max_bitrate << " which is <= 0!";
286 RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
287 encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
288 }
289
290 RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
291 // If send-side BWE is enabled, check if we should apply updated probing and
292 // pacing settings.
293 if (TransportSeqNumExtensionConfigured(*config_)) {
294 has_packet_feedback_ = true;
295
Erik Språngb57ab382018-09-13 10:52:38 +0200296 absl::optional<AlrExperimentSettings> alr_settings =
297 GetAlrSettings(content_type);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200298 if (alr_settings) {
299 transport->EnablePeriodicAlrProbing(true);
300 transport->SetPacingFactor(alr_settings->pacing_factor);
301 configured_pacing_factor_ = alr_settings->pacing_factor;
302 transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
303 } else {
304 transport->EnablePeriodicAlrProbing(false);
305 transport->SetPacingFactor(PacedSender::kDefaultPaceMultiplier);
306 configured_pacing_factor_ = PacedSender::kDefaultPaceMultiplier;
307 transport->SetQueueTimeLimit(PacedSender::kMaxQueueLengthMs);
308 }
309 }
310
311 if (config_->periodic_alr_bandwidth_probing) {
312 transport->EnablePeriodicAlrProbing(true);
313 }
314
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200315 RTC_DCHECK_GE(config_->rtp.payload_type, 0);
316 RTC_DCHECK_LE(config_->rtp.payload_type, 127);
317
318 video_stream_encoder_->SetStartBitrate(
319 bitrate_allocator_->GetStartBitrate(this));
320
321 // Only request rotation at the source when we positively know that the remote
322 // side doesn't support the rotation extension. This allows us to prepare the
323 // encoder in the expectation that rotation is supported - which is the common
324 // case.
325 bool rotation_applied =
326 std::find_if(config_->rtp.extensions.begin(),
327 config_->rtp.extensions.end(),
328 [](const RtpExtension& extension) {
329 return extension.uri == RtpExtension::kVideoRotationUri;
330 }) == config_->rtp.extensions.end();
331
332 video_stream_encoder_->SetSink(this, rotation_applied);
333}
334
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200335VideoSendStreamImpl::~VideoSendStreamImpl() {
336 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200337 RTC_DCHECK(!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200338 << "VideoSendStreamImpl::Stop not called";
339 RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200340 transport_->DestroyRtpVideoSender(rtp_video_sender_);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200341}
342
343void VideoSendStreamImpl::RegisterProcessThread(
344 ProcessThread* module_process_thread) {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200345 rtp_video_sender_->RegisterProcessThread(module_process_thread);
Stefan Holmerdbdb3a02018-07-17 16:03:46 +0200346}
347
348void VideoSendStreamImpl::DeRegisterProcessThread() {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200349 rtp_video_sender_->DeRegisterProcessThread();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200350}
351
352bool VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
353 // Runs on a network thread.
354 RTC_DCHECK(!worker_queue_->IsCurrent());
Stefan Holmer9416ef82018-07-19 10:34:38 +0200355 rtp_video_sender_->DeliverRtcp(packet, length);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200356 return true;
357}
358
359void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
360 const std::vector<bool> active_layers) {
361 RTC_DCHECK_RUN_ON(worker_queue_);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200362 RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200363 bool previously_active = rtp_video_sender_->IsActive();
364 rtp_video_sender_->SetActiveModules(active_layers);
365 if (!rtp_video_sender_->IsActive() && previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200366 // Payload router switched from active to inactive.
367 StopVideoSendStream();
Stefan Holmer9416ef82018-07-19 10:34:38 +0200368 } else if (rtp_video_sender_->IsActive() && !previously_active) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200369 // Payload router switched from inactive to active.
370 StartupVideoSendStream();
371 }
372}
373
374void VideoSendStreamImpl::Start() {
375 RTC_DCHECK_RUN_ON(worker_queue_);
376 RTC_LOG(LS_INFO) << "VideoSendStream::Start";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200377 if (rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200378 return;
379 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200380 rtp_video_sender_->SetActive(true);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200381 StartupVideoSendStream();
382}
383
384void VideoSendStreamImpl::StartupVideoSendStream() {
385 RTC_DCHECK_RUN_ON(worker_queue_);
386 bitrate_allocator_->AddObserver(
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200387 this,
388 MediaStreamAllocationConfig{
389 static_cast<uint32_t>(encoder_min_bitrate_bps_),
390 encoder_max_bitrate_bps_, static_cast<uint32_t>(max_padding_bitrate_),
391 !config_->suspend_below_min_bitrate, config_->track_id,
392 encoder_bitrate_priority_, has_packet_feedback_});
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200393 // Start monitoring encoder activity.
394 {
395 rtc::CritScope lock(&encoder_activity_crit_sect_);
396 RTC_DCHECK(!check_encoder_activity_task_);
397 check_encoder_activity_task_ = new CheckEncoderActivityTask(weak_ptr_);
398 worker_queue_->PostDelayedTask(
399 std::unique_ptr<rtc::QueuedTask>(check_encoder_activity_task_),
400 CheckEncoderActivityTask::kEncoderTimeOutMs);
401 }
402
403 video_stream_encoder_->SendKeyFrame();
404}
405
406void VideoSendStreamImpl::Stop() {
407 RTC_DCHECK_RUN_ON(worker_queue_);
408 RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
Stefan Holmer9416ef82018-07-19 10:34:38 +0200409 if (!rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200410 return;
411 TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
Stefan Holmer9416ef82018-07-19 10:34:38 +0200412 rtp_video_sender_->SetActive(false);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200413 StopVideoSendStream();
414}
415
416void VideoSendStreamImpl::StopVideoSendStream() {
417 bitrate_allocator_->RemoveObserver(this);
418 {
419 rtc::CritScope lock(&encoder_activity_crit_sect_);
420 check_encoder_activity_task_->Stop();
421 check_encoder_activity_task_ = nullptr;
422 }
423 video_stream_encoder_->OnBitrateUpdated(0, 0, 0);
424 stats_proxy_->OnSetEncoderTargetRate(0);
425}
426
427void VideoSendStreamImpl::SignalEncoderTimedOut() {
428 RTC_DCHECK_RUN_ON(worker_queue_);
429 // If the encoder has not produced anything the last kEncoderTimeOutMs and it
430 // is supposed to, deregister as BitrateAllocatorObserver. This can happen
431 // if a camera stops producing frames.
432 if (encoder_target_rate_bps_ > 0) {
433 RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
434 bitrate_allocator_->RemoveObserver(this);
435 }
436}
437
438void VideoSendStreamImpl::OnBitrateAllocationUpdated(
Erik Språng566124a2018-04-23 12:32:22 +0200439 const VideoBitrateAllocation& allocation) {
Erik Språng4e193e42018-09-14 19:01:58 +0200440 if (!worker_queue_->IsCurrent()) {
441 auto ptr = weak_ptr_;
442 worker_queue_->PostTask([=] {
443 if (!ptr.get())
444 return;
445 ptr->OnBitrateAllocationUpdated(allocation);
446 });
447 return;
448 }
449
450 RTC_DCHECK_RUN_ON(worker_queue_);
451
452 int64_t now_ms = rtc::TimeMillis();
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200453 if (encoder_target_rate_bps_ != 0) {
Erik Språng4e193e42018-09-14 19:01:58 +0200454 if (video_bitrate_allocation_context_) {
455 // If new allocation is within kMaxVbaSizeDifferencePercent larger than
456 // the previously sent allocation and the same streams are still enabled,
457 // it is considered "similar". We do not want send similar allocations
458 // more once per kMaxVbaThrottleTimeMs.
459 const VideoBitrateAllocation& last =
460 video_bitrate_allocation_context_->last_sent_allocation;
461 const bool is_similar =
462 allocation.get_sum_bps() >= last.get_sum_bps() &&
463 allocation.get_sum_bps() <
464 (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
465 100 &&
466 SameStreamsEnabled(allocation, last);
467 if (is_similar &&
468 (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
469 kMaxVbaThrottleTimeMs) {
470 // This allocation is too similar, cache it and return.
471 video_bitrate_allocation_context_->throttled_allocation = allocation;
472 return;
473 }
474 } else {
475 video_bitrate_allocation_context_.emplace();
476 }
477
478 video_bitrate_allocation_context_->last_sent_allocation = allocation;
479 video_bitrate_allocation_context_->throttled_allocation.reset();
480 video_bitrate_allocation_context_->last_send_time_ms = now_ms;
481
Erik Språngf4ef2dd2018-09-11 12:37:51 +0200482 // Send bitrate allocation metadata only if encoder is not paused.
483 rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
484 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200485}
486
487void VideoSendStreamImpl::SignalEncoderActive() {
488 RTC_DCHECK_RUN_ON(worker_queue_);
489 RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
490 bitrate_allocator_->AddObserver(
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200491 this,
492 MediaStreamAllocationConfig{
493 static_cast<uint32_t>(encoder_min_bitrate_bps_),
494 encoder_max_bitrate_bps_, static_cast<uint32_t>(max_padding_bitrate_),
495 !config_->suspend_below_min_bitrate, config_->track_id,
496 encoder_bitrate_priority_, has_packet_feedback_});
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200497}
498
499void VideoSendStreamImpl::OnEncoderConfigurationChanged(
500 std::vector<VideoStream> streams,
501 int min_transmit_bitrate_bps) {
502 if (!worker_queue_->IsCurrent()) {
503 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
504 worker_queue_->PostTask([send_stream, streams, min_transmit_bitrate_bps]() {
505 if (send_stream)
506 send_stream->OnEncoderConfigurationChanged(std::move(streams),
507 min_transmit_bitrate_bps);
508 });
509 return;
510 }
511 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
512 TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
513 RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
514 RTC_DCHECK_RUN_ON(worker_queue_);
515
516 encoder_min_bitrate_bps_ =
517 std::max(streams[0].min_bitrate_bps, GetEncoderMinBitrateBps());
518 encoder_max_bitrate_bps_ = 0;
519 double stream_bitrate_priority_sum = 0;
520 for (const auto& stream : streams) {
521 // We don't want to allocate more bitrate than needed to inactive streams.
522 encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
523 if (stream.bitrate_priority) {
524 RTC_DCHECK_GT(*stream.bitrate_priority, 0);
525 stream_bitrate_priority_sum += *stream.bitrate_priority;
526 }
527 }
528 RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
529 encoder_bitrate_priority_ = stream_bitrate_priority_sum;
530 encoder_max_bitrate_bps_ =
531 std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
532 encoder_max_bitrate_bps_);
“Michael277a6562018-06-01 14:09:19 -0500533
534 const VideoCodecType codec_type =
535 PayloadStringToCodecType(config_->rtp.payload_name);
536 if (codec_type == kVideoCodecVP9) {
537 max_padding_bitrate_ = streams[0].target_bitrate_bps;
538 } else {
539 max_padding_bitrate_ = CalculateMaxPadBitrateBps(
Erik Språngb57ab382018-09-13 10:52:38 +0200540 streams, min_transmit_bitrate_bps, config_->suspend_below_min_bitrate,
541 has_alr_probing_);
“Michael277a6562018-06-01 14:09:19 -0500542 }
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200543
544 // Clear stats for disabled layers.
545 for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
546 stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
547 }
548
549 const size_t num_temporal_layers =
550 streams.back().num_temporal_layers.value_or(1);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200551
552 rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
553 num_temporal_layers);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200554
Stefan Holmer9416ef82018-07-19 10:34:38 +0200555 if (rtp_video_sender_->IsActive()) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200556 // The send stream is started already. Update the allocator with new bitrate
557 // limits.
558 bitrate_allocator_->AddObserver(
Sebastian Jansson24ad7202018-04-19 08:25:12 +0200559 this, MediaStreamAllocationConfig{
560 static_cast<uint32_t>(encoder_min_bitrate_bps_),
561 encoder_max_bitrate_bps_,
562 static_cast<uint32_t>(max_padding_bitrate_),
563 !config_->suspend_below_min_bitrate, config_->track_id,
564 encoder_bitrate_priority_, has_packet_feedback_});
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200565 }
566}
567
568EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
569 const EncodedImage& encoded_image,
570 const CodecSpecificInfo* codec_specific_info,
571 const RTPFragmentationHeader* fragmentation) {
572 // Encoded is called on whatever thread the real encoder implementation run
573 // on. In the case of hardware encoders, there might be several encoders
574 // running in parallel on different threads.
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200575 {
576 rtc::CritScope lock(&encoder_activity_crit_sect_);
577 if (check_encoder_activity_task_)
578 check_encoder_activity_task_->UpdateEncoderActivity();
579 }
580
Erik Språng4e193e42018-09-14 19:01:58 +0200581 EncodedImageCallback::Result result = rtp_video_sender_->OnEncodedImage(
582 encoded_image, codec_specific_info, fragmentation);
583
584 // Check if there's a throttled VideoBitrateAllocation that we should try
585 // sending.
586 rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
587 auto update_task = [send_stream]() {
588 if (send_stream) {
589 RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
590 auto& context = send_stream->video_bitrate_allocation_context_;
591 if (context && context->throttled_allocation) {
592 send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
593 }
594 }
595 };
596 if (!worker_queue_->IsCurrent()) {
597 worker_queue_->PostTask(update_task);
598 } else {
599 update_task();
600 }
601
602 return result;
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200603}
604
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200605std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200606 return rtp_video_sender_->GetRtpStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200607}
608
609std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
610 const {
Stefan Holmer9416ef82018-07-19 10:34:38 +0200611 return rtp_video_sender_->GetRtpPayloadStates();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200612}
613
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200614uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200615 RTC_DCHECK_RUN_ON(worker_queue_);
Stefan Holmer9416ef82018-07-19 10:34:38 +0200616 RTC_DCHECK(rtp_video_sender_->IsActive())
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200617 << "VideoSendStream::Start has not been called.";
618
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200619 rtp_video_sender_->OnBitrateUpdated(update.bitrate_bps, update.fraction_loss,
620 update.rtt,
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200621 stats_proxy_->GetSendFrameRate());
622 encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200623 encoder_target_rate_bps_ =
624 std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
625 video_stream_encoder_->OnBitrateUpdated(encoder_target_rate_bps_,
Sebastian Janssonc0e4d452018-10-25 15:08:32 +0200626 update.fraction_loss, update.rtt);
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200627 stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
Stefan Holmer64be7fa2018-10-04 15:21:55 +0200628 return rtp_video_sender_->GetProtectionBitrateBps();
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200629}
630
Sebastian Jansson8e0b15b2018-04-18 19:19:22 +0200631} // namespace internal
632} // namespace webrtc