blob: 85b9e05dc66052e9ac1a5a559d8dc867a53a4642 [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) {
126 prober_.CreateProbeCluster(bitrate.bps(), CurrentTime().ms(), cluster_id);
127}
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) {
236 prober_.OnIncomingPacket(packet->payload_size());
237
238 Timestamp now = CurrentTime();
239 prober_.OnIncomingPacket(packet->payload_size());
240
241 // TODO(sprang): Make sure tests respect this, replace with DCHECK.
242 if (packet->capture_time_ms() < 0) {
243 packet->set_capture_time_ms(now.ms());
244 }
245
246 packet_queue_.Push(priority, now, packet_counter_++, std::move(packet));
247}
248
Erik Språngd05edec2019-08-14 10:43:47 +0200249TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) {
250 TimeDelta elapsed_time = now - time_last_process_;
251 time_last_process_ = now;
252 if (elapsed_time > kMaxElapsedTime) {
253 RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time.ms()
254 << " ms) longer than expected, limiting to "
255 << kMaxElapsedTime.ms();
256 elapsed_time = kMaxElapsedTime;
257 }
258 return elapsed_time;
259}
260
261bool PacingController::ShouldSendKeepalive(Timestamp now) const {
262 if (send_padding_if_silent_ || paused_ || Congested()) {
263 // We send a padding packet every 500 ms to ensure we won't get stuck in
264 // congested state due to no feedback being received.
265 TimeDelta elapsed_since_last_send = now - last_send_time_;
266 if (elapsed_since_last_send >= kCongestedPacketInterval) {
267 // We can not send padding unless a normal packet has first been sent. If
268 // we do, timestamps get messed up.
269 if (packet_counter_ > 0) {
270 return true;
271 }
272 }
273 }
274 return false;
275}
276
277absl::optional<TimeDelta> PacingController::TimeUntilNextProbe() {
278 if (!prober_.IsProbing()) {
279 return absl::nullopt;
280 }
281
282 TimeDelta time_delta =
283 TimeDelta::ms(prober_.TimeUntilNextProbe(CurrentTime().ms()));
284 if (time_delta > TimeDelta::Zero() ||
285 (time_delta == TimeDelta::Zero() && !probing_send_failure_)) {
286 return time_delta;
287 }
288
289 return absl::nullopt;
290}
291
292TimeDelta PacingController::TimeElapsedSinceLastProcess() const {
293 return CurrentTime() - time_last_process_;
294}
295
296void PacingController::ProcessPackets() {
297 Timestamp now = CurrentTime();
298 TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
299 if (ShouldSendKeepalive(now)) {
Erik Språngf5815fa2019-08-21 14:27:31 +0200300 DataSize keepalive_data_sent = DataSize::Zero();
301 std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
302 packet_sender_->GeneratePadding(DataSize::bytes(1));
303 for (auto& packet : keepalive_packets) {
304 keepalive_data_sent +=
305 DataSize::bytes(packet->payload_size() + packet->padding_size());
306 packet_sender_->SendRtpPacket(std::move(packet), PacedPacketInfo());
Erik Språngd05edec2019-08-14 10:43:47 +0200307 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200308 OnPaddingSent(keepalive_data_sent);
Erik Språngd05edec2019-08-14 10:43:47 +0200309 }
310
311 if (paused_)
312 return;
313
314 if (elapsed_time > TimeDelta::Zero()) {
315 DataRate target_rate = pacing_bitrate_;
316 DataSize queue_size_data = packet_queue_.Size();
317 if (queue_size_data > DataSize::Zero()) {
318 // Assuming equal size packets and input/output rate, the average packet
319 // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
320 // time constraint shall be met. Determine bitrate needed for that.
Erik Språngf660e812019-09-01 12:26:44 +0000321 packet_queue_.UpdateQueueTime(CurrentTime());
Erik Språngd05edec2019-08-14 10:43:47 +0200322 if (drain_large_queues_) {
323 TimeDelta avg_time_left =
324 std::max(TimeDelta::ms(1),
325 queue_time_limit - packet_queue_.AverageQueueTime());
326 DataRate min_rate_needed = queue_size_data / avg_time_left;
327 if (min_rate_needed > target_rate) {
328 target_rate = min_rate_needed;
329 RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
330 << target_rate.kbps();
331 }
332 }
333 }
334
335 media_budget_.set_target_rate_kbps(target_rate.kbps());
336 UpdateBudgetWithElapsedTime(elapsed_time);
337 }
338
Erik Språng78c82a42019-10-03 18:46:04 +0200339 bool first_packet_in_probe = false;
Erik Språngd05edec2019-08-14 10:43:47 +0200340 bool is_probing = prober_.IsProbing();
341 PacedPacketInfo pacing_info;
342 absl::optional<DataSize> recommended_probe_size;
343 if (is_probing) {
344 pacing_info = prober_.CurrentCluster();
Erik Språng78c82a42019-10-03 18:46:04 +0200345 first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0;
Erik Språngd05edec2019-08-14 10:43:47 +0200346 recommended_probe_size = DataSize::bytes(prober_.RecommendedMinProbeSize());
347 }
348
349 DataSize data_sent = DataSize::Zero();
350 // The paused state is checked in the loop since it leaves the critical
351 // section allowing the paused state to be changed from other code.
352 while (!paused_) {
Erik Språng78c82a42019-10-03 18:46:04 +0200353 if (small_first_probe_packet_ && first_packet_in_probe) {
354 // If first packet in probe, insert a small padding packet so we have a
355 // more reliable start window for the rate estimation.
356 auto padding = packet_sender_->GeneratePadding(DataSize::bytes(1));
357 // If no RTP modules sending media are registered, we may not get a
358 // padding packet back.
359 if (!padding.empty()) {
360 // Insert with high priority so larger media packets don't preempt it.
361 EnqueuePacketInternal(std::move(padding[0]), kFirstPriority);
362 // We should never get more than one padding packets with a requested
363 // size of 1 byte.
364 RTC_DCHECK_EQ(padding.size(), 1u);
365 }
366 first_packet_in_probe = false;
367 }
368
Erik Språngf660e812019-09-01 12:26:44 +0000369 auto* packet = GetPendingPacket(pacing_info);
370 if (packet == nullptr) {
Erik Språngd05edec2019-08-14 10:43:47 +0200371 // No packet available to send, check if we should send padding.
Erik Språngf5815fa2019-08-21 14:27:31 +0200372 DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
373 if (padding_to_add > DataSize::Zero()) {
374 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
375 packet_sender_->GeneratePadding(padding_to_add);
376 if (padding_packets.empty()) {
377 // No padding packets were generated, quite send loop.
378 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200379 }
Erik Språngf5815fa2019-08-21 14:27:31 +0200380 for (auto& packet : padding_packets) {
381 EnqueuePacket(std::move(packet));
382 }
383 // Continue loop to send the padding that was just added.
384 continue;
Erik Språngd05edec2019-08-14 10:43:47 +0200385 }
386
387 // Can't fetch new packet and no padding to send, exit send loop.
388 break;
389 }
390
Erik Språngf660e812019-09-01 12:26:44 +0000391 std::unique_ptr<RtpPacketToSend> rtp_packet = packet->ReleasePacket();
Erik Språngf5815fa2019-08-21 14:27:31 +0200392 RTC_DCHECK(rtp_packet);
393 packet_sender_->SendRtpPacket(std::move(rtp_packet), pacing_info);
Erik Språngd05edec2019-08-14 10:43:47 +0200394
Erik Språngf660e812019-09-01 12:26:44 +0000395 data_sent += packet->size();
396 // Send succeeded, remove it from the queue.
397 OnPacketSent(packet);
Erik Språngf5815fa2019-08-21 14:27:31 +0200398 if (recommended_probe_size && data_sent > *recommended_probe_size)
Erik Språngd05edec2019-08-14 10:43:47 +0200399 break;
Erik Språngd05edec2019-08-14 10:43:47 +0200400 }
401
402 if (is_probing) {
403 probing_send_failure_ = data_sent == DataSize::Zero();
404 if (!probing_send_failure_) {
405 prober_.ProbeSent(CurrentTime().ms(), data_sent.bytes());
406 }
407 }
408}
409
410DataSize PacingController::PaddingToAdd(
411 absl::optional<DataSize> recommended_probe_size,
412 DataSize data_sent) {
413 if (!packet_queue_.Empty()) {
414 // Actual payload available, no need to add padding.
415 return DataSize::Zero();
416 }
417
418 if (Congested()) {
419 // Don't add padding if congested, even if requested for probing.
420 return DataSize::Zero();
421 }
422
423 if (packet_counter_ == 0) {
424 // We can not send padding unless a normal packet has first been sent. If we
425 // do, timestamps get messed up.
426 return DataSize::Zero();
427 }
428
429 if (recommended_probe_size) {
430 if (*recommended_probe_size > data_sent) {
431 return *recommended_probe_size - data_sent;
432 }
433 return DataSize::Zero();
434 }
435
436 return DataSize::bytes(padding_budget_.bytes_remaining());
437}
438
Erik Språngf660e812019-09-01 12:26:44 +0000439RoundRobinPacketQueue::QueuedPacket* PacingController::GetPendingPacket(
440 const PacedPacketInfo& pacing_info) {
441 if (packet_queue_.Empty()) {
442 return nullptr;
443 }
444
445 // Since we need to release the lock in order to send, we first pop the
446 // element from the priority queue but keep it in storage, so that we can
447 // reinsert it if send fails.
448 RoundRobinPacketQueue::QueuedPacket* packet = packet_queue_.BeginPop();
449 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
450 bool apply_pacing = !audio_packet || pace_audio_;
451 if (apply_pacing && (Congested() || (media_budget_.bytes_remaining() == 0 &&
452 pacing_info.probe_cluster_id ==
453 PacedPacketInfo::kNotAProbe))) {
454 packet_queue_.CancelPop();
455 return nullptr;
456 }
457 return packet;
458}
459
460void PacingController::OnPacketSent(
461 RoundRobinPacketQueue::QueuedPacket* packet) {
462 Timestamp now = CurrentTime();
463 if (!first_sent_packet_time_) {
464 first_sent_packet_time_ = now;
465 }
466 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
467 if (!audio_packet || account_for_audio_) {
468 // Update media bytes sent.
469 UpdateBudgetWithSentData(packet->size());
470 last_send_time_ = now;
471 }
472 // Send succeeded, remove it from the queue.
473 packet_queue_.FinalizePop();
474 padding_failure_state_ = false;
475}
476
Erik Språngd05edec2019-08-14 10:43:47 +0200477void PacingController::OnPaddingSent(DataSize data_sent) {
478 if (data_sent > DataSize::Zero()) {
479 UpdateBudgetWithSentData(data_sent);
480 } else {
481 padding_failure_state_ = true;
482 }
483 last_send_time_ = CurrentTime();
484}
485
486void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
487 delta = std::min(kMaxProcessingInterval, delta);
488 media_budget_.IncreaseBudget(delta.ms());
489 padding_budget_.IncreaseBudget(delta.ms());
490}
491
492void PacingController::UpdateBudgetWithSentData(DataSize size) {
493 outstanding_data_ += size;
494 media_budget_.UseBudget(size.bytes());
495 padding_budget_.UseBudget(size.bytes());
496}
497
498void PacingController::SetQueueTimeLimit(TimeDelta limit) {
499 queue_time_limit = limit;
500}
501
502} // namespace webrtc