blob: 4a5eadd86b8e8ec4efc0c286f721c25e28d7d55b [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ångb210eeb2019-11-05 11:21:48 +0100286 if (probe_time > now) {
287 return probe_time;
288 }
289
290 if (probing_send_failure_ || now - probe_time > TimeDelta::ms(1)) {
291 return Timestamp::PlusInfinity();
292 }
293
294 return probe_time;
Erik Språngd05edec2019-08-14 10:43:47 +0200295}
296
297TimeDelta PacingController::TimeElapsedSinceLastProcess() const {
298 return CurrentTime() - time_last_process_;
299}
300
301void PacingController::ProcessPackets() {
302 Timestamp now = CurrentTime();
303 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
304 if (ShouldSendKeepalive(now)) {
Erik Språngf5815fa2019-08-21 14:27:31 +0200305 DataSize keepalive_data_sent = DataSize::Zero();
306 std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
307 packet_sender_->GeneratePadding(DataSize::bytes(1));
308 for (auto& packet : keepalive_packets) {
309 keepalive_data_sent +=
310 DataSize::bytes(packet->payload_size() + packet->padding_size());
311 packet_sender_->SendRtpPacket(std::move(packet), PacedPacketInfo());
Erik Språngd05edec2019-08-14 10:43:47 +0200312 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200313 OnPaddingSent(keepalive_data_sent);
Erik Språngd05edec2019-08-14 10:43:47 +0200314 }
315
316 if (paused_)
317 return;
318
319 if (elapsed_time > TimeDelta::Zero()) {
320 DataRate target_rate = pacing_bitrate_;
321 DataSize queue_size_data = packet_queue_.Size();
322 if (queue_size_data > DataSize::Zero()) {
323 // Assuming equal size packets and input/output rate, the average packet
324 // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
325 // time constraint shall be met. Determine bitrate needed for that.
Erik Språngf660e812019-09-01 12:26:44 +0000326 packet_queue_.UpdateQueueTime(CurrentTime());
Erik Språngd05edec2019-08-14 10:43:47 +0200327 if (drain_large_queues_) {
328 TimeDelta avg_time_left =
329 std::max(TimeDelta::ms(1),
330 queue_time_limit - packet_queue_.AverageQueueTime());
331 DataRate min_rate_needed = queue_size_data / avg_time_left;
332 if (min_rate_needed > target_rate) {
333 target_rate = min_rate_needed;
334 RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
335 << target_rate.kbps();
336 }
337 }
338 }
339
340 media_budget_.set_target_rate_kbps(target_rate.kbps());
341 UpdateBudgetWithElapsedTime(elapsed_time);
342 }
343
Erik Språng78c82a42019-10-03 18:46:04 +0200344 bool first_packet_in_probe = false;
Erik Språngd05edec2019-08-14 10:43:47 +0200345 bool is_probing = prober_.IsProbing();
346 PacedPacketInfo pacing_info;
347 absl::optional<DataSize> recommended_probe_size;
348 if (is_probing) {
349 pacing_info = prober_.CurrentCluster();
Erik Språng78c82a42019-10-03 18:46:04 +0200350 first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0;
Erik Språngd05edec2019-08-14 10:43:47 +0200351 recommended_probe_size = DataSize::bytes(prober_.RecommendedMinProbeSize());
352 }
353
354 DataSize data_sent = DataSize::Zero();
355 // The paused state is checked in the loop since it leaves the critical
356 // section allowing the paused state to be changed from other code.
357 while (!paused_) {
Erik Språng78c82a42019-10-03 18:46:04 +0200358 if (small_first_probe_packet_ && first_packet_in_probe) {
359 // If first packet in probe, insert a small padding packet so we have a
360 // more reliable start window for the rate estimation.
361 auto padding = packet_sender_->GeneratePadding(DataSize::bytes(1));
362 // If no RTP modules sending media are registered, we may not get a
363 // padding packet back.
364 if (!padding.empty()) {
365 // Insert with high priority so larger media packets don't preempt it.
366 EnqueuePacketInternal(std::move(padding[0]), kFirstPriority);
367 // We should never get more than one padding packets with a requested
368 // size of 1 byte.
369 RTC_DCHECK_EQ(padding.size(), 1u);
370 }
371 first_packet_in_probe = false;
372 }
373
Erik Språngf660e812019-09-01 12:26:44 +0000374 auto* packet = GetPendingPacket(pacing_info);
375 if (packet == nullptr) {
Erik Språngd05edec2019-08-14 10:43:47 +0200376 // No packet available to send, check if we should send padding.
Erik Språngf5815fa2019-08-21 14:27:31 +0200377 DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
378 if (padding_to_add > DataSize::Zero()) {
379 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
380 packet_sender_->GeneratePadding(padding_to_add);
381 if (padding_packets.empty()) {
382 // No padding packets were generated, quite send loop.
383 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200384 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200385 for (auto& packet : padding_packets) {
386 EnqueuePacket(std::move(packet));
387 }
388 // Continue loop to send the padding that was just added.
389 continue;
Erik Språngd05edec2019-08-14 10:43:47 +0200390 }
391
392 // Can't fetch new packet and no padding to send, exit send loop.
393 break;
394 }
395
Erik Språngf660e812019-09-01 12:26:44 +0000396 std::unique_ptr<RtpPacketToSend> rtp_packet = packet->ReleasePacket();
Erik Språngf5815fa2019-08-21 14:27:31 +0200397 RTC_DCHECK(rtp_packet);
398 packet_sender_->SendRtpPacket(std::move(rtp_packet), pacing_info);
Erik Språngd05edec2019-08-14 10:43:47 +0200399
Erik Språngf660e812019-09-01 12:26:44 +0000400 data_sent += packet->size();
401 // Send succeeded, remove it from the queue.
402 OnPacketSent(packet);
Erik Språngf5815fa2019-08-21 14:27:31 +0200403 if (recommended_probe_size && data_sent > *recommended_probe_size)
Erik Språngd05edec2019-08-14 10:43:47 +0200404 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200405 }
406
407 if (is_probing) {
408 probing_send_failure_ = data_sent == DataSize::Zero();
409 if (!probing_send_failure_) {
Erik Språngb210eeb2019-11-05 11:21:48 +0100410 prober_.ProbeSent(CurrentTime(), data_sent.bytes());
Erik Språngd05edec2019-08-14 10:43:47 +0200411 }
412 }
413}
414
415DataSize PacingController::PaddingToAdd(
416 absl::optional<DataSize> recommended_probe_size,
417 DataSize data_sent) {
418 if (!packet_queue_.Empty()) {
419 // Actual payload available, no need to add padding.
420 return DataSize::Zero();
421 }
422
423 if (Congested()) {
424 // Don't add padding if congested, even if requested for probing.
425 return DataSize::Zero();
426 }
427
428 if (packet_counter_ == 0) {
429 // We can not send padding unless a normal packet has first been sent. If we
430 // do, timestamps get messed up.
431 return DataSize::Zero();
432 }
433
434 if (recommended_probe_size) {
435 if (*recommended_probe_size > data_sent) {
436 return *recommended_probe_size - data_sent;
437 }
438 return DataSize::Zero();
439 }
440
441 return DataSize::bytes(padding_budget_.bytes_remaining());
442}
443
Erik Språngf660e812019-09-01 12:26:44 +0000444RoundRobinPacketQueue::QueuedPacket* PacingController::GetPendingPacket(
445 const PacedPacketInfo& pacing_info) {
446 if (packet_queue_.Empty()) {
447 return nullptr;
448 }
449
450 // Since we need to release the lock in order to send, we first pop the
451 // element from the priority queue but keep it in storage, so that we can
452 // reinsert it if send fails.
453 RoundRobinPacketQueue::QueuedPacket* packet = packet_queue_.BeginPop();
454 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
455 bool apply_pacing = !audio_packet || pace_audio_;
456 if (apply_pacing && (Congested() || (media_budget_.bytes_remaining() == 0 &&
457 pacing_info.probe_cluster_id ==
458 PacedPacketInfo::kNotAProbe))) {
459 packet_queue_.CancelPop();
460 return nullptr;
461 }
462 return packet;
463}
464
465void PacingController::OnPacketSent(
466 RoundRobinPacketQueue::QueuedPacket* packet) {
467 Timestamp now = CurrentTime();
468 if (!first_sent_packet_time_) {
469 first_sent_packet_time_ = now;
470 }
471 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
472 if (!audio_packet || account_for_audio_) {
473 // Update media bytes sent.
474 UpdateBudgetWithSentData(packet->size());
475 last_send_time_ = now;
476 }
477 // Send succeeded, remove it from the queue.
478 packet_queue_.FinalizePop();
479 padding_failure_state_ = false;
480}
481
Erik Språngd05edec2019-08-14 10:43:47 +0200482void PacingController::OnPaddingSent(DataSize data_sent) {
483 if (data_sent > DataSize::Zero()) {
484 UpdateBudgetWithSentData(data_sent);
485 } else {
486 padding_failure_state_ = true;
487 }
488 last_send_time_ = CurrentTime();
489}
490
491void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
492 delta = std::min(kMaxProcessingInterval, delta);
493 media_budget_.IncreaseBudget(delta.ms());
494 padding_budget_.IncreaseBudget(delta.ms());
495}
496
497void PacingController::UpdateBudgetWithSentData(DataSize size) {
498 outstanding_data_ += size;
499 media_budget_.UseBudget(size.bytes());
500 padding_budget_.UseBudget(size.bytes());
501}
502
503void PacingController::SetQueueTimeLimit(TimeDelta limit) {
504 queue_time_limit = limit;
505}
506
507} // namespace webrtc