summaryrefslogtreecommitdiffstats
path: root/third_party/libwebrtc/modules/rtp_rtcp/source/rtp_packet_history_unittest.cc
blob: 5019a722965b2c67b74e7fa6c931f8d516df60af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/rtp_rtcp/source/rtp_packet_history.h"

#include <cstdint>
#include <limits>
#include <memory>
#include <utility>

#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
#include "system_wrappers/include/clock.h"
#include "test/gmock.h"
#include "test/gtest.h"

namespace webrtc {
namespace {
// Set a high sequence number so we'll suffer a wrap-around.
constexpr uint16_t kStartSeqNum = 65534u;

// Utility method for truncating sequence numbers to uint16.
uint16_t To16u(size_t sequence_number) {
  return static_cast<uint16_t>(sequence_number & 0xFFFF);
}

using StorageMode = RtpPacketHistory::StorageMode;

using ::testing::AllOf;
using ::testing::Pointee;
using ::testing::Property;

std::unique_ptr<RtpPacketToSend> CreatePacket(
    uint16_t seq_num,
    Timestamp capture_time = Timestamp::Zero()) {
  // Payload, ssrc, timestamp and extensions are irrelevant for this tests.
  std::unique_ptr<RtpPacketToSend> packet(new RtpPacketToSend(nullptr));
  packet->SetSequenceNumber(seq_num);
  packet->set_capture_time(capture_time);
  packet->set_allow_retransmission(true);
  return packet;
}

}  // namespace

class RtpPacketHistoryTest
    : public ::testing::TestWithParam<RtpPacketHistory::PaddingMode> {
 protected:
  RtpPacketHistoryTest()
      : fake_clock_(123456),
        hist_(&fake_clock_, /*enable_padding_prio=*/GetParam()) {}

  SimulatedClock fake_clock_;
  RtpPacketHistory hist_;

  std::unique_ptr<RtpPacketToSend> CreateRtpPacket(uint16_t seq_num) {
    return CreatePacket(seq_num, fake_clock_.CurrentTime());
  }
};

TEST_P(RtpPacketHistoryTest, SetStoreStatus) {
  EXPECT_EQ(StorageMode::kDisabled, hist_.GetStorageMode());
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  EXPECT_EQ(StorageMode::kStoreAndCull, hist_.GetStorageMode());
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  EXPECT_EQ(StorageMode::kStoreAndCull, hist_.GetStorageMode());
  hist_.SetStorePacketsStatus(StorageMode::kDisabled, 0);
  EXPECT_EQ(StorageMode::kDisabled, hist_.GetStorageMode());
}

TEST_P(RtpPacketHistoryTest, ClearsHistoryAfterSetStoreStatus) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum),
                     /*send_time=*/fake_clock_.CurrentTime());
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // Changing store status, even to the current one, will clear the history.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, StartSeqResetAfterReset) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum),
                     /*send_time=*/fake_clock_.CurrentTime());
  // Mark packet as pending so it won't be removed.
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));

  // Changing store status, to clear the history.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));

  // Add a new packet.
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 1)),
                     /*send_time=*/fake_clock_.CurrentTime());
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(To16u(kStartSeqNum + 1)));

  // Advance time past where packet expires.
  fake_clock_.AdvanceTime(RtpPacketHistory::kPacketCullingDelayFactor *
                          RtpPacketHistory::kMinPacketDuration);

  // Add one more packet and verify no state left from packet before reset.
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 2)),
                     /*send_time=*/fake_clock_.CurrentTime());
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 2)));
}

TEST_P(RtpPacketHistoryTest, NoStoreStatus) {
  EXPECT_EQ(StorageMode::kDisabled, hist_.GetStorageMode());
  std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(kStartSeqNum);
  hist_.PutRtpPacket(std::move(packet),
                     /*send_time=*/fake_clock_.CurrentTime());
  // Packet should not be stored.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, GetRtpPacket_NotStored) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  EXPECT_FALSE(hist_.GetPacketState(0));
}

TEST_P(RtpPacketHistoryTest, PutRtpPacket) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(kStartSeqNum);

  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  hist_.PutRtpPacket(std::move(packet),
                     /*send_time=*/fake_clock_.CurrentTime());
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, GetRtpPacket) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  Timestamp capture_time = Timestamp::Millis(1);
  std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(kStartSeqNum);
  packet->set_capture_time(capture_time);
  rtc::CopyOnWriteBuffer buffer = packet->Buffer();
  hist_.PutRtpPacket(std::move(packet),
                     /*send_time=*/fake_clock_.CurrentTime());

  std::unique_ptr<RtpPacketToSend> packet_out =
      hist_.GetPacketAndMarkAsPending(kStartSeqNum);
  ASSERT_TRUE(packet_out);
  EXPECT_EQ(buffer, packet_out->Buffer());
  EXPECT_EQ(capture_time, packet_out->capture_time());
}

TEST_P(RtpPacketHistoryTest, MinResendTime) {
  static const TimeDelta kMinRetransmitInterval = TimeDelta::Millis(100);

  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  hist_.SetRtt(kMinRetransmitInterval);
  Timestamp capture_time = fake_clock_.CurrentTime();
  std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(kStartSeqNum);
  size_t len = packet->size();
  hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());

  // First retransmission - allow early retransmission.
  fake_clock_.AdvanceTimeMilliseconds(1);
  packet = hist_.GetPacketAndMarkAsPending(kStartSeqNum);
  ASSERT_TRUE(packet);
  EXPECT_EQ(len, packet->size());
  EXPECT_EQ(packet->capture_time(), capture_time);
  hist_.MarkPacketAsSent(kStartSeqNum);

  // Second retransmission - advance time to just before retransmission OK.
  fake_clock_.AdvanceTime(kMinRetransmitInterval - TimeDelta::Millis(1));
  EXPECT_FALSE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));

  // Advance time to just after retransmission OK.
  fake_clock_.AdvanceTimeMilliseconds(1);
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, RemovesOldestSentPacketWhenAtMaxSize) {
  const size_t kMaxNumPackets = 10;
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, kMaxNumPackets);

  // History does not allow removing packets within kMinPacketDuration,
  // so in order to test capacity, make sure insertion spans this time.
  const TimeDelta kPacketInterval =
      RtpPacketHistory::kMinPacketDuration / kMaxNumPackets;

  // Add packets until the buffer is full.
  for (size_t i = 0; i < kMaxNumPackets; ++i) {
    std::unique_ptr<RtpPacketToSend> packet =
        CreateRtpPacket(To16u(kStartSeqNum + i));
    // Immediate mark packet as sent.
    hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());
    fake_clock_.AdvanceTime(kPacketInterval);
  }

  // First packet should still be there.
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // History is full, oldest one should be overwritten.
  std::unique_ptr<RtpPacketToSend> packet =
      CreateRtpPacket(To16u(kStartSeqNum + kMaxNumPackets));
  hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());

  // Oldest packet should be gone, but packet after than one still present.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
}

TEST_P(RtpPacketHistoryTest, RemovesOldestPacketWhenAtMaxCapacity) {
  // Tests the absolute upper bound on number of stored packets. Don't allow
  // storing more than this, even if packets have not yet been sent.
  const size_t kMaxNumPackets = RtpPacketHistory::kMaxCapacity;
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull,
                              RtpPacketHistory::kMaxCapacity);

  // Add packets until the buffer is full.
  for (size_t i = 0; i < kMaxNumPackets; ++i) {
    std::unique_ptr<RtpPacketToSend> packet =
        CreateRtpPacket(To16u(kStartSeqNum + i));
    hist_.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock_.CurrentTime());
    // Mark packets as pending, preventing it from being removed.
    hist_.GetPacketAndMarkAsPending(To16u(kStartSeqNum + i));
  }

  // First packet should still be there.
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // History is full, oldest one should be overwritten.
  std::unique_ptr<RtpPacketToSend> packet =
      CreateRtpPacket(To16u(kStartSeqNum + kMaxNumPackets));
  hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());

  // Oldest packet should be gone, but packet after than one still present.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
}

TEST_P(RtpPacketHistoryTest, RemovesLowestPrioPaddingWhenAtMaxCapacity) {
  if (GetParam() != RtpPacketHistory::PaddingMode::kPriority) {
    GTEST_SKIP() << "Padding prioritization required for this test";
  }

  // Tests the absolute upper bound on number of packets in the prioritized
  // set of potential padding packets.
  const size_t kMaxNumPackets = RtpPacketHistory::kMaxPaddingHistory;
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, kMaxNumPackets * 2);
  hist_.SetRtt(TimeDelta::Millis(1));

  // Add packets until the max is reached, and then yet another one.
  for (size_t i = 0; i < kMaxNumPackets + 1; ++i) {
    std::unique_ptr<RtpPacketToSend> packet =
        CreateRtpPacket(To16u(kStartSeqNum + i));
    // Don't mark packets as sent, preventing them from being removed.
    hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());
  }

  // Advance time to allow retransmission/padding.
  fake_clock_.AdvanceTimeMilliseconds(1);

  // The oldest packet will be least prioritized and has fallen out of the
  // priority set.
  for (size_t i = kMaxNumPackets - 1; i > 0; --i) {
    auto packet = hist_.GetPayloadPaddingPacket();
    ASSERT_TRUE(packet);
    EXPECT_EQ(packet->SequenceNumber(), To16u(kStartSeqNum + i + 1));
  }

  // Wrap around to newest padding packet again.
  auto packet = hist_.GetPayloadPaddingPacket();
  ASSERT_TRUE(packet);
  EXPECT_EQ(packet->SequenceNumber(), To16u(kStartSeqNum + kMaxNumPackets));
}

TEST_P(RtpPacketHistoryTest, DontRemoveTooRecentlyTransmittedPackets) {
  // Set size to remove old packets as soon as possible.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  // Add a packet, marked as send, and advance time to just before removal time.
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());
  fake_clock_.AdvanceTime(RtpPacketHistory::kMinPacketDuration -
                          TimeDelta::Millis(1));

  // Add a new packet to trigger culling.
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 1)),
                     fake_clock_.CurrentTime());
  // First packet should still be there.
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // Advance time to where packet will be eligible for removal and try again.
  fake_clock_.AdvanceTimeMilliseconds(1);
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 2)),
                     fake_clock_.CurrentTime());
  // First packet should no be gone, but next one still there.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
}

TEST_P(RtpPacketHistoryTest, DontRemoveTooRecentlyTransmittedPacketsHighRtt) {
  const TimeDelta kRtt = RtpPacketHistory::kMinPacketDuration * 2;
  const TimeDelta kPacketTimeout =
      kRtt * RtpPacketHistory::kMinPacketDurationRtt;

  // Set size to remove old packets as soon as possible.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);
  hist_.SetRtt(kRtt);

  // Add a packet, marked as send, and advance time to just before removal time.
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());
  fake_clock_.AdvanceTime(kPacketTimeout - TimeDelta::Millis(1));

  // Add a new packet to trigger culling.
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 1)),
                     fake_clock_.CurrentTime());
  // First packet should still be there.
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // Advance time to where packet will be eligible for removal and try again.
  fake_clock_.AdvanceTimeMilliseconds(1);
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 2)),
                     fake_clock_.CurrentTime());
  // First packet should no be gone, but next one still there.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
}

TEST_P(RtpPacketHistoryTest, RemovesOldWithCulling) {
  const size_t kMaxNumPackets = 10;
  // Enable culling. Even without feedback, this can trigger early removal.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, kMaxNumPackets);

  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());

  TimeDelta kMaxPacketDuration = RtpPacketHistory::kMinPacketDuration *
                                 RtpPacketHistory::kPacketCullingDelayFactor;
  fake_clock_.AdvanceTime(kMaxPacketDuration - TimeDelta::Millis(1));

  // First packet should still be there.
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // Advance to where packet can be culled, even if buffer is not full.
  fake_clock_.AdvanceTimeMilliseconds(1);
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 1)),
                     fake_clock_.CurrentTime());

  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, RemovesOldWithCullingHighRtt) {
  const size_t kMaxNumPackets = 10;
  const TimeDelta kRtt = RtpPacketHistory::kMinPacketDuration * 2;
  // Enable culling. Even without feedback, this can trigger early removal.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, kMaxNumPackets);
  hist_.SetRtt(kRtt);

  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());

  TimeDelta kMaxPacketDuration = kRtt *
                                 RtpPacketHistory::kMinPacketDurationRtt *
                                 RtpPacketHistory::kPacketCullingDelayFactor;
  fake_clock_.AdvanceTime(kMaxPacketDuration - TimeDelta::Millis(1));

  // First packet should still be there.
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // Advance to where packet can be culled, even if buffer is not full.
  fake_clock_.AdvanceTimeMilliseconds(1);
  hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + 1)),
                     fake_clock_.CurrentTime());

  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, CullWithAcks) {
  const TimeDelta kPacketLifetime = RtpPacketHistory::kMinPacketDuration *
                                    RtpPacketHistory::kPacketCullingDelayFactor;

  const Timestamp start_time = fake_clock_.CurrentTime();
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);

  // Insert three packets 33ms apart, immediately mark them as sent.
  std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(kStartSeqNum);
  packet->SetPayloadSize(50);
  hist_.PutRtpPacket(std::move(packet),
                     /*send_time=*/fake_clock_.CurrentTime());
  fake_clock_.AdvanceTimeMilliseconds(33);
  packet = CreateRtpPacket(To16u(kStartSeqNum + 1));
  packet->SetPayloadSize(50);
  hist_.PutRtpPacket(std::move(packet),
                     /*send_time=*/fake_clock_.CurrentTime());
  fake_clock_.AdvanceTimeMilliseconds(33);
  packet = CreateRtpPacket(To16u(kStartSeqNum + 2));
  packet->SetPayloadSize(50);
  hist_.PutRtpPacket(std::move(packet),
                     /*send_time=*/fake_clock_.CurrentTime());

  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 2)));

  // Remove middle one using ack, check that only that one is gone.
  std::vector<uint16_t> acked_sequence_numbers = {To16u(kStartSeqNum + 1)};
  hist_.CullAcknowledgedPackets(acked_sequence_numbers);

  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_FALSE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 2)));

  // Advance time to where second packet would have expired, verify first packet
  // is removed.
  Timestamp second_packet_expiry_time =
      start_time + kPacketLifetime + TimeDelta::Millis(33 + 1);
  fake_clock_.AdvanceTime(second_packet_expiry_time -
                          fake_clock_.CurrentTime());
  hist_.SetRtt(TimeDelta::Millis(1));  // Trigger culling of old packets.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_FALSE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
  EXPECT_TRUE(hist_.GetPacketState(To16u(kStartSeqNum + 2)));

  // Advance to where last packet expires, verify all gone.
  fake_clock_.AdvanceTimeMilliseconds(33);
  hist_.SetRtt(TimeDelta::Millis(1));  // Trigger culling of old packets.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
  EXPECT_FALSE(hist_.GetPacketState(To16u(kStartSeqNum + 1)));
  EXPECT_FALSE(hist_.GetPacketState(To16u(kStartSeqNum + 2)));
}

TEST_P(RtpPacketHistoryTest, GetPacketAndSetSent) {
  const TimeDelta kRtt = RtpPacketHistory::kMinPacketDuration * 2;
  hist_.SetRtt(kRtt);

  // Set size to remove old packets as soon as possible.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  // Add a sent packet to the history.
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());

  // Retransmission request, first retransmission is allowed immediately.
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));

  // Packet not yet sent, new retransmission not allowed.
  fake_clock_.AdvanceTime(kRtt);
  EXPECT_FALSE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));

  // Mark as sent, but too early for retransmission.
  hist_.MarkPacketAsSent(kStartSeqNum);
  EXPECT_FALSE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));

  // Enough time has passed, retransmission is allowed again.
  fake_clock_.AdvanceTime(kRtt);
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, GetPacketWithEncapsulation) {
  const uint32_t kSsrc = 92384762;
  const TimeDelta kRtt = RtpPacketHistory::kMinPacketDuration * 2;
  hist_.SetRtt(kRtt);

  // Set size to remove old packets as soon as possible.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  // Add a sent packet to the history, with a set SSRC.
  std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(kStartSeqNum);
  packet->SetSsrc(kSsrc);
  hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());

  // Retransmission request, simulate an RTX-like encapsulation, were the packet
  // is sent on a different SSRC.
  std::unique_ptr<RtpPacketToSend> retransmit_packet =
      hist_.GetPacketAndMarkAsPending(
          kStartSeqNum, [](const RtpPacketToSend& packet) {
            auto encapsulated_packet =
                std::make_unique<RtpPacketToSend>(packet);
            encapsulated_packet->SetSsrc(packet.Ssrc() + 1);
            return encapsulated_packet;
          });
  ASSERT_TRUE(retransmit_packet);
  EXPECT_EQ(retransmit_packet->Ssrc(), kSsrc + 1);
}

TEST_P(RtpPacketHistoryTest, GetPacketWithEncapsulationAbortOnNullptr) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());

  // Retransmission request, but the encapsulator determines that this packet is
  // not suitable for retransmission (bandwidth exhausted?) so the retransmit is
  // aborted and the packet is not marked as pending.
  EXPECT_FALSE(hist_.GetPacketAndMarkAsPending(
      kStartSeqNum, [](const RtpPacketToSend&) { return nullptr; }));

  // New try, this time getting the packet should work, and it should not be
  // blocked due to any pending status.
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, DontRemovePendingTransmissions) {
  const TimeDelta kRtt = RtpPacketHistory::kMinPacketDuration * 2;
  const TimeDelta kPacketTimeout =
      kRtt * RtpPacketHistory::kMinPacketDurationRtt;

  // Set size to remove old packets as soon as possible.
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);
  hist_.SetRtt(kRtt);

  // Add a sent packet.
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());

  // Advance clock to just before packet timeout.
  fake_clock_.AdvanceTime(kPacketTimeout - TimeDelta::Millis(1));
  // Mark as enqueued in pacer.
  EXPECT_TRUE(hist_.GetPacketAndMarkAsPending(kStartSeqNum));

  // Advance clock to where packet would have timed out. It should still
  // be there and pending.
  fake_clock_.AdvanceTimeMilliseconds(1);
  EXPECT_TRUE(hist_.GetPacketState(kStartSeqNum));

  // Packet sent. Now it can be removed.
  hist_.MarkPacketAsSent(kStartSeqNum);
  hist_.SetRtt(kRtt);  // Force culling of old packets.
  EXPECT_FALSE(hist_.GetPacketState(kStartSeqNum));
}

TEST_P(RtpPacketHistoryTest, PrioritizedPayloadPadding) {
  if (GetParam() != RtpPacketHistory::PaddingMode::kPriority) {
    GTEST_SKIP() << "Padding prioritization required for this test";
  }

  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  // Add two sent packets, one millisecond apart.
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());
  fake_clock_.AdvanceTimeMilliseconds(1);

  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum + 1),
                     fake_clock_.CurrentTime());
  fake_clock_.AdvanceTimeMilliseconds(1);

  // Latest packet given equal retransmission count.
  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
            kStartSeqNum + 1);

  // Older packet has lower retransmission count.
  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(), kStartSeqNum);

  // Equal retransmission count again, use newest packet.
  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
            kStartSeqNum + 1);

  // Older packet has lower retransmission count.
  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(), kStartSeqNum);

  // Remove newest packet.
  hist_.CullAcknowledgedPackets(std::vector<uint16_t>{kStartSeqNum + 1});

  // Only older packet left.
  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(), kStartSeqNum);

  hist_.CullAcknowledgedPackets(std::vector<uint16_t>{kStartSeqNum});

  EXPECT_EQ(hist_.GetPayloadPaddingPacket(), nullptr);
}

TEST_P(RtpPacketHistoryTest, NoPendingPacketAsPadding) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());
  fake_clock_.AdvanceTimeMilliseconds(1);

  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(), kStartSeqNum);

  // If packet is pending retransmission, don't try to use it as padding.
  hist_.GetPacketAndMarkAsPending(kStartSeqNum);
  if (GetParam() != RtpPacketHistory::PaddingMode::kRecentLargePacket) {
    EXPECT_EQ(nullptr, hist_.GetPayloadPaddingPacket());
  } else {
    // We do allow sending the same packet multiple times in this mode.
    EXPECT_NE(nullptr, hist_.GetPayloadPaddingPacket());
  }

  // Market it as no longer pending, should be usable as padding again.
  hist_.MarkPacketAsSent(kStartSeqNum);
  EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(), kStartSeqNum);
}

TEST_P(RtpPacketHistoryTest, PayloadPaddingWithEncapsulation) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 1);

  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());
  fake_clock_.AdvanceTimeMilliseconds(1);

  // Aborted padding.
  EXPECT_EQ(nullptr, hist_.GetPayloadPaddingPacket(
                         [](const RtpPacketToSend&) { return nullptr; }));

  // Get copy of packet, but with sequence number modified.
  auto padding_packet =
      hist_.GetPayloadPaddingPacket([&](const RtpPacketToSend& packet) {
        auto encapsulated_packet = std::make_unique<RtpPacketToSend>(packet);
        encapsulated_packet->SetSequenceNumber(kStartSeqNum + 1);
        return encapsulated_packet;
      });
  ASSERT_TRUE(padding_packet);
  EXPECT_EQ(padding_packet->SequenceNumber(), kStartSeqNum + 1);
}

TEST_P(RtpPacketHistoryTest, NackAfterAckIsNoop) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 2);
  // Add two sent packets.
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum), fake_clock_.CurrentTime());
  hist_.PutRtpPacket(CreateRtpPacket(kStartSeqNum + 1),
                     fake_clock_.CurrentTime());
  // Remove newest one.
  hist_.CullAcknowledgedPackets(std::vector<uint16_t>{kStartSeqNum + 1});
  // Retransmission request for already acked packet, should be noop.
  auto packet = hist_.GetPacketAndMarkAsPending(kStartSeqNum + 1);
  EXPECT_EQ(packet.get(), nullptr);
}

TEST_P(RtpPacketHistoryTest, OutOfOrderInsertRemoval) {
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);

  // Insert packets, out of order, including both forwards and backwards
  // sequence number wraps.
  const int seq_offsets[] = {0, 1, -1, 2, -2, 3, -3};

  for (int offset : seq_offsets) {
    uint16_t seq_no = To16u(kStartSeqNum + offset);
    std::unique_ptr<RtpPacketToSend> packet = CreateRtpPacket(seq_no);
    packet->SetPayloadSize(50);
    hist_.PutRtpPacket(std::move(packet), fake_clock_.CurrentTime());
    fake_clock_.AdvanceTimeMilliseconds(33);
  }

  // Check packet are there and remove them in the same out-of-order fashion.
  for (int offset : seq_offsets) {
    uint16_t seq_no = To16u(kStartSeqNum + offset);
    EXPECT_TRUE(hist_.GetPacketState(seq_no));
    std::vector<uint16_t> acked_sequence_numbers = {seq_no};
    hist_.CullAcknowledgedPackets(acked_sequence_numbers);
    EXPECT_FALSE(hist_.GetPacketState(seq_no));
  }
}

TEST_P(RtpPacketHistoryTest, UsesLastPacketAsPaddingWithPrioOff) {
  if (GetParam() != RtpPacketHistory::PaddingMode::kDefault) {
    GTEST_SKIP() << "Default padding prioritization required for this test";
  }

  const size_t kHistorySize = 10;
  hist_.SetStorePacketsStatus(StorageMode::kStoreAndCull, kHistorySize);

  EXPECT_EQ(hist_.GetPayloadPaddingPacket(), nullptr);

  for (size_t i = 0; i < kHistorySize; ++i) {
    hist_.PutRtpPacket(CreateRtpPacket(To16u(kStartSeqNum + i)),
                       fake_clock_.CurrentTime());
    hist_.MarkPacketAsSent(To16u(kStartSeqNum + i));
    fake_clock_.AdvanceTimeMilliseconds(1);

    // Last packet always returned.
    EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
              To16u(kStartSeqNum + i));
    EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
              To16u(kStartSeqNum + i));
    EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
              To16u(kStartSeqNum + i));
  }

  // Remove packets from the end, last in the list should be returned.
  for (size_t i = kHistorySize - 1; i > 0; --i) {
    hist_.CullAcknowledgedPackets(
        std::vector<uint16_t>{To16u(kStartSeqNum + i)});

    EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
              To16u(kStartSeqNum + i - 1));
    EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
              To16u(kStartSeqNum + i - 1));
    EXPECT_EQ(hist_.GetPayloadPaddingPacket()->SequenceNumber(),
              To16u(kStartSeqNum + i - 1));
  }

  hist_.CullAcknowledgedPackets(std::vector<uint16_t>{kStartSeqNum});
  EXPECT_EQ(hist_.GetPayloadPaddingPacket(), nullptr);
}

INSTANTIATE_TEST_SUITE_P(
    WithAndWithoutPaddingPrio,
    RtpPacketHistoryTest,
    ::testing::Values(RtpPacketHistory::PaddingMode::kDefault,
                      RtpPacketHistory::PaddingMode::kPriority,
                      RtpPacketHistory::PaddingMode::kRecentLargePacket));

TEST(RtpPacketHistoryRecentLargePacketMode,
     GetPayloadPaddingPacketAfterCullWithAcksReturnOldPacket) {
  SimulatedClock fake_clock(1234);
  RtpPacketHistory history(&fake_clock,
                           RtpPacketHistory::PaddingMode::kRecentLargePacket);

  history.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  std::unique_ptr<RtpPacketToSend> packet = CreatePacket(kStartSeqNum);
  packet->SetPayloadSize(1000);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());
  fake_clock.AdvanceTimeMilliseconds(33);
  history.CullAcknowledgedPackets(std::vector<uint16_t>{kStartSeqNum});

  EXPECT_THAT(
      history.GetPayloadPaddingPacket(),
      Pointee(AllOf(Property(&RtpPacketToSend::SequenceNumber, kStartSeqNum),
                    (Property(&RtpPacketToSend::payload_size, 1000)))));
}

TEST(RtpPacketHistoryRecentLargePacketMode,
     GetPayloadPaddingPacketIgnoreSmallRecentPackets) {
  SimulatedClock fake_clock(1234);
  RtpPacketHistory history(&fake_clock,
                           RtpPacketHistory::PaddingMode::kRecentLargePacket);
  history.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  std::unique_ptr<RtpPacketToSend> packet = CreatePacket(kStartSeqNum);
  packet->SetPayloadSize(1000);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());
  packet = CreatePacket(kStartSeqNum + 1);
  packet->SetPayloadSize(100);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());

  EXPECT_THAT(
      history.GetPayloadPaddingPacket(),
      Pointee(AllOf(Property(&RtpPacketToSend::SequenceNumber, kStartSeqNum),
                    Property(&RtpPacketToSend::payload_size, 1000))));
}

TEST(RtpPacketHistoryRecentLargePacketMode,
     GetPayloadPaddingPacketReturnsRecentPacketIfSizeNearMax) {
  SimulatedClock fake_clock(1234);
  RtpPacketHistory history(&fake_clock,
                           RtpPacketHistory::PaddingMode::kRecentLargePacket);
  history.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  std::unique_ptr<RtpPacketToSend> packet = CreatePacket(kStartSeqNum);
  packet->SetPayloadSize(1000);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());
  packet = CreatePacket(kStartSeqNum + 1);
  packet->SetPayloadSize(950);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());

  EXPECT_THAT(history.GetPayloadPaddingPacket(),
              (Pointee(AllOf(
                  Property(&RtpPacketToSend::SequenceNumber, kStartSeqNum + 1),
                  Property(&RtpPacketToSend::payload_size, 950)))));
}

TEST(RtpPacketHistoryRecentLargePacketMode,
     GetPayloadPaddingPacketReturnsLastPacketAfterLargeSequenceNumberGap) {
  SimulatedClock fake_clock(1234);
  RtpPacketHistory history(&fake_clock,
                           RtpPacketHistory::PaddingMode::kRecentLargePacket);
  history.SetStorePacketsStatus(StorageMode::kStoreAndCull, 10);
  uint16_t sequence_number = std::numeric_limits<uint16_t>::max() - 50;
  std::unique_ptr<RtpPacketToSend> packet = CreatePacket(sequence_number);
  packet->SetPayloadSize(1000);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());
  ASSERT_THAT(
      history.GetPayloadPaddingPacket(),
      Pointee(Property(&RtpPacketToSend::SequenceNumber, sequence_number)));

  // A long time pass... and potentially many small packets are injected, or
  // timestamp jumps.
  sequence_number = 1 << 13;
  packet = CreatePacket(sequence_number);
  packet->SetPayloadSize(100);
  history.PutRtpPacket(std::move(packet),
                       /*send_time=*/fake_clock.CurrentTime());
  EXPECT_THAT(
      history.GetPayloadPaddingPacket(),
      Pointee(Property(&RtpPacketToSend::SequenceNumber, sequence_number)));
}

}  // namespace webrtc