blob: 2d73247c10ce807a7220f3f38f17d85a2aa1ee7d [file] [log] [blame]
Erik Språngd05edec2019-08-14 10:43:47 +02001/*
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>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020014#include <memory>
Erik Språngd05edec2019-08-14 10:43:47 +020015#include <utility>
16#include <vector>
17
Erik Språngd05edec2019-08-14 10:43:47 +020018#include "modules/pacing/bitrate_prober.h"
19#include "modules/pacing/interval_budget.h"
20#include "modules/utility/include/process_thread.h"
21#include "rtc_base/checks.h"
22#include "rtc_base/logging.h"
23#include "rtc_base/time_utils.h"
24#include "system_wrappers/include/clock.h"
25
26namespace webrtc {
27namespace {
28// Time limit in milliseconds between packet bursts.
29constexpr TimeDelta kDefaultMinPacketLimit = TimeDelta::Millis<5>();
30constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis<500>();
31constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds<2>();
32
33// Upper cap on process interval, in case process has not been called in a long
34// time.
35constexpr TimeDelta kMaxProcessingInterval = TimeDelta::Millis<30>();
36
Erik Språng78c82a42019-10-03 18:46:04 +020037constexpr int kFirstPriority = 0;
38
Erik Språngd05edec2019-08-14 10:43:47 +020039bool IsDisabled(const WebRtcKeyValueConfig& field_trials,
40 absl::string_view key) {
41 return field_trials.Lookup(key).find("Disabled") == 0;
42}
43
44bool IsEnabled(const WebRtcKeyValueConfig& field_trials,
45 absl::string_view key) {
46 return field_trials.Lookup(key).find("Enabled") == 0;
47}
48
49int GetPriorityForType(RtpPacketToSend::Type type) {
Erik Språng78c82a42019-10-03 18:46:04 +020050 // Lower number takes priority over higher.
Erik Språngd05edec2019-08-14 10:43:47 +020051 switch (type) {
52 case RtpPacketToSend::Type::kAudio:
53 // Audio is always prioritized over other packet types.
Erik Språng78c82a42019-10-03 18:46:04 +020054 return kFirstPriority + 1;
Erik Språngd05edec2019-08-14 10:43:47 +020055 case RtpPacketToSend::Type::kRetransmission:
56 // Send retransmissions before new media.
Erik Språng78c82a42019-10-03 18:46:04 +020057 return kFirstPriority + 2;
Erik Språngd05edec2019-08-14 10:43:47 +020058 case RtpPacketToSend::Type::kVideo:
Erik Språngd05edec2019-08-14 10:43:47 +020059 case RtpPacketToSend::Type::kForwardErrorCorrection:
Erik Språng78c82a42019-10-03 18:46:04 +020060 // Video has "normal" priority, in the old speak.
Erik Språngd05edec2019-08-14 10:43:47 +020061 // Send redundancy concurrently to video. If it is delayed it might have a
62 // lower chance of being useful.
Erik Språng78c82a42019-10-03 18:46:04 +020063 return kFirstPriority + 3;
Erik Språngd05edec2019-08-14 10:43:47 +020064 case RtpPacketToSend::Type::kPadding:
65 // Packets that are in themselves likely useless, only sent to keep the
66 // BWE high.
Erik Språng78c82a42019-10-03 18:46:04 +020067 return kFirstPriority + 4;
Erik Språngd05edec2019-08-14 10:43:47 +020068 }
69}
70
71} // namespace
72
73const TimeDelta PacingController::kMaxExpectedQueueLength =
74 TimeDelta::Millis<2000>();
75const float PacingController::kDefaultPaceMultiplier = 2.5f;
76const TimeDelta PacingController::kPausedProcessInterval =
77 kCongestedPacketInterval;
78
79PacingController::PacingController(Clock* clock,
80 PacketSender* packet_sender,
81 RtcEventLog* event_log,
82 const WebRtcKeyValueConfig* field_trials)
83 : clock_(clock),
84 packet_sender_(packet_sender),
85 fallback_field_trials_(
Mirko Bonadei317a1f02019-09-17 17:06:18 +020086 !field_trials ? std::make_unique<FieldTrialBasedConfig>() : nullptr),
Erik Språngd05edec2019-08-14 10:43:47 +020087 field_trials_(field_trials ? field_trials : fallback_field_trials_.get()),
88 drain_large_queues_(
89 !IsDisabled(*field_trials_, "WebRTC-Pacer-DrainQueue")),
90 send_padding_if_silent_(
91 IsEnabled(*field_trials_, "WebRTC-Pacer-PadInSilence")),
92 pace_audio_(!IsDisabled(*field_trials_, "WebRTC-Pacer-BlockAudio")),
Erik Språng78c82a42019-10-03 18:46:04 +020093 small_first_probe_packet_(
94 IsEnabled(*field_trials_, "WebRTC-Pacer-SmallFirstProbePacket")),
Erik Språngd05edec2019-08-14 10:43:47 +020095 min_packet_limit_(kDefaultMinPacketLimit),
96 last_timestamp_(clock_->CurrentTime()),
97 paused_(false),
98 media_budget_(0),
99 padding_budget_(0),
100 prober_(*field_trials_),
101 probing_send_failure_(false),
102 padding_failure_state_(false),
103 pacing_bitrate_(DataRate::Zero()),
104 time_last_process_(clock->CurrentTime()),
105 last_send_time_(time_last_process_),
106 packet_queue_(time_last_process_, field_trials),
107 packet_counter_(0),
108 congestion_window_size_(DataSize::PlusInfinity()),
109 outstanding_data_(DataSize::Zero()),
110 queue_time_limit(kMaxExpectedQueueLength),
Erik Språngf5815fa2019-08-21 14:27:31 +0200111 account_for_audio_(false) {
Erik Språngd05edec2019-08-14 10:43:47 +0200112 if (!drain_large_queues_) {
113 RTC_LOG(LS_WARNING) << "Pacer queues will not be drained,"
114 "pushback experiment must be enabled.";
115 }
116 FieldTrialParameter<int> min_packet_limit_ms("", min_packet_limit_.ms());
117 ParseFieldTrial({&min_packet_limit_ms},
118 field_trials_->Lookup("WebRTC-Pacer-MinPacketLimitMs"));
119 min_packet_limit_ = TimeDelta::ms(min_packet_limit_ms.Get());
120 UpdateBudgetWithElapsedTime(min_packet_limit_);
121}
122
123PacingController::~PacingController() = default;
124
125void PacingController::CreateProbeCluster(DataRate bitrate, int cluster_id) {
Erik Språngb210eeb2019-11-05 11:21:48 +0100126 prober_.CreateProbeCluster(bitrate, CurrentTime(), cluster_id);
Erik Språngd05edec2019-08-14 10:43:47 +0200127}
128
129void PacingController::Pause() {
130 if (!paused_)
131 RTC_LOG(LS_INFO) << "PacedSender paused.";
132 paused_ = true;
133 packet_queue_.SetPauseState(true, CurrentTime());
134}
135
136void PacingController::Resume() {
137 if (paused_)
138 RTC_LOG(LS_INFO) << "PacedSender resumed.";
139 paused_ = false;
140 packet_queue_.SetPauseState(false, CurrentTime());
141}
142
143bool PacingController::IsPaused() const {
144 return paused_;
145}
146
147void PacingController::SetCongestionWindow(DataSize congestion_window_size) {
148 congestion_window_size_ = congestion_window_size;
149}
150
151void PacingController::UpdateOutstandingData(DataSize outstanding_data) {
152 outstanding_data_ = outstanding_data;
153}
154
155bool PacingController::Congested() const {
156 if (congestion_window_size_.IsFinite()) {
157 return outstanding_data_ >= congestion_window_size_;
158 }
159 return false;
160}
161
162Timestamp PacingController::CurrentTime() const {
163 Timestamp time = clock_->CurrentTime();
164 if (time < last_timestamp_) {
165 RTC_LOG(LS_WARNING)
166 << "Non-monotonic clock behavior observed. Previous timestamp: "
167 << last_timestamp_.ms() << ", new timestamp: " << time.ms();
168 RTC_DCHECK_GE(time, last_timestamp_);
169 time = last_timestamp_;
170 }
171 last_timestamp_ = time;
172 return time;
173}
174
175void PacingController::SetProbingEnabled(bool enabled) {
176 RTC_CHECK_EQ(0, packet_counter_);
177 prober_.SetEnabled(enabled);
178}
179
180void PacingController::SetPacingRates(DataRate pacing_rate,
181 DataRate padding_rate) {
182 RTC_DCHECK_GT(pacing_rate, DataRate::Zero());
183 pacing_bitrate_ = pacing_rate;
184 padding_budget_.set_target_rate_kbps(padding_rate.kbps());
185
186 RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps="
187 << pacing_bitrate_.kbps()
188 << " padding_budget_kbps=" << padding_rate.kbps();
189}
190
Erik Språngd05edec2019-08-14 10:43:47 +0200191void PacingController::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) {
192 RTC_DCHECK(pacing_bitrate_ > DataRate::Zero())
193 << "SetPacingRate must be called before InsertPacket.";
Erik Språngd05edec2019-08-14 10:43:47 +0200194 RTC_CHECK(packet->packet_type());
Erik Språng78c82a42019-10-03 18:46:04 +0200195 // Get priority first and store in temporary, to avoid chance of object being
196 // moved before GetPriorityForType() being called.
197 const int priority = GetPriorityForType(*packet->packet_type());
198 EnqueuePacketInternal(std::move(packet), priority);
Erik Språngd05edec2019-08-14 10:43:47 +0200199}
200
201void PacingController::SetAccountForAudioPackets(bool account_for_audio) {
202 account_for_audio_ = account_for_audio;
203}
204
205TimeDelta PacingController::ExpectedQueueTime() const {
206 RTC_DCHECK_GT(pacing_bitrate_, DataRate::Zero());
207 return TimeDelta::ms(
208 (QueueSizeData().bytes() * 8 * rtc::kNumMillisecsPerSec) /
209 pacing_bitrate_.bps());
210}
211
212size_t PacingController::QueueSizePackets() const {
213 return packet_queue_.SizeInPackets();
214}
215
216DataSize PacingController::QueueSizeData() const {
217 return packet_queue_.Size();
218}
219
220absl::optional<Timestamp> PacingController::FirstSentPacketTime() const {
221 return first_sent_packet_time_;
222}
223
224TimeDelta PacingController::OldestPacketWaitTime() const {
225 Timestamp oldest_packet = packet_queue_.OldestEnqueueTime();
226 if (oldest_packet.IsInfinite()) {
227 return TimeDelta::Zero();
228 }
229
230 return CurrentTime() - oldest_packet;
231}
232
Erik Språng78c82a42019-10-03 18:46:04 +0200233void PacingController::EnqueuePacketInternal(
234 std::unique_ptr<RtpPacketToSend> packet,
235 int priority) {
Erik Språng78c82a42019-10-03 18:46:04 +0200236 prober_.OnIncomingPacket(packet->payload_size());
237
238 // TODO(sprang): Make sure tests respect this, replace with DCHECK.
Erik Språngb210eeb2019-11-05 11:21:48 +0100239 Timestamp now = CurrentTime();
Erik Språng78c82a42019-10-03 18:46:04 +0200240 if (packet->capture_time_ms() < 0) {
241 packet->set_capture_time_ms(now.ms());
242 }
243
244 packet_queue_.Push(priority, now, packet_counter_++, std::move(packet));
245}
246
Erik Språngd05edec2019-08-14 10:43:47 +0200247TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) {
248 TimeDelta elapsed_time = now - time_last_process_;
249 time_last_process_ = now;
250 if (elapsed_time > kMaxElapsedTime) {
251 RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time.ms()
252 << " ms) longer than expected, limiting to "
253 << kMaxElapsedTime.ms();
254 elapsed_time = kMaxElapsedTime;
255 }
256 return elapsed_time;
257}
258
259bool PacingController::ShouldSendKeepalive(Timestamp now) const {
260 if (send_padding_if_silent_ || paused_ || Congested()) {
261 // We send a padding packet every 500 ms to ensure we won't get stuck in
262 // congested state due to no feedback being received.
263 TimeDelta elapsed_since_last_send = now - last_send_time_;
264 if (elapsed_since_last_send >= kCongestedPacketInterval) {
265 // We can not send padding unless a normal packet has first been sent. If
266 // we do, timestamps get messed up.
267 if (packet_counter_ > 0) {
268 return true;
269 }
270 }
271 }
272 return false;
273}
274
Erik Språngb210eeb2019-11-05 11:21:48 +0100275Timestamp PacingController::NextProbeTime() {
Erik Språngd05edec2019-08-14 10:43:47 +0200276 if (!prober_.IsProbing()) {
Erik Språngb210eeb2019-11-05 11:21:48 +0100277 return Timestamp::PlusInfinity();
Erik Språngd05edec2019-08-14 10:43:47 +0200278 }
279
Erik Språngb210eeb2019-11-05 11:21:48 +0100280 Timestamp now = CurrentTime();
281 Timestamp probe_time = prober_.NextProbeTime(now);
282 if (probe_time.IsInfinite()) {
283 return probe_time;
Erik Språngd05edec2019-08-14 10:43:47 +0200284 }
285
Erik Språng22fd5d72019-11-07 14:21:05 +0100286 if (probe_time <= now && probing_send_failure_) {
Erik Språngb210eeb2019-11-05 11:21:48 +0100287 return Timestamp::PlusInfinity();
288 }
289
290 return probe_time;
Erik Språngd05edec2019-08-14 10:43:47 +0200291}
292
293TimeDelta PacingController::TimeElapsedSinceLastProcess() const {
294 return CurrentTime() - time_last_process_;
295}
296
297void PacingController::ProcessPackets() {
298 Timestamp now = CurrentTime();
299 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
300 if (ShouldSendKeepalive(now)) {
Erik Språngf5815fa2019-08-21 14:27:31 +0200301 DataSize keepalive_data_sent = DataSize::Zero();
302 std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
303 packet_sender_->GeneratePadding(DataSize::bytes(1));
304 for (auto& packet : keepalive_packets) {
305 keepalive_data_sent +=
306 DataSize::bytes(packet->payload_size() + packet->padding_size());
307 packet_sender_->SendRtpPacket(std::move(packet), PacedPacketInfo());
Erik Språngd05edec2019-08-14 10:43:47 +0200308 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200309 OnPaddingSent(keepalive_data_sent);
Erik Språngd05edec2019-08-14 10:43:47 +0200310 }
311
312 if (paused_)
313 return;
314
315 if (elapsed_time > TimeDelta::Zero()) {
316 DataRate target_rate = pacing_bitrate_;
317 DataSize queue_size_data = packet_queue_.Size();
318 if (queue_size_data > DataSize::Zero()) {
319 // Assuming equal size packets and input/output rate, the average packet
320 // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
321 // time constraint shall be met. Determine bitrate needed for that.
Erik Språngf660e812019-09-01 12:26:44 +0000322 packet_queue_.UpdateQueueTime(CurrentTime());
Erik Språngd05edec2019-08-14 10:43:47 +0200323 if (drain_large_queues_) {
324 TimeDelta avg_time_left =
325 std::max(TimeDelta::ms(1),
326 queue_time_limit - packet_queue_.AverageQueueTime());
327 DataRate min_rate_needed = queue_size_data / avg_time_left;
328 if (min_rate_needed > target_rate) {
329 target_rate = min_rate_needed;
330 RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
331 << target_rate.kbps();
332 }
333 }
334 }
335
336 media_budget_.set_target_rate_kbps(target_rate.kbps());
337 UpdateBudgetWithElapsedTime(elapsed_time);
338 }
339
Erik Språng78c82a42019-10-03 18:46:04 +0200340 bool first_packet_in_probe = false;
Erik Språngd05edec2019-08-14 10:43:47 +0200341 bool is_probing = prober_.IsProbing();
342 PacedPacketInfo pacing_info;
343 absl::optional<DataSize> recommended_probe_size;
344 if (is_probing) {
345 pacing_info = prober_.CurrentCluster();
Erik Språng78c82a42019-10-03 18:46:04 +0200346 first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0;
Erik Språngd05edec2019-08-14 10:43:47 +0200347 recommended_probe_size = DataSize::bytes(prober_.RecommendedMinProbeSize());
348 }
349
350 DataSize data_sent = DataSize::Zero();
351 // The paused state is checked in the loop since it leaves the critical
352 // section allowing the paused state to be changed from other code.
353 while (!paused_) {
Erik Språng78c82a42019-10-03 18:46:04 +0200354 if (small_first_probe_packet_ && first_packet_in_probe) {
355 // If first packet in probe, insert a small padding packet so we have a
356 // more reliable start window for the rate estimation.
357 auto padding = packet_sender_->GeneratePadding(DataSize::bytes(1));
358 // If no RTP modules sending media are registered, we may not get a
359 // padding packet back.
360 if (!padding.empty()) {
361 // Insert with high priority so larger media packets don't preempt it.
362 EnqueuePacketInternal(std::move(padding[0]), kFirstPriority);
363 // We should never get more than one padding packets with a requested
364 // size of 1 byte.
365 RTC_DCHECK_EQ(padding.size(), 1u);
366 }
367 first_packet_in_probe = false;
368 }
369
Erik Språngf660e812019-09-01 12:26:44 +0000370 auto* packet = GetPendingPacket(pacing_info);
371 if (packet == nullptr) {
Erik Språngd05edec2019-08-14 10:43:47 +0200372 // No packet available to send, check if we should send padding.
Erik Språngf5815fa2019-08-21 14:27:31 +0200373 DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
374 if (padding_to_add > DataSize::Zero()) {
375 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
376 packet_sender_->GeneratePadding(padding_to_add);
377 if (padding_packets.empty()) {
378 // No padding packets were generated, quite send loop.
379 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200380 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200381 for (auto& packet : padding_packets) {
382 EnqueuePacket(std::move(packet));
383 }
384 // Continue loop to send the padding that was just added.
385 continue;
Erik Språngd05edec2019-08-14 10:43:47 +0200386 }
387
388 // Can't fetch new packet and no padding to send, exit send loop.
389 break;
390 }
391
Erik Språngf660e812019-09-01 12:26:44 +0000392 std::unique_ptr<RtpPacketToSend> rtp_packet = packet->ReleasePacket();
Erik Språngf5815fa2019-08-21 14:27:31 +0200393 RTC_DCHECK(rtp_packet);
394 packet_sender_->SendRtpPacket(std::move(rtp_packet), pacing_info);
Erik Språngd05edec2019-08-14 10:43:47 +0200395
Erik Språngf660e812019-09-01 12:26:44 +0000396 data_sent += packet->size();
397 // Send succeeded, remove it from the queue.
398 OnPacketSent(packet);
Erik Språngf5815fa2019-08-21 14:27:31 +0200399 if (recommended_probe_size && data_sent > *recommended_probe_size)
Erik Språngd05edec2019-08-14 10:43:47 +0200400 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200401 }
402
403 if (is_probing) {
404 probing_send_failure_ = data_sent == DataSize::Zero();
405 if (!probing_send_failure_) {
Erik Språngb210eeb2019-11-05 11:21:48 +0100406 prober_.ProbeSent(CurrentTime(), data_sent.bytes());
Erik Språngd05edec2019-08-14 10:43:47 +0200407 }
408 }
409}
410
411DataSize PacingController::PaddingToAdd(
412 absl::optional<DataSize> recommended_probe_size,
413 DataSize data_sent) {
414 if (!packet_queue_.Empty()) {
415 // Actual payload available, no need to add padding.
416 return DataSize::Zero();
417 }
418
419 if (Congested()) {
420 // Don't add padding if congested, even if requested for probing.
421 return DataSize::Zero();
422 }
423
424 if (packet_counter_ == 0) {
425 // We can not send padding unless a normal packet has first been sent. If we
426 // do, timestamps get messed up.
427 return DataSize::Zero();
428 }
429
430 if (recommended_probe_size) {
431 if (*recommended_probe_size > data_sent) {
432 return *recommended_probe_size - data_sent;
433 }
434 return DataSize::Zero();
435 }
436
437 return DataSize::bytes(padding_budget_.bytes_remaining());
438}
439
Erik Språngf660e812019-09-01 12:26:44 +0000440RoundRobinPacketQueue::QueuedPacket* PacingController::GetPendingPacket(
441 const PacedPacketInfo& pacing_info) {
442 if (packet_queue_.Empty()) {
443 return nullptr;
444 }
445
446 // Since we need to release the lock in order to send, we first pop the
447 // element from the priority queue but keep it in storage, so that we can
448 // reinsert it if send fails.
449 RoundRobinPacketQueue::QueuedPacket* packet = packet_queue_.BeginPop();
450 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
451 bool apply_pacing = !audio_packet || pace_audio_;
452 if (apply_pacing && (Congested() || (media_budget_.bytes_remaining() == 0 &&
453 pacing_info.probe_cluster_id ==
454 PacedPacketInfo::kNotAProbe))) {
455 packet_queue_.CancelPop();
456 return nullptr;
457 }
458 return packet;
459}
460
461void PacingController::OnPacketSent(
462 RoundRobinPacketQueue::QueuedPacket* packet) {
463 Timestamp now = CurrentTime();
464 if (!first_sent_packet_time_) {
465 first_sent_packet_time_ = now;
466 }
467 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
468 if (!audio_packet || account_for_audio_) {
469 // Update media bytes sent.
470 UpdateBudgetWithSentData(packet->size());
471 last_send_time_ = now;
472 }
473 // Send succeeded, remove it from the queue.
474 packet_queue_.FinalizePop();
475 padding_failure_state_ = false;
476}
477
Erik Språngd05edec2019-08-14 10:43:47 +0200478void PacingController::OnPaddingSent(DataSize data_sent) {
479 if (data_sent > DataSize::Zero()) {
480 UpdateBudgetWithSentData(data_sent);
481 } else {
482 padding_failure_state_ = true;
483 }
484 last_send_time_ = CurrentTime();
485}
486
487void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
488 delta = std::min(kMaxProcessingInterval, delta);
489 media_budget_.IncreaseBudget(delta.ms());
490 padding_budget_.IncreaseBudget(delta.ms());
491}
492
493void PacingController::UpdateBudgetWithSentData(DataSize size) {
494 outstanding_data_ += size;
495 media_budget_.UseBudget(size.bytes());
496 padding_budget_.UseBudget(size.bytes());
497}
498
499void PacingController::SetQueueTimeLimit(TimeDelta limit) {
500 queue_time_limit = limit;
501}
502
503} // namespace webrtc