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 <list>
15 #include <memory>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 #include "api/units/data_rate.h"
21 #include "modules/pacing/packet_router.h"
22 #include "system_wrappers/include/clock.h"
23 #include "test/explicit_key_value_config.h"
24 #include "test/field_trial.h"
25 #include "test/gmock.h"
26 #include "test/gtest.h"
27
28 using ::testing::_;
29 using ::testing::Field;
30 using ::testing::Pointee;
31 using ::testing::Property;
32 using ::testing::Return;
33
34 namespace webrtc {
35 namespace test {
36 namespace {
37 constexpr DataRate kFirstClusterRate = DataRate::KilobitsPerSec(900);
38 constexpr DataRate kSecondClusterRate = DataRate::KilobitsPerSec(1800);
39
40 // The error stems from truncating the time interval of probe packets to integer
41 // values. This results in probing slightly higher than the target bitrate.
42 // For 1.8 Mbps, this comes to be about 120 kbps with 1200 probe packets.
43 constexpr DataRate kProbingErrorMargin = DataRate::KilobitsPerSec(150);
44
45 const float kPaceMultiplier = 2.5f;
46
47 constexpr uint32_t kAudioSsrc = 12345;
48 constexpr uint32_t kVideoSsrc = 234565;
49 constexpr uint32_t kVideoRtxSsrc = 34567;
50 constexpr uint32_t kFlexFecSsrc = 45678;
51
52 constexpr DataRate kTargetRate = DataRate::KilobitsPerSec(800);
53
BuildPacket(RtpPacketMediaType type,uint32_t ssrc,uint16_t sequence_number,int64_t capture_time_ms,size_t size)54 std::unique_ptr<RtpPacketToSend> BuildPacket(RtpPacketMediaType type,
55 uint32_t ssrc,
56 uint16_t sequence_number,
57 int64_t capture_time_ms,
58 size_t size) {
59 auto packet = std::make_unique<RtpPacketToSend>(nullptr);
60 packet->set_packet_type(type);
61 packet->SetSsrc(ssrc);
62 packet->SetSequenceNumber(sequence_number);
63 packet->set_capture_time_ms(capture_time_ms);
64 packet->SetPayloadSize(size);
65 return packet;
66 }
67 } // namespace
68
69 // Mock callback proxy, where both new and old api redirects to common mock
70 // methods that focus on core aspects.
71 class MockPacingControllerCallback : public PacingController::PacketSender {
72 public:
SendPacket(std::unique_ptr<RtpPacketToSend> packet,const PacedPacketInfo & cluster_info)73 void SendPacket(std::unique_ptr<RtpPacketToSend> packet,
74 const PacedPacketInfo& cluster_info) override {
75 SendPacket(packet->Ssrc(), packet->SequenceNumber(),
76 packet->capture_time_ms(),
77 packet->packet_type() == RtpPacketMediaType::kRetransmission,
78 packet->packet_type() == RtpPacketMediaType::kPadding);
79 }
80
GeneratePadding(DataSize target_size)81 std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding(
82 DataSize target_size) override {
83 std::vector<std::unique_ptr<RtpPacketToSend>> ret;
84 size_t padding_size = SendPadding(target_size.bytes());
85 if (padding_size > 0) {
86 auto packet = std::make_unique<RtpPacketToSend>(nullptr);
87 packet->SetPayloadSize(padding_size);
88 packet->set_packet_type(RtpPacketMediaType::kPadding);
89 ret.emplace_back(std::move(packet));
90 }
91 return ret;
92 }
93
94 MOCK_METHOD(void,
95 SendPacket,
96 (uint32_t ssrc,
97 uint16_t sequence_number,
98 int64_t capture_timestamp,
99 bool retransmission,
100 bool padding));
101 MOCK_METHOD(std::vector<std::unique_ptr<RtpPacketToSend>>,
102 FetchFec,
103 (),
104 (override));
105 MOCK_METHOD(size_t, SendPadding, (size_t target_size));
106 };
107
108 // Mock callback implementing the raw api.
109 class MockPacketSender : public PacingController::PacketSender {
110 public:
111 MOCK_METHOD(void,
112 SendPacket,
113 (std::unique_ptr<RtpPacketToSend> packet,
114 const PacedPacketInfo& cluster_info),
115 (override));
116 MOCK_METHOD(std::vector<std::unique_ptr<RtpPacketToSend>>,
117 FetchFec,
118 (),
119 (override));
120
121 MOCK_METHOD(std::vector<std::unique_ptr<RtpPacketToSend>>,
122 GeneratePadding,
123 (DataSize target_size),
124 (override));
125 };
126
127 class PacingControllerPadding : public PacingController::PacketSender {
128 public:
129 static const size_t kPaddingPacketSize = 224;
130
PacingControllerPadding()131 PacingControllerPadding() : padding_sent_(0), total_bytes_sent_(0) {}
132
SendPacket(std::unique_ptr<RtpPacketToSend> packet,const PacedPacketInfo & pacing_info)133 void SendPacket(std::unique_ptr<RtpPacketToSend> packet,
134 const PacedPacketInfo& pacing_info) override {
135 total_bytes_sent_ += packet->payload_size();
136 }
137
FetchFec()138 std::vector<std::unique_ptr<RtpPacketToSend>> FetchFec() override {
139 return {};
140 }
141
GeneratePadding(DataSize target_size)142 std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding(
143 DataSize target_size) override {
144 size_t num_packets =
145 (target_size.bytes() + kPaddingPacketSize - 1) / kPaddingPacketSize;
146 std::vector<std::unique_ptr<RtpPacketToSend>> packets;
147 for (size_t i = 0; i < num_packets; ++i) {
148 packets.emplace_back(std::make_unique<RtpPacketToSend>(nullptr));
149 packets.back()->SetPadding(kPaddingPacketSize);
150 packets.back()->set_packet_type(RtpPacketMediaType::kPadding);
151 padding_sent_ += kPaddingPacketSize;
152 }
153 return packets;
154 }
155
padding_sent()156 size_t padding_sent() { return padding_sent_; }
total_bytes_sent()157 size_t total_bytes_sent() { return total_bytes_sent_; }
158
159 private:
160 size_t padding_sent_;
161 size_t total_bytes_sent_;
162 };
163
164 class PacingControllerProbing : public PacingController::PacketSender {
165 public:
PacingControllerProbing()166 PacingControllerProbing() : packets_sent_(0), padding_sent_(0) {}
167
SendPacket(std::unique_ptr<RtpPacketToSend> packet,const PacedPacketInfo & pacing_info)168 void SendPacket(std::unique_ptr<RtpPacketToSend> packet,
169 const PacedPacketInfo& pacing_info) override {
170 if (packet->packet_type() != RtpPacketMediaType::kPadding) {
171 ++packets_sent_;
172 }
173 last_pacing_info_ = pacing_info;
174 }
175
FetchFec()176 std::vector<std::unique_ptr<RtpPacketToSend>> FetchFec() override {
177 return {};
178 }
179
GeneratePadding(DataSize target_size)180 std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding(
181 DataSize target_size) override {
182 // From RTPSender:
183 // Max in the RFC 3550 is 255 bytes, we limit it to be modulus 32 for SRTP.
184 const DataSize kMaxPadding = DataSize::Bytes(224);
185
186 std::vector<std::unique_ptr<RtpPacketToSend>> packets;
187 while (target_size > DataSize::Zero()) {
188 DataSize padding_size = std::min(kMaxPadding, target_size);
189 packets.emplace_back(std::make_unique<RtpPacketToSend>(nullptr));
190 packets.back()->SetPadding(padding_size.bytes());
191 packets.back()->set_packet_type(RtpPacketMediaType::kPadding);
192 padding_sent_ += padding_size.bytes();
193 target_size -= padding_size;
194 }
195 return packets;
196 }
197
packets_sent() const198 int packets_sent() const { return packets_sent_; }
padding_sent() const199 int padding_sent() const { return padding_sent_; }
total_packets_sent() const200 int total_packets_sent() const { return packets_sent_ + padding_sent_; }
last_pacing_info() const201 PacedPacketInfo last_pacing_info() const { return last_pacing_info_; }
202
203 private:
204 int packets_sent_;
205 int padding_sent_;
206 PacedPacketInfo last_pacing_info_;
207 };
208
209 class PacingControllerTest
210 : public ::testing::TestWithParam<PacingController::ProcessMode> {
211 protected:
PacingControllerTest()212 PacingControllerTest() : clock_(123456) {}
213
SetUp()214 void SetUp() override {
215 srand(0);
216 // Need to initialize PacingController after we initialize clock.
217 pacer_ = std::make_unique<PacingController>(&clock_, &callback_, nullptr,
218 nullptr, GetParam());
219 Init();
220 }
221
PeriodicProcess() const222 bool PeriodicProcess() const {
223 return GetParam() == PacingController::ProcessMode::kPeriodic;
224 }
225
Init()226 void Init() {
227 pacer_->CreateProbeCluster(kFirstClusterRate, /*cluster_id=*/0);
228 pacer_->CreateProbeCluster(kSecondClusterRate, /*cluster_id=*/1);
229 // Default to bitrate probing disabled for testing purposes. Probing tests
230 // have to enable probing, either by creating a new PacingController
231 // instance or by calling SetProbingEnabled(true).
232 pacer_->SetProbingEnabled(false);
233 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, DataRate::Zero());
234
235 clock_.AdvanceTime(TimeUntilNextProcess());
236 }
237
Send(RtpPacketMediaType type,uint32_t ssrc,uint16_t sequence_number,int64_t capture_time_ms,size_t size)238 void Send(RtpPacketMediaType type,
239 uint32_t ssrc,
240 uint16_t sequence_number,
241 int64_t capture_time_ms,
242 size_t size) {
243 pacer_->EnqueuePacket(
244 BuildPacket(type, ssrc, sequence_number, capture_time_ms, size));
245 }
246
SendAndExpectPacket(RtpPacketMediaType type,uint32_t ssrc,uint16_t sequence_number,int64_t capture_time_ms,size_t size)247 void SendAndExpectPacket(RtpPacketMediaType type,
248 uint32_t ssrc,
249 uint16_t sequence_number,
250 int64_t capture_time_ms,
251 size_t size) {
252 Send(type, ssrc, sequence_number, capture_time_ms, size);
253 EXPECT_CALL(callback_,
254 SendPacket(ssrc, sequence_number, capture_time_ms,
255 type == RtpPacketMediaType::kRetransmission, false))
256 .Times(1);
257 }
258
BuildRtpPacket(RtpPacketMediaType type)259 std::unique_ptr<RtpPacketToSend> BuildRtpPacket(RtpPacketMediaType type) {
260 auto packet = std::make_unique<RtpPacketToSend>(nullptr);
261 packet->set_packet_type(type);
262 switch (type) {
263 case RtpPacketMediaType::kAudio:
264 packet->SetSsrc(kAudioSsrc);
265 break;
266 case RtpPacketMediaType::kVideo:
267 packet->SetSsrc(kVideoSsrc);
268 break;
269 case RtpPacketMediaType::kRetransmission:
270 case RtpPacketMediaType::kPadding:
271 packet->SetSsrc(kVideoRtxSsrc);
272 break;
273 case RtpPacketMediaType::kForwardErrorCorrection:
274 packet->SetSsrc(kFlexFecSsrc);
275 break;
276 }
277
278 packet->SetPayloadSize(234);
279 return packet;
280 }
281
TimeUntilNextProcess()282 TimeDelta TimeUntilNextProcess() {
283 Timestamp now = clock_.CurrentTime();
284 return std::max(pacer_->NextSendTime() - now, TimeDelta::Zero());
285 }
286
AdvanceTimeAndProcess()287 void AdvanceTimeAndProcess() {
288 Timestamp now = clock_.CurrentTime();
289 Timestamp next_send_time = pacer_->NextSendTime();
290 clock_.AdvanceTime(std::max(TimeDelta::Zero(), next_send_time - now));
291 pacer_->ProcessPackets();
292 }
293
ConsumeInitialBudget()294 void ConsumeInitialBudget() {
295 const uint32_t kSsrc = 54321;
296 uint16_t sequence_number = 1234;
297 int64_t capture_time_ms = clock_.TimeInMilliseconds();
298 const size_t kPacketSize = 250;
299
300 EXPECT_EQ(TimeDelta::Zero(), pacer_->OldestPacketWaitTime());
301
302 // Due to the multiplicative factor we can send 5 packets during a send
303 // interval. (network capacity * multiplier / (8 bits per byte *
304 // (packet size * #send intervals per second)
305 const size_t packets_to_send_per_interval =
306 kTargetRate.bps() * kPaceMultiplier / (8 * kPacketSize * 200);
307 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
308 SendAndExpectPacket(RtpPacketMediaType::kVideo, kSsrc, sequence_number++,
309 capture_time_ms, kPacketSize);
310 }
311
312 while (pacer_->QueueSizePackets() > 0) {
313 if (PeriodicProcess()) {
314 clock_.AdvanceTime(TimeUntilNextProcess());
315 pacer_->ProcessPackets();
316 } else {
317 AdvanceTimeAndProcess();
318 }
319 }
320 }
321
322 SimulatedClock clock_;
323 ::testing::NiceMock<MockPacingControllerCallback> callback_;
324 std::unique_ptr<PacingController> pacer_;
325 };
326
327 class PacingControllerFieldTrialTest
328 : public ::testing::TestWithParam<PacingController::ProcessMode> {
329 protected:
330 struct MediaStream {
331 const RtpPacketMediaType type;
332 const uint32_t ssrc;
333 const size_t packet_size;
334 uint16_t seq_num;
335 };
336
337 const int kProcessIntervalsPerSecond = 1000 / 5;
338
PacingControllerFieldTrialTest()339 PacingControllerFieldTrialTest() : clock_(123456) {}
InsertPacket(PacingController * pacer,MediaStream * stream)340 void InsertPacket(PacingController* pacer, MediaStream* stream) {
341 pacer->EnqueuePacket(
342 BuildPacket(stream->type, stream->ssrc, stream->seq_num++,
343 clock_.TimeInMilliseconds(), stream->packet_size));
344 }
ProcessNext(PacingController * pacer)345 void ProcessNext(PacingController* pacer) {
346 if (GetParam() == PacingController::ProcessMode::kPeriodic) {
347 TimeDelta process_interval = TimeDelta::Millis(5);
348 clock_.AdvanceTime(process_interval);
349 pacer->ProcessPackets();
350 return;
351 }
352
353 Timestamp now = clock_.CurrentTime();
354 Timestamp next_send_time = pacer->NextSendTime();
355 TimeDelta wait_time = std::max(TimeDelta::Zero(), next_send_time - now);
356 clock_.AdvanceTime(wait_time);
357 pacer->ProcessPackets();
358 }
359 MediaStream audio{/*type*/ RtpPacketMediaType::kAudio,
360 /*ssrc*/ 3333, /*packet_size*/ 100, /*seq_num*/ 1000};
361 MediaStream video{/*type*/ RtpPacketMediaType::kVideo,
362 /*ssrc*/ 4444, /*packet_size*/ 1000, /*seq_num*/ 1000};
363 SimulatedClock clock_;
364 MockPacingControllerCallback callback_;
365 };
366
TEST_P(PacingControllerFieldTrialTest,DefaultNoPaddingInSilence)367 TEST_P(PacingControllerFieldTrialTest, DefaultNoPaddingInSilence) {
368 PacingController pacer(&clock_, &callback_, nullptr, nullptr, GetParam());
369 pacer.SetPacingRates(kTargetRate, DataRate::Zero());
370 // Video packet to reset last send time and provide padding data.
371 InsertPacket(&pacer, &video);
372 EXPECT_CALL(callback_, SendPacket).Times(1);
373 clock_.AdvanceTimeMilliseconds(5);
374 pacer.ProcessPackets();
375 EXPECT_CALL(callback_, SendPadding).Times(0);
376 // Waiting 500 ms should not trigger sending of padding.
377 clock_.AdvanceTimeMilliseconds(500);
378 pacer.ProcessPackets();
379 }
380
TEST_P(PacingControllerFieldTrialTest,PaddingInSilenceWithTrial)381 TEST_P(PacingControllerFieldTrialTest, PaddingInSilenceWithTrial) {
382 ScopedFieldTrials trial("WebRTC-Pacer-PadInSilence/Enabled/");
383 PacingController pacer(&clock_, &callback_, nullptr, nullptr, GetParam());
384 pacer.SetPacingRates(kTargetRate, DataRate::Zero());
385 // Video packet to reset last send time and provide padding data.
386 InsertPacket(&pacer, &video);
387 EXPECT_CALL(callback_, SendPacket).Times(2);
388 clock_.AdvanceTimeMilliseconds(5);
389 pacer.ProcessPackets();
390 EXPECT_CALL(callback_, SendPadding).WillOnce(Return(1000));
391 // Waiting 500 ms should trigger sending of padding.
392 clock_.AdvanceTimeMilliseconds(500);
393 pacer.ProcessPackets();
394 }
395
TEST_P(PacingControllerFieldTrialTest,CongestionWindowAffectsAudioInTrial)396 TEST_P(PacingControllerFieldTrialTest, CongestionWindowAffectsAudioInTrial) {
397 ScopedFieldTrials trial("WebRTC-Pacer-BlockAudio/Enabled/");
398 EXPECT_CALL(callback_, SendPadding).Times(0);
399 PacingController pacer(&clock_, &callback_, nullptr, nullptr, GetParam());
400 pacer.SetPacingRates(DataRate::KilobitsPerSec(10000), DataRate::Zero());
401 pacer.SetCongestionWindow(DataSize::Bytes(video.packet_size - 100));
402 pacer.UpdateOutstandingData(DataSize::Zero());
403 // Video packet fills congestion window.
404 InsertPacket(&pacer, &video);
405 EXPECT_CALL(callback_, SendPacket).Times(1);
406 ProcessNext(&pacer);
407 // Audio packet blocked due to congestion.
408 InsertPacket(&pacer, &audio);
409 EXPECT_CALL(callback_, SendPacket).Times(0);
410 if (GetParam() == PacingController::ProcessMode::kDynamic) {
411 // Without interval budget we'll forward time to where we send keep-alive.
412 EXPECT_CALL(callback_, SendPadding(1)).Times(2);
413 }
414 ProcessNext(&pacer);
415 ProcessNext(&pacer);
416 // Audio packet unblocked when congestion window clear.
417 ::testing::Mock::VerifyAndClearExpectations(&callback_);
418 pacer.UpdateOutstandingData(DataSize::Zero());
419 EXPECT_CALL(callback_, SendPacket).Times(1);
420 ProcessNext(&pacer);
421 }
422
TEST_P(PacingControllerFieldTrialTest,DefaultCongestionWindowDoesNotAffectAudio)423 TEST_P(PacingControllerFieldTrialTest,
424 DefaultCongestionWindowDoesNotAffectAudio) {
425 EXPECT_CALL(callback_, SendPadding).Times(0);
426 PacingController pacer(&clock_, &callback_, nullptr, nullptr, GetParam());
427 pacer.SetPacingRates(DataRate::BitsPerSec(10000000), DataRate::Zero());
428 pacer.SetCongestionWindow(DataSize::Bytes(800));
429 pacer.UpdateOutstandingData(DataSize::Zero());
430 // Video packet fills congestion window.
431 InsertPacket(&pacer, &video);
432 EXPECT_CALL(callback_, SendPacket).Times(1);
433 ProcessNext(&pacer);
434 // Audio not blocked due to congestion.
435 InsertPacket(&pacer, &audio);
436 EXPECT_CALL(callback_, SendPacket).Times(1);
437 ProcessNext(&pacer);
438 }
439
TEST_P(PacingControllerFieldTrialTest,BudgetAffectsAudioInTrial)440 TEST_P(PacingControllerFieldTrialTest, BudgetAffectsAudioInTrial) {
441 ScopedFieldTrials trial("WebRTC-Pacer-BlockAudio/Enabled/");
442 PacingController pacer(&clock_, &callback_, nullptr, nullptr, GetParam());
443 DataRate pacing_rate = DataRate::BitsPerSec(video.packet_size / 3 * 8 *
444 kProcessIntervalsPerSecond);
445 pacer.SetPacingRates(pacing_rate, DataRate::Zero());
446 // Video fills budget for following process periods.
447 InsertPacket(&pacer, &video);
448 EXPECT_CALL(callback_, SendPacket).Times(1);
449 ProcessNext(&pacer);
450 // Audio packet blocked due to budget limit.
451 InsertPacket(&pacer, &audio);
452 Timestamp wait_start_time = clock_.CurrentTime();
453 Timestamp wait_end_time = Timestamp::MinusInfinity();
454 EXPECT_CALL(callback_, SendPacket)
455 .WillOnce([&](uint32_t ssrc, uint16_t sequence_number,
456 int64_t capture_timestamp, bool retransmission,
457 bool padding) { wait_end_time = clock_.CurrentTime(); });
458 while (!wait_end_time.IsFinite()) {
459 ProcessNext(&pacer);
460 }
461 const TimeDelta expected_wait_time =
462 DataSize::Bytes(video.packet_size) / pacing_rate;
463 // Verify delay is near expectation, within timing margin.
464 EXPECT_LT(((wait_end_time - wait_start_time) - expected_wait_time).Abs(),
465 GetParam() == PacingController::ProcessMode::kPeriodic
466 ? TimeDelta::Millis(5)
467 : PacingController::kMinSleepTime);
468 }
469
TEST_P(PacingControllerFieldTrialTest,DefaultBudgetDoesNotAffectAudio)470 TEST_P(PacingControllerFieldTrialTest, DefaultBudgetDoesNotAffectAudio) {
471 EXPECT_CALL(callback_, SendPadding).Times(0);
472 PacingController pacer(&clock_, &callback_, nullptr, nullptr, GetParam());
473 pacer.SetPacingRates(DataRate::BitsPerSec(video.packet_size / 3 * 8 *
474 kProcessIntervalsPerSecond),
475 DataRate::Zero());
476 // Video fills budget for following process periods.
477 InsertPacket(&pacer, &video);
478 EXPECT_CALL(callback_, SendPacket).Times(1);
479 ProcessNext(&pacer);
480 // Audio packet not blocked due to budget limit.
481 EXPECT_CALL(callback_, SendPacket).Times(1);
482 InsertPacket(&pacer, &audio);
483 ProcessNext(&pacer);
484 }
485
486 INSTANTIATE_TEST_SUITE_P(WithAndWithoutIntervalBudget,
487 PacingControllerFieldTrialTest,
488 ::testing::Values(false, true));
489
TEST_P(PacingControllerTest,FirstSentPacketTimeIsSet)490 TEST_P(PacingControllerTest, FirstSentPacketTimeIsSet) {
491 uint16_t sequence_number = 1234;
492 const uint32_t kSsrc = 12345;
493 const size_t kSizeBytes = 250;
494 const size_t kPacketToSend = 3;
495 const Timestamp kStartTime = clock_.CurrentTime();
496
497 // No packet sent.
498 EXPECT_FALSE(pacer_->FirstSentPacketTime().has_value());
499
500 for (size_t i = 0; i < kPacketToSend; ++i) {
501 SendAndExpectPacket(RtpPacketMediaType::kVideo, kSsrc, sequence_number++,
502 clock_.TimeInMilliseconds(), kSizeBytes);
503 clock_.AdvanceTime(TimeUntilNextProcess());
504 pacer_->ProcessPackets();
505 }
506 EXPECT_EQ(kStartTime, pacer_->FirstSentPacketTime());
507 }
508
TEST_P(PacingControllerTest,QueuePacket)509 TEST_P(PacingControllerTest, QueuePacket) {
510 if (!PeriodicProcess()) {
511 // This test checks behavior applicable only when using interval budget.
512 return;
513 }
514
515 uint32_t ssrc = 12345;
516 uint16_t sequence_number = 1234;
517 // Due to the multiplicative factor we can send 5 packets during a 5ms send
518 // interval. (network capacity * multiplier / (8 bits per byte *
519 // (packet size * #send intervals per second)
520 const size_t kPacketsToSend =
521 kTargetRate.bps() * kPaceMultiplier / (8 * 250 * 200);
522 for (size_t i = 0; i < kPacketsToSend; ++i) {
523 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
524 clock_.TimeInMilliseconds(), 250);
525 }
526 EXPECT_CALL(callback_, SendPadding).Times(0);
527
528 // Enqueue one extra packet.
529 int64_t queued_packet_timestamp = clock_.TimeInMilliseconds();
530 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number,
531 queued_packet_timestamp, 250);
532 EXPECT_EQ(kPacketsToSend + 1, pacer_->QueueSizePackets());
533
534 // The first kPacketsToSend packets will be sent with budget from the
535 // initial 5ms interval.
536 pacer_->ProcessPackets();
537 EXPECT_EQ(1u, pacer_->QueueSizePackets());
538
539 // Advance time to next interval, make sure the last packet is sent.
540 clock_.AdvanceTimeMilliseconds(5);
541 EXPECT_CALL(callback_, SendPacket(ssrc, sequence_number++,
542 queued_packet_timestamp, false, false))
543 .Times(1);
544 pacer_->ProcessPackets();
545 sequence_number++;
546 EXPECT_EQ(0u, pacer_->QueueSizePackets());
547
548 // We can send packets_to_send -1 packets of size 250 during the current
549 // interval since one packet has already been sent.
550 for (size_t i = 0; i < kPacketsToSend - 1; ++i) {
551 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
552 clock_.TimeInMilliseconds(), 250);
553 }
554 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
555 clock_.TimeInMilliseconds(), 250);
556 EXPECT_EQ(kPacketsToSend, pacer_->QueueSizePackets());
557 pacer_->ProcessPackets();
558 EXPECT_EQ(1u, pacer_->QueueSizePackets());
559 }
560
TEST_P(PacingControllerTest,QueueAndPacePackets)561 TEST_P(PacingControllerTest, QueueAndPacePackets) {
562 if (PeriodicProcess()) {
563 // This test checks behavior when not using interval budget.
564 return;
565 }
566
567 const uint32_t kSsrc = 12345;
568 uint16_t sequence_number = 1234;
569 const DataSize kPackeSize = DataSize::Bytes(250);
570 const TimeDelta kSendInterval = TimeDelta::Millis(5);
571
572 // Due to the multiplicative factor we can send 5 packets during a 5ms send
573 // interval. (send interval * network capacity * multiplier / packet size)
574 const size_t kPacketsToSend = (kSendInterval * kTargetRate).bytes() *
575 kPaceMultiplier / kPackeSize.bytes();
576
577 for (size_t i = 0; i < kPacketsToSend; ++i) {
578 SendAndExpectPacket(RtpPacketMediaType::kVideo, kSsrc, sequence_number++,
579 clock_.TimeInMilliseconds(), kPackeSize.bytes());
580 }
581 EXPECT_CALL(callback_, SendPadding).Times(0);
582
583 // Enqueue one extra packet.
584 int64_t queued_packet_timestamp = clock_.TimeInMilliseconds();
585 Send(RtpPacketMediaType::kVideo, kSsrc, sequence_number,
586 queued_packet_timestamp, kPackeSize.bytes());
587 EXPECT_EQ(kPacketsToSend + 1, pacer_->QueueSizePackets());
588
589 // Send packets until the initial kPacketsToSend packets are done.
590 Timestamp start_time = clock_.CurrentTime();
591 while (pacer_->QueueSizePackets() > 1) {
592 AdvanceTimeAndProcess();
593 }
594 EXPECT_LT(clock_.CurrentTime() - start_time, kSendInterval);
595
596 // Proceed till last packet can be sent.
597 EXPECT_CALL(callback_, SendPacket(kSsrc, sequence_number,
598 queued_packet_timestamp, false, false))
599 .Times(1);
600 AdvanceTimeAndProcess();
601 EXPECT_GE(clock_.CurrentTime() - start_time, kSendInterval);
602 EXPECT_EQ(pacer_->QueueSizePackets(), 0u);
603 }
604
TEST_P(PacingControllerTest,PaceQueuedPackets)605 TEST_P(PacingControllerTest, PaceQueuedPackets) {
606 uint32_t ssrc = 12345;
607 uint16_t sequence_number = 1234;
608 const size_t kPacketSize = 250;
609
610 // Due to the multiplicative factor we can send 5 packets during a send
611 // interval. (network capacity * multiplier / (8 bits per byte *
612 // (packet size * #send intervals per second)
613 const size_t packets_to_send_per_interval =
614 kTargetRate.bps() * kPaceMultiplier / (8 * kPacketSize * 200);
615 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
616 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
617 clock_.TimeInMilliseconds(), kPacketSize);
618 }
619
620 for (size_t j = 0; j < packets_to_send_per_interval * 10; ++j) {
621 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
622 clock_.TimeInMilliseconds(), kPacketSize);
623 }
624 EXPECT_EQ(packets_to_send_per_interval + packets_to_send_per_interval * 10,
625 pacer_->QueueSizePackets());
626 if (PeriodicProcess()) {
627 pacer_->ProcessPackets();
628 } else {
629 while (pacer_->QueueSizePackets() > packets_to_send_per_interval * 10) {
630 AdvanceTimeAndProcess();
631 }
632 }
633 EXPECT_EQ(pacer_->QueueSizePackets(), packets_to_send_per_interval * 10);
634 EXPECT_CALL(callback_, SendPadding).Times(0);
635
636 EXPECT_CALL(callback_, SendPacket(ssrc, _, _, false, false))
637 .Times(pacer_->QueueSizePackets());
638 const TimeDelta expected_pace_time =
639 DataSize::Bytes(pacer_->QueueSizePackets() * kPacketSize) /
640 (kPaceMultiplier * kTargetRate);
641 Timestamp start_time = clock_.CurrentTime();
642 while (pacer_->QueueSizePackets() > 0) {
643 if (PeriodicProcess()) {
644 clock_.AdvanceTime(TimeUntilNextProcess());
645 pacer_->ProcessPackets();
646 } else {
647 AdvanceTimeAndProcess();
648 }
649 }
650 const TimeDelta actual_pace_time = clock_.CurrentTime() - start_time;
651 EXPECT_LT((actual_pace_time - expected_pace_time).Abs(),
652 PeriodicProcess() ? TimeDelta::Millis(5)
653 : PacingController::kMinSleepTime);
654
655 EXPECT_EQ(0u, pacer_->QueueSizePackets());
656 clock_.AdvanceTime(TimeUntilNextProcess());
657 EXPECT_EQ(0u, pacer_->QueueSizePackets());
658 pacer_->ProcessPackets();
659
660 // Send some more packet, just show that we can..?
661 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
662 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
663 clock_.TimeInMilliseconds(), 250);
664 }
665 EXPECT_EQ(packets_to_send_per_interval, pacer_->QueueSizePackets());
666 if (PeriodicProcess()) {
667 pacer_->ProcessPackets();
668 } else {
669 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
670 AdvanceTimeAndProcess();
671 }
672 }
673 EXPECT_EQ(0u, pacer_->QueueSizePackets());
674 }
675
TEST_P(PacingControllerTest,RepeatedRetransmissionsAllowed)676 TEST_P(PacingControllerTest, RepeatedRetransmissionsAllowed) {
677 // Send one packet, then two retransmissions of that packet.
678 for (size_t i = 0; i < 3; i++) {
679 constexpr uint32_t ssrc = 333;
680 constexpr uint16_t sequence_number = 444;
681 constexpr size_t bytes = 250;
682 bool is_retransmission = (i != 0); // Original followed by retransmissions.
683 SendAndExpectPacket(is_retransmission ? RtpPacketMediaType::kRetransmission
684 : RtpPacketMediaType::kVideo,
685 ssrc, sequence_number, clock_.TimeInMilliseconds(),
686 bytes);
687 clock_.AdvanceTimeMilliseconds(5);
688 }
689 if (PeriodicProcess()) {
690 pacer_->ProcessPackets();
691 } else {
692 while (pacer_->QueueSizePackets() > 0) {
693 AdvanceTimeAndProcess();
694 }
695 }
696 }
697
TEST_P(PacingControllerTest,CanQueuePacketsWithSameSequenceNumberOnDifferentSsrcs)698 TEST_P(PacingControllerTest,
699 CanQueuePacketsWithSameSequenceNumberOnDifferentSsrcs) {
700 uint32_t ssrc = 12345;
701 uint16_t sequence_number = 1234;
702
703 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number,
704 clock_.TimeInMilliseconds(), 250);
705
706 // Expect packet on second ssrc to be queued and sent as well.
707 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc + 1, sequence_number,
708 clock_.TimeInMilliseconds(), 250);
709
710 clock_.AdvanceTimeMilliseconds(1000);
711 if (PeriodicProcess()) {
712 pacer_->ProcessPackets();
713 } else {
714 while (pacer_->QueueSizePackets() > 0) {
715 AdvanceTimeAndProcess();
716 }
717 }
718 }
719
TEST_P(PacingControllerTest,Padding)720 TEST_P(PacingControllerTest, Padding) {
721 uint32_t ssrc = 12345;
722 uint16_t sequence_number = 1234;
723 const size_t kPacketSize = 250;
724
725 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, kTargetRate);
726
727 if (PeriodicProcess()) {
728 ConsumeInitialBudget();
729
730 // 5 milliseconds later should not send padding since we filled the buffers
731 // initially.
732 EXPECT_CALL(callback_, SendPadding(kPacketSize)).Times(0);
733 clock_.AdvanceTime(TimeUntilNextProcess());
734 pacer_->ProcessPackets();
735
736 // 5 milliseconds later we have enough budget to send some padding.
737 EXPECT_CALL(callback_, SendPadding(250)).WillOnce(Return(kPacketSize));
738 EXPECT_CALL(callback_, SendPacket(_, _, _, _, true)).Times(1);
739 clock_.AdvanceTime(TimeUntilNextProcess());
740 pacer_->ProcessPackets();
741 } else {
742 const size_t kPacketsToSend = 20;
743 for (size_t i = 0; i < kPacketsToSend; ++i) {
744 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
745 clock_.TimeInMilliseconds(), kPacketSize);
746 }
747 const TimeDelta expected_pace_time =
748 DataSize::Bytes(pacer_->QueueSizePackets() * kPacketSize) /
749 (kPaceMultiplier * kTargetRate);
750 EXPECT_CALL(callback_, SendPadding).Times(0);
751 // Only the media packets should be sent.
752 Timestamp start_time = clock_.CurrentTime();
753 while (pacer_->QueueSizePackets() > 0) {
754 AdvanceTimeAndProcess();
755 }
756 const TimeDelta actual_pace_time = clock_.CurrentTime() - start_time;
757 EXPECT_LE((actual_pace_time - expected_pace_time).Abs(),
758 PacingController::kMinSleepTime);
759
760 // Pacing media happens at 2.5x, but padding was configured with 1.0x
761 // factor. We have to wait until the padding debt is gone before we start
762 // sending padding.
763 const TimeDelta time_to_padding_debt_free =
764 (expected_pace_time * kPaceMultiplier) - actual_pace_time;
765 clock_.AdvanceTime(time_to_padding_debt_free -
766 PacingController::kMinSleepTime);
767 pacer_->ProcessPackets();
768
769 // Send 10 padding packets.
770 const size_t kPaddingPacketsToSend = 10;
771 DataSize padding_sent = DataSize::Zero();
772 size_t packets_sent = 0;
773 Timestamp first_send_time = Timestamp::MinusInfinity();
774 Timestamp last_send_time = Timestamp::MinusInfinity();
775
776 EXPECT_CALL(callback_, SendPadding)
777 .Times(kPaddingPacketsToSend)
778 .WillRepeatedly([&](size_t target_size) {
779 ++packets_sent;
780 if (packets_sent < kPaddingPacketsToSend) {
781 // Don't count bytes of last packet, instead just
782 // use this as the time the last packet finished
783 // sending.
784 padding_sent += DataSize::Bytes(target_size);
785 }
786 if (first_send_time.IsInfinite()) {
787 first_send_time = clock_.CurrentTime();
788 } else {
789 last_send_time = clock_.CurrentTime();
790 }
791 return target_size;
792 });
793 EXPECT_CALL(callback_, SendPacket(_, _, _, false, true))
794 .Times(kPaddingPacketsToSend);
795
796 while (packets_sent < kPaddingPacketsToSend) {
797 AdvanceTimeAndProcess();
798 }
799
800 // Verify rate of sent padding.
801 TimeDelta padding_duration = last_send_time - first_send_time;
802 DataRate padding_rate = padding_sent / padding_duration;
803 EXPECT_EQ(padding_rate, kTargetRate);
804 }
805 }
806
TEST_P(PacingControllerTest,NoPaddingBeforeNormalPacket)807 TEST_P(PacingControllerTest, NoPaddingBeforeNormalPacket) {
808 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, kTargetRate);
809
810 EXPECT_CALL(callback_, SendPadding).Times(0);
811
812 pacer_->ProcessPackets();
813 clock_.AdvanceTime(TimeUntilNextProcess());
814
815 pacer_->ProcessPackets();
816 clock_.AdvanceTime(TimeUntilNextProcess());
817
818 uint32_t ssrc = 12345;
819 uint16_t sequence_number = 1234;
820 int64_t capture_time_ms = 56789;
821
822 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
823 capture_time_ms, 250);
824 bool padding_sent = false;
825 EXPECT_CALL(callback_, SendPadding).WillOnce([&](size_t padding) {
826 padding_sent = true;
827 return padding;
828 });
829 EXPECT_CALL(callback_, SendPacket(_, _, _, _, true)).Times(1);
830 if (PeriodicProcess()) {
831 pacer_->ProcessPackets();
832 } else {
833 while (!padding_sent) {
834 AdvanceTimeAndProcess();
835 }
836 }
837 }
838
TEST_P(PacingControllerTest,VerifyPaddingUpToBitrate)839 TEST_P(PacingControllerTest, VerifyPaddingUpToBitrate) {
840 if (!PeriodicProcess()) {
841 // Already tested in PacingControllerTest.Padding.
842 return;
843 }
844
845 uint32_t ssrc = 12345;
846 uint16_t sequence_number = 1234;
847 int64_t capture_time_ms = 56789;
848 const int kTimeStep = 5;
849 const int64_t kBitrateWindow = 100;
850 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, kTargetRate);
851
852 int64_t start_time = clock_.TimeInMilliseconds();
853 while (clock_.TimeInMilliseconds() - start_time < kBitrateWindow) {
854 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
855 capture_time_ms, 250);
856 EXPECT_CALL(callback_, SendPadding(250)).WillOnce(Return(250));
857 EXPECT_CALL(callback_, SendPacket(_, _, _, _, true)).Times(1);
858 pacer_->ProcessPackets();
859 clock_.AdvanceTimeMilliseconds(kTimeStep);
860 }
861 }
862
TEST_P(PacingControllerTest,VerifyAverageBitrateVaryingMediaPayload)863 TEST_P(PacingControllerTest, VerifyAverageBitrateVaryingMediaPayload) {
864 uint32_t ssrc = 12345;
865 uint16_t sequence_number = 1234;
866 int64_t capture_time_ms = 56789;
867 const int kTimeStep = 5;
868 const TimeDelta kAveragingWindowLength = TimeDelta::Seconds(10);
869 PacingControllerPadding callback;
870 pacer_ = std::make_unique<PacingController>(&clock_, &callback, nullptr,
871 nullptr, GetParam());
872 pacer_->SetProbingEnabled(false);
873 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, kTargetRate);
874
875 Timestamp start_time = clock_.CurrentTime();
876 size_t media_bytes = 0;
877 while (clock_.CurrentTime() - start_time < kAveragingWindowLength) {
878 // Maybe add some new media packets corresponding to expected send rate.
879 int rand_value = rand(); // NOLINT (rand_r instead of rand)
880 while (
881 media_bytes <
882 (kTargetRate * (clock_.CurrentTime() - start_time)).bytes<size_t>()) {
883 size_t media_payload = rand_value % 400 + 800; // [400, 1200] bytes.
884 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++, capture_time_ms,
885 media_payload);
886 media_bytes += media_payload;
887 }
888
889 if (PeriodicProcess()) {
890 clock_.AdvanceTimeMilliseconds(kTimeStep);
891 pacer_->ProcessPackets();
892 } else {
893 AdvanceTimeAndProcess();
894 }
895 }
896
897 EXPECT_NEAR(
898 kTargetRate.bps(),
899 (DataSize::Bytes(callback.total_bytes_sent()) / kAveragingWindowLength)
900 .bps(),
901 (kTargetRate * 0.01 /* 1% error marging */).bps());
902 }
903
TEST_P(PacingControllerTest,Priority)904 TEST_P(PacingControllerTest, Priority) {
905 uint32_t ssrc_low_priority = 12345;
906 uint32_t ssrc = 12346;
907 uint16_t sequence_number = 1234;
908 int64_t capture_time_ms = 56789;
909 int64_t capture_time_ms_low_priority = 1234567;
910
911 ConsumeInitialBudget();
912
913 // Expect normal and low priority to be queued and high to pass through.
914 Send(RtpPacketMediaType::kVideo, ssrc_low_priority, sequence_number++,
915 capture_time_ms_low_priority, 250);
916
917 const size_t packets_to_send_per_interval =
918 kTargetRate.bps() * kPaceMultiplier / (8 * 250 * 200);
919 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
920 Send(RtpPacketMediaType::kRetransmission, ssrc, sequence_number++,
921 capture_time_ms, 250);
922 }
923 Send(RtpPacketMediaType::kAudio, ssrc, sequence_number++, capture_time_ms,
924 250);
925
926 // Expect all high and normal priority to be sent out first.
927 EXPECT_CALL(callback_, SendPadding).Times(0);
928 EXPECT_CALL(callback_, SendPacket(ssrc, _, capture_time_ms, _, _))
929 .Times(packets_to_send_per_interval + 1);
930
931 if (PeriodicProcess()) {
932 clock_.AdvanceTime(TimeUntilNextProcess());
933 pacer_->ProcessPackets();
934 } else {
935 while (pacer_->QueueSizePackets() > 1) {
936 AdvanceTimeAndProcess();
937 }
938 }
939
940 EXPECT_EQ(1u, pacer_->QueueSizePackets());
941
942 EXPECT_CALL(callback_, SendPacket(ssrc_low_priority, _,
943 capture_time_ms_low_priority, _, _))
944 .Times(1);
945 if (PeriodicProcess()) {
946 clock_.AdvanceTime(TimeUntilNextProcess());
947 pacer_->ProcessPackets();
948 } else {
949 AdvanceTimeAndProcess();
950 }
951 }
952
TEST_P(PacingControllerTest,RetransmissionPriority)953 TEST_P(PacingControllerTest, RetransmissionPriority) {
954 uint32_t ssrc = 12345;
955 uint16_t sequence_number = 1234;
956 int64_t capture_time_ms = 45678;
957 int64_t capture_time_ms_retransmission = 56789;
958
959 // Due to the multiplicative factor we can send 5 packets during a send
960 // interval. (network capacity * multiplier / (8 bits per byte *
961 // (packet size * #send intervals per second)
962 const size_t packets_to_send_per_interval =
963 kTargetRate.bps() * kPaceMultiplier / (8 * 250 * 200);
964 pacer_->ProcessPackets();
965 EXPECT_EQ(0u, pacer_->QueueSizePackets());
966
967 // Alternate retransmissions and normal packets.
968 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
969 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++, capture_time_ms,
970 250);
971 Send(RtpPacketMediaType::kRetransmission, ssrc, sequence_number++,
972 capture_time_ms_retransmission, 250);
973 }
974 EXPECT_EQ(2 * packets_to_send_per_interval, pacer_->QueueSizePackets());
975
976 // Expect all retransmissions to be sent out first despite having a later
977 // capture time.
978 EXPECT_CALL(callback_, SendPadding).Times(0);
979 EXPECT_CALL(callback_, SendPacket(_, _, _, false, _)).Times(0);
980 EXPECT_CALL(callback_,
981 SendPacket(ssrc, _, capture_time_ms_retransmission, true, _))
982 .Times(packets_to_send_per_interval);
983
984 if (PeriodicProcess()) {
985 clock_.AdvanceTime(TimeUntilNextProcess());
986 pacer_->ProcessPackets();
987 } else {
988 while (pacer_->QueueSizePackets() > packets_to_send_per_interval) {
989 AdvanceTimeAndProcess();
990 }
991 }
992 EXPECT_EQ(packets_to_send_per_interval, pacer_->QueueSizePackets());
993
994 // Expect the remaining (non-retransmission) packets to be sent.
995 EXPECT_CALL(callback_, SendPadding).Times(0);
996 EXPECT_CALL(callback_, SendPacket(_, _, _, true, _)).Times(0);
997 EXPECT_CALL(callback_, SendPacket(ssrc, _, capture_time_ms, false, _))
998 .Times(packets_to_send_per_interval);
999
1000 if (PeriodicProcess()) {
1001 clock_.AdvanceTime(TimeUntilNextProcess());
1002 pacer_->ProcessPackets();
1003 } else {
1004 while (pacer_->QueueSizePackets() > 0) {
1005 AdvanceTimeAndProcess();
1006 }
1007 }
1008
1009 EXPECT_EQ(0u, pacer_->QueueSizePackets());
1010 }
1011
TEST_P(PacingControllerTest,HighPrioDoesntAffectBudget)1012 TEST_P(PacingControllerTest, HighPrioDoesntAffectBudget) {
1013 const size_t kPacketSize = 250;
1014 uint32_t ssrc = 12346;
1015 uint16_t sequence_number = 1234;
1016 int64_t capture_time_ms = 56789;
1017
1018 // As high prio packets doesn't affect the budget, we should be able to send
1019 // a high number of them at once.
1020 const size_t kNumAudioPackets = 25;
1021 for (size_t i = 0; i < kNumAudioPackets; ++i) {
1022 SendAndExpectPacket(RtpPacketMediaType::kAudio, ssrc, sequence_number++,
1023 capture_time_ms, kPacketSize);
1024 }
1025 pacer_->ProcessPackets();
1026 // Low prio packets does affect the budget.
1027 // Due to the multiplicative factor we can send 5 packets during a send
1028 // interval. (network capacity * multiplier / (8 bits per byte *
1029 // (packet size * #send intervals per second)
1030 const size_t kPacketsToSendPerInterval =
1031 kTargetRate.bps() * kPaceMultiplier / (8 * kPacketSize * 200);
1032 for (size_t i = 0; i < kPacketsToSendPerInterval; ++i) {
1033 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1034 clock_.TimeInMilliseconds(), kPacketSize);
1035 }
1036
1037 // Send all packets and measure pace time.
1038 Timestamp start_time = clock_.CurrentTime();
1039 while (pacer_->QueueSizePackets() > 0) {
1040 if (PeriodicProcess()) {
1041 clock_.AdvanceTime(TimeUntilNextProcess());
1042 pacer_->ProcessPackets();
1043 } else {
1044 AdvanceTimeAndProcess();
1045 }
1046 }
1047
1048 // Measure pacing time. Expect only low-prio packets to affect this.
1049 TimeDelta pacing_time = clock_.CurrentTime() - start_time;
1050 TimeDelta expected_pacing_time =
1051 DataSize::Bytes(kPacketsToSendPerInterval * kPacketSize) /
1052 (kTargetRate * kPaceMultiplier);
1053 EXPECT_NEAR(pacing_time.us<double>(), expected_pacing_time.us<double>(),
1054 PeriodicProcess() ? 5000.0
1055 : PacingController::kMinSleepTime.us<double>());
1056 }
1057
TEST_P(PacingControllerTest,SendsOnlyPaddingWhenCongested)1058 TEST_P(PacingControllerTest, SendsOnlyPaddingWhenCongested) {
1059 uint32_t ssrc = 202020;
1060 uint16_t sequence_number = 1000;
1061 int kPacketSize = 250;
1062 int kCongestionWindow = kPacketSize * 10;
1063
1064 pacer_->UpdateOutstandingData(DataSize::Zero());
1065 pacer_->SetCongestionWindow(DataSize::Bytes(kCongestionWindow));
1066 int sent_data = 0;
1067 while (sent_data < kCongestionWindow) {
1068 sent_data += kPacketSize;
1069 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1070 clock_.TimeInMilliseconds(), kPacketSize);
1071 AdvanceTimeAndProcess();
1072 }
1073 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1074 EXPECT_CALL(callback_, SendPacket).Times(0);
1075 EXPECT_CALL(callback_, SendPadding).Times(0);
1076
1077 size_t blocked_packets = 0;
1078 int64_t expected_time_until_padding = 500;
1079 while (expected_time_until_padding > 5) {
1080 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1081 clock_.TimeInMilliseconds(), kPacketSize);
1082 blocked_packets++;
1083 clock_.AdvanceTimeMilliseconds(5);
1084 pacer_->ProcessPackets();
1085 expected_time_until_padding -= 5;
1086 }
1087 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1088 EXPECT_CALL(callback_, SendPadding(1)).WillOnce(Return(1));
1089 EXPECT_CALL(callback_, SendPacket(_, _, _, _, true)).Times(1);
1090 clock_.AdvanceTimeMilliseconds(5);
1091 pacer_->ProcessPackets();
1092 EXPECT_EQ(blocked_packets, pacer_->QueueSizePackets());
1093 }
1094
TEST_P(PacingControllerTest,DoesNotAllowOveruseAfterCongestion)1095 TEST_P(PacingControllerTest, DoesNotAllowOveruseAfterCongestion) {
1096 uint32_t ssrc = 202020;
1097 uint16_t seq_num = 1000;
1098 int size = 1000;
1099 auto now_ms = [this] { return clock_.TimeInMilliseconds(); };
1100 EXPECT_CALL(callback_, SendPadding).Times(0);
1101 // The pacing rate is low enough that the budget should not allow two packets
1102 // to be sent in a row.
1103 pacer_->SetPacingRates(DataRate::BitsPerSec(400 * 8 * 1000 / 5),
1104 DataRate::Zero());
1105 // The congestion window is small enough to only let one packet through.
1106 pacer_->SetCongestionWindow(DataSize::Bytes(800));
1107 pacer_->UpdateOutstandingData(DataSize::Zero());
1108 // Not yet budget limited or congested, packet is sent.
1109 Send(RtpPacketMediaType::kVideo, ssrc, seq_num++, now_ms(), size);
1110 EXPECT_CALL(callback_, SendPacket).Times(1);
1111 clock_.AdvanceTimeMilliseconds(5);
1112 pacer_->ProcessPackets();
1113 // Packet blocked due to congestion.
1114 Send(RtpPacketMediaType::kVideo, ssrc, seq_num++, now_ms(), size);
1115 EXPECT_CALL(callback_, SendPacket).Times(0);
1116 clock_.AdvanceTimeMilliseconds(5);
1117 pacer_->ProcessPackets();
1118 // Packet blocked due to congestion.
1119 Send(RtpPacketMediaType::kVideo, ssrc, seq_num++, now_ms(), size);
1120 EXPECT_CALL(callback_, SendPacket).Times(0);
1121 clock_.AdvanceTimeMilliseconds(5);
1122 pacer_->ProcessPackets();
1123 // Congestion removed and budget has recovered, packet is sent.
1124 Send(RtpPacketMediaType::kVideo, ssrc, seq_num++, now_ms(), size);
1125 EXPECT_CALL(callback_, SendPacket).Times(1);
1126 clock_.AdvanceTimeMilliseconds(5);
1127 pacer_->UpdateOutstandingData(DataSize::Zero());
1128 pacer_->ProcessPackets();
1129 // Should be blocked due to budget limitation as congestion has be removed.
1130 Send(RtpPacketMediaType::kVideo, ssrc, seq_num++, now_ms(), size);
1131 EXPECT_CALL(callback_, SendPacket).Times(0);
1132 clock_.AdvanceTimeMilliseconds(5);
1133 pacer_->ProcessPackets();
1134 }
1135
TEST_P(PacingControllerTest,ResumesSendingWhenCongestionEnds)1136 TEST_P(PacingControllerTest, ResumesSendingWhenCongestionEnds) {
1137 uint32_t ssrc = 202020;
1138 uint16_t sequence_number = 1000;
1139 int64_t kPacketSize = 250;
1140 int64_t kCongestionCount = 10;
1141 int64_t kCongestionWindow = kPacketSize * kCongestionCount;
1142 int64_t kCongestionTimeMs = 1000;
1143
1144 pacer_->UpdateOutstandingData(DataSize::Zero());
1145 pacer_->SetCongestionWindow(DataSize::Bytes(kCongestionWindow));
1146 int sent_data = 0;
1147 while (sent_data < kCongestionWindow) {
1148 sent_data += kPacketSize;
1149 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1150 clock_.TimeInMilliseconds(), kPacketSize);
1151 clock_.AdvanceTimeMilliseconds(5);
1152 pacer_->ProcessPackets();
1153 }
1154 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1155 EXPECT_CALL(callback_, SendPacket).Times(0);
1156 int unacked_packets = 0;
1157 for (int duration = 0; duration < kCongestionTimeMs; duration += 5) {
1158 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1159 clock_.TimeInMilliseconds(), kPacketSize);
1160 unacked_packets++;
1161 clock_.AdvanceTimeMilliseconds(5);
1162 pacer_->ProcessPackets();
1163 }
1164 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1165
1166 // First mark half of the congested packets as cleared and make sure that just
1167 // as many are sent
1168 int ack_count = kCongestionCount / 2;
1169 EXPECT_CALL(callback_, SendPacket(ssrc, _, _, false, _)).Times(ack_count);
1170 pacer_->UpdateOutstandingData(
1171 DataSize::Bytes(kCongestionWindow - kPacketSize * ack_count));
1172
1173 for (int duration = 0; duration < kCongestionTimeMs; duration += 5) {
1174 clock_.AdvanceTimeMilliseconds(5);
1175 pacer_->ProcessPackets();
1176 }
1177 unacked_packets -= ack_count;
1178 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1179
1180 // Second make sure all packets are sent if sent packets are continuously
1181 // marked as acked.
1182 EXPECT_CALL(callback_, SendPacket(ssrc, _, _, false, _))
1183 .Times(unacked_packets);
1184 for (int duration = 0; duration < kCongestionTimeMs; duration += 5) {
1185 pacer_->UpdateOutstandingData(DataSize::Zero());
1186 clock_.AdvanceTimeMilliseconds(5);
1187 pacer_->ProcessPackets();
1188 }
1189 }
1190
TEST_P(PacingControllerTest,Pause)1191 TEST_P(PacingControllerTest, Pause) {
1192 uint32_t ssrc_low_priority = 12345;
1193 uint32_t ssrc = 12346;
1194 uint32_t ssrc_high_priority = 12347;
1195 uint16_t sequence_number = 1234;
1196
1197 EXPECT_EQ(TimeDelta::Zero(), pacer_->OldestPacketWaitTime());
1198
1199 ConsumeInitialBudget();
1200
1201 pacer_->Pause();
1202
1203 int64_t capture_time_ms = clock_.TimeInMilliseconds();
1204 const size_t packets_to_send_per_interval =
1205 kTargetRate.bps() * kPaceMultiplier / (8 * 250 * 200);
1206 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
1207 Send(RtpPacketMediaType::kVideo, ssrc_low_priority, sequence_number++,
1208 capture_time_ms, 250);
1209 Send(RtpPacketMediaType::kRetransmission, ssrc, sequence_number++,
1210 capture_time_ms, 250);
1211 Send(RtpPacketMediaType::kAudio, ssrc_high_priority, sequence_number++,
1212 capture_time_ms, 250);
1213 }
1214 clock_.AdvanceTimeMilliseconds(10000);
1215 int64_t second_capture_time_ms = clock_.TimeInMilliseconds();
1216 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
1217 Send(RtpPacketMediaType::kVideo, ssrc_low_priority, sequence_number++,
1218 second_capture_time_ms, 250);
1219 Send(RtpPacketMediaType::kRetransmission, ssrc, sequence_number++,
1220 second_capture_time_ms, 250);
1221 Send(RtpPacketMediaType::kAudio, ssrc_high_priority, sequence_number++,
1222 second_capture_time_ms, 250);
1223 }
1224
1225 // Expect everything to be queued.
1226 EXPECT_EQ(TimeDelta::Millis(second_capture_time_ms - capture_time_ms),
1227 pacer_->OldestPacketWaitTime());
1228
1229 // Process triggers keep-alive packet.
1230 EXPECT_CALL(callback_, SendPadding).WillOnce([](size_t padding) {
1231 return padding;
1232 });
1233 EXPECT_CALL(callback_, SendPacket(_, _, _, _, true)).Times(1);
1234 pacer_->ProcessPackets();
1235
1236 // Verify no packets sent for the rest of the paused process interval.
1237 const TimeDelta kProcessInterval = TimeDelta::Millis(5);
1238 TimeDelta expected_time_until_send = PacingController::kPausedProcessInterval;
1239 EXPECT_CALL(callback_, SendPadding).Times(0);
1240 while (expected_time_until_send >= kProcessInterval) {
1241 pacer_->ProcessPackets();
1242 clock_.AdvanceTime(kProcessInterval);
1243 expected_time_until_send -= kProcessInterval;
1244 }
1245
1246 // New keep-alive packet.
1247 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1248 EXPECT_CALL(callback_, SendPadding).WillOnce([](size_t padding) {
1249 return padding;
1250 });
1251 EXPECT_CALL(callback_, SendPacket(_, _, _, _, true)).Times(1);
1252 clock_.AdvanceTime(kProcessInterval);
1253 pacer_->ProcessPackets();
1254 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1255
1256 // Expect high prio packets to come out first followed by normal
1257 // prio packets and low prio packets (all in capture order).
1258 {
1259 ::testing::InSequence sequence;
1260 EXPECT_CALL(callback_,
1261 SendPacket(ssrc_high_priority, _, capture_time_ms, _, _))
1262 .Times(packets_to_send_per_interval);
1263 EXPECT_CALL(callback_,
1264 SendPacket(ssrc_high_priority, _, second_capture_time_ms, _, _))
1265 .Times(packets_to_send_per_interval);
1266
1267 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
1268 EXPECT_CALL(callback_, SendPacket(ssrc, _, capture_time_ms, _, _))
1269 .Times(1);
1270 }
1271 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
1272 EXPECT_CALL(callback_, SendPacket(ssrc, _, second_capture_time_ms, _, _))
1273 .Times(1);
1274 }
1275 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
1276 EXPECT_CALL(callback_,
1277 SendPacket(ssrc_low_priority, _, capture_time_ms, _, _))
1278 .Times(1);
1279 }
1280 for (size_t i = 0; i < packets_to_send_per_interval; ++i) {
1281 EXPECT_CALL(callback_, SendPacket(ssrc_low_priority, _,
1282 second_capture_time_ms, _, _))
1283 .Times(1);
1284 }
1285 }
1286 pacer_->Resume();
1287
1288 if (PeriodicProcess()) {
1289 // The pacer was resumed directly after the previous process call finished.
1290 // It will therefore wait 5 ms until next process.
1291 clock_.AdvanceTime(TimeUntilNextProcess());
1292
1293 for (size_t i = 0; i < 4; i++) {
1294 pacer_->ProcessPackets();
1295 clock_.AdvanceTime(TimeUntilNextProcess());
1296 }
1297 } else {
1298 while (pacer_->QueueSizePackets() > 0) {
1299 AdvanceTimeAndProcess();
1300 }
1301 }
1302
1303 EXPECT_EQ(TimeDelta::Zero(), pacer_->OldestPacketWaitTime());
1304 }
1305
TEST_P(PacingControllerTest,InactiveFromStart)1306 TEST_P(PacingControllerTest, InactiveFromStart) {
1307 // Recreate the pacer without the inital time forwarding.
1308 pacer_ = std::make_unique<PacingController>(&clock_, &callback_, nullptr,
1309 nullptr, GetParam());
1310 pacer_->SetProbingEnabled(false);
1311 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, kTargetRate);
1312
1313 if (PeriodicProcess()) {
1314 // In period mode, pause the pacer to check the same idle behavior as
1315 // dynamic.
1316 pacer_->Pause();
1317 }
1318
1319 // No packets sent, there should be no keep-alives sent either.
1320 EXPECT_CALL(callback_, SendPadding).Times(0);
1321 EXPECT_CALL(callback_, SendPacket).Times(0);
1322 pacer_->ProcessPackets();
1323
1324 const Timestamp start_time = clock_.CurrentTime();
1325
1326 // Determine the margin need so we can advance to the last possible moment
1327 // that will not cause a process event.
1328 const TimeDelta time_margin =
1329 (GetParam() == PacingController::ProcessMode::kDynamic
1330 ? PacingController::kMinSleepTime
1331 : TimeDelta::Zero()) +
1332 TimeDelta::Micros(1);
1333
1334 EXPECT_EQ(pacer_->NextSendTime() - start_time,
1335 PacingController::kPausedProcessInterval);
1336 clock_.AdvanceTime(PacingController::kPausedProcessInterval - time_margin);
1337 pacer_->ProcessPackets();
1338 EXPECT_EQ(pacer_->NextSendTime() - start_time,
1339 PacingController::kPausedProcessInterval);
1340
1341 clock_.AdvanceTime(time_margin);
1342 pacer_->ProcessPackets();
1343 EXPECT_EQ(pacer_->NextSendTime() - start_time,
1344 2 * PacingController::kPausedProcessInterval);
1345 }
1346
TEST_P(PacingControllerTest,ExpectedQueueTimeMs)1347 TEST_P(PacingControllerTest, ExpectedQueueTimeMs) {
1348 uint32_t ssrc = 12346;
1349 uint16_t sequence_number = 1234;
1350 const size_t kNumPackets = 60;
1351 const size_t kPacketSize = 1200;
1352 const int32_t kMaxBitrate = kPaceMultiplier * 30000;
1353 EXPECT_EQ(TimeDelta::Zero(), pacer_->OldestPacketWaitTime());
1354
1355 pacer_->SetPacingRates(DataRate::BitsPerSec(30000 * kPaceMultiplier),
1356 DataRate::Zero());
1357 for (size_t i = 0; i < kNumPackets; ++i) {
1358 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1359 clock_.TimeInMilliseconds(), kPacketSize);
1360 }
1361
1362 // Queue in ms = 1000 * (bytes in queue) *8 / (bits per second)
1363 TimeDelta queue_time =
1364 TimeDelta::Millis(1000 * kNumPackets * kPacketSize * 8 / kMaxBitrate);
1365 EXPECT_EQ(queue_time, pacer_->ExpectedQueueTime());
1366
1367 const Timestamp time_start = clock_.CurrentTime();
1368 while (pacer_->QueueSizePackets() > 0) {
1369 clock_.AdvanceTime(TimeUntilNextProcess());
1370 pacer_->ProcessPackets();
1371 }
1372 TimeDelta duration = clock_.CurrentTime() - time_start;
1373
1374 EXPECT_EQ(TimeDelta::Zero(), pacer_->ExpectedQueueTime());
1375
1376 // Allow for aliasing, duration should be within one pack of max time limit.
1377 const TimeDelta deviation =
1378 duration - PacingController::kMaxExpectedQueueLength;
1379 EXPECT_LT(deviation.Abs(),
1380 TimeDelta::Millis(1000 * kPacketSize * 8 / kMaxBitrate));
1381 }
1382
TEST_P(PacingControllerTest,QueueTimeGrowsOverTime)1383 TEST_P(PacingControllerTest, QueueTimeGrowsOverTime) {
1384 uint32_t ssrc = 12346;
1385 uint16_t sequence_number = 1234;
1386 EXPECT_EQ(TimeDelta::Zero(), pacer_->OldestPacketWaitTime());
1387
1388 pacer_->SetPacingRates(DataRate::BitsPerSec(30000 * kPaceMultiplier),
1389 DataRate::Zero());
1390 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number,
1391 clock_.TimeInMilliseconds(), 1200);
1392
1393 clock_.AdvanceTimeMilliseconds(500);
1394 EXPECT_EQ(TimeDelta::Millis(500), pacer_->OldestPacketWaitTime());
1395 pacer_->ProcessPackets();
1396 EXPECT_EQ(TimeDelta::Zero(), pacer_->OldestPacketWaitTime());
1397 }
1398
TEST_P(PacingControllerTest,ProbingWithInsertedPackets)1399 TEST_P(PacingControllerTest, ProbingWithInsertedPackets) {
1400 const size_t kPacketSize = 1200;
1401 const int kInitialBitrateBps = 300000;
1402 uint32_t ssrc = 12346;
1403 uint16_t sequence_number = 1234;
1404
1405 PacingControllerProbing packet_sender;
1406 pacer_ = std::make_unique<PacingController>(&clock_, &packet_sender, nullptr,
1407 nullptr, GetParam());
1408 pacer_->CreateProbeCluster(kFirstClusterRate,
1409 /*cluster_id=*/0);
1410 pacer_->CreateProbeCluster(kSecondClusterRate,
1411 /*cluster_id=*/1);
1412 pacer_->SetPacingRates(
1413 DataRate::BitsPerSec(kInitialBitrateBps * kPaceMultiplier),
1414 DataRate::Zero());
1415
1416 for (int i = 0; i < 10; ++i) {
1417 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1418 clock_.TimeInMilliseconds(), kPacketSize);
1419 }
1420
1421 int64_t start = clock_.TimeInMilliseconds();
1422 while (packet_sender.packets_sent() < 5) {
1423 clock_.AdvanceTime(TimeUntilNextProcess());
1424 pacer_->ProcessPackets();
1425 }
1426 int packets_sent = packet_sender.packets_sent();
1427 // Validate first cluster bitrate. Note that we have to account for number
1428 // of intervals and hence (packets_sent - 1) on the first cluster.
1429 EXPECT_NEAR((packets_sent - 1) * kPacketSize * 8000 /
1430 (clock_.TimeInMilliseconds() - start),
1431 kFirstClusterRate.bps(), kProbingErrorMargin.bps());
1432 EXPECT_EQ(0, packet_sender.padding_sent());
1433
1434 clock_.AdvanceTime(TimeUntilNextProcess());
1435 start = clock_.TimeInMilliseconds();
1436 while (packet_sender.packets_sent() < 10) {
1437 clock_.AdvanceTime(TimeUntilNextProcess());
1438 pacer_->ProcessPackets();
1439 }
1440 packets_sent = packet_sender.packets_sent() - packets_sent;
1441 // Validate second cluster bitrate.
1442 EXPECT_NEAR((packets_sent - 1) * kPacketSize * 8000 /
1443 (clock_.TimeInMilliseconds() - start),
1444 kSecondClusterRate.bps(), kProbingErrorMargin.bps());
1445 }
1446
TEST_P(PacingControllerTest,SkipsProbesWhenProcessIntervalTooLarge)1447 TEST_P(PacingControllerTest, SkipsProbesWhenProcessIntervalTooLarge) {
1448 const size_t kPacketSize = 1200;
1449 const int kInitialBitrateBps = 300000;
1450 const uint32_t ssrc = 12346;
1451 const int kProbeClusterId = 3;
1452
1453 // Test with both legacy and new probe discard modes.
1454 // TODO(bugs.webrtc.org/11780): Clean up when legacy is gone.
1455 for (bool abort_delayed_probes : {false, true}) {
1456 uint16_t sequence_number = 1234;
1457
1458 PacingControllerProbing packet_sender;
1459
1460 const test::ExplicitKeyValueConfig trials(
1461 abort_delayed_probes ? "WebRTC-Bwe-ProbingBehavior/"
1462 "abort_delayed_probes:1,max_probe_delay:2ms/"
1463 : "WebRTC-Bwe-ProbingBehavior/"
1464 "abort_delayed_probes:0,max_probe_delay:2ms/");
1465 pacer_ = std::make_unique<PacingController>(&clock_, &packet_sender,
1466 nullptr, &trials, GetParam());
1467 pacer_->SetPacingRates(
1468 DataRate::BitsPerSec(kInitialBitrateBps * kPaceMultiplier),
1469 DataRate::BitsPerSec(kInitialBitrateBps));
1470
1471 for (int i = 0; i < 10; ++i) {
1472 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1473 clock_.TimeInMilliseconds(), kPacketSize);
1474 }
1475 while (pacer_->QueueSizePackets() > 0) {
1476 clock_.AdvanceTime(TimeUntilNextProcess());
1477 pacer_->ProcessPackets();
1478 }
1479
1480 // Probe at a very high rate.
1481 pacer_->CreateProbeCluster(DataRate::KilobitsPerSec(10000), // 10 Mbps.
1482 /*cluster_id=*/kProbeClusterId);
1483 // We need one packet to start the probe.
1484 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1485 clock_.TimeInMilliseconds(), kPacketSize);
1486 const int packets_sent_before_probe = packet_sender.packets_sent();
1487 clock_.AdvanceTime(TimeUntilNextProcess());
1488 pacer_->ProcessPackets();
1489 EXPECT_EQ(packet_sender.packets_sent(), packets_sent_before_probe + 1);
1490
1491 // Figure out how long between probe packets.
1492 Timestamp start_time = clock_.CurrentTime();
1493 clock_.AdvanceTime(TimeUntilNextProcess());
1494 TimeDelta time_between_probes = clock_.CurrentTime() - start_time;
1495 // Advance that distance again + 1ms.
1496 clock_.AdvanceTime(time_between_probes);
1497
1498 // Send second probe packet.
1499 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1500 clock_.TimeInMilliseconds(), kPacketSize);
1501 pacer_->ProcessPackets();
1502 EXPECT_EQ(packet_sender.packets_sent(), packets_sent_before_probe + 2);
1503 PacedPacketInfo last_pacing_info = packet_sender.last_pacing_info();
1504 EXPECT_EQ(last_pacing_info.probe_cluster_id, kProbeClusterId);
1505
1506 // We're exactly where we should be for the next probe.
1507 const Timestamp probe_time = clock_.CurrentTime();
1508 EXPECT_EQ(pacer_->NextSendTime(), clock_.CurrentTime());
1509
1510 BitrateProberConfig probing_config(&trials);
1511 EXPECT_GT(probing_config.max_probe_delay.Get(), TimeDelta::Zero());
1512 // Advance to within max probe delay, should still return same target.
1513 clock_.AdvanceTime(probing_config.max_probe_delay.Get());
1514 EXPECT_EQ(pacer_->NextSendTime(), probe_time);
1515
1516 // Too high probe delay, drop it!
1517 clock_.AdvanceTime(TimeDelta::Micros(1));
1518
1519 int packets_sent_before_timeout = packet_sender.total_packets_sent();
1520 if (abort_delayed_probes) {
1521 // Expected next process time is unchanged, but calling should not
1522 // generate new packets.
1523 EXPECT_EQ(pacer_->NextSendTime(), probe_time);
1524 pacer_->ProcessPackets();
1525 EXPECT_EQ(packet_sender.total_packets_sent(),
1526 packets_sent_before_timeout);
1527
1528 // Next packet sent is not part of probe.
1529 if (PeriodicProcess()) {
1530 do {
1531 AdvanceTimeAndProcess();
1532 } while (packet_sender.total_packets_sent() ==
1533 packets_sent_before_timeout);
1534 } else {
1535 AdvanceTimeAndProcess();
1536 }
1537 const int expected_probe_id = PacedPacketInfo::kNotAProbe;
1538 EXPECT_EQ(packet_sender.last_pacing_info().probe_cluster_id,
1539 expected_probe_id);
1540 } else {
1541 // Legacy behaviour, probe "aborted" so send time moved back. Next call to
1542 // ProcessPackets() still results in packets being marked as part of probe
1543 // cluster.
1544 EXPECT_GT(pacer_->NextSendTime(), probe_time);
1545 AdvanceTimeAndProcess();
1546 EXPECT_GT(packet_sender.total_packets_sent(),
1547 packets_sent_before_timeout);
1548 const int expected_probe_id = last_pacing_info.probe_cluster_id;
1549 EXPECT_EQ(packet_sender.last_pacing_info().probe_cluster_id,
1550 expected_probe_id);
1551
1552 // Time between sent packets keeps being too large, but we still mark the
1553 // packets as being part of the cluster.
1554 Timestamp a = clock_.CurrentTime();
1555 AdvanceTimeAndProcess();
1556 EXPECT_GT(packet_sender.total_packets_sent(),
1557 packets_sent_before_timeout);
1558 EXPECT_EQ(packet_sender.last_pacing_info().probe_cluster_id,
1559 expected_probe_id);
1560 EXPECT_GT(clock_.CurrentTime() - a, time_between_probes);
1561 }
1562 }
1563 }
1564
TEST_P(PacingControllerTest,ProbingWithPaddingSupport)1565 TEST_P(PacingControllerTest, ProbingWithPaddingSupport) {
1566 const size_t kPacketSize = 1200;
1567 const int kInitialBitrateBps = 300000;
1568 uint32_t ssrc = 12346;
1569 uint16_t sequence_number = 1234;
1570
1571 PacingControllerProbing packet_sender;
1572 pacer_ = std::make_unique<PacingController>(&clock_, &packet_sender, nullptr,
1573 nullptr, GetParam());
1574 pacer_->CreateProbeCluster(kFirstClusterRate,
1575 /*cluster_id=*/0);
1576 pacer_->SetPacingRates(
1577 DataRate::BitsPerSec(kInitialBitrateBps * kPaceMultiplier),
1578 DataRate::Zero());
1579
1580 for (int i = 0; i < 3; ++i) {
1581 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1582 clock_.TimeInMilliseconds(), kPacketSize);
1583 }
1584
1585 int64_t start = clock_.TimeInMilliseconds();
1586 int process_count = 0;
1587 while (process_count < 5) {
1588 clock_.AdvanceTime(TimeUntilNextProcess());
1589 pacer_->ProcessPackets();
1590 ++process_count;
1591 }
1592 int packets_sent = packet_sender.packets_sent();
1593 int padding_sent = packet_sender.padding_sent();
1594 EXPECT_GT(packets_sent, 0);
1595 EXPECT_GT(padding_sent, 0);
1596 // Note that the number of intervals here for kPacketSize is
1597 // packets_sent due to padding in the same cluster.
1598 EXPECT_NEAR((packets_sent * kPacketSize * 8000 + padding_sent) /
1599 (clock_.TimeInMilliseconds() - start),
1600 kFirstClusterRate.bps(), kProbingErrorMargin.bps());
1601 }
1602
TEST_P(PacingControllerTest,PaddingOveruse)1603 TEST_P(PacingControllerTest, PaddingOveruse) {
1604 uint32_t ssrc = 12346;
1605 uint16_t sequence_number = 1234;
1606 const size_t kPacketSize = 1200;
1607
1608 // Initially no padding rate.
1609 pacer_->ProcessPackets();
1610 pacer_->SetPacingRates(DataRate::BitsPerSec(60000 * kPaceMultiplier),
1611 DataRate::Zero());
1612
1613 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1614 clock_.TimeInMilliseconds(), kPacketSize);
1615 pacer_->ProcessPackets();
1616
1617 // Add 30kbit padding. When increasing budget, media budget will increase from
1618 // negative (overuse) while padding budget will increase from 0.
1619 clock_.AdvanceTimeMilliseconds(5);
1620 pacer_->SetPacingRates(DataRate::BitsPerSec(60000 * kPaceMultiplier),
1621 DataRate::BitsPerSec(30000));
1622
1623 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1624 clock_.TimeInMilliseconds(), kPacketSize);
1625 EXPECT_LT(TimeDelta::Millis(5), pacer_->ExpectedQueueTime());
1626 // Don't send padding if queue is non-empty, even if padding budget > 0.
1627 EXPECT_CALL(callback_, SendPadding).Times(0);
1628 if (PeriodicProcess()) {
1629 pacer_->ProcessPackets();
1630 } else {
1631 AdvanceTimeAndProcess();
1632 }
1633 }
1634
TEST_P(PacingControllerTest,ProbeClusterId)1635 TEST_P(PacingControllerTest, ProbeClusterId) {
1636 MockPacketSender callback;
1637
1638 pacer_ = std::make_unique<PacingController>(&clock_, &callback, nullptr,
1639 nullptr, GetParam());
1640 Init();
1641
1642 uint32_t ssrc = 12346;
1643 uint16_t sequence_number = 1234;
1644 const size_t kPacketSize = 1200;
1645
1646 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, kTargetRate);
1647 pacer_->SetProbingEnabled(true);
1648 for (int i = 0; i < 10; ++i) {
1649 Send(RtpPacketMediaType::kVideo, ssrc, sequence_number++,
1650 clock_.TimeInMilliseconds(), kPacketSize);
1651 }
1652
1653 // First probing cluster.
1654 EXPECT_CALL(callback,
1655 SendPacket(_, Field(&PacedPacketInfo::probe_cluster_id, 0)))
1656 .Times(5);
1657
1658 for (int i = 0; i < 5; ++i) {
1659 AdvanceTimeAndProcess();
1660 }
1661
1662 // Second probing cluster.
1663 EXPECT_CALL(callback,
1664 SendPacket(_, Field(&PacedPacketInfo::probe_cluster_id, 1)))
1665 .Times(5);
1666
1667 for (int i = 0; i < 5; ++i) {
1668 AdvanceTimeAndProcess();
1669 }
1670
1671 // Needed for the Field comparer below.
1672 const int kNotAProbe = PacedPacketInfo::kNotAProbe;
1673 // No more probing packets.
1674 EXPECT_CALL(callback, GeneratePadding).WillOnce([&](DataSize padding_size) {
1675 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets;
1676 padding_packets.emplace_back(
1677 BuildPacket(RtpPacketMediaType::kPadding, ssrc, sequence_number++,
1678 clock_.TimeInMilliseconds(), padding_size.bytes()));
1679 return padding_packets;
1680 });
1681 bool non_probe_packet_seen = false;
1682 EXPECT_CALL(callback, SendPacket)
1683 .WillOnce([&](std::unique_ptr<RtpPacketToSend> packet,
1684 const PacedPacketInfo& cluster_info) {
1685 EXPECT_EQ(cluster_info.probe_cluster_id, kNotAProbe);
1686 non_probe_packet_seen = true;
1687 });
1688 while (!non_probe_packet_seen) {
1689 AdvanceTimeAndProcess();
1690 }
1691 }
1692
TEST_P(PacingControllerTest,OwnedPacketPrioritizedOnType)1693 TEST_P(PacingControllerTest, OwnedPacketPrioritizedOnType) {
1694 MockPacketSender callback;
1695 pacer_ = std::make_unique<PacingController>(&clock_, &callback, nullptr,
1696 nullptr, GetParam());
1697 Init();
1698
1699 // Insert a packet of each type, from low to high priority. Since priority
1700 // is weighted higher than insert order, these should come out of the pacer
1701 // in backwards order with the exception of FEC and Video.
1702 for (RtpPacketMediaType type :
1703 {RtpPacketMediaType::kPadding,
1704 RtpPacketMediaType::kForwardErrorCorrection, RtpPacketMediaType::kVideo,
1705 RtpPacketMediaType::kRetransmission, RtpPacketMediaType::kAudio}) {
1706 pacer_->EnqueuePacket(BuildRtpPacket(type));
1707 }
1708
1709 ::testing::InSequence seq;
1710 EXPECT_CALL(
1711 callback,
1712 SendPacket(Pointee(Property(&RtpPacketToSend::Ssrc, kAudioSsrc)), _));
1713 EXPECT_CALL(
1714 callback,
1715 SendPacket(Pointee(Property(&RtpPacketToSend::Ssrc, kVideoRtxSsrc)), _));
1716
1717 // FEC and video actually have the same priority, so will come out in
1718 // insertion order.
1719 EXPECT_CALL(
1720 callback,
1721 SendPacket(Pointee(Property(&RtpPacketToSend::Ssrc, kFlexFecSsrc)), _));
1722 EXPECT_CALL(
1723 callback,
1724 SendPacket(Pointee(Property(&RtpPacketToSend::Ssrc, kVideoSsrc)), _));
1725
1726 EXPECT_CALL(
1727 callback,
1728 SendPacket(Pointee(Property(&RtpPacketToSend::Ssrc, kVideoRtxSsrc)), _));
1729
1730 while (pacer_->QueueSizePackets() > 0) {
1731 if (PeriodicProcess()) {
1732 clock_.AdvanceTimeMilliseconds(5);
1733 pacer_->ProcessPackets();
1734 } else {
1735 AdvanceTimeAndProcess();
1736 }
1737 }
1738 }
1739
TEST_P(PacingControllerTest,SmallFirstProbePacket)1740 TEST_P(PacingControllerTest, SmallFirstProbePacket) {
1741 ScopedFieldTrials trial("WebRTC-Pacer-SmallFirstProbePacket/Enabled/");
1742 MockPacketSender callback;
1743 pacer_ = std::make_unique<PacingController>(&clock_, &callback, nullptr,
1744 nullptr, GetParam());
1745 pacer_->CreateProbeCluster(kFirstClusterRate, /*cluster_id=*/0);
1746 pacer_->SetPacingRates(kTargetRate * kPaceMultiplier, DataRate::Zero());
1747
1748 // Add high prio media.
1749 pacer_->EnqueuePacket(BuildRtpPacket(RtpPacketMediaType::kAudio));
1750
1751 // Expect small padding packet to be requested.
1752 EXPECT_CALL(callback, GeneratePadding(DataSize::Bytes(1)))
1753 .WillOnce([&](DataSize padding_size) {
1754 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets;
1755 padding_packets.emplace_back(
1756 BuildPacket(RtpPacketMediaType::kPadding, kAudioSsrc, 1,
1757 clock_.TimeInMilliseconds(), 1));
1758 return padding_packets;
1759 });
1760
1761 size_t packets_sent = 0;
1762 bool media_seen = false;
1763 EXPECT_CALL(callback, SendPacket)
1764 .Times(::testing::AnyNumber())
1765 .WillRepeatedly([&](std::unique_ptr<RtpPacketToSend> packet,
1766 const PacedPacketInfo& cluster_info) {
1767 if (packets_sent == 0) {
1768 EXPECT_EQ(packet->packet_type(), RtpPacketMediaType::kPadding);
1769 } else {
1770 if (packet->packet_type() == RtpPacketMediaType::kAudio) {
1771 media_seen = true;
1772 }
1773 }
1774 packets_sent++;
1775 });
1776 while (!media_seen) {
1777 pacer_->ProcessPackets();
1778 clock_.AdvanceTimeMilliseconds(5);
1779 }
1780 }
1781
TEST_P(PacingControllerTest,TaskLate)1782 TEST_P(PacingControllerTest, TaskLate) {
1783 if (PeriodicProcess()) {
1784 // This test applies only when NOT using interval budget.
1785 return;
1786 }
1787
1788 // Set a low send rate to more easily test timing issues.
1789 DataRate kSendRate = DataRate::KilobitsPerSec(30);
1790 pacer_->SetPacingRates(kSendRate, DataRate::Zero());
1791
1792 // Add four packets of equal size and priority.
1793 pacer_->EnqueuePacket(BuildRtpPacket(RtpPacketMediaType::kVideo));
1794 pacer_->EnqueuePacket(BuildRtpPacket(RtpPacketMediaType::kVideo));
1795 pacer_->EnqueuePacket(BuildRtpPacket(RtpPacketMediaType::kVideo));
1796 pacer_->EnqueuePacket(BuildRtpPacket(RtpPacketMediaType::kVideo));
1797
1798 // Process packets, only first should be sent.
1799 EXPECT_CALL(callback_, SendPacket).Times(1);
1800 pacer_->ProcessPackets();
1801
1802 Timestamp next_send_time = pacer_->NextSendTime();
1803 // Determine time between packets (ca 62ms)
1804 const TimeDelta time_between_packets = next_send_time - clock_.CurrentTime();
1805
1806 // Simulate a late process call, executed just before we allow sending the
1807 // fourth packet.
1808 const TimeDelta kOffset = TimeDelta::Millis(1);
1809 clock_.AdvanceTime((time_between_packets * 3) - kOffset);
1810
1811 EXPECT_CALL(callback_, SendPacket).Times(2);
1812 pacer_->ProcessPackets();
1813
1814 // Check that next scheduled send time is in ca 1ms.
1815 next_send_time = pacer_->NextSendTime();
1816 const TimeDelta time_left = next_send_time - clock_.CurrentTime();
1817 EXPECT_EQ(time_left.RoundTo(TimeDelta::Millis(1)), kOffset);
1818
1819 clock_.AdvanceTime(time_left);
1820 EXPECT_CALL(callback_, SendPacket);
1821 pacer_->ProcessPackets();
1822 }
1823
TEST_P(PacingControllerTest,NoProbingWhilePaused)1824 TEST_P(PacingControllerTest, NoProbingWhilePaused) {
1825 uint32_t ssrc = 12345;
1826 uint16_t sequence_number = 1234;
1827
1828 pacer_->SetProbingEnabled(true);
1829
1830 // Send at least one packet so probing can initate.
1831 SendAndExpectPacket(RtpPacketMediaType::kVideo, ssrc, sequence_number,
1832 clock_.TimeInMilliseconds(), 250);
1833 while (pacer_->QueueSizePackets() > 0) {
1834 AdvanceTimeAndProcess();
1835 }
1836
1837 // Trigger probing.
1838 pacer_->CreateProbeCluster(DataRate::KilobitsPerSec(10000), // 10 Mbps.
1839 /*cluster_id=*/3);
1840
1841 // Time to next send time should be small.
1842 EXPECT_LT(pacer_->NextSendTime() - clock_.CurrentTime(),
1843 PacingController::kPausedProcessInterval);
1844
1845 // Pause pacer, time to next send time should now be the pause process
1846 // interval.
1847 pacer_->Pause();
1848
1849 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(),
1850 PacingController::kPausedProcessInterval);
1851 }
1852
TEST_P(PacingControllerTest,AudioNotPacedEvenWhenAccountedFor)1853 TEST_P(PacingControllerTest, AudioNotPacedEvenWhenAccountedFor) {
1854 const uint32_t kSsrc = 12345;
1855 uint16_t sequence_number = 1234;
1856 const size_t kPacketSize = 123;
1857
1858 // Account for audio - so that audio packets can cause pushback on other
1859 // types such as video. Audio packet should still be immediated passed
1860 // through though ("WebRTC-Pacer-BlockAudio" needs to be enabled in order
1861 // to pace audio packets).
1862 pacer_->SetAccountForAudioPackets(true);
1863
1864 // Set pacing rate to 1 packet/s, no padding.
1865 pacer_->SetPacingRates(DataSize::Bytes(kPacketSize) / TimeDelta::Seconds(1),
1866 DataRate::Zero());
1867
1868 // Add and send an audio packet.
1869 SendAndExpectPacket(RtpPacketMediaType::kAudio, kSsrc, sequence_number++,
1870 clock_.TimeInMilliseconds(), kPacketSize);
1871 pacer_->ProcessPackets();
1872
1873 // Advance time, add another audio packet and process. It should be sent
1874 // immediately.
1875 clock_.AdvanceTimeMilliseconds(5);
1876 SendAndExpectPacket(RtpPacketMediaType::kAudio, kSsrc, sequence_number++,
1877 clock_.TimeInMilliseconds(), kPacketSize);
1878 pacer_->ProcessPackets();
1879 }
1880
TEST_P(PacingControllerTest,PaddingResumesAfterSaturationEvenWithConcurrentAudio)1881 TEST_P(PacingControllerTest,
1882 PaddingResumesAfterSaturationEvenWithConcurrentAudio) {
1883 const uint32_t kSsrc = 12345;
1884 const DataRate kPacingDataRate = DataRate::KilobitsPerSec(125);
1885 const DataRate kPaddingDataRate = DataRate::KilobitsPerSec(100);
1886 const TimeDelta kMaxBufferInTime = TimeDelta::Millis(500);
1887 const DataSize kPacketSize = DataSize::Bytes(130);
1888 const TimeDelta kAudioPacketInterval = TimeDelta::Millis(20);
1889
1890 // In this test, we fist send a burst of video in order to saturate the
1891 // padding debt level.
1892 // We then proceed to send audio at a bitrate that is slightly lower than
1893 // the padding rate, meaning there will be a period with audio but no
1894 // padding sent while the debt is draining, then audio and padding will
1895 // be interlieved.
1896
1897 // Verify both with and without accounting for audio.
1898 for (bool account_for_audio : {false, true}) {
1899 uint16_t sequence_number = 1234;
1900 MockPacketSender callback;
1901 EXPECT_CALL(callback, SendPacket).Times(::testing::AnyNumber());
1902 pacer_ = std::make_unique<PacingController>(&clock_, &callback, nullptr,
1903 nullptr, GetParam());
1904 pacer_->SetAccountForAudioPackets(account_for_audio);
1905
1906 // First, saturate the padding budget.
1907 pacer_->SetPacingRates(kPacingDataRate, kPaddingDataRate);
1908
1909 const TimeDelta kPaddingSaturationTime =
1910 kMaxBufferInTime * kPaddingDataRate /
1911 (kPacingDataRate - kPaddingDataRate);
1912 const DataSize kVideoToSend = kPaddingSaturationTime * kPacingDataRate;
1913 const DataSize kVideoPacketSize = DataSize::Bytes(1200);
1914 DataSize video_sent = DataSize::Zero();
1915 while (video_sent < kVideoToSend) {
1916 pacer_->EnqueuePacket(
1917 BuildPacket(RtpPacketMediaType::kVideo, kSsrc, sequence_number++,
1918 clock_.TimeInMilliseconds(), kVideoPacketSize.bytes()));
1919 video_sent += kVideoPacketSize;
1920 }
1921 while (pacer_->QueueSizePackets() > 0) {
1922 AdvanceTimeAndProcess();
1923 }
1924
1925 // Add a stream of audio packets at a rate slightly lower than the padding
1926 // rate, once the padding debt is paid off we expect padding to be
1927 // generated.
1928 pacer_->SetPacingRates(kPacingDataRate, kPaddingDataRate);
1929 bool padding_seen = false;
1930 EXPECT_CALL(callback, GeneratePadding).WillOnce([&](DataSize padding_size) {
1931 padding_seen = true;
1932 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets;
1933 padding_packets.emplace_back(
1934 BuildPacket(RtpPacketMediaType::kPadding, kSsrc, sequence_number++,
1935 clock_.TimeInMilliseconds(), padding_size.bytes()));
1936 return padding_packets;
1937 });
1938
1939 Timestamp start_time = clock_.CurrentTime();
1940 Timestamp last_audio_time = start_time;
1941 while (!padding_seen) {
1942 Timestamp now = clock_.CurrentTime();
1943 Timestamp next_send_time = pacer_->NextSendTime();
1944 TimeDelta sleep_time =
1945 std::min(next_send_time, last_audio_time + kAudioPacketInterval) -
1946 now;
1947 clock_.AdvanceTime(sleep_time);
1948 while (clock_.CurrentTime() >= last_audio_time + kAudioPacketInterval) {
1949 pacer_->EnqueuePacket(
1950 BuildPacket(RtpPacketMediaType::kAudio, kSsrc, sequence_number++,
1951 clock_.TimeInMilliseconds(), kPacketSize.bytes()));
1952 last_audio_time += kAudioPacketInterval;
1953 }
1954 pacer_->ProcessPackets();
1955 }
1956
1957 // Verify how long it took to drain the padding debt. Allow 2% error margin.
1958 const DataRate kAudioDataRate = kPacketSize / kAudioPacketInterval;
1959 const TimeDelta expected_drain_time =
1960 account_for_audio ? (kMaxBufferInTime * kPaddingDataRate /
1961 (kPaddingDataRate - kAudioDataRate))
1962 : kMaxBufferInTime;
1963 const TimeDelta actual_drain_time = clock_.CurrentTime() - start_time;
1964 EXPECT_NEAR(actual_drain_time.ms(), expected_drain_time.ms(),
1965 expected_drain_time.ms() * 0.02)
1966 << " where account_for_audio = "
1967 << (account_for_audio ? "true" : "false");
1968 }
1969 }
1970
TEST_P(PacingControllerTest,AccountsForAudioEnqueuTime)1971 TEST_P(PacingControllerTest, AccountsForAudioEnqueuTime) {
1972 if (PeriodicProcess()) {
1973 // This test applies only when NOT using interval budget.
1974 return;
1975 }
1976
1977 const uint32_t kSsrc = 12345;
1978 const DataRate kPacingDataRate = DataRate::KilobitsPerSec(125);
1979 const DataRate kPaddingDataRate = DataRate::Zero();
1980 const DataSize kPacketSize = DataSize::Bytes(130);
1981 const TimeDelta kPacketPacingTime = kPacketSize / kPacingDataRate;
1982
1983 uint32_t sequnce_number = 1;
1984 // Audio not paced, but still accounted for in budget.
1985 pacer_->SetAccountForAudioPackets(true);
1986 pacer_->SetPacingRates(kPacingDataRate, kPaddingDataRate);
1987
1988 // Enqueue two audio packets, advance clock to where one packet
1989 // should have drained the buffer already, has they been sent
1990 // immediately.
1991 SendAndExpectPacket(RtpPacketMediaType::kAudio, kSsrc, sequnce_number++,
1992 clock_.TimeInMilliseconds(), kPacketSize.bytes());
1993 SendAndExpectPacket(RtpPacketMediaType::kAudio, kSsrc, sequnce_number++,
1994 clock_.TimeInMilliseconds(), kPacketSize.bytes());
1995 clock_.AdvanceTime(kPacketPacingTime);
1996 // Now process and make sure both packets were sent.
1997 pacer_->ProcessPackets();
1998 ::testing::Mock::VerifyAndClearExpectations(&callback_);
1999
2000 // Add a video packet. I can't be sent until debt from audio
2001 // packets have been drained.
2002 Send(RtpPacketMediaType::kVideo, kSsrc + 1, sequnce_number++,
2003 clock_.TimeInMilliseconds(), kPacketSize.bytes());
2004 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(), kPacketPacingTime);
2005 }
2006
TEST_P(PacingControllerTest,NextSendTimeAccountsForPadding)2007 TEST_P(PacingControllerTest, NextSendTimeAccountsForPadding) {
2008 if (PeriodicProcess()) {
2009 // This test applies only when NOT using interval budget.
2010 return;
2011 }
2012
2013 const uint32_t kSsrc = 12345;
2014 const DataRate kPacingDataRate = DataRate::KilobitsPerSec(125);
2015 const DataSize kPacketSize = DataSize::Bytes(130);
2016 const TimeDelta kPacketPacingTime = kPacketSize / kPacingDataRate;
2017
2018 uint32_t sequnce_number = 1;
2019
2020 // Start with no padding.
2021 pacer_->SetPacingRates(kPacingDataRate, DataRate::Zero());
2022
2023 // Send a single packet.
2024 SendAndExpectPacket(RtpPacketMediaType::kVideo, kSsrc, sequnce_number++,
2025 clock_.TimeInMilliseconds(), kPacketSize.bytes());
2026 pacer_->ProcessPackets();
2027 ::testing::Mock::VerifyAndClearExpectations(&callback_);
2028
2029 // With current conditions, no need to wake until next keep-alive.
2030 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(),
2031 PacingController::kPausedProcessInterval);
2032
2033 // Enqueue a new packet, that can't be sent until previous buffer has
2034 // drained.
2035 SendAndExpectPacket(RtpPacketMediaType::kVideo, kSsrc, sequnce_number++,
2036 clock_.TimeInMilliseconds(), kPacketSize.bytes());
2037 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(), kPacketPacingTime);
2038 clock_.AdvanceTime(kPacketPacingTime);
2039 pacer_->ProcessPackets();
2040 ::testing::Mock::VerifyAndClearExpectations(&callback_);
2041
2042 // With current conditions, again no need to wake until next keep-alive.
2043 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(),
2044 PacingController::kPausedProcessInterval);
2045
2046 // Set a non-zero padding rate. Padding also can't be sent until
2047 // previous debt has cleared. Since padding was disabled before, there
2048 // currently is no padding debt.
2049 pacer_->SetPacingRates(kPacingDataRate, kPacingDataRate / 2);
2050 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(), kPacketPacingTime);
2051
2052 // Advance time, expect padding.
2053 EXPECT_CALL(callback_, SendPadding).WillOnce(Return(kPacketSize.bytes()));
2054 clock_.AdvanceTime(kPacketPacingTime);
2055 pacer_->ProcessPackets();
2056 ::testing::Mock::VerifyAndClearExpectations(&callback_);
2057
2058 // Since padding rate is half of pacing rate, next time we can send
2059 // padding is double the packet pacing time.
2060 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(),
2061 kPacketPacingTime * 2);
2062
2063 // Insert a packet to be sent, this take precedence again.
2064 Send(RtpPacketMediaType::kVideo, kSsrc, sequnce_number++,
2065 clock_.TimeInMilliseconds(), kPacketSize.bytes());
2066 EXPECT_EQ(pacer_->NextSendTime() - clock_.CurrentTime(), kPacketPacingTime);
2067 }
2068
TEST_P(PacingControllerTest,PaddingTargetAccountsForPaddingRate)2069 TEST_P(PacingControllerTest, PaddingTargetAccountsForPaddingRate) {
2070 if (PeriodicProcess()) {
2071 // This test applies only when NOT using interval budget.
2072 return;
2073 }
2074
2075 // Re-init pacer with an explicitly set padding target of 10ms;
2076 const TimeDelta kPaddingTarget = TimeDelta::Millis(10);
2077 ScopedFieldTrials field_trials(
2078 "WebRTC-Pacer-DynamicPaddingTarget/timedelta:10ms/");
2079 SetUp();
2080
2081 const uint32_t kSsrc = 12345;
2082 const DataRate kPacingDataRate = DataRate::KilobitsPerSec(125);
2083 const DataSize kPacketSize = DataSize::Bytes(130);
2084
2085 uint32_t sequnce_number = 1;
2086
2087 // Start with pacing and padding rate equal.
2088 pacer_->SetPacingRates(kPacingDataRate, kPacingDataRate);
2089
2090 // Send a single packet.
2091 SendAndExpectPacket(RtpPacketMediaType::kVideo, kSsrc, sequnce_number++,
2092 clock_.TimeInMilliseconds(), kPacketSize.bytes());
2093 AdvanceTimeAndProcess();
2094 ::testing::Mock::VerifyAndClearExpectations(&callback_);
2095
2096 size_t expected_padding_target_bytes =
2097 (kPaddingTarget * kPacingDataRate).bytes();
2098 EXPECT_CALL(callback_, SendPadding(expected_padding_target_bytes))
2099 .WillOnce(Return(expected_padding_target_bytes));
2100 AdvanceTimeAndProcess();
2101
2102 // Half the padding rate - expect half the padding target.
2103 pacer_->SetPacingRates(kPacingDataRate, kPacingDataRate / 2);
2104 EXPECT_CALL(callback_, SendPadding(expected_padding_target_bytes / 2))
2105 .WillOnce(Return(expected_padding_target_bytes / 2));
2106 AdvanceTimeAndProcess();
2107 }
2108
TEST_P(PacingControllerTest,SendsDeferredFecPackets)2109 TEST_P(PacingControllerTest, SendsDeferredFecPackets) {
2110 ScopedFieldTrials trial("WebRTC-DeferredFecGeneration/Enabled/");
2111 SetUp();
2112
2113 const uint32_t kSsrc = 12345;
2114 const uint32_t kFlexSsrc = 54321;
2115 uint16_t sequence_number = 1234;
2116 uint16_t flexfec_sequence_number = 4321;
2117 const size_t kPacketSize = 123;
2118
2119 // Set pacing rate to 1000 packet/s, no padding.
2120 pacer_->SetPacingRates(
2121 DataSize::Bytes(1000 * kPacketSize) / TimeDelta::Seconds(1),
2122 DataRate::Zero());
2123
2124 int64_t now = clock_.TimeInMilliseconds();
2125 Send(RtpPacketMediaType::kVideo, kSsrc, sequence_number, now, kPacketSize);
2126 EXPECT_CALL(callback_, SendPacket(kSsrc, sequence_number, now, false, false));
2127 EXPECT_CALL(callback_, FetchFec).WillOnce([&]() {
2128 EXPECT_CALL(callback_, SendPacket(kFlexSsrc, flexfec_sequence_number, now,
2129 false, false));
2130 EXPECT_CALL(callback_, FetchFec);
2131 std::vector<std::unique_ptr<RtpPacketToSend>> fec_packets;
2132 fec_packets.push_back(
2133 BuildPacket(RtpPacketMediaType::kForwardErrorCorrection, kFlexSsrc,
2134 flexfec_sequence_number, now, kPacketSize));
2135 return fec_packets;
2136 });
2137 AdvanceTimeAndProcess();
2138 AdvanceTimeAndProcess();
2139 }
2140
2141 INSTANTIATE_TEST_SUITE_P(
2142 WithAndWithoutIntervalBudget,
2143 PacingControllerTest,
2144 ::testing::Values(PacingController::ProcessMode::kPeriodic,
2145 PacingController::ProcessMode::kDynamic));
2146
2147 } // namespace test
2148 } // namespace webrtc
2149