xref: /aosp_15_r20/external/webrtc/modules/pacing/pacing_controller.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2019 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 
11 #include "modules/pacing/pacing_controller.h"
12 
13 #include <algorithm>
14 #include <memory>
15 #include <utility>
16 #include <vector>
17 
18 #include "absl/strings/match.h"
19 #include "modules/pacing/bitrate_prober.h"
20 #include "modules/pacing/interval_budget.h"
21 #include "rtc_base/checks.h"
22 #include "rtc_base/experiments/field_trial_parser.h"
23 #include "rtc_base/logging.h"
24 #include "rtc_base/time_utils.h"
25 #include "system_wrappers/include/clock.h"
26 
27 namespace webrtc {
28 namespace {
29 // Time limit in milliseconds between packet bursts.
30 constexpr TimeDelta kDefaultMinPacketLimit = TimeDelta::Millis(5);
31 constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis(500);
32 // TODO(sprang): Consider dropping this limit.
33 // The maximum debt level, in terms of time, capped when sending packets.
34 constexpr TimeDelta kMaxDebtInTime = TimeDelta::Millis(500);
35 constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds(2);
36 
IsDisabled(const FieldTrialsView & field_trials,absl::string_view key)37 bool IsDisabled(const FieldTrialsView& field_trials, absl::string_view key) {
38   return absl::StartsWith(field_trials.Lookup(key), "Disabled");
39 }
40 
IsEnabled(const FieldTrialsView & field_trials,absl::string_view key)41 bool IsEnabled(const FieldTrialsView& field_trials, absl::string_view key) {
42   return absl::StartsWith(field_trials.Lookup(key), "Enabled");
43 }
44 
45 }  // namespace
46 
47 const TimeDelta PacingController::kMaxExpectedQueueLength =
48     TimeDelta::Millis(2000);
49 const TimeDelta PacingController::kPausedProcessInterval =
50     kCongestedPacketInterval;
51 const TimeDelta PacingController::kMinSleepTime = TimeDelta::Millis(1);
52 const TimeDelta PacingController::kTargetPaddingDuration = TimeDelta::Millis(5);
53 const TimeDelta PacingController::kMaxPaddingReplayDuration =
54     TimeDelta::Millis(50);
55 const TimeDelta PacingController::kMaxEarlyProbeProcessing =
56     TimeDelta::Millis(1);
57 
PacingController(Clock * clock,PacketSender * packet_sender,const FieldTrialsView & field_trials)58 PacingController::PacingController(Clock* clock,
59                                    PacketSender* packet_sender,
60                                    const FieldTrialsView& field_trials)
61     : clock_(clock),
62       packet_sender_(packet_sender),
63       field_trials_(field_trials),
64       drain_large_queues_(
65           !IsDisabled(field_trials_, "WebRTC-Pacer-DrainQueue")),
66       send_padding_if_silent_(
67           IsEnabled(field_trials_, "WebRTC-Pacer-PadInSilence")),
68       pace_audio_(IsEnabled(field_trials_, "WebRTC-Pacer-BlockAudio")),
69       ignore_transport_overhead_(
70           IsEnabled(field_trials_, "WebRTC-Pacer-IgnoreTransportOverhead")),
71       fast_retransmissions_(
72           IsEnabled(field_trials_, "WebRTC-Pacer-FastRetransmissions")),
73       min_packet_limit_(kDefaultMinPacketLimit),
74       transport_overhead_per_packet_(DataSize::Zero()),
75       send_burst_interval_(TimeDelta::Zero()),
76       last_timestamp_(clock_->CurrentTime()),
77       paused_(false),
78       media_debt_(DataSize::Zero()),
79       padding_debt_(DataSize::Zero()),
80       pacing_rate_(DataRate::Zero()),
81       adjusted_media_rate_(DataRate::Zero()),
82       padding_rate_(DataRate::Zero()),
83       prober_(field_trials_),
84       probing_send_failure_(false),
85       last_process_time_(clock->CurrentTime()),
86       last_send_time_(last_process_time_),
87       seen_first_packet_(false),
88       packet_queue_(/*creation_time=*/last_process_time_),
89       congested_(false),
90       queue_time_limit_(kMaxExpectedQueueLength),
91       account_for_audio_(false),
92       include_overhead_(false),
93       circuit_breaker_threshold_(1 << 16) {
94   if (!drain_large_queues_) {
95     RTC_LOG(LS_WARNING) << "Pacer queues will not be drained,"
96                            "pushback experiment must be enabled.";
97   }
98   FieldTrialParameter<int> min_packet_limit_ms("", min_packet_limit_.ms());
99   ParseFieldTrial({&min_packet_limit_ms},
100                   field_trials_.Lookup("WebRTC-Pacer-MinPacketLimitMs"));
101   min_packet_limit_ = TimeDelta::Millis(min_packet_limit_ms.Get());
102   UpdateBudgetWithElapsedTime(min_packet_limit_);
103 }
104 
105 PacingController::~PacingController() = default;
106 
CreateProbeCluster(DataRate bitrate,int cluster_id)107 void PacingController::CreateProbeCluster(DataRate bitrate, int cluster_id) {
108   prober_.CreateProbeCluster({.at_time = CurrentTime(),
109                               .target_data_rate = bitrate,
110                               .target_duration = TimeDelta::Millis(15),
111                               .target_probe_count = 5,
112                               .id = cluster_id});
113 }
114 
CreateProbeClusters(rtc::ArrayView<const ProbeClusterConfig> probe_cluster_configs)115 void PacingController::CreateProbeClusters(
116     rtc::ArrayView<const ProbeClusterConfig> probe_cluster_configs) {
117   for (const ProbeClusterConfig probe_cluster_config : probe_cluster_configs) {
118     prober_.CreateProbeCluster(probe_cluster_config);
119   }
120 }
121 
Pause()122 void PacingController::Pause() {
123   if (!paused_)
124     RTC_LOG(LS_INFO) << "PacedSender paused.";
125   paused_ = true;
126   packet_queue_.SetPauseState(true, CurrentTime());
127 }
128 
Resume()129 void PacingController::Resume() {
130   if (paused_)
131     RTC_LOG(LS_INFO) << "PacedSender resumed.";
132   paused_ = false;
133   packet_queue_.SetPauseState(false, CurrentTime());
134 }
135 
IsPaused() const136 bool PacingController::IsPaused() const {
137   return paused_;
138 }
139 
SetCongested(bool congested)140 void PacingController::SetCongested(bool congested) {
141   if (congested_ && !congested) {
142     UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(CurrentTime()));
143   }
144   congested_ = congested;
145 }
146 
SetCircuitBreakerThreshold(int num_iterations)147 void PacingController::SetCircuitBreakerThreshold(int num_iterations) {
148   circuit_breaker_threshold_ = num_iterations;
149 }
150 
IsProbing() const151 bool PacingController::IsProbing() const {
152   return prober_.is_probing();
153 }
154 
CurrentTime() const155 Timestamp PacingController::CurrentTime() const {
156   Timestamp time = clock_->CurrentTime();
157   if (time < last_timestamp_) {
158     RTC_LOG(LS_WARNING)
159         << "Non-monotonic clock behavior observed. Previous timestamp: "
160         << last_timestamp_.ms() << ", new timestamp: " << time.ms();
161     RTC_DCHECK_GE(time, last_timestamp_);
162     time = last_timestamp_;
163   }
164   last_timestamp_ = time;
165   return time;
166 }
167 
SetProbingEnabled(bool enabled)168 void PacingController::SetProbingEnabled(bool enabled) {
169   RTC_CHECK(!seen_first_packet_);
170   prober_.SetEnabled(enabled);
171 }
172 
SetPacingRates(DataRate pacing_rate,DataRate padding_rate)173 void PacingController::SetPacingRates(DataRate pacing_rate,
174                                       DataRate padding_rate) {
175   static constexpr DataRate kMaxRate = DataRate::KilobitsPerSec(100'000);
176   RTC_CHECK_GT(pacing_rate, DataRate::Zero());
177   RTC_CHECK_GE(padding_rate, DataRate::Zero());
178   if (padding_rate > pacing_rate) {
179     RTC_LOG(LS_WARNING) << "Padding rate " << padding_rate.kbps()
180                         << "kbps is higher than the pacing rate "
181                         << pacing_rate.kbps() << "kbps, capping.";
182     padding_rate = pacing_rate;
183   }
184 
185   if (pacing_rate > kMaxRate || padding_rate > kMaxRate) {
186     RTC_LOG(LS_WARNING) << "Very high pacing rates ( > " << kMaxRate.kbps()
187                         << " kbps) configured: pacing = " << pacing_rate.kbps()
188                         << " kbps, padding = " << padding_rate.kbps()
189                         << " kbps.";
190   }
191   pacing_rate_ = pacing_rate;
192   padding_rate_ = padding_rate;
193   MaybeUpdateMediaRateDueToLongQueue(CurrentTime());
194 
195   RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps=" << pacing_rate_.kbps()
196                       << " padding_budget_kbps=" << padding_rate.kbps();
197 }
198 
EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet)199 void PacingController::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) {
200   RTC_DCHECK(pacing_rate_ > DataRate::Zero())
201       << "SetPacingRate must be called before InsertPacket.";
202   RTC_CHECK(packet->packet_type());
203 
204   prober_.OnIncomingPacket(DataSize::Bytes(packet->payload_size()));
205 
206   const Timestamp now = CurrentTime();
207   if (packet_queue_.Empty()) {
208     // If queue is empty, we need to "fast-forward" the last process time,
209     // so that we don't use passed time as budget for sending the first new
210     // packet.
211     Timestamp target_process_time = now;
212     Timestamp next_send_time = NextSendTime();
213     if (next_send_time.IsFinite()) {
214       // There was already a valid planned send time, such as a keep-alive.
215       // Use that as last process time only if it's prior to now.
216       target_process_time = std::min(now, next_send_time);
217     }
218     UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(target_process_time));
219   }
220   packet_queue_.Push(now, std::move(packet));
221   seen_first_packet_ = true;
222 
223   // Queue length has increased, check if we need to change the pacing rate.
224   MaybeUpdateMediaRateDueToLongQueue(now);
225 }
226 
SetAccountForAudioPackets(bool account_for_audio)227 void PacingController::SetAccountForAudioPackets(bool account_for_audio) {
228   account_for_audio_ = account_for_audio;
229 }
230 
SetIncludeOverhead()231 void PacingController::SetIncludeOverhead() {
232   include_overhead_ = true;
233 }
234 
SetTransportOverhead(DataSize overhead_per_packet)235 void PacingController::SetTransportOverhead(DataSize overhead_per_packet) {
236   if (ignore_transport_overhead_)
237     return;
238   transport_overhead_per_packet_ = overhead_per_packet;
239 }
240 
SetSendBurstInterval(TimeDelta burst_interval)241 void PacingController::SetSendBurstInterval(TimeDelta burst_interval) {
242   send_burst_interval_ = burst_interval;
243 }
244 
ExpectedQueueTime() const245 TimeDelta PacingController::ExpectedQueueTime() const {
246   RTC_DCHECK_GT(adjusted_media_rate_, DataRate::Zero());
247   return QueueSizeData() / adjusted_media_rate_;
248 }
249 
QueueSizePackets() const250 size_t PacingController::QueueSizePackets() const {
251   return rtc::checked_cast<size_t>(packet_queue_.SizeInPackets());
252 }
253 
254 const std::array<int, kNumMediaTypes>&
SizeInPacketsPerRtpPacketMediaType() const255 PacingController::SizeInPacketsPerRtpPacketMediaType() const {
256   return packet_queue_.SizeInPacketsPerRtpPacketMediaType();
257 }
258 
QueueSizeData() const259 DataSize PacingController::QueueSizeData() const {
260   DataSize size = packet_queue_.SizeInPayloadBytes();
261   if (include_overhead_) {
262     size += static_cast<int64_t>(packet_queue_.SizeInPackets()) *
263             transport_overhead_per_packet_;
264   }
265   return size;
266 }
267 
CurrentBufferLevel() const268 DataSize PacingController::CurrentBufferLevel() const {
269   return std::max(media_debt_, padding_debt_);
270 }
271 
FirstSentPacketTime() const272 absl::optional<Timestamp> PacingController::FirstSentPacketTime() const {
273   return first_sent_packet_time_;
274 }
275 
OldestPacketEnqueueTime() const276 Timestamp PacingController::OldestPacketEnqueueTime() const {
277   return packet_queue_.OldestEnqueueTime();
278 }
279 
UpdateTimeAndGetElapsed(Timestamp now)280 TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) {
281   // If no previous processing, or last process was "in the future" because of
282   // early probe processing, then there is no elapsed time to add budget for.
283   if (last_process_time_.IsMinusInfinity() || now < last_process_time_) {
284     return TimeDelta::Zero();
285   }
286   TimeDelta elapsed_time = now - last_process_time_;
287   last_process_time_ = now;
288   if (elapsed_time > kMaxElapsedTime) {
289     RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time.ms()
290                         << " ms) longer than expected, limiting to "
291                         << kMaxElapsedTime.ms();
292     elapsed_time = kMaxElapsedTime;
293   }
294   return elapsed_time;
295 }
296 
ShouldSendKeepalive(Timestamp now) const297 bool PacingController::ShouldSendKeepalive(Timestamp now) const {
298   if (send_padding_if_silent_ || paused_ || congested_ || !seen_first_packet_) {
299     // We send a padding packet every 500 ms to ensure we won't get stuck in
300     // congested state due to no feedback being received.
301     if (now - last_send_time_ >= kCongestedPacketInterval) {
302       return true;
303     }
304   }
305   return false;
306 }
307 
NextSendTime() const308 Timestamp PacingController::NextSendTime() const {
309   const Timestamp now = CurrentTime();
310   Timestamp next_send_time = Timestamp::PlusInfinity();
311 
312   if (paused_) {
313     return last_send_time_ + kPausedProcessInterval;
314   }
315 
316   // If probing is active, that always takes priority.
317   if (prober_.is_probing() && !probing_send_failure_) {
318     Timestamp probe_time = prober_.NextProbeTime(now);
319     if (!probe_time.IsPlusInfinity()) {
320       return probe_time.IsMinusInfinity() ? now : probe_time;
321     }
322   }
323 
324   // If queue contains a packet which should not be paced, its target send time
325   // is the time at which it was enqueued.
326   Timestamp unpaced_send_time = NextUnpacedSendTime();
327   if (unpaced_send_time.IsFinite()) {
328     return unpaced_send_time;
329   }
330 
331   if (congested_ || !seen_first_packet_) {
332     // We need to at least send keep-alive packets with some interval.
333     return last_send_time_ + kCongestedPacketInterval;
334   }
335 
336   if (adjusted_media_rate_ > DataRate::Zero() && !packet_queue_.Empty()) {
337     // If packets are allowed to be sent in a burst, the
338     // debt is allowed to grow up to one packet more than what can be sent
339     // during 'send_burst_period_'.
340     TimeDelta drain_time = media_debt_ / adjusted_media_rate_;
341     next_send_time =
342         last_process_time_ +
343         ((send_burst_interval_ > drain_time) ? TimeDelta::Zero() : drain_time);
344   } else if (padding_rate_ > DataRate::Zero() && packet_queue_.Empty()) {
345     // If we _don't_ have pending packets, check how long until we have
346     // bandwidth for padding packets. Both media and padding debts must
347     // have been drained to do this.
348     RTC_DCHECK_GT(adjusted_media_rate_, DataRate::Zero());
349     TimeDelta drain_time = std::max(media_debt_ / adjusted_media_rate_,
350                                     padding_debt_ / padding_rate_);
351 
352     if (drain_time.IsZero() &&
353         (!media_debt_.IsZero() || !padding_debt_.IsZero())) {
354       // We have a non-zero debt, but drain time is smaller than tick size of
355       // TimeDelta, round it up to the smallest possible non-zero delta.
356       drain_time = TimeDelta::Micros(1);
357     }
358     next_send_time = last_process_time_ + drain_time;
359   } else {
360     // Nothing to do.
361     next_send_time = last_process_time_ + kPausedProcessInterval;
362   }
363 
364   if (send_padding_if_silent_) {
365     next_send_time =
366         std::min(next_send_time, last_send_time_ + kPausedProcessInterval);
367   }
368 
369   return next_send_time;
370 }
371 
ProcessPackets()372 void PacingController::ProcessPackets() {
373   const Timestamp now = CurrentTime();
374   Timestamp target_send_time = now;
375 
376   if (ShouldSendKeepalive(now)) {
377     DataSize keepalive_data_sent = DataSize::Zero();
378     // We can not send padding unless a normal packet has first been sent. If
379     // we do, timestamps get messed up.
380     if (seen_first_packet_) {
381       std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
382           packet_sender_->GeneratePadding(DataSize::Bytes(1));
383       for (auto& packet : keepalive_packets) {
384         keepalive_data_sent +=
385             DataSize::Bytes(packet->payload_size() + packet->padding_size());
386         packet_sender_->SendPacket(std::move(packet), PacedPacketInfo());
387         for (auto& packet : packet_sender_->FetchFec()) {
388           EnqueuePacket(std::move(packet));
389         }
390       }
391     }
392     OnPacketSent(RtpPacketMediaType::kPadding, keepalive_data_sent, now);
393   }
394 
395   if (paused_) {
396     return;
397   }
398 
399   TimeDelta early_execute_margin =
400       prober_.is_probing() ? kMaxEarlyProbeProcessing : TimeDelta::Zero();
401 
402   target_send_time = NextSendTime();
403   if (now + early_execute_margin < target_send_time) {
404     // We are too early, but if queue is empty still allow draining some debt.
405     // Probing is allowed to be sent up to kMinSleepTime early.
406     UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(now));
407     return;
408   }
409 
410   TimeDelta elapsed_time = UpdateTimeAndGetElapsed(target_send_time);
411 
412   if (elapsed_time > TimeDelta::Zero()) {
413     UpdateBudgetWithElapsedTime(elapsed_time);
414   }
415 
416   PacedPacketInfo pacing_info;
417   DataSize recommended_probe_size = DataSize::Zero();
418   bool is_probing = prober_.is_probing();
419   if (is_probing) {
420     // Probe timing is sensitive, and handled explicitly by BitrateProber, so
421     // use actual send time rather than target.
422     pacing_info = prober_.CurrentCluster(now).value_or(PacedPacketInfo());
423     if (pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe) {
424       recommended_probe_size = prober_.RecommendedMinProbeSize();
425       RTC_DCHECK_GT(recommended_probe_size, DataSize::Zero());
426     } else {
427       // No valid probe cluster returned, probe might have timed out.
428       is_probing = false;
429     }
430   }
431 
432   DataSize data_sent = DataSize::Zero();
433   int iteration = 0;
434   int packets_sent = 0;
435   int padding_packets_generated = 0;
436   for (; iteration < circuit_breaker_threshold_; ++iteration) {
437     // Fetch packet, so long as queue is not empty or budget is not
438     // exhausted.
439     std::unique_ptr<RtpPacketToSend> rtp_packet =
440         GetPendingPacket(pacing_info, target_send_time, now);
441     if (rtp_packet == nullptr) {
442       // No packet available to send, check if we should send padding.
443       if (now - target_send_time > kMaxPaddingReplayDuration) {
444         // The target send time is more than `kMaxPaddingReplayDuration` behind
445         // the real-time clock. This can happen if the clock is adjusted forward
446         // without `ProcessPackets()` having been called at the expected times.
447         target_send_time = now - kMaxPaddingReplayDuration;
448         last_process_time_ = std::max(last_process_time_, target_send_time);
449       }
450 
451       DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
452       if (padding_to_add > DataSize::Zero()) {
453         std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
454             packet_sender_->GeneratePadding(padding_to_add);
455         if (!padding_packets.empty()) {
456           padding_packets_generated += padding_packets.size();
457           for (auto& packet : padding_packets) {
458             EnqueuePacket(std::move(packet));
459           }
460           // Continue loop to send the padding that was just added.
461           continue;
462         } else {
463           // Can't generate padding, still update padding budget for next send
464           // time.
465           UpdatePaddingBudgetWithSentData(padding_to_add);
466         }
467       }
468       // Can't fetch new packet and no padding to send, exit send loop.
469       break;
470     } else {
471       RTC_DCHECK(rtp_packet);
472       RTC_DCHECK(rtp_packet->packet_type().has_value());
473       const RtpPacketMediaType packet_type = *rtp_packet->packet_type();
474       DataSize packet_size = DataSize::Bytes(rtp_packet->payload_size() +
475                                              rtp_packet->padding_size());
476 
477       if (include_overhead_) {
478         packet_size += DataSize::Bytes(rtp_packet->headers_size()) +
479                        transport_overhead_per_packet_;
480       }
481 
482       packet_sender_->SendPacket(std::move(rtp_packet), pacing_info);
483       for (auto& packet : packet_sender_->FetchFec()) {
484         EnqueuePacket(std::move(packet));
485       }
486       data_sent += packet_size;
487       ++packets_sent;
488 
489       // Send done, update send time.
490       OnPacketSent(packet_type, packet_size, now);
491 
492       if (is_probing) {
493         pacing_info.probe_cluster_bytes_sent += packet_size.bytes();
494         // If we are currently probing, we need to stop the send loop when we
495         // have reached the send target.
496         if (data_sent >= recommended_probe_size) {
497           break;
498         }
499       }
500 
501       // Update target send time in case that are more packets that we are late
502       // in processing.
503       target_send_time = NextSendTime();
504       if (target_send_time > now) {
505         // Exit loop if not probing.
506         if (!is_probing) {
507           break;
508         }
509         target_send_time = now;
510       }
511       UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(target_send_time));
512     }
513   }
514 
515   if (iteration >= circuit_breaker_threshold_) {
516     // Circuit break activated. Log warning, adjust send time and return.
517     // TODO(sprang): Consider completely clearing state.
518     RTC_LOG(LS_ERROR)
519         << "PacingController exceeded max iterations in "
520            "send-loop. Debug info: "
521         << " packets sent = " << packets_sent
522         << ", padding packets generated = " << padding_packets_generated
523         << ", bytes sent = " << data_sent.bytes()
524         << ", probing = " << (is_probing ? "true" : "false")
525         << ", recommended_probe_size = " << recommended_probe_size.bytes()
526         << ", now = " << now.us()
527         << ", target_send_time = " << target_send_time.us()
528         << ", last_process_time = " << last_process_time_.us()
529         << ", last_send_time = " << last_send_time_.us()
530         << ", paused = " << (paused_ ? "true" : "false")
531         << ", media_debt = " << media_debt_.bytes()
532         << ", padding_debt = " << padding_debt_.bytes()
533         << ", pacing_rate = " << pacing_rate_.bps()
534         << ", adjusted_media_rate = " << adjusted_media_rate_.bps()
535         << ", padding_rate = " << padding_rate_.bps()
536         << ", queue size (packets) = " << packet_queue_.SizeInPackets()
537         << ", queue size (payload bytes) = "
538         << packet_queue_.SizeInPayloadBytes();
539     last_send_time_ = now;
540     last_process_time_ = now;
541     return;
542   }
543 
544   if (is_probing) {
545     probing_send_failure_ = data_sent == DataSize::Zero();
546     if (!probing_send_failure_) {
547       prober_.ProbeSent(CurrentTime(), data_sent);
548     }
549   }
550 
551   // Queue length has probably decreased, check if pacing rate needs to updated.
552   // Poll the time again, since we might have enqueued new fec/padding packets
553   // with a later timestamp than `now`.
554   MaybeUpdateMediaRateDueToLongQueue(CurrentTime());
555 }
556 
PaddingToAdd(DataSize recommended_probe_size,DataSize data_sent) const557 DataSize PacingController::PaddingToAdd(DataSize recommended_probe_size,
558                                         DataSize data_sent) const {
559   if (!packet_queue_.Empty()) {
560     // Actual payload available, no need to add padding.
561     return DataSize::Zero();
562   }
563 
564   if (congested_) {
565     // Don't add padding if congested, even if requested for probing.
566     return DataSize::Zero();
567   }
568 
569   if (!seen_first_packet_) {
570     // We can not send padding unless a normal packet has first been sent. If
571     // we do, timestamps get messed up.
572     return DataSize::Zero();
573   }
574 
575   if (!recommended_probe_size.IsZero()) {
576     if (recommended_probe_size > data_sent) {
577       return recommended_probe_size - data_sent;
578     }
579     return DataSize::Zero();
580   }
581 
582   if (padding_rate_ > DataRate::Zero() && padding_debt_ == DataSize::Zero()) {
583     return kTargetPaddingDuration * padding_rate_;
584   }
585   return DataSize::Zero();
586 }
587 
GetPendingPacket(const PacedPacketInfo & pacing_info,Timestamp target_send_time,Timestamp now)588 std::unique_ptr<RtpPacketToSend> PacingController::GetPendingPacket(
589     const PacedPacketInfo& pacing_info,
590     Timestamp target_send_time,
591     Timestamp now) {
592   const bool is_probe =
593       pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe;
594   // If first packet in probe, insert a small padding packet so we have a
595   // more reliable start window for the rate estimation.
596   if (is_probe && pacing_info.probe_cluster_bytes_sent == 0) {
597     auto padding = packet_sender_->GeneratePadding(DataSize::Bytes(1));
598     // If no RTP modules sending media are registered, we may not get a
599     // padding packet back.
600     if (!padding.empty()) {
601       // We should never get more than one padding packets with a requested
602       // size of 1 byte.
603       RTC_DCHECK_EQ(padding.size(), 1u);
604       return std::move(padding[0]);
605     }
606   }
607 
608   if (packet_queue_.Empty()) {
609     return nullptr;
610   }
611 
612   // First, check if there is any reason _not_ to send the next queued packet.
613   // Unpaced packets and probes are exempted from send checks.
614   if (NextUnpacedSendTime().IsInfinite() && !is_probe) {
615     if (congested_) {
616       // Don't send anything if congested.
617       return nullptr;
618     }
619 
620     if (now <= target_send_time && send_burst_interval_.IsZero()) {
621       // We allow sending slightly early if we think that we would actually
622       // had been able to, had we been right on time - i.e. the current debt
623       // is not more than would be reduced to zero at the target sent time.
624       // If we allow packets to be sent in a burst, packet are allowed to be
625       // sent early.
626       TimeDelta flush_time = media_debt_ / adjusted_media_rate_;
627       if (now + flush_time > target_send_time) {
628         return nullptr;
629       }
630     }
631   }
632 
633   return packet_queue_.Pop();
634 }
635 
OnPacketSent(RtpPacketMediaType packet_type,DataSize packet_size,Timestamp send_time)636 void PacingController::OnPacketSent(RtpPacketMediaType packet_type,
637                                     DataSize packet_size,
638                                     Timestamp send_time) {
639   if (!first_sent_packet_time_ && packet_type != RtpPacketMediaType::kPadding) {
640     first_sent_packet_time_ = send_time;
641   }
642 
643   bool audio_packet = packet_type == RtpPacketMediaType::kAudio;
644   if ((!audio_packet || account_for_audio_) && packet_size > DataSize::Zero()) {
645     UpdateBudgetWithSentData(packet_size);
646   }
647 
648   last_send_time_ = send_time;
649 }
650 
UpdateBudgetWithElapsedTime(TimeDelta delta)651 void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
652   media_debt_ -= std::min(media_debt_, adjusted_media_rate_ * delta);
653   padding_debt_ -= std::min(padding_debt_, padding_rate_ * delta);
654 }
655 
UpdateBudgetWithSentData(DataSize size)656 void PacingController::UpdateBudgetWithSentData(DataSize size) {
657   media_debt_ += size;
658   media_debt_ = std::min(media_debt_, adjusted_media_rate_ * kMaxDebtInTime);
659   UpdatePaddingBudgetWithSentData(size);
660 }
661 
UpdatePaddingBudgetWithSentData(DataSize size)662 void PacingController::UpdatePaddingBudgetWithSentData(DataSize size) {
663   padding_debt_ += size;
664   padding_debt_ = std::min(padding_debt_, padding_rate_ * kMaxDebtInTime);
665 }
666 
SetQueueTimeLimit(TimeDelta limit)667 void PacingController::SetQueueTimeLimit(TimeDelta limit) {
668   queue_time_limit_ = limit;
669 }
670 
MaybeUpdateMediaRateDueToLongQueue(Timestamp now)671 void PacingController::MaybeUpdateMediaRateDueToLongQueue(Timestamp now) {
672   adjusted_media_rate_ = pacing_rate_;
673   if (!drain_large_queues_) {
674     return;
675   }
676 
677   DataSize queue_size_data = QueueSizeData();
678   if (queue_size_data > DataSize::Zero()) {
679     // Assuming equal size packets and input/output rate, the average packet
680     // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
681     // time constraint shall be met. Determine bitrate needed for that.
682     packet_queue_.UpdateAverageQueueTime(now);
683     TimeDelta avg_time_left =
684         std::max(TimeDelta::Millis(1),
685                  queue_time_limit_ - packet_queue_.AverageQueueTime());
686     DataRate min_rate_needed = queue_size_data / avg_time_left;
687     if (min_rate_needed > pacing_rate_) {
688       adjusted_media_rate_ = min_rate_needed;
689       RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
690                           << pacing_rate_.kbps();
691     }
692   }
693 }
694 
NextUnpacedSendTime() const695 Timestamp PacingController::NextUnpacedSendTime() const {
696   if (!pace_audio_) {
697     Timestamp leading_audio_send_time =
698         packet_queue_.LeadingPacketEnqueueTime(RtpPacketMediaType::kAudio);
699     if (leading_audio_send_time.IsFinite()) {
700       return leading_audio_send_time;
701     }
702   }
703   if (fast_retransmissions_) {
704     Timestamp leading_retransmission_send_time =
705         packet_queue_.LeadingPacketEnqueueTime(
706             RtpPacketMediaType::kRetransmission);
707     if (leading_retransmission_send_time.IsFinite()) {
708       return leading_retransmission_send_time;
709     }
710   }
711   return Timestamp::MinusInfinity();
712 }
713 
714 }  // namespace webrtc
715