forked from catid/siamese
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSiameseEncoder.cpp
1460 lines (1186 loc) · 50.8 KB
/
SiameseEncoder.cpp
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** \file
\brief Siamese FEC Implementation: Encoder
\copyright Copyright (c) 2017 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Siamese nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "SiameseEncoder.h"
#include "SiameseSerializers.h"
namespace siamese {
#ifdef SIAMESE_ENCODER_DUMP_VERBOSE
static logger::Channel Logger("Encoder", logger::Level::Debug);
#else
static logger::Channel Logger("Encoder", logger::Level::Error);
#endif
//------------------------------------------------------------------------------
// EncoderStats
EncoderStats::EncoderStats()
{
for (unsigned i = 0; i < SiameseEncoderStats_Count; ++i) {
Counts[i] = 0;
}
}
//------------------------------------------------------------------------------
// EncoderPacketWindow
EncoderPacketWindow::EncoderPacketWindow()
{
NextColumn = 0;
ColumnStart = 0;
ClearWindow();
}
void EncoderPacketWindow::ClearWindow()
{
FirstUnremovedElement = 0;
Count = 0;
LongestPacket = 0;
SumStartElement = 0;
SumEndElement = 0;
for (unsigned laneIndex = 0; laneIndex < kColumnLaneCount; ++laneIndex)
{
EncoderColumnLane& lane = Lanes[laneIndex];
for (unsigned sumIndex = 0; sumIndex < kColumnSumCount; ++sumIndex)
{
lane.Sum[sumIndex].Bytes = 0;
lane.NextElement[sumIndex] = laneIndex;
}
lane.LongestPacket = 0;
}
}
SiameseResult EncoderPacketWindow::Add(SiameseOriginalPacket& packet)
{
if (EmergencyDisabled) {
return Siamese_Disabled;
}
if (GetRemainingSlots() <= 0) {
// This is not invalid input - The application often does not have
// control over how much data it tries to send. Instead it must
// listen for our feedback return code to decide when to slow down.
return Siamese_MaxPacketsReached;
}
const unsigned column = NextColumn;
const unsigned subwindowCount = Subwindows.GetSize();
unsigned element = Count;
// Assign packet number
packet.PacketNum = column;
// If there is not enough room for this new element:
// Note: Adding a buffer of kColumnLaneCount to create space ahead for
// snapshots as a subwindow is filled and we need to store its snapshot
if (element + kColumnLaneCount >= subwindowCount * kSubwindowSize)
{
EncoderSubwindow* subwindow = TheAllocator->Construct<EncoderSubwindow>();
if (!subwindow || !Subwindows.Append(subwindow))
{
EmergencyDisabled = true;
Logger.Error("WindowAdd.Construct OOM");
SIAMESE_DEBUG_BREAK();
return Siamese_Disabled;
}
}
if (Count > 0) {
++Count;
}
else
{
// Start a new window:
element = column % kColumnLaneCount;
StartNewWindow(column);
}
// Initialize original packet with received data
OriginalPacket* original = GetWindowElement(element);
if (0 == original->Initialize(TheAllocator, packet))
{
EmergencyDisabled = true;
Logger.Error("WindowAdd.Initialize OOM");
SIAMESE_DEBUG_BREAK();
return Siamese_Disabled;
}
SIAMESE_DEBUG_ASSERT(original->Column % kColumnLaneCount == element % kColumnLaneCount);
// Attach original send time in milliseconds
*GetWindowElementTimestampPtr(element) = static_cast<uint32_t>(GetTimeMsec());
// Roll next column to assign
NextColumn = IncrementColumn1(NextColumn);
// Update longest packet
const unsigned originalBytes = original->Buffer.Bytes;
const unsigned laneIndex = column % kColumnLaneCount;
EncoderColumnLane& lane = Lanes[laneIndex];
if (lane.LongestPacket < originalBytes) {
lane.LongestPacket = originalBytes;
}
if (LongestPacket < originalBytes) {
LongestPacket = originalBytes;
}
Stats->Counts[SiameseEncoderStats_OriginalCount]++;
Stats->Counts[SiameseEncoderStats_OriginalBytes] += packet.DataBytes;
return Siamese_Success;
}
void EncoderPacketWindow::StartNewWindow(unsigned column)
{
// Maintain the invariant that element % 8 == column % 8 by skipping some
const unsigned element = column % kColumnLaneCount;
ColumnStart = column - element;
SIAMESE_DEBUG_ASSERT(column >= element && ColumnStart < kColumnPeriod);
SumStartElement = element;
SumEndElement = element;
FirstUnremovedElement = element;
Count = element + 1;
// Reset longest packet
LongestPacket = 0;
for (unsigned laneIndex = 0; laneIndex < kColumnLaneCount; ++laneIndex) {
Lanes[laneIndex].LongestPacket = 0;
}
Logger.Info(">>> Starting a new window from column ", ColumnStart);
}
void EncoderPacketWindow::RemoveBefore(unsigned firstKeptColumn)
{
if (EmergencyDisabled) {
return;
}
// Convert column to element, handling wrap-around:
const unsigned firstKeptElement = ColumnToElement(firstKeptColumn);
// If the column is outside of the window:
if (InvalidElement(firstKeptElement))
{
// If the element was before the window:
if (IsColumnDeltaNegative(firstKeptElement)) {
Logger.Info("Remove before column ", firstKeptColumn, " - Ignored before window");
}
else
{
// Removed everything
Count = 0;
Logger.Info("Remove before column ", firstKeptColumn, " - Removed everything");
}
}
else
{
Logger.Info("Remove before column ", firstKeptColumn, " element ", firstKeptElement);
// Mark these elements for removal next time we generate output
if (FirstUnremovedElement < firstKeptElement) {
FirstUnremovedElement = firstKeptElement;
}
}
}
void EncoderPacketWindow::ResetSums(unsigned elementStart)
{
// Recreate all the sums from scratch after this:
for (unsigned laneIndex = 0; laneIndex < kColumnLaneCount; ++laneIndex)
{
// Calculate first element to accumulate for this lane
const unsigned nextElement = GetNextLaneElement(elementStart, laneIndex);
for (unsigned sumIndex = 0; sumIndex < kColumnSumCount; ++sumIndex)
{
Lanes[laneIndex].NextElement[sumIndex] = nextElement;
Lanes[laneIndex].Sum[sumIndex].Bytes = 0;
}
}
SumStartElement = elementStart;
SumEndElement = elementStart;
SumColumnStart = ElementToColumn(elementStart);
SumErasedCount = 0;
}
void EncoderPacketWindow::RemoveElements()
{
const unsigned firstKeptSubwindow = FirstUnremovedElement / kSubwindowSize;
const unsigned removedElementCount = firstKeptSubwindow * kSubwindowSize;
SIAMESE_DEBUG_ASSERT(firstKeptSubwindow >= 1);
SIAMESE_DEBUG_ASSERT(firstKeptSubwindow < Subwindows.GetSize());
SIAMESE_DEBUG_ASSERT(removedElementCount % kColumnLaneCount == 0);
SIAMESE_DEBUG_ASSERT(removedElementCount <= FirstUnremovedElement);
Logger.Info("******** Removing up to ", FirstUnremovedElement, " and startColumn=", ColumnStart);
// If there are running sums:
if (SumEndElement > SumStartElement)
{
// Roll up the sums past the removal point
for (unsigned laneIndex = 0; laneIndex < kColumnLaneCount; ++laneIndex)
{
for (unsigned sumIndex = 0; sumIndex < kColumnSumCount; ++sumIndex)
{
GetSum(laneIndex, sumIndex, removedElementCount);
SIAMESE_DEBUG_ASSERT(Lanes[laneIndex].NextElement[sumIndex] >= removedElementCount);
Lanes[laneIndex].NextElement[sumIndex] -= removedElementCount;
}
}
if (removedElementCount > SumStartElement) {
SumErasedCount += removedElementCount - SumStartElement;
}
if (SumEndElement > removedElementCount) {
SumEndElement -= removedElementCount;
}
else {
SumEndElement = 0;
}
if (SumStartElement > removedElementCount) {
SumStartElement -= removedElementCount;
}
else {
SumStartElement = 0;
}
}
// Shift kept subwindows to the front of the vector:
// Resize a temporary buffer for removed subwindows
if (!SubwindowsShift.SetSize_NoCopy(firstKeptSubwindow))
{
SIAMESE_DEBUG_BREAK(); // OOM
EmergencyDisabled = true;
return;
}
// Store removed subwindows temporarily
memcpy(
SubwindowsShift.GetPtr(0),
Subwindows.GetPtr(0),
firstKeptSubwindow * sizeof(EncoderSubwindow*)
);
const unsigned subwindowsShifted = Subwindows.GetSize() - firstKeptSubwindow;
// Shift subwindows to front that are being kept
memmove(
Subwindows.GetPtr(0),
Subwindows.GetPtr(firstKeptSubwindow),
subwindowsShifted * sizeof(EncoderSubwindow*)
);
// Removed subwindows are moved to the end (unordered) for later reuse
memcpy(
Subwindows.GetPtr(subwindowsShifted),
SubwindowsShift.GetPtr(0),
firstKeptSubwindow * sizeof(EncoderSubwindow*)
);
// Update the count of elements in the window
SIAMESE_DEBUG_ASSERT(Count >= removedElementCount);
Count -= removedElementCount;
// Roll up the ColumnStart member
ColumnStart = ElementToColumn(removedElementCount);
SIAMESE_DEBUG_ASSERT(ColumnStart == Subwindows.GetRef(0)->Originals[0].Column);
// Roll up the FirstUnremovedElement member
SIAMESE_DEBUG_ASSERT(FirstUnremovedElement % kSubwindowSize == FirstUnremovedElement - removedElementCount);
SIAMESE_DEBUG_ASSERT(FirstUnremovedElement >= removedElementCount);
FirstUnremovedElement -= removedElementCount;
// Determine the new longest packets
unsigned longestPacket = 0;
unsigned laneLongest[kColumnLaneCount] = { 0 };
for (unsigned i = FirstUnremovedElement, count = Count; i < count; ++i)
{
OriginalPacket* original = GetWindowElement(i);
const unsigned originalBytes = original->Buffer.Bytes;
if (longestPacket < originalBytes) {
longestPacket = originalBytes;
}
SIAMESE_DEBUG_ASSERT(original->Column % kColumnLaneCount == i % kColumnLaneCount);
const unsigned laneIndex = i % kColumnLaneCount;
if (laneLongest[laneIndex] < originalBytes) {
laneLongest[laneIndex] = originalBytes;
}
}
// Update longest packet fields
LongestPacket = longestPacket;
for (unsigned laneIndex = 0; laneIndex < kColumnLaneCount; ++laneIndex) {
Lanes[laneIndex].LongestPacket = laneLongest[laneIndex];
}
// If there are no running sums:
if (SumEndElement <= SumStartElement) {
ResetSums(FirstUnremovedElement);
}
}
const GrowingAlignedDataBuffer* EncoderPacketWindow::GetSum(unsigned laneIndex, unsigned sumIndex, unsigned elementEnd)
{
EncoderColumnLane& lane = Lanes[laneIndex];
unsigned element = lane.NextElement[sumIndex];
SIAMESE_DEBUG_ASSERT(element % kColumnLaneCount == laneIndex);
SIAMESE_DEBUG_ASSERT(element < Count + kColumnLaneCount);
if (element < elementEnd)
{
GrowingAlignedDataBuffer& sum = lane.Sum[sumIndex];
// Grow this sum for this lane to fit new (larger) data if needed
if (lane.LongestPacket > 0 &&
!sum.GrowZeroPadded(TheAllocator, lane.LongestPacket))
{
EmergencyDisabled = true;
goto ExitSum;
}
do
{
Logger.Info("Lane ", laneIndex, " sum ", sumIndex, " accumulating column: ", ColumnStart + element);
OriginalPacket* original = GetWindowElement(element);
const unsigned column = original->Column;
unsigned addBytes = original->Buffer.Bytes;
if (!sum.GrowZeroPadded(TheAllocator, addBytes))
{
EmergencyDisabled = true;
goto ExitSum;
}
SIAMESE_DEBUG_ASSERT(original->Buffer.Bytes <= sum.Bytes || element < FirstUnremovedElement);
// Sum += PacketData
if (sumIndex == 0) {
gf256_add_mem(sum.Data, original->Buffer.Data, addBytes);
}
else
{
// Sum += CX[2] * PacketData
uint8_t CX = GetColumnValue(column);
if (sumIndex == 2) {
CX = gf256_sqr(CX);
}
gf256_muladd_mem(sum.Data, CX, original->Buffer.Data, addBytes);
}
SIAMESE_DEBUG_ASSERT(original->Column % kColumnLaneCount == laneIndex);
element += kColumnLaneCount;
} while (element < elementEnd);
// Store next element to accumulate
lane.NextElement[sumIndex] = element;
}
ExitSum:
return &lane.Sum[sumIndex];
}
//------------------------------------------------------------------------------
// EncoderAcknowledgementState
/**
Siamese Retransmission Timeout (RTO) calculation
TL;DR: RTO = Max(RTT) * 1.5
Why calculate RTO?
There are three times when retransmission timeouts must be decided:
(1) When the receiver receives a datagram out of order.
(2) When the sender does not get any acknowledgement back for a datagram.
(3) When the sender retransmits a datagram due to (1) or (2) and does not
get any acknowledgement back for that datagram.
For case (1) the receiver has full data on reorder variance and can improve
on the RTO for sequence number holes that it notices. Sending a NACK right
away once a hole is noticed might enable the sender to retransmit faster.
For case (2) and (3) the encoder must decide what the RTO should be without
any feedback from the decoder except prior acknowledgements. These are the
cases where Siamese must determine the appropriate RTO.
How does Siamese calculate RTO?
The RTO is used to decide when to retransmit data if no acknowledgements
have been received, so we need to estimate the maximum time it takes to get
back an acknowledgement for sent data.
The delay between when siamese_encoder_add() indicates a packet was sent
and when siamese_encoder_ack() indicates that packet was received is the
data available in Encoder::Acknowledge(). This delay is called the Round-
Trip Time (RTT).
The Siamese encoder sends (a) original data, (b) FEC recovery packets, and
(c) retransmissions of original data, each of which can cause the Siamese
decoder to acknowledge the receipt of the data. In the acknowledgement
timing data, the RTT for (a) is mixed in with the RTTs in cases (b)
and (c) and there is no way to tell those cases apart.
Fortunately, the maximum RTT in each set acknowledged data is a good
guide for the RTO value. For case (a) it helps put an upper bound on
the time it takes to acknowledge original data. For case (b) the delay
values will be unexpectedly small so will be mostly eliminated from the
data. For case (c) the delay will either be useful or too small if the
RTO was too small and the original was just taking too long to arrive.
The only remaining issue is if any set of acknowledged data is entirely
made up of values that are too small. To resolve that problem, a
windowed maximum is updated over time.
An advantage of basing the RTO on the maximum RTT is that it can react
to the leading edge of increasing delays due to cross-traffic, self-
congestion, and other network changes. As soon as the delays start
increasing, the maximum value will be updated immediately.
The RTO is chosen to be 50% higher than the largest RTT seen lately,
avoiding unnecessary retransmissions when the delay starts to increase.
This rough value may overestimate the proper RTO, but it does not need
to be particularly accurate (see below).
What other approaches exist?
For ARQ schemes that need to estimate RTT in addition to RTO, it is more
important to sort cases (a) from (b) and (c). Google's QUIC assigns
each packet a different nonce instead of reusing the same reliable packet
sequence number, enabling it to differentiate these cases. For Siamese,
only RTO is needed so that would be overkill.
Does RTO need to be very accurate? No.
For delay-sensitive flows, FEC recovery is clearly preferred over any of
these options. By the time RTT * 2 has elapsed, a few recovery packets
must have been received, and it is likely that the missing data is
already recovered. Basically in case (3) FEC does almost all the heavy
lifting already, and a larger RTO should be used. And even in case (2) it
can play a large role in reducing delay.
With careful estimation on the receiver side, a NACK can be sent sooner for
reordered data to cut the overall retransmission time to RTT * 1.5 at best.
This would require a lot more complexity at the receiver and it would also
provide no practical benefit over recovering with FEC.
For high-speed flows, FEC recovery is not desireable because there is no
delay requirement on the data. So instead a long RTO can be selected to
safely avoid retransmitting data unnecessarily, optimizing for bandwidth.
*/
bool EncoderAcknowledgementState::OnAcknowledgementData(const uint8_t* data, unsigned bytes)
{
unsigned nextColumnExpected = 0;
int headerBytes = DeserializeHeader_PacketNum(data, bytes, nextColumnExpected);
if (headerBytes < 1) {
SIAMESE_DEBUG_BREAK(); // Invalid input
return false;
}
data += headerBytes, bytes -= headerBytes;
// If we received ack data out of order:
unsigned columnDelta = SubtractColumns(nextColumnExpected, NextColumnExpected);
if (IsColumnDeltaNegative(columnDelta)) {
// Ignore any older data since it would lose information.
return true;
}
/*
Ignore duplicate data.
Note if we get the same packet number twice and the data bytes changed
we will accept the new data. This means that if datagrams are received
out of order, the old one might win.
This can be avoided by including the latest acknowledged datagram nonce
at the protocol level with each acknowledgement. Then assuming that
data is being received regularly it will allow a quick reject for old
acknowledgement data.
*/
if (NextColumnExpected == nextColumnExpected &&
Data && bytes == DataBytes &&
0 == memcmp(data, Data, bytes))
{
return true;
}
// Update next expected column
NextColumnExpected = nextColumnExpected;
// Reset message decoder state
Offset = 0;
LossColumn = NextColumnExpected;
LossCount = 0;
DataBytes = bytes;
// If there are NACK ranges:
if (bytes > 0)
{
// Copy the new data into place with some padding at the end
Data = TheAllocator->Reallocate(Data, bytes + kPaddingBytes,
pktalloc::Realloc::Uninitialized);
memcpy(Data, data, bytes);
memset(Data + bytes, 0, kPaddingBytes); // Zero guard bytes
// Returns false if decoding the first loss range fails
if (!DecodeNextRange()) {
return false;
}
SIAMESE_DEBUG_ASSERT(IsIteratorAtFront()); // Invalid data
}
// Update RTO estimation based on the latest loss ranges and rollup
UpdateRTO();
// Remove data the given column
TheWindow->RemoveBefore(NextColumnExpected);
return true;
}
void EncoderAcknowledgementState::UpdateRTO()
{
const unsigned windowCount = TheWindow->Count;
// If there is no unacknowledged data:
unsigned firstLoss = TheWindow->ColumnToElement(NextColumnExpected);
if (firstLoss >= windowCount) {
return;
}
// Get current time
const uint64_t nowMsec64 = GetTimeMsec();
const uint32_t nowMsec = static_cast<uint32_t>(nowMsec64);
unsigned longestAckDelayMsec = 0;
// Locate first unacknowledged element
unsigned element = TheWindow->ColumnToElement(NextRTOColumn);
if (element >= windowCount)
{
Logger.Warning("NextRTOColumn was invalid, so rolling up to FirstUnremovedElement = ", TheWindow->FirstUnremovedElement);
element = TheWindow->FirstUnremovedElement;
}
// First walk through all the rollups:
for (; element < firstLoss; ++element)
{
// Get last time this was sent (maybe the second time)
const uint32_t* sendMsecPtr = TheWindow->GetWindowElementTimestampPtr(element);
SIAMESE_DEBUG_ASSERT(*sendMsecPtr != 0);
// Calculate delay since it was sent
const int32_t delayMsec = nowMsec - *sendMsecPtr;
if ((unsigned)delayMsec > longestAckDelayMsec && delayMsec > 0)
{
longestAckDelayMsec = delayMsec;
Logger.Info("ACKED TS = ", *sendMsecPtr, " for ID=", element + TheWindow->ColumnStart, " <- new max delay: ", delayMsec);
}
else
{
Logger.Info("acked ts = ", *sendMsecPtr, " for ID=", element + TheWindow->ColumnStart, " - not max delay - ", delayMsec);
}
}
// Scan the selective acknowledgements implied by the NACK ranges:
unsigned remaining = DataBytes;
const uint8_t* data = Data;
while (remaining > 0)
{
// Decode NACK loss range
unsigned relativeStart, lossCountM1;
const int lossRangeBytes = DeserializeHeader_NACKLossRange(
data, remaining + kPaddingBytes, relativeStart, lossCountM1);
if (lossRangeBytes < 0 ||
lossRangeBytes > (int)remaining)
{
SIAMESE_DEBUG_BREAK(); // Invalid input
return;
}
data += lossRangeBytes, remaining -= lossRangeBytes;
// If element has not rolled up to the first acknowledged packet:
if (element + 1 < firstLoss) {
element = firstLoss - 1; // Roll it up
}
// Calculat the first loss in this NACK range
firstLoss += relativeStart;
// Note that element may already be beyond this NACK range because we
// may have seen this NACK range in a prior Acknowledgement message.
// For each element up to the first loss:
for (; element < firstLoss; ++element)
{
if (element >= windowCount) {
SIAMESE_DEBUG_BREAK(); // Invalid input
return;
}
// Get last time this was sent (maybe the second time)
const uint32_t* sendMsecPtr = TheWindow->GetWindowElementTimestampPtr(element);
SIAMESE_DEBUG_ASSERT(*sendMsecPtr != 0);
// Calculate delay since it was sent
const int32_t delayMsec = nowMsec - *sendMsecPtr;
if ((unsigned)delayMsec > longestAckDelayMsec && delayMsec > 0)
{
longestAckDelayMsec = delayMsec;
Logger.Info("NACKED TS = ", *sendMsecPtr, " for ID=", element + TheWindow->ColumnStart, " <- new max delay: ", delayMsec);
}
else
{
Logger.Info("nacked ts = ", *sendMsecPtr, " for ID=", element + TheWindow->ColumnStart, " - not max delay - ", delayMsec);
}
}
// Update loss offset to keep in sync with NACK range encoder
firstLoss += lossCountM1 + 2;
}
// Update next expected column for RTT calculation
NextRTOColumn = TheWindow->ElementToColumn(element);
// If there was no delay measurement:
if (longestAckDelayMsec <= 0) {
return;
}
// Recalculate the window size based on current timeout
static const uint64_t kMaxWindowMsec = 4000;
static const uint64_t kMinWindowMsec = 100;
uint64_t windowMsec = RetransmitTimeoutMsec * 2;
if (windowMsec < kMinWindowMsec) {
windowMsec = kMinWindowMsec;
}
else if (windowMsec > kMaxWindowMsec) {
windowMsec = kMaxWindowMsec;
}
// Update estimate of maximum RTT
MaxWindowedRTT.Update(
longestAckDelayMsec,
nowMsec64,
windowMsec);
const unsigned RTT_max = MaxWindowedRTT.GetBest();
// Pick an RTO that is 50% higher than the windowed maximum
RetransmitTimeoutMsec = (RTT_max * 3) / 2;
// Do not allow the RTO to get so small that OS scheduling delays might cause timeouts.
static const unsigned kMinimumRTOMsec = 20;
if (RetransmitTimeoutMsec < kMinimumRTOMsec) {
RetransmitTimeoutMsec = kMinimumRTOMsec;
}
Logger.Info("Calculated windowMsec = ", windowMsec, " and RTT_max = ", RTT_max, " and RetransmitTimeoutMsec = ", RetransmitTimeoutMsec, " from longestAckDelayMsec = ", longestAckDelayMsec, " NextRTOColumn=", NextRTOColumn);
}
bool EncoderAcknowledgementState::DecodeNextRange()
{
// If there is no more loss range data to process:
if (Offset >= DataBytes) {
return false;
}
// Decode loss range format:
SIAMESE_DEBUG_ASSERT(Data && DataBytes >= 1);
unsigned relativeStart, lossCountM1;
const int lossRangeBytes = DeserializeHeader_NACKLossRange(
Data + Offset, DataBytes + kPaddingBytes - Offset, relativeStart, lossCountM1);
if (lossRangeBytes < 0) {
return false;
}
Offset += lossRangeBytes;
if (Offset > DataBytes) {
SIAMESE_DEBUG_BREAK(); // Invalid input
// TBD: Disable codec here?
return false;
}
// Move ahead the loss column
LossColumn = AddColumns(LossColumn, relativeStart);
LossCount = lossCountM1 + 1;
return true;
}
bool EncoderAcknowledgementState::GetNextLossColumn(unsigned& columnOut)
{
if (LossCount <= 0)
{
// Note: LossColumn is used as the offset for the next loss range, so
// we should increment it to one beyond the end of the current region
// when we get to the end of the region.
LossColumn = IncrementColumn1(LossColumn);
if (!DecodeNextRange()) {
return false;
}
}
columnOut = LossColumn;
LossColumn = IncrementColumn1(LossColumn);
--LossCount;
return true;
}
void EncoderAcknowledgementState::RestartLossIterator()
{
// Reset message decoder state
Offset = 0;
LossColumn = NextColumnExpected;
LossCount = 0;
DecodeNextRange();
// Note: Ignore return value
}
void EncoderAcknowledgementState::Clear()
{
// Reset message decoder state
Offset = 0;
LossColumn = 0;
LossCount = 0;
DataBytes = 0;
// Reset the oldest column
FoundOldest = false;
}
//------------------------------------------------------------------------------
// Encoder
Encoder::Encoder()
{
Window.TheAllocator = &TheAllocator;
Window.Stats = &Stats;
Ack.TheAllocator = &TheAllocator;
Ack.TheWindow = &Window;
}
SiameseResult Encoder::Acknowledge(
const uint8_t* data,
unsigned bytes,
unsigned& nextExpectedPacketNumOut)
{
if (Window.EmergencyDisabled) {
return Siamese_Disabled;
}
if (!Ack.OnAcknowledgementData(data, bytes)) {
return Siamese_InvalidInput;
}
// Report the next expected packet number
nextExpectedPacketNumOut = Ack.NextColumnExpected;
Stats.Counts[SiameseEncoderStats_AckCount]++;
Stats.Counts[SiameseEncoderStats_AckBytes] += bytes;
return Siamese_Success;
}
static unsigned LoadOriginal(OriginalPacket* original, SiameseOriginalPacket& originalOut)
{
const unsigned headerBytes = original->HeaderBytes;
SIAMESE_DEBUG_ASSERT(headerBytes > 0 && original->Buffer.Bytes > headerBytes);
const unsigned length = original->Buffer.Bytes - headerBytes;
#ifdef SIAMESE_DEBUG
// Check: Deserialize length from the front
unsigned lengthCheck;
int headerBytesCheck = DeserializeHeader_PacketLength(original->Buffer.Data, original->Buffer.Bytes, lengthCheck);
if (lengthCheck != length || (int)headerBytes != headerBytesCheck ||
headerBytesCheck < 1 || lengthCheck == 0 ||
lengthCheck + headerBytesCheck != original->Buffer.Bytes)
{
SIAMESE_DEBUG_BREAK(); // Invalid input
return 0;
}
#endif // SIAMESE_DEBUG
originalOut.PacketNum = original->Column;
originalOut.Data = original->Buffer.Data + headerBytes;
originalOut.DataBytes = length;
return length;
}
SiameseResult Encoder::AttemptRetransmit(
OriginalPacket* original,
SiameseOriginalPacket& originalOut)
{
// Load original data and length
const unsigned length = LoadOriginal(original, originalOut);
if (length == 0) {
Window.EmergencyDisabled = true;
return Siamese_Disabled;
}
Stats.Counts[SiameseEncoderStats_RetransmitCount]++;
Stats.Counts[SiameseEncoderStats_RetransmitBytes] += length;
return Siamese_Success;
}
SiameseResult Encoder::Retransmit(SiameseOriginalPacket& originalOut)
{
originalOut.Data = nullptr;
originalOut.DataBytes = 0;
if (Window.EmergencyDisabled) {
return Siamese_Disabled;
}
// If there is no unacknowledged data:
if (Window.GetUnacknowledgedCount() <= 0)
{
Ack.FoundOldest = false; // Reset Ack state
return Siamese_NeedMoreData;
}
// Get the window element first the first column expected by the receiver
const unsigned firstElement = SubtractColumns(Ack.NextColumnExpected, Window.ColumnStart);
const unsigned count = Window.Count;
// If the peer's next expected column is outside the window:
if (IsColumnDeltaNegative(firstElement) ||
firstElement < Window.FirstUnremovedElement ||
firstElement >= count)
{
return Siamese_NeedMoreData;
}
const uint32_t nowMsec = static_cast<uint32_t>(siamese::GetTimeMsec());
const uint32_t retransmitMsec = Ack.RetransmitTimeoutMsec;
// If the oldest column is already found:
if (Ack.FoundOldest)
{
// Calculate the oldest element
const unsigned element = SubtractColumns(Ack.OldestColumn, Window.ColumnStart);
// If the oldest element is still within the window:
if (!IsColumnDeltaNegative(element) &&
element >= firstElement &&
element < count)
{
OriginalPacket* original = Window.GetWindowElement(element);
SIAMESE_DEBUG_ASSERT(original->Buffer.Data != nullptr);
SIAMESE_DEBUG_ASSERT(original->Buffer.Bytes > 0);
uint32_t* lastSendMsecPtr = Window.GetWindowElementTimestampPtr(element);
const uint32_t lastSendMsec = *lastSendMsecPtr;
SIAMESE_DEBUG_ASSERT(lastSendMsec != 0);
// If RTO has not elapsed for the oldest entry:
if ((uint32_t)(nowMsec - lastSendMsec) < retransmitMsec) {
// Keep FoundOldest true for next time and stop for now
return Siamese_NeedMoreData;
}
// Update last send time
*lastSendMsecPtr = nowMsec;
// Look again for the oldest column next time
Ack.FoundOldest = false;
Logger.Debug("Retransmitting oldest in window. RTO = ", retransmitMsec, ", ID=", original->Column);
return AttemptRetransmit(original, originalOut);
}
// Keep searching for the oldest column
Ack.FoundOldest = false;
}
// Find the first column ready to go, or the oldest column in the set:
// If the first one is already ready to go:
unsigned nackElement = firstElement;
OriginalPacket* oldestOriginal = Window.GetWindowElement(nackElement);
uint32_t* firstSendMsecPtr = Window.GetWindowElementTimestampPtr(nackElement);
uint32_t oldestSendMsec = *firstSendMsecPtr;
// If the first packet RTO expired:
if ((uint32_t)(nowMsec - oldestSendMsec) >= retransmitMsec)
{
// Update last send time
*firstSendMsecPtr = nowMsec;
Logger.Debug("Retransmitting first in window. RTO = ", retransmitMsec, ", ID=", oldestOriginal->Column);
return AttemptRetransmit(oldestOriginal, originalOut);
}
// If NACK list is available:
if (Ack.HasNegativeAcknowledgements())
{
// Restart loss iterator for next time
Ack.RestartLossIterator();
// While there is another NACK column to process:
unsigned column;
while (Ack.GetNextLossColumn(column))
{
// If the receiver has already seen all the packets we sent:
nackElement = Window.ColumnToElement(column);
if (nackElement >= count) {
break; // Stop here
}
// Lookup original packet and send time
OriginalPacket* original = Window.GetWindowElement(nackElement);
SIAMESE_DEBUG_ASSERT(original->Buffer.Data != nullptr);
SIAMESE_DEBUG_ASSERT(original->Buffer.Bytes > 0);
uint32_t* lastSendMsecPtr = Window.GetWindowElementTimestampPtr(nackElement);
const uint32_t lastSendMsec = *lastSendMsecPtr;
SIAMESE_DEBUG_ASSERT(lastSendMsec != 0);
// If RTO expired:
if ((uint32_t)(nowMsec - lastSendMsec) >= retransmitMsec)
{
// Update last send time
*lastSendMsecPtr = nowMsec;
Logger.Debug("Retransmitting NACK: RTO = ", retransmitMsec, ", ID=", original->Column);
return AttemptRetransmit(original, originalOut);
}