xref: /aosp_15_r20/external/webrtc/video/video_send_stream_impl.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
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 <stdio.h>
13 
14 #include <algorithm>
15 #include <cstdint>
16 #include <string>
17 #include <utility>
18 
19 #include "absl/algorithm/container.h"
20 #include "api/crypto/crypto_options.h"
21 #include "api/rtp_parameters.h"
22 #include "api/scoped_refptr.h"
23 #include "api/sequence_checker.h"
24 #include "api/task_queue/pending_task_safety_flag.h"
25 #include "api/task_queue/task_queue_base.h"
26 #include "api/video_codecs/video_codec.h"
27 #include "call/rtp_transport_controller_send_interface.h"
28 #include "call/video_send_stream.h"
29 #include "modules/pacing/pacing_controller.h"
30 #include "rtc_base/checks.h"
31 #include "rtc_base/experiments/alr_experiment.h"
32 #include "rtc_base/experiments/field_trial_parser.h"
33 #include "rtc_base/experiments/min_video_bitrate_experiment.h"
34 #include "rtc_base/experiments/rate_control_settings.h"
35 #include "rtc_base/logging.h"
36 #include "rtc_base/numerics/safe_conversions.h"
37 #include "rtc_base/trace_event.h"
38 #include "system_wrappers/include/clock.h"
39 #include "system_wrappers/include/field_trial.h"
40 
41 namespace webrtc {
42 namespace internal {
43 namespace {
44 
45 // Max positive size difference to treat allocations as "similar".
46 static constexpr int kMaxVbaSizeDifferencePercent = 10;
47 // Max time we will throttle similar video bitrate allocations.
48 static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
49 
50 constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds(2);
51 
52 constexpr double kVideoHysteresis = 1.2;
53 constexpr double kScreenshareHysteresis = 1.35;
54 
55 // When send-side BWE is used a stricter 1.1x pacing factor is used, rather than
56 // the 2.5x which is used with receive-side BWE. Provides a more careful
57 // bandwidth rampup with less risk of overshoots causing adverse effects like
58 // packet loss. Not used for receive side BWE, since there we lack the probing
59 // feature and so may result in too slow initial rampup.
60 static constexpr double kStrictPacingMultiplier = 1.1;
61 
TransportSeqNumExtensionConfigured(const VideoSendStream::Config & config)62 bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
63   const std::vector<RtpExtension>& extensions = config.rtp.extensions;
64   return absl::c_any_of(extensions, [](const RtpExtension& ext) {
65     return ext.uri == RtpExtension::kTransportSequenceNumberUri;
66   });
67 }
68 
69 // Calculate max padding bitrate for a multi layer codec.
CalculateMaxPadBitrateBps(const std::vector<VideoStream> & streams,bool is_svc,VideoEncoderConfig::ContentType content_type,int min_transmit_bitrate_bps,bool pad_to_min_bitrate,bool alr_probing)70 int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
71                               bool is_svc,
72                               VideoEncoderConfig::ContentType content_type,
73                               int min_transmit_bitrate_bps,
74                               bool pad_to_min_bitrate,
75                               bool alr_probing) {
76   int pad_up_to_bitrate_bps = 0;
77 
78   RTC_DCHECK(!is_svc || streams.size() <= 1) << "Only one stream is allowed in "
79                                                 "SVC mode.";
80 
81   // Filter out only the active streams;
82   std::vector<VideoStream> active_streams;
83   for (const VideoStream& stream : streams) {
84     if (stream.active)
85       active_streams.emplace_back(stream);
86   }
87 
88   if (active_streams.size() > 1 || (!active_streams.empty() && is_svc)) {
89     // Simulcast or SVC is used.
90     // if SVC is used, stream bitrates should already encode svc bitrates:
91     // min_bitrate = min bitrate of a lowest svc layer.
92     // target_bitrate = sum of target bitrates of lower layers + min bitrate
93     // of the last one (as used in the calculations below).
94     // max_bitrate = sum of all active layers' max_bitrate.
95     if (alr_probing) {
96       // With alr probing, just pad to the min bitrate of the lowest stream,
97       // probing will handle the rest of the rampup.
98       pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
99     } else {
100       // Without alr probing, pad up to start bitrate of the
101       // highest active stream.
102       const double hysteresis_factor =
103           content_type == VideoEncoderConfig::ContentType::kScreen
104               ? kScreenshareHysteresis
105               : kVideoHysteresis;
106       if (is_svc) {
107         // For SVC, since there is only one "stream", the padding bitrate
108         // needed to enable the top spatial layer is stored in the
109         // `target_bitrate_bps` field.
110         // TODO(sprang): This behavior needs to die.
111         pad_up_to_bitrate_bps = static_cast<int>(
112             hysteresis_factor * active_streams[0].target_bitrate_bps + 0.5);
113       } else {
114         const size_t top_active_stream_idx = active_streams.size() - 1;
115         pad_up_to_bitrate_bps = std::min(
116             static_cast<int>(
117                 hysteresis_factor *
118                     active_streams[top_active_stream_idx].min_bitrate_bps +
119                 0.5),
120             active_streams[top_active_stream_idx].target_bitrate_bps);
121 
122         // Add target_bitrate_bps of the lower active streams.
123         for (size_t i = 0; i < top_active_stream_idx; ++i) {
124           pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
125         }
126       }
127     }
128   } else if (!active_streams.empty() && pad_to_min_bitrate) {
129     pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
130   }
131 
132   pad_up_to_bitrate_bps =
133       std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
134 
135   return pad_up_to_bitrate_bps;
136 }
137 
GetAlrSettings(VideoEncoderConfig::ContentType content_type)138 absl::optional<AlrExperimentSettings> GetAlrSettings(
139     VideoEncoderConfig::ContentType content_type) {
140   if (content_type == VideoEncoderConfig::ContentType::kScreen) {
141     return AlrExperimentSettings::CreateFromFieldTrial(
142         AlrExperimentSettings::kScreenshareProbingBweExperimentName);
143   }
144   return AlrExperimentSettings::CreateFromFieldTrial(
145       AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
146 }
147 
SameStreamsEnabled(const VideoBitrateAllocation & lhs,const VideoBitrateAllocation & rhs)148 bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
149                         const VideoBitrateAllocation& rhs) {
150   for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
151     for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
152       if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
153         return false;
154       }
155     }
156   }
157   return true;
158 }
159 
160 // Returns an optional that has value iff TransportSeqNumExtensionConfigured
161 // is `true` for the given video send stream config.
GetConfiguredPacingFactor(const VideoSendStream::Config & config,VideoEncoderConfig::ContentType content_type,const PacingConfig & default_pacing_config)162 absl::optional<float> GetConfiguredPacingFactor(
163     const VideoSendStream::Config& config,
164     VideoEncoderConfig::ContentType content_type,
165     const PacingConfig& default_pacing_config) {
166   if (!TransportSeqNumExtensionConfigured(config))
167     return absl::nullopt;
168 
169   absl::optional<AlrExperimentSettings> alr_settings =
170       GetAlrSettings(content_type);
171   if (alr_settings)
172     return alr_settings->pacing_factor;
173 
174   RateControlSettings rate_control_settings =
175       RateControlSettings::ParseFromFieldTrials();
176   return rate_control_settings.GetPacingFactor().value_or(
177       default_pacing_config.pacing_factor);
178 }
179 
GetInitialEncoderMaxBitrate(int initial_encoder_max_bitrate)180 uint32_t GetInitialEncoderMaxBitrate(int initial_encoder_max_bitrate) {
181   if (initial_encoder_max_bitrate > 0)
182     return rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
183 
184   // TODO(srte): Make sure max bitrate is not set to negative values. We don't
185   // have any way to handle unset values in downstream code, such as the
186   // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
187   // behaviour that is not safe. Converting to 10 Mbps should be safe for
188   // reasonable use cases as it allows adding the max of multiple streams
189   // without wrappping around.
190   const int kFallbackMaxBitrateBps = 10000000;
191   RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
192                      << initial_encoder_max_bitrate << " which is <= 0!";
193   RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
194   return kFallbackMaxBitrateBps;
195 }
196 
197 }  // namespace
198 
PacingConfig(const FieldTrialsView & field_trials)199 PacingConfig::PacingConfig(const FieldTrialsView& field_trials)
200     : pacing_factor("factor", kStrictPacingMultiplier),
201       max_pacing_delay("max_delay", PacingController::kMaxExpectedQueueLength) {
202   ParseFieldTrial({&pacing_factor, &max_pacing_delay},
203                   field_trials.Lookup("WebRTC-Video-Pacing"));
204 }
205 PacingConfig::PacingConfig(const PacingConfig&) = default;
206 PacingConfig::~PacingConfig() = default;
207 
VideoSendStreamImpl(Clock * clock,SendStatisticsProxy * stats_proxy,RtpTransportControllerSendInterface * transport,BitrateAllocatorInterface * bitrate_allocator,VideoStreamEncoderInterface * video_stream_encoder,const VideoSendStream::Config * config,int initial_encoder_max_bitrate,double initial_encoder_bitrate_priority,VideoEncoderConfig::ContentType content_type,RtpVideoSenderInterface * rtp_video_sender,const FieldTrialsView & field_trials)208 VideoSendStreamImpl::VideoSendStreamImpl(
209     Clock* clock,
210     SendStatisticsProxy* stats_proxy,
211     RtpTransportControllerSendInterface* transport,
212     BitrateAllocatorInterface* bitrate_allocator,
213     VideoStreamEncoderInterface* video_stream_encoder,
214     const VideoSendStream::Config* config,
215     int initial_encoder_max_bitrate,
216     double initial_encoder_bitrate_priority,
217     VideoEncoderConfig::ContentType content_type,
218     RtpVideoSenderInterface* rtp_video_sender,
219     const FieldTrialsView& field_trials)
220     : clock_(clock),
221       has_alr_probing_(config->periodic_alr_bandwidth_probing ||
222                        GetAlrSettings(content_type)),
223       pacing_config_(PacingConfig(field_trials)),
224       stats_proxy_(stats_proxy),
225       config_(config),
226       rtp_transport_queue_(transport->GetWorkerQueue()),
227       timed_out_(false),
228       transport_(transport),
229       bitrate_allocator_(bitrate_allocator),
230       disable_padding_(true),
231       max_padding_bitrate_(0),
232       encoder_min_bitrate_bps_(0),
233       encoder_max_bitrate_bps_(
234           GetInitialEncoderMaxBitrate(initial_encoder_max_bitrate)),
235       encoder_target_rate_bps_(0),
236       encoder_bitrate_priority_(initial_encoder_bitrate_priority),
237       video_stream_encoder_(video_stream_encoder),
238       bandwidth_observer_(transport->GetBandwidthObserver()),
239       rtp_video_sender_(rtp_video_sender),
240       configured_pacing_factor_(
241           GetConfiguredPacingFactor(*config_, content_type, pacing_config_)) {
242   RTC_DCHECK_GE(config_->rtp.payload_type, 0);
243   RTC_DCHECK_LE(config_->rtp.payload_type, 127);
244   RTC_DCHECK(!config_->rtp.ssrcs.empty());
245   RTC_DCHECK(transport_);
246   RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
247   RTC_LOG(LS_INFO) << "VideoSendStreamImpl: " << config_->ToString();
248 
249   RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
250 
251   // Only request rotation at the source when we positively know that the remote
252   // side doesn't support the rotation extension. This allows us to prepare the
253   // encoder in the expectation that rotation is supported - which is the common
254   // case.
255   bool rotation_applied = absl::c_none_of(
256       config_->rtp.extensions, [](const RtpExtension& extension) {
257         return extension.uri == RtpExtension::kVideoRotationUri;
258       });
259 
260   video_stream_encoder_->SetSink(this, rotation_applied);
261 
262   absl::optional<bool> enable_alr_bw_probing;
263 
264   // If send-side BWE is enabled, check if we should apply updated probing and
265   // pacing settings.
266   if (configured_pacing_factor_) {
267     absl::optional<AlrExperimentSettings> alr_settings =
268         GetAlrSettings(content_type);
269     int queue_time_limit_ms;
270     if (alr_settings) {
271       enable_alr_bw_probing = true;
272       queue_time_limit_ms = alr_settings->max_paced_queue_time;
273     } else {
274       RateControlSettings rate_control_settings =
275           RateControlSettings::ParseFromFieldTrials();
276       enable_alr_bw_probing = rate_control_settings.UseAlrProbing();
277       queue_time_limit_ms = pacing_config_.max_pacing_delay.Get().ms();
278     }
279 
280     transport->SetQueueTimeLimit(queue_time_limit_ms);
281   }
282 
283   if (config_->periodic_alr_bandwidth_probing) {
284     enable_alr_bw_probing = config_->periodic_alr_bandwidth_probing;
285   }
286 
287   if (enable_alr_bw_probing) {
288     transport->EnablePeriodicAlrProbing(*enable_alr_bw_probing);
289   }
290 
291   rtp_transport_queue_->RunOrPost(SafeTask(transport_queue_safety_, [this] {
292     if (configured_pacing_factor_)
293       transport_->SetPacingFactor(*configured_pacing_factor_);
294 
295     video_stream_encoder_->SetStartBitrate(
296         bitrate_allocator_->GetStartBitrate(this));
297   }));
298 }
299 
~VideoSendStreamImpl()300 VideoSendStreamImpl::~VideoSendStreamImpl() {
301   RTC_DCHECK_RUN_ON(&thread_checker_);
302   RTC_LOG(LS_INFO) << "~VideoSendStreamImpl: " << config_->ToString();
303   // TODO(webrtc:14502): Change `transport_queue_safety_` to be of type
304   // ScopedTaskSafety if experiment WebRTC-SendPacketsOnWorkerThread succeed.
305   if (rtp_transport_queue_->IsCurrent()) {
306     transport_queue_safety_->SetNotAlive();
307   }
308 }
309 
DeliverRtcp(const uint8_t * packet,size_t length)310 void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
311   // Runs on a worker thread.
312   rtp_video_sender_->DeliverRtcp(packet, length);
313 }
314 
StartPerRtpStream(const std::vector<bool> active_layers)315 void VideoSendStreamImpl::StartPerRtpStream(
316     const std::vector<bool> active_layers) {
317   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
318   bool previously_active = rtp_video_sender_->IsActive();
319   rtp_video_sender_->SetActiveModules(active_layers);
320   if (!rtp_video_sender_->IsActive() && previously_active) {
321     StopVideoSendStream();
322   } else if (rtp_video_sender_->IsActive() && !previously_active) {
323     StartupVideoSendStream();
324   }
325 }
326 
StartupVideoSendStream()327 void VideoSendStreamImpl::StartupVideoSendStream() {
328   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
329   transport_queue_safety_->SetAlive();
330 
331   bitrate_allocator_->AddObserver(this, GetAllocationConfig());
332   // Start monitoring encoder activity.
333   {
334     RTC_DCHECK(!check_encoder_activity_task_.Running());
335 
336     activity_ = false;
337     timed_out_ = false;
338     check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
339         rtp_transport_queue_->TaskQueueForDelayedTasks(), kEncoderTimeOut,
340         [this] {
341           RTC_DCHECK_RUN_ON(rtp_transport_queue_);
342           if (!activity_) {
343             if (!timed_out_) {
344               SignalEncoderTimedOut();
345             }
346             timed_out_ = true;
347             disable_padding_ = true;
348           } else if (timed_out_) {
349             SignalEncoderActive();
350             timed_out_ = false;
351           }
352           activity_ = false;
353           return kEncoderTimeOut;
354         });
355   }
356 
357   video_stream_encoder_->SendKeyFrame();
358 }
359 
Stop()360 void VideoSendStreamImpl::Stop() {
361   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
362   RTC_LOG(LS_INFO) << "VideoSendStreamImpl::Stop";
363   if (!rtp_video_sender_->IsActive())
364     return;
365 
366   RTC_DCHECK(transport_queue_safety_->alive());
367   TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
368   rtp_video_sender_->Stop();
369   StopVideoSendStream();
370 }
371 
StopVideoSendStream()372 void VideoSendStreamImpl::StopVideoSendStream() {
373   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
374   bitrate_allocator_->RemoveObserver(this);
375   check_encoder_activity_task_.Stop();
376   video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
377                                           DataRate::Zero(), 0, 0, 0);
378   stats_proxy_->OnSetEncoderTargetRate(0);
379   transport_queue_safety_->SetNotAlive();
380 }
381 
SignalEncoderTimedOut()382 void VideoSendStreamImpl::SignalEncoderTimedOut() {
383   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
384   // If the encoder has not produced anything the last kEncoderTimeOut and it
385   // is supposed to, deregister as BitrateAllocatorObserver. This can happen
386   // if a camera stops producing frames.
387   if (encoder_target_rate_bps_ > 0) {
388     RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
389     bitrate_allocator_->RemoveObserver(this);
390   }
391 }
392 
OnBitrateAllocationUpdated(const VideoBitrateAllocation & allocation)393 void VideoSendStreamImpl::OnBitrateAllocationUpdated(
394     const VideoBitrateAllocation& allocation) {
395   // OnBitrateAllocationUpdated is invoked from  the encoder task queue or
396   // the rtp_transport_queue_.
397   auto task = [=] {
398     RTC_DCHECK_RUN_ON(rtp_transport_queue_);
399     if (encoder_target_rate_bps_ == 0) {
400       return;
401     }
402     int64_t now_ms = clock_->TimeInMilliseconds();
403     if (video_bitrate_allocation_context_) {
404       // If new allocation is within kMaxVbaSizeDifferencePercent larger
405       // than the previously sent allocation and the same streams are still
406       // enabled, it is considered "similar". We do not want send similar
407       // allocations more once per kMaxVbaThrottleTimeMs.
408       const VideoBitrateAllocation& last =
409           video_bitrate_allocation_context_->last_sent_allocation;
410       const bool is_similar =
411           allocation.get_sum_bps() >= last.get_sum_bps() &&
412           allocation.get_sum_bps() <
413               (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
414                   100 &&
415           SameStreamsEnabled(allocation, last);
416       if (is_similar &&
417           (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
418               kMaxVbaThrottleTimeMs) {
419         // This allocation is too similar, cache it and return.
420         video_bitrate_allocation_context_->throttled_allocation = allocation;
421         return;
422       }
423     } else {
424       video_bitrate_allocation_context_.emplace();
425     }
426 
427     video_bitrate_allocation_context_->last_sent_allocation = allocation;
428     video_bitrate_allocation_context_->throttled_allocation.reset();
429     video_bitrate_allocation_context_->last_send_time_ms = now_ms;
430 
431     // Send bitrate allocation metadata only if encoder is not paused.
432     rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
433   };
434   if (!rtp_transport_queue_->IsCurrent()) {
435     rtp_transport_queue_->TaskQueueForPost()->PostTask(
436         SafeTask(transport_queue_safety_, std::move(task)));
437   } else {
438     task();
439   }
440 }
441 
OnVideoLayersAllocationUpdated(VideoLayersAllocation allocation)442 void VideoSendStreamImpl::OnVideoLayersAllocationUpdated(
443     VideoLayersAllocation allocation) {
444   // OnVideoLayersAllocationUpdated is handled on the encoder task queue in
445   // order to not race with OnEncodedImage callbacks.
446   rtp_video_sender_->OnVideoLayersAllocationUpdated(allocation);
447 }
448 
SignalEncoderActive()449 void VideoSendStreamImpl::SignalEncoderActive() {
450   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
451   if (rtp_video_sender_->IsActive()) {
452     RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
453     bitrate_allocator_->AddObserver(this, GetAllocationConfig());
454   }
455 }
456 
GetAllocationConfig() const457 MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
458   return MediaStreamAllocationConfig{
459       static_cast<uint32_t>(encoder_min_bitrate_bps_),
460       encoder_max_bitrate_bps_,
461       static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
462       /* priority_bitrate */ 0,
463       !config_->suspend_below_min_bitrate,
464       encoder_bitrate_priority_};
465 }
466 
OnEncoderConfigurationChanged(std::vector<VideoStream> streams,bool is_svc,VideoEncoderConfig::ContentType content_type,int min_transmit_bitrate_bps)467 void VideoSendStreamImpl::OnEncoderConfigurationChanged(
468     std::vector<VideoStream> streams,
469     bool is_svc,
470     VideoEncoderConfig::ContentType content_type,
471     int min_transmit_bitrate_bps) {
472   // Currently called on the encoder TQ
473   RTC_DCHECK(!rtp_transport_queue_->IsCurrent());
474   auto closure = [this, streams = std::move(streams), is_svc, content_type,
475                   min_transmit_bitrate_bps]() mutable {
476     RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
477     TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
478     RTC_DCHECK_RUN_ON(rtp_transport_queue_);
479 
480     const VideoCodecType codec_type =
481         PayloadStringToCodecType(config_->rtp.payload_name);
482 
483     const absl::optional<DataRate> experimental_min_bitrate =
484         GetExperimentalMinVideoBitrate(codec_type);
485     encoder_min_bitrate_bps_ =
486         experimental_min_bitrate
487             ? experimental_min_bitrate->bps()
488             : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
489 
490     encoder_max_bitrate_bps_ = 0;
491     double stream_bitrate_priority_sum = 0;
492     for (const auto& stream : streams) {
493       // We don't want to allocate more bitrate than needed to inactive streams.
494       encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
495       if (stream.bitrate_priority) {
496         RTC_DCHECK_GT(*stream.bitrate_priority, 0);
497         stream_bitrate_priority_sum += *stream.bitrate_priority;
498       }
499     }
500     RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
501     encoder_bitrate_priority_ = stream_bitrate_priority_sum;
502     encoder_max_bitrate_bps_ =
503         std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
504                  encoder_max_bitrate_bps_);
505 
506     // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
507     max_padding_bitrate_ = CalculateMaxPadBitrateBps(
508         streams, is_svc, content_type, min_transmit_bitrate_bps,
509         config_->suspend_below_min_bitrate, has_alr_probing_);
510 
511     // Clear stats for disabled layers.
512     for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
513       stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
514     }
515 
516     const size_t num_temporal_layers =
517         streams.back().num_temporal_layers.value_or(1);
518 
519     rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
520                                        num_temporal_layers);
521 
522     if (rtp_video_sender_->IsActive()) {
523       // The send stream is started already. Update the allocator with new
524       // bitrate limits.
525       bitrate_allocator_->AddObserver(this, GetAllocationConfig());
526     }
527   };
528 
529   rtp_transport_queue_->TaskQueueForPost()->PostTask(
530       SafeTask(transport_queue_safety_, std::move(closure)));
531 }
532 
OnEncodedImage(const EncodedImage & encoded_image,const CodecSpecificInfo * codec_specific_info)533 EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
534     const EncodedImage& encoded_image,
535     const CodecSpecificInfo* codec_specific_info) {
536   // Encoded is called on whatever thread the real encoder implementation run
537   // on. In the case of hardware encoders, there might be several encoders
538   // running in parallel on different threads.
539 
540   // Indicate that there still is activity going on.
541   activity_ = true;
542   RTC_DCHECK(!rtp_transport_queue_->IsCurrent());
543 
544   auto task_to_run_on_worker = [this]() {
545     RTC_DCHECK_RUN_ON(rtp_transport_queue_);
546     if (disable_padding_) {
547       disable_padding_ = false;
548       // To ensure that padding bitrate is propagated to the bitrate allocator.
549       SignalEncoderActive();
550     }
551     // Check if there's a throttled VideoBitrateAllocation that we should try
552     // sending.
553     auto& context = video_bitrate_allocation_context_;
554     if (context && context->throttled_allocation) {
555       OnBitrateAllocationUpdated(*context->throttled_allocation);
556     }
557   };
558   rtp_transport_queue_->TaskQueueForPost()->PostTask(
559       SafeTask(transport_queue_safety_, std::move(task_to_run_on_worker)));
560 
561   return rtp_video_sender_->OnEncodedImage(encoded_image, codec_specific_info);
562 }
563 
OnDroppedFrame(EncodedImageCallback::DropReason reason)564 void VideoSendStreamImpl::OnDroppedFrame(
565     EncodedImageCallback::DropReason reason) {
566   activity_ = true;
567 }
568 
GetRtpStates() const569 std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
570   return rtp_video_sender_->GetRtpStates();
571 }
572 
GetRtpPayloadStates() const573 std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
574     const {
575   return rtp_video_sender_->GetRtpPayloadStates();
576 }
577 
OnBitrateUpdated(BitrateAllocationUpdate update)578 uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
579   RTC_DCHECK_RUN_ON(rtp_transport_queue_);
580   RTC_DCHECK(rtp_video_sender_->IsActive())
581       << "VideoSendStream::Start has not been called.";
582 
583   // When the BWE algorithm doesn't pass a stable estimate, we'll use the
584   // unstable one instead.
585   if (update.stable_target_bitrate.IsZero()) {
586     update.stable_target_bitrate = update.target_bitrate;
587   }
588 
589   rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
590   encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
591   const uint32_t protection_bitrate_bps =
592       rtp_video_sender_->GetProtectionBitrateBps();
593   DataRate link_allocation = DataRate::Zero();
594   if (encoder_target_rate_bps_ > protection_bitrate_bps) {
595     link_allocation =
596         DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps);
597   }
598   DataRate overhead =
599       update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_);
600   DataRate encoder_stable_target_rate = update.stable_target_bitrate;
601   if (encoder_stable_target_rate > overhead) {
602     encoder_stable_target_rate = encoder_stable_target_rate - overhead;
603   } else {
604     encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
605   }
606 
607   encoder_target_rate_bps_ =
608       std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
609 
610   encoder_stable_target_rate =
611       std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_),
612                encoder_stable_target_rate);
613 
614   DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_);
615   link_allocation = std::max(encoder_target_rate, link_allocation);
616   video_stream_encoder_->OnBitrateUpdated(
617       encoder_target_rate, encoder_stable_target_rate, link_allocation,
618       rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
619       update.round_trip_time.ms(), update.cwnd_reduce_ratio);
620   stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
621   return protection_bitrate_bps;
622 }
623 
624 }  // namespace internal
625 }  // namespace webrtc
626