-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSiameseDecoder.cpp
2703 lines (2235 loc) · 94.4 KB
/
SiameseDecoder.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: Decoder
\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 "SiameseDecoder.h"
#include "SiameseSerializers.h"
namespace siamese {
#ifdef SIAMESE_DECODER_DUMP_VERBOSE
static logger::Channel Logger("Decoder", logger::Level::Debug);
#else
static logger::Channel Logger("Decoder", logger::Level::Silent);
#endif
//------------------------------------------------------------------------------
// DecoderStats
DecoderStats::DecoderStats()
{
for (unsigned i = 0; i < SiameseDecoderStats_Count; ++i) {
Counts[i] = 0;
}
}
//------------------------------------------------------------------------------
// Decoder
Decoder::Decoder()
{
RecoveryPackets.TheAllocator = &TheAllocator;
RecoveryPackets.CheckedRegion = &CheckedRegion;
Window.TheAllocator = &TheAllocator;
Window.Stats = &Stats;
Window.CheckedRegion = &CheckedRegion;
Window.RecoveryPackets = &RecoveryPackets;
Window.RecoveryMatrix = &RecoveryMatrix;
RecoveryMatrix.TheAllocator = &TheAllocator;
RecoveryMatrix.Window = &Window;
RecoveryMatrix.CheckedRegion = &CheckedRegion;
CheckedRegion.RecoveryMatrix = &RecoveryMatrix;
}
SiameseResult Decoder::Get(SiameseOriginalPacket& packetOut)
{
// Note: Keep this in sync with Encoder::Get
if (Window.EmergencyDisabled) {
return Siamese_Disabled;
}
// Note: This also works when Count == 0
const unsigned element = Window.ColumnToElement(packetOut.PacketNum);
if (Window.InvalidElement(element))
{
// Set default return value
packetOut.Data = nullptr;
packetOut.DataBytes = 0;
return Siamese_NeedMoreData;
}
// Return the packet data
OriginalPacket* original = Window.GetWindowElement(element);
if (original->Buffer.Bytes <= 0)
{
packetOut.Data = nullptr;
packetOut.DataBytes = 0;
return Siamese_NeedMoreData;
}
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
Window.EmergencyDisabled = true;
return Siamese_Disabled;
}
#endif // SIAMESE_DEBUG
packetOut.Data = original->Buffer.Data + headerBytes;
packetOut.DataBytes = length;
return Siamese_Success;
}
SiameseResult Decoder::GenerateAcknowledgement(
uint8_t* buffer,
unsigned byteLimit,
unsigned& usedBytesOut)
{
if (Window.EmergencyDisabled) {
return Siamese_Disabled;
}
SIAMESE_DEBUG_ASSERT(byteLimit >= SIAMESE_ACK_MIN_BYTES);
std::ostringstream* pDebugMsg = nullptr;
// If we have no data yet:
const unsigned windowCount = Window.Count;
if (windowCount == 0)
{
// This should only happen before we receive any data at all.
// After we receive some data we keep a window of data around to decode FEC packets
SIAMESE_DEBUG_ASSERT(Window.ColumnStart == 0);
usedBytesOut = 0;
return Siamese_NeedMoreData;
}
const uint8_t* bufferStart = buffer;
// Calculate next column we expect to receive
const unsigned nextElementExpected = Window.NextExpectedElement;
SIAMESE_DEBUG_ASSERT(nextElementExpected <= windowCount);
const unsigned nextColumnExpected = Window.ElementToColumn(nextElementExpected);
unsigned headerBytes = SerializeHeader_PacketNum(nextColumnExpected, buffer);
buffer += headerBytes, byteLimit -= headerBytes;
// If there is no missing data:
if (Window.InvalidElement(nextElementExpected))
{
// Write used bytes
usedBytesOut = (unsigned)(uintptr_t)(buffer - bufferStart);
Stats.Counts[SiameseDecoderStats_AckCount]++;
Stats.Counts[SiameseDecoderStats_AckBytes] += usedBytesOut;
return Siamese_Success;
}
SIAMESE_DEBUG_ASSERT(Window.GetWindowElement(nextElementExpected)->Buffer.Bytes == 0);
// Start searching for the next set bit at the next after the next expected element
unsigned rangeOffset = nextElementExpected;
if (Logger.ShouldLog(logger::Level::Debug))
{
delete pDebugMsg;
pDebugMsg = new std::ostringstream();
*pDebugMsg << "Building ack from nextExpectedColumn=" << nextColumnExpected << " : NACKs = {";
}
// While there is room for another maximum-length loss range:
while (byteLimit >= kMaxLossRangeFieldBytes)
{
const unsigned rangeStart = Window.FindNextLostElement(rangeOffset);
if (rangeStart >= windowCount)
{
SIAMESE_DEBUG_ASSERT(rangeStart == windowCount);
if (pDebugMsg)
*pDebugMsg << " next:" << AddColumns(Window.ColumnStart, rangeStart);
// Noticed this can happen somehow
if (windowCount >= rangeOffset)
{
// Take range start relative to the range offset
const unsigned relativeStart = windowCount - rangeOffset;
// Serialize this NACK loss range into the buffer
const unsigned encodedBytes = SerializeHeader_NACKLossRange(relativeStart, 0, buffer);
buffer += encodedBytes;
}
break;
}
SIAMESE_DEBUG_ASSERT(rangeStart >= rangeOffset);
unsigned rangeEnd = Window.FindNextGotElement(rangeStart + 1);
SIAMESE_DEBUG_ASSERT(rangeEnd > rangeStart);
SIAMESE_DEBUG_ASSERT(rangeEnd <= windowCount);
unsigned lossCountM1 = rangeEnd - rangeStart - 1; // Loss count minus 1
if (pDebugMsg)
{
if (lossCountM1 > 0) {
*pDebugMsg << " " << AddColumns(Window.ColumnStart, rangeStart)
<< "-" << Window.ElementToColumn(rangeEnd - 1);
}
else {
*pDebugMsg << " " << AddColumns(Window.ColumnStart, rangeStart);
}
}
// Take range start relative to the range offset
SIAMESE_DEBUG_ASSERT(rangeStart >= rangeOffset);
const unsigned relativeStart = rangeStart - rangeOffset;
// Serialize this NACK loss range into the buffer
const unsigned encodedBytes = SerializeHeader_NACKLossRange(relativeStart, lossCountM1, buffer);
// Range end is one beyond the end of the loss region.
// The next loss cannot be before one after the range end, since we
// either found a received packet id there, or we hit end of range.
// This is also where we should start searching for losses again
rangeOffset = rangeEnd + 1;
// Advance buffer write pointer
buffer += encodedBytes;
byteLimit -= encodedBytes;
}
// Note that the loss range list may have been truncated due to the buffer space constraint
if (pDebugMsg)
{
*pDebugMsg << " }";
Logger.Debug(pDebugMsg->str());
}
// Write used bytes
usedBytesOut = (unsigned)(uintptr_t)(buffer - bufferStart);
Stats.Counts[SiameseDecoderStats_AckCount]++;
Stats.Counts[SiameseDecoderStats_AckBytes] += usedBytesOut;
return Siamese_Success;
}
SiameseResult Decoder::AddRecovery(const SiameseRecoveryPacket& packet)
{
if (Window.EmergencyDisabled) {
return Siamese_Disabled;
}
// Deserialize the recovery metadata from the front of the packet
RecoveryMetadata metadata;
int footerSize = DeserializeFooter_RecoveryMetadata(packet.Data, packet.DataBytes, metadata);
if (footerSize < 0)
{
Window.EmergencyDisabled = true;
Logger.Error("AddRecovery: Corrupt recovery metadata");
SIAMESE_DEBUG_BREAK(); // Should never happen
return Siamese_Disabled;
}
Stats.Counts[SiameseDecoderStats_RecoveryCount]++;
Stats.Counts[SiameseDecoderStats_RecoveryBytes] += packet.DataBytes;
// Check if recovery packet was received out of order
bool outOfOrder = IsColumnDeltaNegative(metadata.ColumnStart + metadata.SumCount - LatestColumn);
if (!outOfOrder) {
// Update the latest received column
LatestColumn = (metadata.ColumnStart + metadata.SumCount) % kColumnPeriod;
}
#if 0
if (outOfOrder)
{
Logger.Warning("Ignoring recovery packet received out of order");
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success; // This packet cannot be used for recovery
}
#endif
unsigned elementStart, elementEnd;
// Check if we need this recovery packet:
if (Window.Count <= 0)
{
if (outOfOrder)
{
Logger.Warning("Recovery packet cannot be used because it was received by an empty window out of order");
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success; // This packet cannot be used for recovery
}
Logger.Info("Got first recovery packet: ColumnStart=", metadata.ColumnStart, " SumCount=", metadata.SumCount, " LDPC_Count=", metadata.LDPCCount, " Row=", metadata.Row);
Window.ColumnStart = metadata.ColumnStart;
if (!Window.GrowWindow(metadata.SumCount))
{
Window.EmergencyDisabled = true;
Logger.Error("AddRecovery.GrowWindow: OOM");
return Siamese_Disabled;
}
elementEnd = metadata.SumCount;
elementStart = elementEnd - metadata.LDPCCount;
// This should only happen at the start if we get recovery first before data
SIAMESE_DEBUG_ASSERT(Window.NextExpectedElement == 0);
}
else
{
Logger.Info("Got recovery packet: ColumnStart=", metadata.ColumnStart, " SumCount=", metadata.SumCount, " LDPC_Count=", metadata.LDPCCount, " Row=", metadata.Row);
elementEnd = Window.ColumnToElement(metadata.ColumnStart + metadata.SumCount);
// Ignore data from too long ago
if (IsColumnDeltaNegative(elementEnd))
{
Logger.Info("Packet cannot be used because it ends before the window starts");
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success;
}
// If we clipped the LDPC region already out of the window:
if (elementEnd < metadata.LDPCCount)
{
Logger.Warning("Recovery packet cannot be used because we clipped its LDPC region already: Received too far out of order?");
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success; // This packet cannot be used for recovery
}
elementStart = elementEnd - metadata.LDPCCount;
// Ignore data we already have
if (elementEnd <= Window.NextExpectedElement)
{
if (outOfOrder)
{
Logger.Warning("Recovery packet does not contain new data and is out of order, so ignoring it");
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success; // This packet cannot be used for recovery
}
Logger.Debug("Ignoring unnecessary recovery packet for data we received successfully");
if (elementStart >= kDecoderRemoveThreshold)
{
const unsigned recoveryBytes = packet.DataBytes - footerSize;
// Update the last received recovery metadata
RecoveryPackets.LastRecoveryMetadata = metadata;
RecoveryPackets.LastRecoveryBytes = recoveryBytes;
Window.RemoveElements();
}
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success;
}
// Ignore sums that include data we have removed already
#ifdef SIAMESE_ENABLE_CAUCHY
// If it is a Siamese sum row:
if (metadata.SumCount > SIAMESE_CAUCHY_THRESHOLD)
#endif
{
// If there is no running sum or it does not match the new one:
if (Window.SumColumnCount == 0 || Window.SumColumnStart != metadata.ColumnStart)
{
// Then we need to have all the data in the sum at hand or it is useless.
const unsigned elementSumStart = Window.ColumnToElement(metadata.ColumnStart);
if (Window.InvalidElement(elementSumStart))
{
Logger.Info("Recovery packet cannot be used because we clipped its Sum region already : " \
"Received too far out of order: Window.SumColumnStart = ",
Window.SumColumnStart, ", Window.SumColumnCount = ", Window.SumColumnCount,
", metadata.ColumnStart = ", metadata.ColumnStart);
Stats.Counts[SiameseDecoderStats_DupedRecoveryCount]++;
return Siamese_Success;
}
}
}
// Grow the original packet window to cover all the packets this one protects
if (!Window.GrowWindow(elementEnd))
{
Window.EmergencyDisabled = true;
Logger.Error("AddRecovery.GrowWindow2: OOM");
return Siamese_Disabled;
}
}
// If this is a single (duplicate) packet:
if (metadata.SumCount == 1)
{
if (!AddSingleRecovery(packet, metadata, footerSize))
{
Window.EmergencyDisabled = true;
Logger.Error("AddRecovery.AddSingleRecovery failed");
return Siamese_Disabled;
}
return Siamese_Success;
}
// Allocate a packet object
RecoveryPacket* recovery = (RecoveryPacket*)TheAllocator.Construct<RecoveryPacket>();
if (!recovery)
{
Window.EmergencyDisabled = true;
Logger.Error("AddRecovery.Construct OOM");
return Siamese_Disabled;
}
SIAMESE_DEBUG_ASSERT((unsigned)footerSize < packet.DataBytes);
const unsigned recoveryBytes = packet.DataBytes - footerSize;
SIAMESE_DEBUG_ASSERT(recoveryBytes > 0);
if (!recovery->Buffer.Initialize(&TheAllocator, recoveryBytes))
{
TheAllocator.Destruct(recovery);
Window.EmergencyDisabled = true;
Logger.Error("AddRecovery.Initialize OOM");
return Siamese_Disabled;
}
// Fill in the packet object
memcpy(recovery->Buffer.Data, packet.Data, recoveryBytes);
recovery->Metadata = metadata;
recovery->ElementStart = elementStart;
recovery->ElementEnd = elementEnd;
// Insert it into the sorted packet list
RecoveryPackets.Insert(recovery, outOfOrder);
// Remove elements from the front if possible
if (elementStart >= kDecoderRemoveThreshold) {
Window.RemoveElements();
}
return Siamese_Success;
}
bool Decoder::AddSingleRecovery(const SiameseRecoveryPacket& packet, const RecoveryMetadata& metadata, int footerSize)
{
const unsigned element = Window.ColumnToElement(metadata.ColumnStart);
if (Window.InvalidElement(element)) {
SIAMESE_DEBUG_BREAK(); // Should never happen
return false;
}
// Note: In this case the length is already prefixed to the data
SIAMESE_DEBUG_ASSERT(metadata.LDPCCount == 1 && metadata.Row == 0);
OriginalPacket* windowOriginal = Window.GetWindowElement(element);
// Ignore duplicate data
if (windowOriginal->Buffer.Bytes != 0) {
return true;
}
// Check: Deserialize length from the front
SIAMESE_DEBUG_ASSERT(packet.DataBytes > (unsigned)footerSize);
const unsigned lengthPlusDataBytes = packet.DataBytes - footerSize;
unsigned lengthCheck;
int headerBytes = DeserializeHeader_PacketLength(packet.Data, lengthPlusDataBytes, lengthCheck);
if (headerBytes < 1 || lengthCheck == 0 ||
lengthCheck + headerBytes != lengthPlusDataBytes)
{
SIAMESE_DEBUG_BREAK(); // Invalid input
return false;
}
SiameseOriginalPacket original;
SIAMESE_DEBUG_ASSERT((int)packet.DataBytes > footerSize + headerBytes);
original.DataBytes = packet.DataBytes - footerSize - headerBytes;
original.Data = packet.Data + headerBytes;
original.PacketNum = metadata.ColumnStart;
unsigned newHeaderBytes = windowOriginal->Initialize(&TheAllocator, original);
SIAMESE_DEBUG_ASSERT(newHeaderBytes == (unsigned)headerBytes);
if (0 == newHeaderBytes) {
SIAMESE_DEBUG_BREAK(); // Invalid input
return false;
}
SIAMESE_DEBUG_ASSERT(windowOriginal->Buffer.Bytes > 1);
if (!Window.HasRecoveredPackets)
{
Window.HasRecoveredPackets = true;
Window.RecoveredPackets.Clear();
}
original.Data = windowOriginal->Buffer.Data + newHeaderBytes;
SIAMESE_DEBUG_ASSERT(original.DataBytes == windowOriginal->Buffer.Bytes - headerBytes);
if (!Window.RecoveredPackets.Append(original)) {
SIAMESE_DEBUG_BREAK(); // OOM
return false;
}
if (!Window.RecoveredColumns.Append(metadata.ColumnStart)) {
SIAMESE_DEBUG_BREAK(); // OOM
return false;
}
// If the added element is somewhere inside the previously checked region:
if (element >= CheckedRegion.ElementStart &&
element < CheckedRegion.NextCheckStart)
{
CheckedRegion.Reset();
}
// If this was the next expected element:
if (Window.MarkGotColumn(metadata.ColumnStart))
{
SIAMESE_DEBUG_ASSERT(element == Window.NextExpectedElement);
// Iterate the next expected element beyond the recovery region
Window.IterateNextExpectedElement(element + 1);
Logger.Debug("AddSingleRecovery: Deleting recovery packets before element ", Window.NextExpectedElement, " column = ", (Window.NextExpectedElement + Window.ColumnStart));
RecoveryPackets.DeletePacketsBefore(Window.NextExpectedElement);
if (CheckedRegion.NextCheckStart >= kDecoderRemoveThreshold) {
Window.RemoveElements();
}
}
return true;
}
bool Decoder::CheckRecoveryPossible()
{
if (Window.EmergencyDisabled) {
return false;
}
RecoveryPacket* recovery;
unsigned nextCheckStart, recoveryCount, lostCount;
// If we just started checking again:
if (!CheckedRegion.LastRecovery)
{
recovery = RecoveryPackets.Head;
if (!recovery) {
return false; // No recovery data
}
CheckedRegion.FirstRecovery = recovery;
CheckedRegion.ElementStart = recovery->ElementStart;
#ifdef SIAMESE_DEBUG
const unsigned lostPacketsBeforeLDPC = Window.RangeLostPackets(0, recovery->ElementStart);
SIAMESE_DEBUG_ASSERT(0 == lostPacketsBeforeLDPC);
#endif
recoveryCount = 1;
nextCheckStart = recovery->ElementEnd;
lostCount = Window.RangeLostPackets(recovery->ElementStart, nextCheckStart);
CheckedRegion.SolveFailed = false;
// Keep track of how many losses this recovery packet is facing
recovery->LostCount = lostCount;
}
else
{
recoveryCount = CheckedRegion.RecoveryCount;
lostCount = CheckedRegion.LostCount;
if (recoveryCount >= lostCount && !CheckedRegion.SolveFailed)
{
// If maximum loss recovery count is exceeded:
if (lostCount > kMaximumLossRecoveryCount) {
return false; // Limit was hit
}
return true; // It is already possible
}
recovery = CheckedRegion.LastRecovery;
nextCheckStart = CheckedRegion.NextCheckStart;
}
SIAMESE_DEBUG_ASSERT(lostCount > 0);
// While we do not have enough recovery data:
while ((recoveryCount < lostCount || CheckedRegion.SolveFailed) &&
(recovery->Next != nullptr))
{
recovery = recovery->Next;
++recoveryCount;
// Accumulate losses within the range of this recovery packet, skipping
// losses we've already accumulated into the checked region
unsigned elementEnd = recovery->ElementEnd;
if (elementEnd < nextCheckStart) {
elementEnd = nextCheckStart; // This can happen when interleaved with Cauchy packets
}
Logger.Debug("RecoveryPossible? Searching between ", nextCheckStart, " and ", elementEnd);
lostCount += Window.RangeLostPackets(nextCheckStart, elementEnd);
SIAMESE_DEBUG_ASSERT(lostCount > 0);
nextCheckStart = elementEnd;
// Keep track of how many losses this recovery packet is facing
recovery->LostCount = lostCount;
CheckedRegion.SolveFailed = false;
}
// Remember state for the next time around
CheckedRegion.LastRecovery = recovery;
CheckedRegion.RecoveryCount = recoveryCount;
CheckedRegion.LostCount = lostCount;
CheckedRegion.NextCheckStart = nextCheckStart;
Logger.Debug("RecoveryPossible? LostCount=", CheckedRegion.LostCount, " RecoveryCount=", CheckedRegion.RecoveryCount);
// If maximum loss recovery count is exceeded:
if (lostCount > kMaximumLossRecoveryCount) {
return false; // Limit was hit
}
return recoveryCount >= lostCount && !CheckedRegion.SolveFailed;
}
SiameseResult Decoder::Decode(SiameseOriginalPacket** packetsPtrOut, unsigned* countOut)
{
if (Window.EmergencyDisabled) {
return Siamese_Disabled;
}
// If there are already recovered packets to report:
if (Window.HasRecoveredPackets)
{
Window.HasRecoveredPackets = false;
SIAMESE_DEBUG_ASSERT(Window.RecoveredPackets.GetSize() != 0);
if (packetsPtrOut)
{
*packetsPtrOut = Window.RecoveredPackets.GetPtr(0);
*countOut = Window.RecoveredPackets.GetSize();
}
return Siamese_Success;
}
// Default return on failure
if (packetsPtrOut)
{
*packetsPtrOut = nullptr;
*countOut = 0;
}
/*
The goal of this routine is to determine if solutions to the matrix inverse
problem exists with minimal work, and to keep track of the data operations
required to arrive at the solution. Given the row and column descriptions,
we generate the square matrix to invert. Then we use Gaussian Elimination
while keeping track of what values are multiplied in place of the original
matrix elements. If successful, the resulting matrix can be multiplied by
the recovery data in the solution order to recover the lost data.
*/
// Advance the checked region to the first possible solution
if (!CheckRecoveryPossible()) {
return Siamese_NeedMoreData;
}
RecoveryPacket* recovery = CheckedRegion.LastRecovery;
unsigned nextCheckStart = CheckedRegion.NextCheckStart;
unsigned recoveryCount = CheckedRegion.RecoveryCount;
unsigned lostCount = CheckedRegion.LostCount;
SIAMESE_DEBUG_ASSERT(recovery != nullptr && nextCheckStart > CheckedRegion.ElementStart);
SIAMESE_DEBUG_ASSERT(lostCount > 0 && lostCount <= recoveryCount);
for (;;)
{
if (recoveryCount >= lostCount)
{
SiameseResult result = DecodeCheckedRegion();
// Pass error or success up; continue on decode failure
if (result == Siamese_Success)
{
if (packetsPtrOut)
{
*packetsPtrOut = Window.RecoveredPackets.GetPtr(0);
*countOut = Window.RecoveredPackets.GetSize();
}
return Siamese_Success;
}
if (result != Siamese_NeedMoreData) {
return result;
}
}
if (recovery->Next == nullptr) {
break;
}
recovery = recovery->Next;
++recoveryCount;
// Accumulate losses within the range of this recovery packet, skipping
// losses we've already accumulated into the checked region
unsigned elementEnd = recovery->ElementEnd;
if (elementEnd < nextCheckStart) {
elementEnd = nextCheckStart; // This can happen when interleaved with Cauchy packets
}
lostCount += Window.RangeLostPackets(nextCheckStart, elementEnd);
// Keep track of how many lost packets this recovery packet is facing
recovery->LostCount = lostCount;
nextCheckStart = elementEnd;
}
// Remember state for the next time around
CheckedRegion.LastRecovery = recovery;
CheckedRegion.NextCheckStart = nextCheckStart;
CheckedRegion.RecoveryCount = recoveryCount;
CheckedRegion.LostCount = lostCount;
return Siamese_NeedMoreData;
}
SiameseResult Decoder::DecodeCheckedRegion()
{
Logger.Debug("Attempting decode...");
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
bool skipLog = CheckedRegion.LostCount <= 1;
if (!skipLog)
Logger.Debug("For ", CheckedRegion.LostCount, " losses:");
uint64_t t0 = GetTimeUsec();
#endif
// Generate updated recovery matrix
if (!RecoveryMatrix.GenerateMatrix())
{
Window.EmergencyDisabled = true;
Logger.Error("DecodeCheckedRegion.GenerateMatrix failed");
return Siamese_Disabled;
}
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
uint64_t t1 = GetTimeUsec();
#endif
// Attempt to solve the linear system
if (!RecoveryMatrix.GaussianElimination())
{
CheckedRegion.SolveFailed = true;
Stats.Counts[SiameseDecoderStats_SolveFailCount]++;
return Siamese_NeedMoreData;
}
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
uint64_t t2 = GetTimeUsec();
#endif
if (!EliminateOriginalData())
{
Window.EmergencyDisabled = true;
Logger.Error("DecodeCheckedRegion.EliminateOriginalData failed");
return Siamese_Disabled;
}
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
uint64_t t3 = GetTimeUsec();
#endif
if (!MultiplyLowerTriangle())
{
Window.EmergencyDisabled = true;
Logger.Error("DecodeCheckedRegion.MultiplyLowerTriangle failed");
return Siamese_Disabled;
}
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
uint64_t t4 = GetTimeUsec();
#endif
SiameseResult solveResult = BackSubstitution();
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
uint64_t t5 = GetTimeUsec();
#endif
CheckedRegion.Reset();
#ifdef SIAMESE_DECODER_DUMP_SOLVER_PERF
uint64_t t6 = GetTimeUsec();
if (!skipLog)
{
Logger.Info("RecoveryMatrix.GenerateMatrix: ", (t1 - t0), " usec");
Logger.Info("RecoveryMatrix.GaussianElimination: ", (t2 - t1), " usec");
Logger.Info("EliminateOriginalData: ", (t3 - t2), " usec");
Logger.Info("MultiplyLowerTriangle: ", (t4 - t3), " usec");
Logger.Info("BackSubstitution: ", (t5 - t4), " usec");
Logger.Info("Cleanup: ", (t6 - t5), " usec");
}
#endif
return solveResult;
}
bool Decoder::EliminateOriginalData()
{
SIAMESE_DEBUG_ASSERT(CheckedRegion.LostCount == RecoveryMatrix.Columns.GetSize());
std::ostringstream* pDebugMsg = nullptr;
// Note: This is done because the Siamese sums need to be accumulated from
// left to right in the same order that the encoder generated them.
// This step tends to be slow because there is a lot of data that was
// successfully received that we need to eliminate from the recovery sums
const unsigned rows = CheckedRegion.RecoveryCount;
SIAMESE_DEBUG_ASSERT(CheckedRegion.RecoveryCount == RecoveryMatrix.Rows.GetSize());
// Eliminate data in sorted row order regardless of pivot order:
for (unsigned matrixRowIndex = 0; matrixRowIndex < rows; ++matrixRowIndex)
{
if (!RecoveryMatrix.Rows.GetRef(matrixRowIndex).UsedForSolution) {
continue;
}
RecoveryPacket* recovery = RecoveryMatrix.Rows.GetRef(matrixRowIndex).Recovery;
const RecoveryMetadata metadata = recovery->Metadata;
const unsigned elementStart = recovery->ElementStart;
const unsigned elementEnd = recovery->ElementEnd;
GrowingAlignedDataBuffer& recoveryBuffer = recovery->Buffer;
SIAMESE_DEBUG_ASSERT(recoveryBuffer.Data && recoveryBuffer.Bytes > 0);
#ifdef SIAMESE_ENABLE_CAUCHY
// If it is a Cauchy or parity row:
if (metadata.SumCount <= SIAMESE_CAUCHY_THRESHOLD)
{
// If this is a parity row:
if (metadata.Row == 0)
{
// Fill columns from left for new rows:
for (unsigned j = elementStart; j < elementEnd; ++j)
{
OriginalPacket* original = Window.GetWindowElement(j);
unsigned addBytes = original->Buffer.Bytes;
if (addBytes > 0)
{
if (addBytes > recoveryBuffer.Bytes) {
SIAMESE_DEBUG_BREAK(); // Should never happen
addBytes = recoveryBuffer.Bytes;
}
gf256_add_mem(recoveryBuffer.Data, original->Buffer.Data, addBytes);
}
}
}
else // This is a Cauchy row:
{
// Fill columns from left for new rows:
for (unsigned j = elementStart; j < elementEnd; ++j)
{
OriginalPacket* original = Window.GetWindowElement(j);
unsigned addBytes = original->Buffer.Bytes;
if (addBytes > 0)
{
const uint8_t y = CauchyElement(metadata.Row - 1, original->Column % kCauchyMaxColumns);
if (addBytes > recoveryBuffer.Bytes) {
SIAMESE_DEBUG_BREAK(); // Should never happen
addBytes = recoveryBuffer.Bytes;
}
gf256_muladd_mem(recoveryBuffer.Data, y, original->Buffer.Data, addBytes);
}
}
}
continue;
}
#endif // SIAMESE_ENABLE_CAUCHY
// Zero the product sum
const unsigned recoveryBytes = recoveryBuffer.Bytes;
if (!ProductSum.Initialize(&TheAllocator, recoveryBytes)) {
return false;
}
memset(ProductSum.Data, 0, recoveryBytes);
Logger.Debug("Starting sums for row=", recovery->Metadata.Row, " start=", recovery->Metadata.ColumnStart, " count=", recovery->Metadata.SumCount);
// Convert column start to window element.
// If some of the summed elements have fallen out of the window,
// then start it at the first element in the window (0).
unsigned sumElementStart = Window.ColumnToElement(recovery->Metadata.ColumnStart);
/*
If the recovery packet indicates a different siamese sum, then we
will need to clear the running sums and recreate them from scratch.
Sums need to be restarted if the start point changed, which should
be a jump of over 128 packets that were acknowledged. They would
also need to be restarted if the number of summed columns has
reduced instead of increased. In both cases, data needs to be
removed from the running sum. Instead of being clever about how to
remove that data, we just start over from scratch to avoid a huge
amount of extra complexity.
TBD: Collect real data on how much it would help to checkpoint on
the decoder side. I suspect it would not help much because multi-
packet losses probably do not often straddle these checkpoints.
For example if start point changes 1/128 packets, then the benefit
of checkpoints is only felt in about 1% of the multi-loss cases,
which are already much less common than single losses.
Due to the way we order recovery packets in the list, and therefore
how they get ordered as matrix rows for the matrix we are solving,
often times sums will only roll forward or skip ahead.
*/
if (metadata.ColumnStart != Window.SumColumnStart ||
metadata.SumCount < Window.SumColumnCount)
{
// If we have to restart the sums but the data is not available:
if (Window.InvalidElement(sumElementStart)) {
// This should never happen. The code that decides when to
// remove data from the window should have kept this data.
SIAMESE_DEBUG_BREAK();
return false;
}
Window.ResetSums(sumElementStart);
Window.SumColumnStart = metadata.ColumnStart;
}
else
{
if (Window.InvalidElement(sumElementStart)) {
sumElementStart = 0;
}
// Prepare any lane sums that have not accumulated data yet to
// receive data, since we are about to start accumulaing into
// some of these running sums.
if (!Window.StartSums(sumElementStart, recoveryBytes)) {
return false;
}
}
Window.SumColumnCount = metadata.SumCount;
// Eliminate dense recovery data outside of matrix:
for (unsigned laneIndex = 0; laneIndex < kColumnLaneCount; ++laneIndex)
{
const unsigned opcode = GetRowOpcode(laneIndex, metadata.Row);
// For summations into the RecoveryPacket buffer:
unsigned mask = 1;
for (unsigned sumIndex = 0; sumIndex < kColumnSumCount; ++sumIndex)
{
if (opcode & mask)
{
const GrowingAlignedDataBuffer* sum = Window.GetSum(laneIndex, sumIndex, elementEnd);
SIAMESE_DEBUG_ASSERT(elementEnd + kColumnLaneCount >= Window.Lanes[laneIndex].Sums[sumIndex].ElementEnd);
unsigned addBytes = sum->Bytes;
if (addBytes > 0)
{
if (addBytes > recoveryBytes) {
addBytes = recoveryBytes;
}
gf256_add_mem(recoveryBuffer.Data, sum->Data, addBytes);
}
}
mask <<= 1;
}
// For summations into the ProductWorkspace buffer:
for (unsigned sumIndex = 0; sumIndex < kColumnSumCount; ++sumIndex)
{
if (opcode & mask)
{
const GrowingAlignedDataBuffer* sum = Window.GetSum(laneIndex, sumIndex, elementEnd);
SIAMESE_DEBUG_ASSERT(elementEnd + kColumnLaneCount >= Window.Lanes[laneIndex].Sums[sumIndex].ElementEnd);
unsigned addBytes = sum->Bytes;
if (addBytes > 0)
{
if (addBytes > recoveryBytes)
addBytes = recoveryBytes;
gf256_add_mem(ProductSum.Data, sum->Data, addBytes);
}
}
mask <<= 1;
}
}
// Eliminate light recovery data outside of matrix:
PCGRandom prng;
prng.Seed(metadata.Row, metadata.LDPCCount);
SIAMESE_DEBUG_ASSERT(metadata.SumCount >= metadata.LDPCCount);
if (Logger.ShouldLog(logger::Level::Debug))