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 "modules/utility/include/process_thread.h"
22 #include "rtc_base/checks.h"
23 #include "rtc_base/experiments/field_trial_parser.h"
24 #include "rtc_base/logging.h"
25 #include "rtc_base/time_utils.h"
26 #include "system_wrappers/include/clock.h"
27
28 namespace webrtc {
29 namespace {
30 // Time limit in milliseconds between packet bursts.
31 constexpr TimeDelta kDefaultMinPacketLimit = TimeDelta::Millis(5);
32 constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis(500);
33 // TODO(sprang): Consider dropping this limit.
34 // The maximum debt level, in terms of time, capped when sending packets.
35 constexpr TimeDelta kMaxDebtInTime = TimeDelta::Millis(500);
36 constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds(2);
37
38 // Upper cap on process interval, in case process has not been called in a long
39 // time. Applies only to periodic mode.
40 constexpr TimeDelta kMaxProcessingInterval = TimeDelta::Millis(30);
41
42 constexpr int kFirstPriority = 0;
43
IsDisabled(const WebRtcKeyValueConfig & field_trials,absl::string_view key)44 bool IsDisabled(const WebRtcKeyValueConfig& field_trials,
45 absl::string_view key) {
46 return absl::StartsWith(field_trials.Lookup(key), "Disabled");
47 }
48
IsEnabled(const WebRtcKeyValueConfig & field_trials,absl::string_view key)49 bool IsEnabled(const WebRtcKeyValueConfig& field_trials,
50 absl::string_view key) {
51 return absl::StartsWith(field_trials.Lookup(key), "Enabled");
52 }
53
GetDynamicPaddingTarget(const WebRtcKeyValueConfig & field_trials)54 TimeDelta GetDynamicPaddingTarget(const WebRtcKeyValueConfig& field_trials) {
55 FieldTrialParameter<TimeDelta> padding_target("timedelta",
56 TimeDelta::Millis(5));
57 ParseFieldTrial({&padding_target},
58 field_trials.Lookup("WebRTC-Pacer-DynamicPaddingTarget"));
59 return padding_target.Get();
60 }
61
GetPriorityForType(RtpPacketMediaType type)62 int GetPriorityForType(RtpPacketMediaType type) {
63 // Lower number takes priority over higher.
64 switch (type) {
65 case RtpPacketMediaType::kAudio:
66 // Audio is always prioritized over other packet types.
67 return kFirstPriority + 1;
68 case RtpPacketMediaType::kRetransmission:
69 // Send retransmissions before new media.
70 return kFirstPriority + 2;
71 case RtpPacketMediaType::kVideo:
72 case RtpPacketMediaType::kForwardErrorCorrection:
73 // Video has "normal" priority, in the old speak.
74 // Send redundancy concurrently to video. If it is delayed it might have a
75 // lower chance of being useful.
76 return kFirstPriority + 3;
77 case RtpPacketMediaType::kPadding:
78 // Packets that are in themselves likely useless, only sent to keep the
79 // BWE high.
80 return kFirstPriority + 4;
81 }
82 }
83
84 } // namespace
85
86 const TimeDelta PacingController::kMaxExpectedQueueLength =
87 TimeDelta::Millis(2000);
88 const float PacingController::kDefaultPaceMultiplier = 2.5f;
89 const TimeDelta PacingController::kPausedProcessInterval =
90 kCongestedPacketInterval;
91 const TimeDelta PacingController::kMinSleepTime = TimeDelta::Millis(1);
92
PacingController(Clock * clock,PacketSender * packet_sender,RtcEventLog * event_log,const WebRtcKeyValueConfig * field_trials,ProcessMode mode)93 PacingController::PacingController(Clock* clock,
94 PacketSender* packet_sender,
95 RtcEventLog* event_log,
96 const WebRtcKeyValueConfig* field_trials,
97 ProcessMode mode)
98 : mode_(mode),
99 clock_(clock),
100 packet_sender_(packet_sender),
101 fallback_field_trials_(
102 !field_trials ? std::make_unique<FieldTrialBasedConfig>() : nullptr),
103 field_trials_(field_trials ? field_trials : fallback_field_trials_.get()),
104 drain_large_queues_(
105 !IsDisabled(*field_trials_, "WebRTC-Pacer-DrainQueue")),
106 send_padding_if_silent_(
107 IsEnabled(*field_trials_, "WebRTC-Pacer-PadInSilence")),
108 pace_audio_(IsEnabled(*field_trials_, "WebRTC-Pacer-BlockAudio")),
109 small_first_probe_packet_(
110 IsEnabled(*field_trials_, "WebRTC-Pacer-SmallFirstProbePacket")),
111 ignore_transport_overhead_(
112 IsEnabled(*field_trials_, "WebRTC-Pacer-IgnoreTransportOverhead")),
113 padding_target_duration_(GetDynamicPaddingTarget(*field_trials_)),
114 min_packet_limit_(kDefaultMinPacketLimit),
115 transport_overhead_per_packet_(DataSize::Zero()),
116 last_timestamp_(clock_->CurrentTime()),
117 paused_(false),
118 media_budget_(0),
119 padding_budget_(0),
120 media_debt_(DataSize::Zero()),
121 padding_debt_(DataSize::Zero()),
122 media_rate_(DataRate::Zero()),
123 padding_rate_(DataRate::Zero()),
124 prober_(*field_trials_),
125 probing_send_failure_(false),
126 pacing_bitrate_(DataRate::Zero()),
127 last_process_time_(clock->CurrentTime()),
128 last_send_time_(last_process_time_),
129 packet_queue_(last_process_time_, field_trials_),
130 packet_counter_(0),
131 congestion_window_size_(DataSize::PlusInfinity()),
132 outstanding_data_(DataSize::Zero()),
133 queue_time_limit(kMaxExpectedQueueLength),
134 account_for_audio_(false),
135 include_overhead_(false) {
136 if (!drain_large_queues_) {
137 RTC_LOG(LS_WARNING) << "Pacer queues will not be drained,"
138 "pushback experiment must be enabled.";
139 }
140 FieldTrialParameter<int> min_packet_limit_ms("", min_packet_limit_.ms());
141 ParseFieldTrial({&min_packet_limit_ms},
142 field_trials_->Lookup("WebRTC-Pacer-MinPacketLimitMs"));
143 min_packet_limit_ = TimeDelta::Millis(min_packet_limit_ms.Get());
144 UpdateBudgetWithElapsedTime(min_packet_limit_);
145 }
146
147 PacingController::~PacingController() = default;
148
CreateProbeCluster(DataRate bitrate,int cluster_id)149 void PacingController::CreateProbeCluster(DataRate bitrate, int cluster_id) {
150 prober_.CreateProbeCluster(bitrate, CurrentTime(), cluster_id);
151 }
152
Pause()153 void PacingController::Pause() {
154 if (!paused_)
155 RTC_LOG(LS_INFO) << "PacedSender paused.";
156 paused_ = true;
157 packet_queue_.SetPauseState(true, CurrentTime());
158 }
159
Resume()160 void PacingController::Resume() {
161 if (paused_)
162 RTC_LOG(LS_INFO) << "PacedSender resumed.";
163 paused_ = false;
164 packet_queue_.SetPauseState(false, CurrentTime());
165 }
166
IsPaused() const167 bool PacingController::IsPaused() const {
168 return paused_;
169 }
170
SetCongestionWindow(DataSize congestion_window_size)171 void PacingController::SetCongestionWindow(DataSize congestion_window_size) {
172 const bool was_congested = Congested();
173 congestion_window_size_ = congestion_window_size;
174 if (was_congested && !Congested()) {
175 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(CurrentTime());
176 UpdateBudgetWithElapsedTime(elapsed_time);
177 }
178 }
179
UpdateOutstandingData(DataSize outstanding_data)180 void PacingController::UpdateOutstandingData(DataSize outstanding_data) {
181 const bool was_congested = Congested();
182 outstanding_data_ = outstanding_data;
183 if (was_congested && !Congested()) {
184 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(CurrentTime());
185 UpdateBudgetWithElapsedTime(elapsed_time);
186 }
187 }
188
Congested() const189 bool PacingController::Congested() const {
190 if (congestion_window_size_.IsFinite()) {
191 return outstanding_data_ >= congestion_window_size_;
192 }
193 return false;
194 }
195
IsProbing() const196 bool PacingController::IsProbing() const {
197 return prober_.is_probing();
198 }
199
CurrentTime() const200 Timestamp PacingController::CurrentTime() const {
201 Timestamp time = clock_->CurrentTime();
202 if (time < last_timestamp_) {
203 RTC_LOG(LS_WARNING)
204 << "Non-monotonic clock behavior observed. Previous timestamp: "
205 << last_timestamp_.ms() << ", new timestamp: " << time.ms();
206 RTC_DCHECK_GE(time, last_timestamp_);
207 time = last_timestamp_;
208 }
209 last_timestamp_ = time;
210 return time;
211 }
212
SetProbingEnabled(bool enabled)213 void PacingController::SetProbingEnabled(bool enabled) {
214 RTC_CHECK_EQ(0, packet_counter_);
215 prober_.SetEnabled(enabled);
216 }
217
SetPacingRates(DataRate pacing_rate,DataRate padding_rate)218 void PacingController::SetPacingRates(DataRate pacing_rate,
219 DataRate padding_rate) {
220 RTC_DCHECK_GT(pacing_rate, DataRate::Zero());
221 media_rate_ = pacing_rate;
222 padding_rate_ = padding_rate;
223 pacing_bitrate_ = pacing_rate;
224 padding_budget_.set_target_rate_kbps(padding_rate.kbps());
225
226 RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps="
227 << pacing_bitrate_.kbps()
228 << " padding_budget_kbps=" << padding_rate.kbps();
229 }
230
EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet)231 void PacingController::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) {
232 RTC_DCHECK(pacing_bitrate_ > DataRate::Zero())
233 << "SetPacingRate must be called before InsertPacket.";
234 RTC_CHECK(packet->packet_type());
235 // Get priority first and store in temporary, to avoid chance of object being
236 // moved before GetPriorityForType() being called.
237 const int priority = GetPriorityForType(*packet->packet_type());
238 EnqueuePacketInternal(std::move(packet), priority);
239 }
240
SetAccountForAudioPackets(bool account_for_audio)241 void PacingController::SetAccountForAudioPackets(bool account_for_audio) {
242 account_for_audio_ = account_for_audio;
243 }
244
SetIncludeOverhead()245 void PacingController::SetIncludeOverhead() {
246 include_overhead_ = true;
247 packet_queue_.SetIncludeOverhead();
248 }
249
SetTransportOverhead(DataSize overhead_per_packet)250 void PacingController::SetTransportOverhead(DataSize overhead_per_packet) {
251 if (ignore_transport_overhead_)
252 return;
253 transport_overhead_per_packet_ = overhead_per_packet;
254 packet_queue_.SetTransportOverhead(overhead_per_packet);
255 }
256
ExpectedQueueTime() const257 TimeDelta PacingController::ExpectedQueueTime() const {
258 RTC_DCHECK_GT(pacing_bitrate_, DataRate::Zero());
259 return TimeDelta::Millis(
260 (QueueSizeData().bytes() * 8 * rtc::kNumMillisecsPerSec) /
261 pacing_bitrate_.bps());
262 }
263
QueueSizePackets() const264 size_t PacingController::QueueSizePackets() const {
265 return packet_queue_.SizeInPackets();
266 }
267
QueueSizeData() const268 DataSize PacingController::QueueSizeData() const {
269 return packet_queue_.Size();
270 }
271
CurrentBufferLevel() const272 DataSize PacingController::CurrentBufferLevel() const {
273 return std::max(media_debt_, padding_debt_);
274 }
275
FirstSentPacketTime() const276 absl::optional<Timestamp> PacingController::FirstSentPacketTime() const {
277 return first_sent_packet_time_;
278 }
279
OldestPacketWaitTime() const280 TimeDelta PacingController::OldestPacketWaitTime() const {
281 Timestamp oldest_packet = packet_queue_.OldestEnqueueTime();
282 if (oldest_packet.IsInfinite()) {
283 return TimeDelta::Zero();
284 }
285
286 return CurrentTime() - oldest_packet;
287 }
288
EnqueuePacketInternal(std::unique_ptr<RtpPacketToSend> packet,int priority)289 void PacingController::EnqueuePacketInternal(
290 std::unique_ptr<RtpPacketToSend> packet,
291 int priority) {
292 prober_.OnIncomingPacket(DataSize::Bytes(packet->payload_size()));
293
294 // TODO(sprang): Make sure tests respect this, replace with DCHECK.
295 Timestamp now = CurrentTime();
296 if (packet->capture_time_ms() < 0) {
297 packet->set_capture_time_ms(now.ms());
298 }
299
300 if (mode_ == ProcessMode::kDynamic && packet_queue_.Empty() &&
301 NextSendTime() <= now) {
302 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
303 UpdateBudgetWithElapsedTime(elapsed_time);
304 }
305 packet_queue_.Push(priority, now, packet_counter_++, std::move(packet));
306 }
307
UpdateTimeAndGetElapsed(Timestamp now)308 TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) {
309 if (last_process_time_.IsMinusInfinity()) {
310 return TimeDelta::Zero();
311 }
312 RTC_DCHECK_GE(now, last_process_time_);
313 TimeDelta elapsed_time = now - last_process_time_;
314 last_process_time_ = now;
315 if (elapsed_time > kMaxElapsedTime) {
316 RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time.ms()
317 << " ms) longer than expected, limiting to "
318 << kMaxElapsedTime.ms();
319 elapsed_time = kMaxElapsedTime;
320 }
321 return elapsed_time;
322 }
323
ShouldSendKeepalive(Timestamp now) const324 bool PacingController::ShouldSendKeepalive(Timestamp now) const {
325 if (send_padding_if_silent_ || paused_ || Congested() ||
326 packet_counter_ == 0) {
327 // We send a padding packet every 500 ms to ensure we won't get stuck in
328 // congested state due to no feedback being received.
329 TimeDelta elapsed_since_last_send = now - last_send_time_;
330 if (elapsed_since_last_send >= kCongestedPacketInterval) {
331 return true;
332 }
333 }
334 return false;
335 }
336
NextSendTime() const337 Timestamp PacingController::NextSendTime() const {
338 const Timestamp now = CurrentTime();
339
340 if (paused_) {
341 return last_send_time_ + kPausedProcessInterval;
342 }
343
344 // If probing is active, that always takes priority.
345 if (prober_.is_probing()) {
346 Timestamp probe_time = prober_.NextProbeTime(now);
347 // |probe_time| == PlusInfinity indicates no probe scheduled.
348 if (probe_time != Timestamp::PlusInfinity() && !probing_send_failure_) {
349 return probe_time;
350 }
351 }
352
353 if (mode_ == ProcessMode::kPeriodic) {
354 // In periodic non-probing mode, we just have a fixed interval.
355 return last_process_time_ + min_packet_limit_;
356 }
357
358 // In dynamic mode, figure out when the next packet should be sent,
359 // given the current conditions.
360
361 if (!pace_audio_) {
362 // Not pacing audio, if leading packet is audio its target send
363 // time is the time at which it was enqueued.
364 absl::optional<Timestamp> audio_enqueue_time =
365 packet_queue_.LeadingAudioPacketEnqueueTime();
366 if (audio_enqueue_time.has_value()) {
367 return *audio_enqueue_time;
368 }
369 }
370
371 if (Congested() || packet_counter_ == 0) {
372 // We need to at least send keep-alive packets with some interval.
373 return last_send_time_ + kCongestedPacketInterval;
374 }
375
376 // Check how long until we can send the next media packet.
377 if (media_rate_ > DataRate::Zero() && !packet_queue_.Empty()) {
378 return std::min(last_send_time_ + kPausedProcessInterval,
379 last_process_time_ + media_debt_ / media_rate_);
380 }
381
382 // If we _don't_ have pending packets, check how long until we have
383 // bandwidth for padding packets. Both media and padding debts must
384 // have been drained to do this.
385 if (padding_rate_ > DataRate::Zero() && packet_queue_.Empty()) {
386 TimeDelta drain_time =
387 std::max(media_debt_ / media_rate_, padding_debt_ / padding_rate_);
388 return std::min(last_send_time_ + kPausedProcessInterval,
389 last_process_time_ + drain_time);
390 }
391
392 if (send_padding_if_silent_) {
393 return last_send_time_ + kPausedProcessInterval;
394 }
395 return last_process_time_ + kPausedProcessInterval;
396 }
397
ProcessPackets()398 void PacingController::ProcessPackets() {
399 Timestamp now = CurrentTime();
400 Timestamp target_send_time = now;
401 if (mode_ == ProcessMode::kDynamic) {
402 target_send_time = NextSendTime();
403 if (target_send_time.IsMinusInfinity()) {
404 target_send_time = now;
405 } else if (now < target_send_time) {
406 // We are too early, but if queue is empty still allow draining some debt.
407 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
408 UpdateBudgetWithElapsedTime(elapsed_time);
409 return;
410 }
411
412 if (target_send_time < last_process_time_) {
413 // After the last process call, at time X, the target send time
414 // shifted to be earlier than X. This should normally not happen
415 // but we want to make sure rounding errors or erratic behavior
416 // of NextSendTime() does not cause issue. In particular, if the
417 // buffer reduction of
418 // rate * (target_send_time - previous_process_time)
419 // in the main loop doesn't clean up the existing debt we may not
420 // be able to send again. We don't want to check this reordering
421 // there as it is the normal exit condtion when the buffer is
422 // exhausted and there are packets in the queue.
423 UpdateBudgetWithElapsedTime(last_process_time_ - target_send_time);
424 target_send_time = last_process_time_;
425 }
426 }
427
428 Timestamp previous_process_time = last_process_time_;
429 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
430
431 if (ShouldSendKeepalive(now)) {
432 // We can not send padding unless a normal packet has first been sent. If
433 // we do, timestamps get messed up.
434 if (packet_counter_ == 0) {
435 last_send_time_ = now;
436 } else {
437 DataSize keepalive_data_sent = DataSize::Zero();
438 std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
439 packet_sender_->GeneratePadding(DataSize::Bytes(1));
440 for (auto& packet : keepalive_packets) {
441 keepalive_data_sent +=
442 DataSize::Bytes(packet->payload_size() + packet->padding_size());
443 packet_sender_->SendPacket(std::move(packet), PacedPacketInfo());
444 for (auto& packet : packet_sender_->FetchFec()) {
445 EnqueuePacket(std::move(packet));
446 }
447 }
448 OnPaddingSent(keepalive_data_sent);
449 }
450 }
451
452 if (paused_) {
453 return;
454 }
455
456 if (elapsed_time > TimeDelta::Zero()) {
457 DataRate target_rate = pacing_bitrate_;
458 DataSize queue_size_data = packet_queue_.Size();
459 if (queue_size_data > DataSize::Zero()) {
460 // Assuming equal size packets and input/output rate, the average packet
461 // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
462 // time constraint shall be met. Determine bitrate needed for that.
463 packet_queue_.UpdateQueueTime(now);
464 if (drain_large_queues_) {
465 TimeDelta avg_time_left =
466 std::max(TimeDelta::Millis(1),
467 queue_time_limit - packet_queue_.AverageQueueTime());
468 DataRate min_rate_needed = queue_size_data / avg_time_left;
469 if (min_rate_needed > target_rate) {
470 target_rate = min_rate_needed;
471 RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
472 << target_rate.kbps();
473 }
474 }
475 }
476
477 if (mode_ == ProcessMode::kPeriodic) {
478 // In periodic processing mode, the IntevalBudget allows positive budget
479 // up to (process interval duration) * (target rate), so we only need to
480 // update it once before the packet sending loop.
481 media_budget_.set_target_rate_kbps(target_rate.kbps());
482 UpdateBudgetWithElapsedTime(elapsed_time);
483 } else {
484 media_rate_ = target_rate;
485 }
486 }
487
488 bool first_packet_in_probe = false;
489 PacedPacketInfo pacing_info;
490 DataSize recommended_probe_size = DataSize::Zero();
491 bool is_probing = prober_.is_probing();
492 if (is_probing) {
493 // Probe timing is sensitive, and handled explicitly by BitrateProber, so
494 // use actual send time rather than target.
495 pacing_info = prober_.CurrentCluster(now).value_or(PacedPacketInfo());
496 if (pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe) {
497 first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0;
498 recommended_probe_size = prober_.RecommendedMinProbeSize();
499 RTC_DCHECK_GT(recommended_probe_size, DataSize::Zero());
500 } else {
501 // No valid probe cluster returned, probe might have timed out.
502 is_probing = false;
503 }
504 }
505
506 DataSize data_sent = DataSize::Zero();
507
508 // The paused state is checked in the loop since it leaves the critical
509 // section allowing the paused state to be changed from other code.
510 while (!paused_) {
511 if (small_first_probe_packet_ && first_packet_in_probe) {
512 // If first packet in probe, insert a small padding packet so we have a
513 // more reliable start window for the rate estimation.
514 auto padding = packet_sender_->GeneratePadding(DataSize::Bytes(1));
515 // If no RTP modules sending media are registered, we may not get a
516 // padding packet back.
517 if (!padding.empty()) {
518 // Insert with high priority so larger media packets don't preempt it.
519 EnqueuePacketInternal(std::move(padding[0]), kFirstPriority);
520 // We should never get more than one padding packets with a requested
521 // size of 1 byte.
522 RTC_DCHECK_EQ(padding.size(), 1u);
523 }
524 first_packet_in_probe = false;
525 }
526
527 if (mode_ == ProcessMode::kDynamic &&
528 previous_process_time < target_send_time) {
529 // Reduce buffer levels with amount corresponding to time between last
530 // process and target send time for the next packet.
531 // If the process call is late, that may be the time between the optimal
532 // send times for two packets we should already have sent.
533 UpdateBudgetWithElapsedTime(target_send_time - previous_process_time);
534 previous_process_time = target_send_time;
535 }
536
537 // Fetch the next packet, so long as queue is not empty or budget is not
538 // exhausted.
539 std::unique_ptr<RtpPacketToSend> rtp_packet =
540 GetPendingPacket(pacing_info, target_send_time, now);
541
542 if (rtp_packet == nullptr) {
543 // No packet available to send, check if we should send padding.
544 DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
545 if (padding_to_add > DataSize::Zero()) {
546 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
547 packet_sender_->GeneratePadding(padding_to_add);
548 if (padding_packets.empty()) {
549 // No padding packets were generated, quite send loop.
550 break;
551 }
552 for (auto& packet : padding_packets) {
553 EnqueuePacket(std::move(packet));
554 }
555 // Continue loop to send the padding that was just added.
556 continue;
557 }
558
559 // Can't fetch new packet and no padding to send, exit send loop.
560 break;
561 }
562
563 RTC_DCHECK(rtp_packet);
564 RTC_DCHECK(rtp_packet->packet_type().has_value());
565 const RtpPacketMediaType packet_type = *rtp_packet->packet_type();
566 DataSize packet_size = DataSize::Bytes(rtp_packet->payload_size() +
567 rtp_packet->padding_size());
568
569 if (include_overhead_) {
570 packet_size += DataSize::Bytes(rtp_packet->headers_size()) +
571 transport_overhead_per_packet_;
572 }
573
574 packet_sender_->SendPacket(std::move(rtp_packet), pacing_info);
575 for (auto& packet : packet_sender_->FetchFec()) {
576 EnqueuePacket(std::move(packet));
577 }
578 data_sent += packet_size;
579
580 // Send done, update send/process time to the target send time.
581 OnPacketSent(packet_type, packet_size, target_send_time);
582
583 // If we are currently probing, we need to stop the send loop when we have
584 // reached the send target.
585 if (is_probing && data_sent > recommended_probe_size) {
586 break;
587 }
588
589 if (mode_ == ProcessMode::kDynamic) {
590 // Update target send time in case that are more packets that we are late
591 // in processing.
592 Timestamp next_send_time = NextSendTime();
593 if (next_send_time.IsMinusInfinity()) {
594 target_send_time = now;
595 } else {
596 target_send_time = std::min(now, next_send_time);
597 }
598 }
599 }
600
601 last_process_time_ = std::max(last_process_time_, previous_process_time);
602
603 if (is_probing) {
604 probing_send_failure_ = data_sent == DataSize::Zero();
605 if (!probing_send_failure_) {
606 prober_.ProbeSent(CurrentTime(), data_sent);
607 }
608 }
609 }
610
PaddingToAdd(DataSize recommended_probe_size,DataSize data_sent) const611 DataSize PacingController::PaddingToAdd(DataSize recommended_probe_size,
612 DataSize data_sent) const {
613 if (!packet_queue_.Empty()) {
614 // Actual payload available, no need to add padding.
615 return DataSize::Zero();
616 }
617
618 if (Congested()) {
619 // Don't add padding if congested, even if requested for probing.
620 return DataSize::Zero();
621 }
622
623 if (packet_counter_ == 0) {
624 // We can not send padding unless a normal packet has first been sent. If we
625 // do, timestamps get messed up.
626 return DataSize::Zero();
627 }
628
629 if (!recommended_probe_size.IsZero()) {
630 if (recommended_probe_size > data_sent) {
631 return recommended_probe_size - data_sent;
632 }
633 return DataSize::Zero();
634 }
635
636 if (mode_ == ProcessMode::kPeriodic) {
637 return DataSize::Bytes(padding_budget_.bytes_remaining());
638 } else if (padding_rate_ > DataRate::Zero() &&
639 padding_debt_ == DataSize::Zero()) {
640 return padding_target_duration_ * padding_rate_;
641 }
642 return DataSize::Zero();
643 }
644
GetPendingPacket(const PacedPacketInfo & pacing_info,Timestamp target_send_time,Timestamp now)645 std::unique_ptr<RtpPacketToSend> PacingController::GetPendingPacket(
646 const PacedPacketInfo& pacing_info,
647 Timestamp target_send_time,
648 Timestamp now) {
649 if (packet_queue_.Empty()) {
650 return nullptr;
651 }
652
653 // First, check if there is any reason _not_ to send the next queued packet.
654
655 // Unpaced audio packets and probes are exempted from send checks.
656 bool unpaced_audio_packet =
657 !pace_audio_ && packet_queue_.LeadingAudioPacketEnqueueTime().has_value();
658 bool is_probe = pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe;
659 if (!unpaced_audio_packet && !is_probe) {
660 if (Congested()) {
661 // Don't send anything if congested.
662 return nullptr;
663 }
664
665 if (mode_ == ProcessMode::kPeriodic) {
666 if (media_budget_.bytes_remaining() <= 0) {
667 // Not enough budget.
668 return nullptr;
669 }
670 } else {
671 // Dynamic processing mode.
672 if (now <= target_send_time) {
673 // We allow sending slightly early if we think that we would actually
674 // had been able to, had we been right on time - i.e. the current debt
675 // is not more than would be reduced to zero at the target sent time.
676 TimeDelta flush_time = media_debt_ / media_rate_;
677 if (now + flush_time > target_send_time) {
678 return nullptr;
679 }
680 }
681 }
682 }
683
684 return packet_queue_.Pop();
685 }
686
OnPacketSent(RtpPacketMediaType packet_type,DataSize packet_size,Timestamp send_time)687 void PacingController::OnPacketSent(RtpPacketMediaType packet_type,
688 DataSize packet_size,
689 Timestamp send_time) {
690 if (!first_sent_packet_time_) {
691 first_sent_packet_time_ = send_time;
692 }
693 bool audio_packet = packet_type == RtpPacketMediaType::kAudio;
694 if (!audio_packet || account_for_audio_) {
695 // Update media bytes sent.
696 UpdateBudgetWithSentData(packet_size);
697 }
698 last_send_time_ = send_time;
699 last_process_time_ = send_time;
700 }
701
OnPaddingSent(DataSize data_sent)702 void PacingController::OnPaddingSent(DataSize data_sent) {
703 if (data_sent > DataSize::Zero()) {
704 UpdateBudgetWithSentData(data_sent);
705 }
706 last_send_time_ = CurrentTime();
707 last_process_time_ = CurrentTime();
708 }
709
UpdateBudgetWithElapsedTime(TimeDelta delta)710 void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
711 if (mode_ == ProcessMode::kPeriodic) {
712 delta = std::min(kMaxProcessingInterval, delta);
713 media_budget_.IncreaseBudget(delta.ms());
714 padding_budget_.IncreaseBudget(delta.ms());
715 } else {
716 media_debt_ -= std::min(media_debt_, media_rate_ * delta);
717 padding_debt_ -= std::min(padding_debt_, padding_rate_ * delta);
718 }
719 }
720
UpdateBudgetWithSentData(DataSize size)721 void PacingController::UpdateBudgetWithSentData(DataSize size) {
722 outstanding_data_ += size;
723 if (mode_ == ProcessMode::kPeriodic) {
724 media_budget_.UseBudget(size.bytes());
725 padding_budget_.UseBudget(size.bytes());
726 } else {
727 media_debt_ += size;
728 media_debt_ = std::min(media_debt_, media_rate_ * kMaxDebtInTime);
729 padding_debt_ += size;
730 padding_debt_ = std::min(padding_debt_, padding_rate_ * kMaxDebtInTime);
731 }
732 }
733
SetQueueTimeLimit(TimeDelta limit)734 void PacingController::SetQueueTimeLimit(TimeDelta limit) {
735 queue_time_limit = limit;
736 }
737
738 } // namespace webrtc
739