forked from Haivision/srt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfec.cpp
More file actions
2589 lines (2185 loc) · 94.1 KB
/
fec.cpp
File metadata and controls
2589 lines (2185 loc) · 94.1 KB
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
/*
* SRT - Secure, Reliable, Transport
* Copyright (c) 2019 Haivision Systems Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include "platform_sys.h"
#include <string>
#include <map>
#include <vector>
#include <deque>
#include <iterator>
#include "packetfilter.h"
#include "core.h"
#include "packet.h"
#include "logging.h"
#include "fec.h"
// Maximum allowed "history" remembered in the receiver groups.
// This is calculated in series, that is, this number will be
// multiplied by sizeRow() and sizeCol() to get the value being
// a maximum distance between the FEC group base sequence and
// the sequence to which a request comes in.
// XXX Might be that this parameter should be configurable
#define SRT_FEC_MAX_RCV_HISTORY 10
using namespace std;
using namespace srt::logging;
using namespace hvu; // ofmt
namespace srt {
const char FECFilterBuiltin::defaultConfig [] = "fec,rows:1,layout:staircase,arq:onreq";
struct StringKeys
{
string operator()(const pair<const string, const string> item)
{
return item.first;
}
};
bool FECFilterBuiltin::verifyConfig(const SrtFilterConfig& cfg, string& w_error)
{
string arspec = map_get(cfg.parameters, "layout");
if (arspec != "" && arspec != "even" && arspec != "staircase")
{
w_error = "value for 'layout' must be 'even' or 'staircase'";
return false;
}
string colspec = map_get(cfg.parameters, "cols"), rowspec = map_get(cfg.parameters, "rows");
int out_rows = 1;
if (colspec != "")
{
int out_cols = atoi(colspec.c_str());
if (out_cols < 2)
{
w_error = "at least 'cols' must be specified and > 1";
return false;
}
}
if (rowspec != "")
{
out_rows = atoi(rowspec.c_str());
if (out_rows >= -1 && out_rows < 1)
{
w_error = "'rows' must be >=1 or negative < -1";
return false;
}
}
// Extra interpret level, if found, default never.
// Check only those that are managed.
string level = map_get(cfg.parameters, "arq");
if (level != "")
{
static const char* const levelnames [] = {"never", "onreq", "always"};
size_t i = 0;
for (i = 0; i < Size(levelnames); ++i)
{
if (strcmp(level.c_str(), levelnames[i]) == 0)
break;
}
if (i == Size(levelnames))
{
w_error = "'arq' value '" + level + "' invalid. Allowed: never, onreq, always";
return false;
}
}
set<string> keys;
transform(cfg.parameters.begin(), cfg.parameters.end(), inserter(keys, keys.begin()), StringKeys());
// Delete all default parameters
SrtFilterConfig defconf;
ParseFilterConfig(defaultConfig, (defconf));
for (map<string,string>::const_iterator i = defconf.parameters.begin();
i != defconf.parameters.end(); ++i)
keys.erase(i->first);
// Delete mandatory parameters
keys.erase("cols");
if (!keys.empty())
{
w_error = "Extra parameters. Allowed only: cols, rows, layout, arq";
return false;
}
return true;
}
FECFilterBuiltin::FECFilterBuiltin(const SrtFilterInitializer &init, std::vector<SrtPacket> &provided, const string &confstr)
: SrtPacketFilterBase(init)
, m_fallback_level(SRT_ARQ_ONREQ)
, m_arrangement_staircase(true)
, rcv(provided)
{
if (!ParseFilterConfig(confstr, cfg))
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
string ermsg;
if (!verifyConfig(cfg, (ermsg)))
{
LOGC(pflog.Error, log << "IPE: Filter config failed: " << ermsg);
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
// Configuration supported:
// - row only (number_rows == 1)
// - columns only, no row FEC/CTL (number_rows < -1)
// - columns and rows (both > 1)
// Disallowed configurations:
// - number_cols < 1
// - number_rows [-1, 0]
string arspec = map_get(cfg.parameters, "layout");
string shorter = arspec.size() > 5 ? arspec.substr(0, 5) : arspec;
if (shorter == "even")
m_arrangement_staircase = false;
string colspec = map_get(cfg.parameters, "cols"), rowspec = map_get(cfg.parameters, "rows");
if (colspec == "")
{
LOGC(pflog.Error, log << "FEC filter config: parameter 'cols' is mandatory");
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
int out_rows = 1;
int out_cols = atoi(colspec.c_str());
m_number_cols = out_cols;
if (rowspec != "")
{
out_rows = atoi(rowspec.c_str());
}
if (out_rows < 0)
{
m_number_rows = -out_rows;
m_cols_only = true;
}
else
{
m_number_rows = out_rows;
m_cols_only = false;
}
// Extra interpret level, if found, default never.
// Check only those that are managed.
string level = cfg.parameters["arq"];
int lv = -1;
if (level != "")
{
static const char* levelnames [] = { "never", "onreq", "always" };
for (size_t i = 0; i < Size(levelnames); ++i)
{
if (level == levelnames[i])
{
lv = int(i);
break;
}
}
}
if (lv != -1)
{
m_fallback_level = SRT_ARQLevel(lv);
}
else
{
m_fallback_level = SRT_ARQ_ONREQ;
}
// Required to store in the header when rebuilding
rcv.id = socketID();
// Setup the bit matrix, initialize everything with false.
// Vertical size (y)
rcv.cells.resize(sizeCol() * sizeRow(), false);
// These sequence numbers are both the value of ISN-1 at the moment
// when the handshake is done. The sender ISN is generated here, the
// receiver ISN by the peer. Both should be known after the handshake.
// Later they will be updated as packets are transmitted.
int32_t snd_isn = CSeqNo::incseq(sndISN());
int32_t rcv_isn = CSeqNo::incseq(rcvISN());
// Alright, now we need to get the ISN from m_parent
// to extract the sequence number allowing qualification to the group.
// The base values must be prepared so that feedSource can qualify them.
// SEPARATE FOR SENDING AND RECEIVING!
// Now, assignment of the groups requires:
// For row groups, simply the size of the group suffices.
// For column groups, you need a whole matrix of all sequence
// numbers that are base sequence numbers for the group.
// Sequences that belong to this group are:
// 1. First packet has seq+1 towards the base.
// 2. Every next packet has this value + the size of the row group.
// So: group dispatching is:
// - get the column number
// - extract the group data for that column
// - check if the sequence is later than the group base sequence, if not, report no group for the packet
// - sanity check, if the seqdiff divided by row size gets 0 remainder
// - The result from the above division can't exceed the column size, otherwise
// it's another group. The number of currently collected data should be in 'collected'.
// Now set up the group starting sequences.
// The very first group in both dimensions will have the value of ISN in particular direction.
// Set up sender part.
//
// Size: rows
// Step: 1 (next packet in group is 1 past the previous one)
// Slip: rows (first packet in the next group is distant to first packet in the previous group by 'rows')
HLOGC(pflog.Debug, log << "FEC: INIT: ISN { snd=" << snd_isn << " rcv=" << rcv_isn << " }; sender single row");
ConfigureGroup(snd.row, snd_isn, 1, sizeRow());
// In the beginning we need just one reception group. New reception
// groups will be created in tact with receiving packets outside this one.
// The value of rcv.row[0].base will be used as an absolute base for calculating
// the index of the group for a given received packet.
rcv.rowq.resize(1);
HLOGP(pflog.Debug, "FEC: INIT: receiver first row");
ConfigureGroup(rcv.rowq[0], rcv_isn, 1, sizeRow());
if (sizeCol() > 1)
{
// Size: cols
// Step: rows (the next packet in the group is one row later)
// Slip: rows+1 (the first packet in the next group is later by 1 column + one whole row down)
HLOGP(pflog.Debug, "FEC: INIT: sender first N columns");
ConfigureColumns(snd.cols, snd_isn);
HLOGP(pflog.Debug, "FEC: INIT: receiver first N columns");
ConfigureColumns(rcv.colq, rcv_isn);
}
// The bit markers that mark the received/lost packets will be expanded
// as packets come in.
rcv.cell_base = rcv_isn;
}
template <class Container>
void FECFilterBuiltin::ConfigureColumns(Container& which, int32_t isn)
{
// This is to initialize the first set of groups.
// which: group vector.
// numberCols(): number of packets in one group
// sizeCol(): seqdiff between two packets consecutive in the group
// m_column_slip: seqdiff between the first packet in one group and first packet in the next group
// isn: sequence number of the first packet in the first group
size_t zero = which.size();
// The first series of initialization should embrace:
// - if multiplayer == 1, EVERYTHING (also the case of SOLID matrix)
// - if more, ONLY THE FIRST SQUARE.
which.resize(zero + numberCols());
if (!m_arrangement_staircase)
{
HLOGC(pflog.Debug, log << "ConfigureColumns: new "
<< numberCols() << " columns, START AT: " << zero);
// With even arrangement, just use a plain loop.
// Initialize straight way all groups in the size.
int32_t seqno = isn;
for (size_t i = zero; i < which.size(); ++i)
{
// ARGS:
// - seqno: sequence number of the first packet in the group
// - step: distance between two consecutive packets in the group
// - drop: distance between base sequence numbers in groups in consecutive series
// (meaning: with row size 6, group with index 2 and 8 are in the
// same column 2, lying in 0 and 1 series respectively).
ConfigureGroup(which[i], seqno, sizeRow(), sizeCol() * numberCols());
seqno = CSeqNo::incseq(seqno);
}
return;
}
// With staircase, the next column's base sequence is
// shifted by 1 AND the length of the row. When this shift
// becomes below the column 0 bottom, reset it to the row 0
// and continue.
// Start here. The 'isn' is still the absolute base sequence value.
size_t offset = 0;
HLOGC(pflog.Debug, log << "ConfigureColumns: " << (which.size() - zero)
<< " columns, START AT: " << zero);
for (size_t i = zero; i < which.size(); ++i)
{
int32_t seq = CSeqNo::incseq(isn, int(offset));
size_t col = i - zero;
HLOGC(pflog.Debug, log << "ConfigureColumns: [" << col << "]: -> ConfigureGroup...");
ConfigureGroup(which[i], seq, sizeRow(), sizeCol() * numberCols());
if (col % numberRows() == numberRows() - 1)
{
offset = col + 1; // +1 because we want it for the next column
HLOGC(pflog.Debug, log << "ConfigureColumns: [" << (int(col)+1) << "]... (resetting to row 0: +"
<< offset << " %" << CSeqNo::incseq(isn, (int32_t)offset) << ")");
}
else
{
offset += 1 + sizeRow();
HLOGC(pflog.Debug, log << "ConfigureColumns: [" << (int(col)+1) << "] ... (continue +"
<< offset << " %" << CSeqNo::incseq(isn, (int32_t)offset) << ")");
}
}
}
void FECFilterBuiltin::ConfigureGroup(Group& g, int32_t seqno, size_t gstep, size_t drop)
{
g.base = seqno;
g.step = gstep;
// This actually rewrites the size of the group here, but
// by having this value precalculated we simply close the
// group by adding this value to the base sequence.
g.drop = drop;
g.collected = 0;
// Now the buffer spaces for clips.
g.payload_clip.resize(payloadSize());
g.length_clip = 0;
g.flag_clip = 0;
g.timestamp_clip = 0;
HLOGC(pflog.Debug, log << "FEC: ConfigureGroup: base %" << seqno << " step=" << gstep << " drop=" << drop);
// Preallocate the buffer that will be used for storing it for
// the needs of passing the data through the network.
// This will be filled with zeros initially, which is unnecessary,
// but it happeens just once after connection.
}
void FECFilterBuiltin::ResetGroup(Group& g)
{
const int32_t new_seq_base = CSeqNo::incseq(g.base, int(g.drop));
HLOGC(pflog.Debug, log << "FEC: ResetGroup (step=" << g.step << "): base %" << g.base << " -> %" << new_seq_base);
g.base = new_seq_base;
g.collected = 0;
// This isn't necessary for ConfigureGroup because the
// vector after resizing is filled with a given value,
// by default the default value of the type, char(), that is 0.
g.length_clip = 0;
g.flag_clip = 0;
g.timestamp_clip = 0;
memset(&g.payload_clip[0], 0, g.payload_clip.size());
}
void FECFilterBuiltin::feedSource(CPacket& packet)
{
// Hang on the matrix. Find by packet->getSeqNo().
// (The "absolute base" is the cell 0 in vertical groups)
int32_t base = snd.row.base;
// (we are guaranteed that this packet is a data packet, so
// we don't have to check if this isn't a control packet)
int baseoff = CSeqNo::seqoff(base, packet.getSeqNo());
int horiz_pos = baseoff;
if (CheckGroupClose(snd.row, horiz_pos, sizeRow()))
{
HLOGC(pflog.Debug, log << "FEC:... HORIZ group closed, B=%" << snd.row.base);
}
ClipPacket(snd.row, packet);
snd.row.collected++;
// Don't do any column feeding if using column size 1
if (sizeCol() < 2)
{
// The above logging instruction in case of no columns
HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo()
<< " B:%" << baseoff << " H:*[" << horiz_pos << "]"
<< " size=" << packet.size()
<< " TS=" << packet.getMsgTimeStamp()
<< " !" << BufferStamp(packet.data(), packet.size()));
HLOGC(pflog.Debug, log << "FEC collected: H: " << snd.row.collected);
return;
}
// 1. Get the number of group in both vertical and horizontal groups:
// - Vertical: offset towards base (% row size, but with updated Base seq unnecessary)
// (Just for a case).
int vert_gx = baseoff % sizeRow();
// 2. Define the position of this packet in the group
// - Horizontal: offset towards base (of the given group, not absolute!)
// - Vertical: (seq-base)/column_size
int32_t vert_base = snd.cols[vert_gx].base;
int vert_off = CSeqNo::seqoff(vert_base, packet.getSeqNo());
// It MAY HAPPEN that the base is newer than the sequence of the packet.
// This may normally happen in the beginning period, where the bases
// set up initially for all columns got the shift, so they are kinda from
// the future, and "this sequence" is in a group that is already closed.
// In this case simply can't clip the packet in the column group.
HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo() << " rowoff=" << baseoff
<< " column=" << vert_gx << " .base=%" << vert_base << " coloff=" << vert_off);
// [[assert sizeCol() >= 2]]; // see the condition above.
if (vert_off >= 0)
{
// BEWARE! X % Y with different signedness upgrades int to unsigned!
// SANITY: check if the rule applies on the group
if (vert_off % sizeRow())
{
LOGC(pflog.Fatal, log << "FEC:feedSource: IPE: VGroup #" << vert_gx << " base=%" << vert_base
<< " WRONG with horiz base=%" << base << "coloff(" << vert_off
<< ") % sizeRow(" << sizeRow() << ") = " << (vert_off % sizeRow()));
// Do not place it, it would be wrong.
return;
}
// [[assert vert_off >= 0]]; // this condition branch
int vert_pos = vert_off / int(sizeRow());
HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo()
<< " B:%" << baseoff << " H:*[" << horiz_pos << "] V(B=%" << vert_base
<< ")[col=" << vert_gx << "][" << vert_pos << "/" << sizeCol() << "] "
<< " size=" << packet.size()
<< " TS=" << packet.getMsgTimeStamp()
<< " !" << BufferStamp(packet.data(), packet.size()));
// 3. The group should be check for the necessity of being closed.
// Note that FEC packet extraction doesn't change the state of the
// VERTICAL groups (it can be potentially extracted multiple times),
// only the horizontal in order to mark that the vertical FEC is
// extracted already. So, anyway, check if the group limit was reached
// and it wasn't closed.
// 4. Apply the clip
// 5. Increase collected.
if (CheckGroupClose(snd.cols[vert_gx], vert_pos, sizeCol()))
{
HLOGC(pflog.Debug, log << "FEC:... VERT group closed, B=%" << snd.cols[vert_gx].base);
}
ClipPacket(snd.cols[vert_gx], packet);
snd.cols[vert_gx].collected++;
}
else
{
HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo()
<< " B:%" << baseoff << " H:*[" << horiz_pos << "] V(B=%" << vert_base
<< ")[col=" << vert_gx << "]<NO-COLUMN>"
<< " size=" << packet.size()
<< " TS=" << packet.getMsgTimeStamp()
<< " !" << BufferStamp(packet.data(), packet.size()));
}
HLOGC(pflog.Debug, log << "FEC collected: H: " << snd.row.collected << " V[" << vert_gx << "]: " << snd.cols[vert_gx].collected);
}
bool FECFilterBuiltin::CheckGroupClose(Group& g, size_t pos, size_t size)
{
if (pos < size)
return false;
ResetGroup(g);
return true;
}
void FECFilterBuiltin::ClipPacket(Group& g, const CPacket& pkt)
{
// Both length and timestamp must be taken as NETWORK ORDER
// before applying the clip.
uint16_t length_net = htons(uint16_t(pkt.size()));
uint8_t kflg = uint8_t(pkt.getMsgCryptoFlags());
// NOTE: Unlike length, the TIMESTAMP is NOT endian-reordered
// because it will be written into the TIMESTAMP field in the
// header, and header is inverted automatically when sending,
// unlike the contents of the payload, where the length will be written.
uint32_t timestamp_hw = pkt.getMsgTimeStamp();
ClipData(g, length_net, kflg, timestamp_hw, pkt.data(), pkt.size());
HLOGC(pflog.Debug, log << "FEC DATA PKT CLIP: "
<< "FLAGS=" << fmt<unsigned>(kflg, hex)
<< " LENGTH[ne]=" << fmt(length_net, hex)
<< " TS[he]=" << fmt(timestamp_hw, hex)
<< " CLIP STATE: FLAGS=" << fmt<unsigned>(g.flag_clip, hex)
<< " LENGTH[ne]=" << fmt(g.length_clip, hex)
<< " TS[he]=" << fmt(g.timestamp_clip, hex)
<< " PL4=" << fmt(*(uint32_t*)&g.payload_clip[0], hex));
}
// Clipping a control packet does merely the same, just the packet has
// different contents, so it must be differetly interpreted.
void FECFilterBuiltin::ClipControlPacket(Group& g, const CPacket& pkt)
{
// Both length and timestamp must be taken as NETWORK ORDER
// before applying the clip.
const char* fec_header = pkt.data();
const char* payload = fec_header + 4;
size_t payload_clip_len = pkt.size() - 4;
const uint8_t* flag_clip = (const uint8_t*)(fec_header + 1);
const uint16_t* length_clip = (const uint16_t*)(fec_header + 2);
uint32_t timestamp_hw = pkt.getMsgTimeStamp();
ClipData(g, *length_clip, *flag_clip, timestamp_hw, payload, payload_clip_len);
HLOGC(pflog.Debug, log << "FEC/CTL CLIP: "
<< "FLAGS=" << fmt<unsigned>(*flag_clip, hex)
<< " LENGTH[ne]=" << fmt(*length_clip, hex)
<< " TS[he]=" << fmt(timestamp_hw, hex)
<< " CLIP STATE: FLAGS=" << fmt<unsigned>(g.flag_clip, hex)
<< " LENGTH[ne]=" << fmt(g.length_clip, hex)
<< " TS[he]=" << fmt(g.timestamp_clip, hex)
<< " PL4=" << fmt(*(uint32_t*)&g.payload_clip[0], hex));
}
void FECFilterBuiltin::ClipRebuiltPacket(Group& g, Receive::PrivPacket& pkt)
{
uint16_t length_net = htons(uint16_t(pkt.length));
uint8_t kflg = MSGNO_ENCKEYSPEC::unwrap(pkt.hdr[SRT_PH_MSGNO]);
// NOTE: Unlike length, the TIMESTAMP is NOT endian-reordered
// because it will be written into the TIMESTAMP field in the
// header, and header is inverted automatically when sending,
// unlike the contents of the payload, where the length will be written.
uint32_t timestamp_hw = pkt.hdr[SRT_PH_TIMESTAMP];
ClipData(g, length_net, kflg, timestamp_hw, pkt.buffer, pkt.length);
HLOGC(pflog.Debug, log << "FEC REBUILT DATA CLIP: "
<< "FLAGS=" << fmt<unsigned>(kflg, hex)
<< " LENGTH[ne]=" << fmt(length_net, hex)
<< " TS[he]=" << fmt(timestamp_hw, hex)
<< " CLIP STATE: FLAGS=" << fmt<unsigned>(g.flag_clip, hex)
<< " LENGTH[ne]=" << fmt(g.length_clip, hex)
<< " TS[he]=" << fmt(g.timestamp_clip, hex)
<< " PL4=" << fmt(*(uint32_t*)&g.payload_clip[0], hex));
}
void FECFilterBuiltin::ClipData(Group& g, uint16_t length_net, uint8_t kflg,
uint32_t timestamp_hw, const char* payload, size_t payload_size)
{
g.length_clip = g.length_clip ^ length_net;
g.flag_clip = g.flag_clip ^ kflg;
g.timestamp_clip = g.timestamp_clip ^ timestamp_hw;
HLOGC(pflog.Debug, log << "FEC CLIP: data pkt.size=" << payload_size
<< " to a clip buffer size=" << payloadSize());
// Payload goes "as is".
for (size_t i = 0; i < payload_size; ++i)
{
g.payload_clip[i] = g.payload_clip[i] ^ payload[i];
}
// Fill the rest with zeros. When this packet is going to be
// recovered, the payload extracted from this process will have
// the maximum length, but it will be cut to the right length
// and these padding 0s taken out.
for (size_t i = payload_size; i < payloadSize(); ++i)
g.payload_clip[i] = g.payload_clip[i] ^ 0;
}
bool FECFilterBuiltin::packControlPacket(SrtPacket& rpkt, int32_t seq)
{
// If the FEC packet is not yet ready for extraction, do nothing and return false.
// Check if seq is the last sequence of the group.
// Check VERTICAL group first, then HORIZONTAL.
//
// This is because when it happens that HORIZONTAL group is to be
// FEC-CTL reported, it also shifts the base to the next row, whereas
// this base sequence is used to determine the column index that is
// needed to reach the right column group and it must stay unupdated
// until the last packet in this row is checked for VERTICAL groups.
// If it's ready for extraction, extract it, and write into the packet.
//
// NOTE: seq is the sequence number of the LAST PACKET SENT regularly.
// This is only about to be shifted forward by 1 to be placed on the
// data packet. The packet in `r_packet` doesn't have the sequence number
// installed yet
// For BOTH vertical and horizontal snd groups:
// - Check if the "full group" condition is satisfied (all packets from the group are clipped)
// - If not, simply return false and do nothing
// - If so, store the current clip state into the referenced packet, give it the 'seq' sequence
// After packing the FEC packet:
// - update the base sequence in the group for which it's packed
// - make sure that pointers are reset to not suggest the packet is ready
// Handle the special case of m_number_rows == 1, which
// means we don't use columns.
if (m_number_rows <= 1)
{
HLOGC(pflog.Debug, log << "FEC/CTL not checking VERT group - rows only config");
// PASS ON to Horizontal group check
}
else
{
int offset_to_row_base = CSeqNo::seqoff(snd.row.base, seq);
int vert_gx = (offset_to_row_base + int(m_number_cols)) % int(m_number_cols);
// This can actually happen only for the very first sent packet.
// It looks like "following the last packet from the previous group",
// however there was no previous group because this is the first packet.
if (offset_to_row_base < 0)
{
HLOGC(pflog.Debug, log << "FEC/CTL not checking VERT group [" << vert_gx << "] - negative offset_to_row_base %"
<< snd.row.base << " -> %" << seq << " (" << offset_to_row_base
<< ") (collected " << snd.cols[abs(vert_gx)].collected << "/" << sizeCol() << ")");
// PASS ON to Horizontal group check
}
else
{
if (snd.cols[vert_gx].collected >= m_number_rows)
{
HLOGC(pflog.Debug, log << "FEC/CTL ready for VERT group [" << vert_gx << "]: %" << seq
<< " (base %" << snd.cols[vert_gx].base << ")");
// SHIP THE VERTICAL FEC packet.
PackControl(snd.cols[vert_gx], vert_gx, rpkt, seq);
// RESET THE GROUP THAT WAS SENT
ResetGroup(snd.cols[vert_gx]);
return true;
}
HLOGC(pflog.Debug, log << "FEC/CTL NOT ready for VERT group [" << vert_gx << "]: %" << seq
<< " (base %" << snd.cols[vert_gx].base << ")"
<< " - collected " << snd.cols[vert_gx].collected << "/" << m_number_rows);
}
}
if (snd.row.collected >= m_number_cols)
{
if (!m_cols_only)
{
HLOGC(pflog.Debug, log << "FEC/CTL ready for HORIZ group: %" << seq << " (base %" << snd.row.base << ")");
// SHIP THE HORIZONTAL FEC packet.
PackControl(snd.row, -1, rpkt, seq);
HLOGC(pflog.Debug, log << "...PACKET size=" << rpkt.length
<< " TS=" << rpkt.hdr[SRT_PH_TIMESTAMP]
<< " !" << BufferStamp(rpkt.buffer, rpkt.length));
}
// RESET THE HORIZONTAL GROUP.
// ALWAYS, even in columns-only.
ResetGroup(snd.row);
if (!m_cols_only)
{
// In columns-only you didn't pack anything, so check
// for column control.
return true;
}
}
else
{
HLOGC(pflog.Debug, log << "FEC/CTL NOT ready for HORIZ group: %" << seq
<< " (base %" << snd.row.base << ")"
<< " - collected " << snd.row.collected << "/" << m_number_cols);
}
return false;
}
void FECFilterBuiltin::PackControl(const Group& g, signed char index, SrtPacket& pkt, int32_t seq)
{
// Allocate as much space as needed, regardless of the PAYLOADSIZE value.
static const size_t INDEX_SIZE = 1;
size_t total_size =
INDEX_SIZE
+ sizeof(g.flag_clip)
+ sizeof(g.length_clip)
+ g.payload_clip.size();
// Sanity
#if ENABLE_DEBUG
if (g.output_buffer.size() < total_size)
{
LOGC(pflog.Fatal, log << "OUTPUT BUFFER TOO SMALL!");
abort();
}
#endif
char* out = pkt.buffer;
size_t off = 0;
// Spread the index. This is the index of the payload in the vertical group.
// For horizontal group this value is always -1.
out[off++] = index;
// Flags, currently only the encryption flags
out[off++] = g.flag_clip;
// Ok, now the length clip
memcpy((out + off), &g.length_clip, sizeof g.length_clip);
off += sizeof g.length_clip;
// And finally the payload clip
memcpy((out + off), &g.payload_clip[0], g.payload_clip.size());
// Ready. Now fill the header and finalize other data.
pkt.length = total_size;
pkt.hdr[SRT_PH_TIMESTAMP] = g.timestamp_clip;
pkt.hdr[SRT_PH_SEQNO] = seq;
HLOGC(pflog.Debug, log << "FEC: PackControl: hdr("
<< (total_size - g.payload_clip.size()) << "): INDEX="
<< int(index) << " LENGTH[ne]=" << fmt(g.length_clip, hex)
<< " FLAGS=" << fmt<int>(g.flag_clip, hex) << " TS=" << fmt(g.timestamp_clip, hex)
<< " PL(" << g.payload_clip.size() << ")[0-4]="
<< fmt(*(uint32_t*)&g.payload_clip[0], hex));
}
bool FECFilterBuiltin::receive(const CPacket& rpkt, loss_seqs_t& loss_seqs)
{
// Add this packet to the group where it belongs.
// Light up the cell of this packet to mark it received.
// Check if any of the groups to which the packet belongs
// have changed the status into RECOVERABLE.
//
// The group has RECOVERABLE status when it has FEC
// packet received and the number of collected packets counts
// exactly group_size - 1.
bool want_packet = false;
struct IsFec
{
bool row;
bool col;
signed char colx;
} isfec = { false, false, -1 };
// The sequence number must be checked prematurely, or it can otherwise
// cause large resource allocation. This might be even survived, provided
// that this will make the packet seen as exceeding the series 0 matrix,
// so all matrices in previous series should be dismissed thereafter. But
// this short living resource spike may be destructive, so let's do
// matrix dismissal FIRST before this packet is going to be handled.
CheckLargeDrop(rpkt.getSeqNo());
if (rpkt.getMsgSeq() == SRT_MSGNO_CONTROL)
{
// Interpret the first byte of the contents.
const char* payload = rpkt.data();
isfec.colx = payload[0];
if (isfec.colx == -1)
{
isfec.row = true;
}
else
{
isfec.col = true;
}
HLOGC(pflog.Debug, log << "FEC: RECEIVED %" << rpkt.getSeqNo() << " msgno=0, FEC/CTL packet. INDEX=" << int(payload[0]));
// This marks the cell as NOT received, but still does extend the
// cell container up to this sequence. The HangHorizontal and HangVertical
// functions that would also do cell dismissal, RELY ON IT.
MarkCellReceived(rpkt.getSeqNo(), CELL_EXTEND);
}
else
{
// Data packet, check if this packet was already received.
// If so, ignore it. This may happen if you have configured
// FEC and ARQ to cooperate, so a packet once rebuilt might
// be simultaneously also retransmitted. This may confuse the tables.
int celloff = CSeqNo::seqoff(rcv.cell_base, rpkt.getSeqNo());
bool past = celloff < 0;
bool exists = celloff < int(rcv.cells.size()) && !past && rcv.cells[celloff];
if (past || exists)
{
HLOGC(pflog.Debug, log << "FEC: packet %" << rpkt.getSeqNo() << " "
<< (past ? "in the PAST" : "already known") << ", IGNORING.");
return true;
}
want_packet = true;
HLOGC(pflog.Debug, log << "FEC: RECEIVED %" << rpkt.getSeqNo() << " msgno=" << rpkt.getMsgSeq() << " DATA PACKET.");
MarkCellReceived(rpkt.getSeqNo());
// Remember this simply every time a packet comes in. In live mode usually
// this flag is ORD_RELAXED (false), but some earlier versions used ORD_REQUIRED.
// Even though this flag is now usually ORD_RELAXED, it's fate in live mode
// isn't completely decided yet, so stay flexible. We believe at least that this
// flag will stay unchanged during whole connection.
rcv.order_required = rpkt.getMsgOrderFlag();
}
loss_seqs_t irrecover_row, irrecover_col;
#if HVU_ENABLE_HEAVY_LOGGING
static string hangname [] = {"NOT-DONE", "SUCCESS", "PAST", "CRAZY"};
#endif
// Required for EHangStatus
using namespace std::rel_ops;
EHangStatus okh = HANG_NOTDONE;
if (!isfec.col) // == regular packet or FEC/ROW
{
// Don't manage this packet for horizontal group,
// if it was a vertical FEC/CTL packet.
okh = HangHorizontal(rpkt, isfec.row, irrecover_row);
HLOGC(pflog.Debug, log << "FEC: HangHorizontal %" << rpkt.getSeqNo()
<< " msgno=" << rpkt.getMsgSeq()
<< " RESULT=" << hangname[okh] << " IRRECOVERABLE: " << Printable(irrecover_row));
}
if (okh > HANG_SUCCESS)
{
// Just informative.
LOGC(pflog.Warn, log << "FEC/H: rebuilding/hanging FAILED.");
}
EHangStatus okv = HANG_NOTDONE;
// Don't do HangVertical in case of row-only configuration
if (!isfec.row && m_number_rows > 1) // == regular packet or FEC/COL
{
// NOTE FOR IPE REPORTING:
// It is allowed that
// - Both HangVertical and HangHorizontal
okv = HangVertical(rpkt, isfec.colx, irrecover_col);
IF_HEAVY_LOGGING(bool discrep = (okv == HANG_CRAZY) ? int(okh) < HANG_CRAZY : false);
HLOGC(pflog.Debug, log << "FEC: HangVertical %" << rpkt.getSeqNo()
<< " msgno=" << rpkt.getMsgSeq()
<< " RESULT=" << hangname[okh]
<< (discrep ? " IPE: H successful and V failed!" : "")
<< " IRRECOVERABLE: " << Printable(irrecover_col));
}
if (okv > HANG_SUCCESS)
{
// Just informative.
LOGC(pflog.Warn, log << "FEC/V: rebuilding/hanging FAILED.");
}
if (okv == HANG_CRAZY || okh == HANG_CRAZY)
{
// Mark the cell not received, if it was rejected by the
// FEC group facility, otherwise it will deny to try to rebuild an
// allegedly existing packet.
MarkCellReceived(rpkt.getSeqNo(), CELL_REMOVE);
}
// Pack the following packets as irrecoverable:
if (m_fallback_level == SRT_ARQ_ONREQ)
{
// Use irrecover_row with rows only because there is
// never anything collected in irrecover_col.
if (m_number_rows == 1)
loss_seqs = irrecover_row;
else
loss_seqs = irrecover_col;
}
return want_packet;
// Get the packet from the incoming stream, already recognized
// as data packet, and then:
//
// (Note that the default builtin FEC mechanism uses such rules:
// - allows SRT to get the packet, even if it follows the loss
// - depending on m_fallback_level, confirms or denies the need that SRT handle the loss
// - in loss_seqs we return those that are not recoverable at the current level
// - FEC has no extra header provided, so regular data are passed as is
//)
// So, the needs to implement:
//
// 1. If this is a FEC packet, close the group, check for lost packets, try to recover.
// Check if there is recovery possible, if so, request a new unit and pack the recovered packet there.
// Report the loss to be reported by SRT according to m_fallback_level:
// - ARQ_ALWAYS: N/A for a FEC packet
// - ARQ_EARLY: When Horizontal group is closed and the packet is not recoverable, report this in loss_seqs
// - ARQ_LATELY: When Horizontal and Vertical group is closed and the packet is not recoverable, report it.
// - ARQ_NEVER: Always return empty loss_seqs
//
// 2. If this is a regular packet, use it for building the FEC group.
// - ARQ_ALWAYS: always return true and leave loss_seqs empty.
// - others: return false and return nothing in loss_seqs
}
void FECFilterBuiltin::CheckLargeDrop(int32_t seqno)
{
// Ok, first try to pick up the column and series
int offset = CSeqNo::seqoff(rcv.rowq[0].base, seqno);
if (offset < 0)
{
return;
}
// For row-only configuration, check only parts referring
// to a row.
if (m_number_rows == 1)
{
// We have no columns. So just check if exceeds 5* the row size.
// If so, clear the rows and reconfigure them.
if (offset > int(5 * sizeRow()))
{
// Calculate the new row base, without breaking the current
// layout. Make a skip by some number of rows so that the new
// first row is prepared to receive this packet.
int32_t oldbase = rcv.rowq[0].base;
size_t rowdist = offset / sizeRow();
int32_t newbase = CSeqNo::incseq(oldbase, int(rowdist * sizeRow()));
LOGC(pflog.Warn, log << "FEC: LARGE DROP detected! Resetting row groups. Base: %" << oldbase
<< " -> %" << newbase << "(shift by " << CSeqNo::seqoff(oldbase, newbase) << ")");
rcv.rowq.clear();
rcv.cells.clear();
rcv.rowq.resize(1);
HLOGP(pflog.Debug, "FEC: RE-INIT: receiver first row");
ConfigureGroup(rcv.rowq[0], newbase, 1, sizeRow());
}
return;
}
bool reset_anyway = false;
if (offset != CSeqNo::seqoff(rcv.colq[0].base, seqno))
{
reset_anyway = true;
HLOGC(pflog.Debug, log << "FEC: IPE: row.base %" << rcv.rowq[0].base << " != %" << rcv.colq[0].base << " - resetting");
}
// Number of column - regardless of series.
int colx = offset % numberCols();