blob: b603bce394d258dd62d29ba357856af2bcd3ded2 [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ångbb56d4b2019-11-04 13:53:09 +0000126 prober_.CreateProbeCluster(bitrate.bps(), CurrentTime().ms(), 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ångbb56d4b2019-11-04 13:53:09 +0000236 Timestamp now = CurrentTime();
Erik Språng78c82a42019-10-03 18:46:04 +0200237 prober_.OnIncomingPacket(packet->payload_size());
238
239 // TODO(sprang): Make sure tests respect this, replace with DCHECK.
240 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ångbb56d4b2019-11-04 13:53:09 +0000275absl::optional<TimeDelta> PacingController::TimeUntilNextProbe() {
Erik Språngd05edec2019-08-14 10:43:47 +0200276 if (!prober_.IsProbing()) {
Erik Språngbb56d4b2019-11-04 13:53:09 +0000277 return absl::nullopt;
Erik Språngd05edec2019-08-14 10:43:47 +0200278 }
279
Erik Språngbb56d4b2019-11-04 13:53:09 +0000280 TimeDelta time_delta =
281 TimeDelta::ms(prober_.TimeUntilNextProbe(CurrentTime().ms()));
282 if (time_delta > TimeDelta::Zero() ||
283 (time_delta == TimeDelta::Zero() && !probing_send_failure_)) {
284 return time_delta;
Erik Språngd05edec2019-08-14 10:43:47 +0200285 }
286
Erik Språngbb56d4b2019-11-04 13:53:09 +0000287 return absl::nullopt;
Erik Språngd05edec2019-08-14 10:43:47 +0200288}
289
290TimeDelta PacingController::TimeElapsedSinceLastProcess() const {
291 return CurrentTime() - time_last_process_;
292}
293
294void PacingController::ProcessPackets() {
295 Timestamp now = CurrentTime();
296 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
297 if (ShouldSendKeepalive(now)) {
Erik Språngf5815fa2019-08-21 14:27:31 +0200298 DataSize keepalive_data_sent = DataSize::Zero();
299 std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
300 packet_sender_->GeneratePadding(DataSize::bytes(1));
301 for (auto& packet : keepalive_packets) {
302 keepalive_data_sent +=
303 DataSize::bytes(packet->payload_size() + packet->padding_size());
304 packet_sender_->SendRtpPacket(std::move(packet), PacedPacketInfo());
Erik Språngd05edec2019-08-14 10:43:47 +0200305 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200306 OnPaddingSent(keepalive_data_sent);
Erik Språngd05edec2019-08-14 10:43:47 +0200307 }
308
309 if (paused_)
310 return;
311
312 if (elapsed_time > TimeDelta::Zero()) {
313 DataRate target_rate = pacing_bitrate_;
314 DataSize queue_size_data = packet_queue_.Size();
315 if (queue_size_data > DataSize::Zero()) {
316 // Assuming equal size packets and input/output rate, the average packet
317 // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
318 // time constraint shall be met. Determine bitrate needed for that.
Erik Språngf660e812019-09-01 12:26:44 +0000319 packet_queue_.UpdateQueueTime(CurrentTime());
Erik Språngd05edec2019-08-14 10:43:47 +0200320 if (drain_large_queues_) {
321 TimeDelta avg_time_left =
322 std::max(TimeDelta::ms(1),
323 queue_time_limit - packet_queue_.AverageQueueTime());
324 DataRate min_rate_needed = queue_size_data / avg_time_left;
325 if (min_rate_needed > target_rate) {
326 target_rate = min_rate_needed;
327 RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
328 << target_rate.kbps();
329 }
330 }
331 }
332
333 media_budget_.set_target_rate_kbps(target_rate.kbps());
334 UpdateBudgetWithElapsedTime(elapsed_time);
335 }
336
Erik Språng78c82a42019-10-03 18:46:04 +0200337 bool first_packet_in_probe = false;
Erik Språngd05edec2019-08-14 10:43:47 +0200338 bool is_probing = prober_.IsProbing();
339 PacedPacketInfo pacing_info;
340 absl::optional<DataSize> recommended_probe_size;
341 if (is_probing) {
342 pacing_info = prober_.CurrentCluster();
Erik Språng78c82a42019-10-03 18:46:04 +0200343 first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0;
Erik Språngd05edec2019-08-14 10:43:47 +0200344 recommended_probe_size = DataSize::bytes(prober_.RecommendedMinProbeSize());
345 }
346
347 DataSize data_sent = DataSize::Zero();
348 // The paused state is checked in the loop since it leaves the critical
349 // section allowing the paused state to be changed from other code.
350 while (!paused_) {
Erik Språng78c82a42019-10-03 18:46:04 +0200351 if (small_first_probe_packet_ && first_packet_in_probe) {
352 // If first packet in probe, insert a small padding packet so we have a
353 // more reliable start window for the rate estimation.
354 auto padding = packet_sender_->GeneratePadding(DataSize::bytes(1));
355 // If no RTP modules sending media are registered, we may not get a
356 // padding packet back.
357 if (!padding.empty()) {
358 // Insert with high priority so larger media packets don't preempt it.
359 EnqueuePacketInternal(std::move(padding[0]), kFirstPriority);
360 // We should never get more than one padding packets with a requested
361 // size of 1 byte.
362 RTC_DCHECK_EQ(padding.size(), 1u);
363 }
364 first_packet_in_probe = false;
365 }
366
Erik Språngf660e812019-09-01 12:26:44 +0000367 auto* packet = GetPendingPacket(pacing_info);
368 if (packet == nullptr) {
Erik Språngd05edec2019-08-14 10:43:47 +0200369 // No packet available to send, check if we should send padding.
Erik Språngf5815fa2019-08-21 14:27:31 +0200370 DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
371 if (padding_to_add > DataSize::Zero()) {
372 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
373 packet_sender_->GeneratePadding(padding_to_add);
374 if (padding_packets.empty()) {
375 // No padding packets were generated, quite send loop.
376 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200377 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200378 for (auto& packet : padding_packets) {
379 EnqueuePacket(std::move(packet));
380 }
381 // Continue loop to send the padding that was just added.
382 continue;
Erik Språngd05edec2019-08-14 10:43:47 +0200383 }
384
385 // Can't fetch new packet and no padding to send, exit send loop.
386 break;
387 }
388
Erik Språngf660e812019-09-01 12:26:44 +0000389 std::unique_ptr<RtpPacketToSend> rtp_packet = packet->ReleasePacket();
Erik Språngf5815fa2019-08-21 14:27:31 +0200390 RTC_DCHECK(rtp_packet);
391 packet_sender_->SendRtpPacket(std::move(rtp_packet), pacing_info);
Erik Språngd05edec2019-08-14 10:43:47 +0200392
Erik Språngf660e812019-09-01 12:26:44 +0000393 data_sent += packet->size();
394 // Send succeeded, remove it from the queue.
395 OnPacketSent(packet);
Erik Språngf5815fa2019-08-21 14:27:31 +0200396 if (recommended_probe_size && data_sent > *recommended_probe_size)
Erik Språngd05edec2019-08-14 10:43:47 +0200397 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200398 }
399
400 if (is_probing) {
401 probing_send_failure_ = data_sent == DataSize::Zero();
402 if (!probing_send_failure_) {
Erik Språngbb56d4b2019-11-04 13:53:09 +0000403 prober_.ProbeSent(CurrentTime().ms(), data_sent.bytes());
Erik Språngd05edec2019-08-14 10:43:47 +0200404 }
405 }
406}
407
408DataSize PacingController::PaddingToAdd(
409 absl::optional<DataSize> recommended_probe_size,
410 DataSize data_sent) {
411 if (!packet_queue_.Empty()) {
412 // Actual payload available, no need to add padding.
413 return DataSize::Zero();
414 }
415
416 if (Congested()) {
417 // Don't add padding if congested, even if requested for probing.
418 return DataSize::Zero();
419 }
420
421 if (packet_counter_ == 0) {
422 // We can not send padding unless a normal packet has first been sent. If we
423 // do, timestamps get messed up.
424 return DataSize::Zero();
425 }
426
427 if (recommended_probe_size) {
428 if (*recommended_probe_size > data_sent) {
429 return *recommended_probe_size - data_sent;
430 }
431 return DataSize::Zero();
432 }
433
434 return DataSize::bytes(padding_budget_.bytes_remaining());
435}
436
Erik Språngf660e812019-09-01 12:26:44 +0000437RoundRobinPacketQueue::QueuedPacket* PacingController::GetPendingPacket(
438 const PacedPacketInfo& pacing_info) {
439 if (packet_queue_.Empty()) {
440 return nullptr;
441 }
442
443 // Since we need to release the lock in order to send, we first pop the
444 // element from the priority queue but keep it in storage, so that we can
445 // reinsert it if send fails.
446 RoundRobinPacketQueue::QueuedPacket* packet = packet_queue_.BeginPop();
447 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
448 bool apply_pacing = !audio_packet || pace_audio_;
449 if (apply_pacing && (Congested() || (media_budget_.bytes_remaining() == 0 &&
450 pacing_info.probe_cluster_id ==
451 PacedPacketInfo::kNotAProbe))) {
452 packet_queue_.CancelPop();
453 return nullptr;
454 }
455 return packet;
456}
457
458void PacingController::OnPacketSent(
459 RoundRobinPacketQueue::QueuedPacket* packet) {
460 Timestamp now = CurrentTime();
461 if (!first_sent_packet_time_) {
462 first_sent_packet_time_ = now;
463 }
464 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
465 if (!audio_packet || account_for_audio_) {
466 // Update media bytes sent.
467 UpdateBudgetWithSentData(packet->size());
468 last_send_time_ = now;
469 }
470 // Send succeeded, remove it from the queue.
471 packet_queue_.FinalizePop();
472 padding_failure_state_ = false;
473}
474
Erik Språngd05edec2019-08-14 10:43:47 +0200475void PacingController::OnPaddingSent(DataSize data_sent) {
476 if (data_sent > DataSize::Zero()) {
477 UpdateBudgetWithSentData(data_sent);
478 } else {
479 padding_failure_state_ = true;
480 }
481 last_send_time_ = CurrentTime();
482}
483
484void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
485 delta = std::min(kMaxProcessingInterval, delta);
486 media_budget_.IncreaseBudget(delta.ms());
487 padding_budget_.IncreaseBudget(delta.ms());
488}
489
490void PacingController::UpdateBudgetWithSentData(DataSize size) {
491 outstanding_data_ += size;
492 media_budget_.UseBudget(size.bytes());
493 padding_budget_.UseBudget(size.bytes());
494}
495
496void PacingController::SetQueueTimeLimit(TimeDelta limit) {
497 queue_time_limit = limit;
498}
499
500} // namespace webrtc