fec.cpp 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  1. /*
  2. * SRT - Secure, Reliable, Transport
  3. * Copyright (c) 2019 Haivision Systems Inc.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. *
  9. */
  10. #include "platform_sys.h"
  11. #include <string>
  12. #include <map>
  13. #include <vector>
  14. #include <deque>
  15. #include <iterator>
  16. #include "packetfilter.h"
  17. #include "core.h"
  18. #include "packet.h"
  19. #include "logging.h"
  20. #include "fec.h"
  21. // Maximum allowed "history" remembered in the receiver groups.
  22. // This is calculated in series, that is, this number will be
  23. // multiplied by sizeRow() and sizeCol() to get the value being
  24. // a maximum distance between the FEC group base sequence and
  25. // the sequence to which a request comes in.
  26. // XXX Might be that this parameter should be configurable
  27. #define SRT_FEC_MAX_RCV_HISTORY 10
  28. using namespace std;
  29. using namespace srt_logging;
  30. namespace srt {
  31. const char FECFilterBuiltin::defaultConfig [] = "fec,rows:1,layout:staircase,arq:onreq";
  32. struct StringKeys
  33. {
  34. string operator()(const pair<const string, const string> item)
  35. {
  36. return item.first;
  37. }
  38. };
  39. bool FECFilterBuiltin::verifyConfig(const SrtFilterConfig& cfg, string& w_error)
  40. {
  41. string arspec = map_get(cfg.parameters, "layout");
  42. if (arspec != "" && arspec != "even" && arspec != "staircase")
  43. {
  44. w_error = "value for 'layout' must be 'even' or 'staircase'";
  45. return false;
  46. }
  47. string colspec = map_get(cfg.parameters, "cols"), rowspec = map_get(cfg.parameters, "rows");
  48. int out_rows = 1;
  49. if (colspec != "")
  50. {
  51. int out_cols = atoi(colspec.c_str());
  52. if (out_cols < 2)
  53. {
  54. w_error = "at least 'cols' must be specified and > 1";
  55. return false;
  56. }
  57. }
  58. if (rowspec != "")
  59. {
  60. out_rows = atoi(rowspec.c_str());
  61. if (out_rows >= -1 && out_rows < 1)
  62. {
  63. w_error = "'rows' must be >=1 or negative < -1";
  64. return false;
  65. }
  66. }
  67. // Extra interpret level, if found, default never.
  68. // Check only those that are managed.
  69. string level = map_get(cfg.parameters, "arq");
  70. if (level != "")
  71. {
  72. static const char* const levelnames [] = {"never", "onreq", "always"};
  73. size_t i = 0;
  74. for (i = 0; i < Size(levelnames); ++i)
  75. {
  76. if (strcmp(level.c_str(), levelnames[i]) == 0)
  77. break;
  78. }
  79. if (i == Size(levelnames))
  80. {
  81. w_error = "'arq' value '" + level + "' invalid. Allowed: never, onreq, always";
  82. return false;
  83. }
  84. }
  85. set<string> keys;
  86. transform(cfg.parameters.begin(), cfg.parameters.end(), inserter(keys, keys.begin()), StringKeys());
  87. // Delete all default parameters
  88. SrtFilterConfig defconf;
  89. ParseFilterConfig(defaultConfig, (defconf));
  90. for (map<string,string>::const_iterator i = defconf.parameters.begin();
  91. i != defconf.parameters.end(); ++i)
  92. keys.erase(i->first);
  93. // Delete mandatory parameters
  94. keys.erase("cols");
  95. if (!keys.empty())
  96. {
  97. w_error = "Extra parameters. Allowed only: cols, rows, layout, arq";
  98. return false;
  99. }
  100. return true;
  101. }
  102. FECFilterBuiltin::FECFilterBuiltin(const SrtFilterInitializer &init, std::vector<SrtPacket> &provided, const string &confstr)
  103. : SrtPacketFilterBase(init)
  104. , m_fallback_level(SRT_ARQ_ONREQ)
  105. , m_arrangement_staircase(true)
  106. , rcv(provided)
  107. {
  108. if (!ParseFilterConfig(confstr, cfg))
  109. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  110. string ermsg;
  111. if (!verifyConfig(cfg, (ermsg)))
  112. {
  113. LOGC(pflog.Error, log << "IPE: Filter config failed: " << ermsg);
  114. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  115. }
  116. // Configuration supported:
  117. // - row only (number_rows == 1)
  118. // - columns only, no row FEC/CTL (number_rows < -1)
  119. // - columns and rows (both > 1)
  120. // Disallowed configurations:
  121. // - number_cols < 1
  122. // - number_rows [-1, 0]
  123. string arspec = map_get(cfg.parameters, "layout");
  124. string shorter = arspec.size() > 5 ? arspec.substr(0, 5) : arspec;
  125. if (shorter == "even")
  126. m_arrangement_staircase = false;
  127. string colspec = map_get(cfg.parameters, "cols"), rowspec = map_get(cfg.parameters, "rows");
  128. if (colspec == "")
  129. {
  130. LOGC(pflog.Error, log << "FEC filter config: parameter 'cols' is mandatory");
  131. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  132. }
  133. int out_rows = 1;
  134. int out_cols = atoi(colspec.c_str());
  135. m_number_cols = out_cols;
  136. if (rowspec != "")
  137. {
  138. out_rows = atoi(rowspec.c_str());
  139. }
  140. if (out_rows < 0)
  141. {
  142. m_number_rows = -out_rows;
  143. m_cols_only = true;
  144. }
  145. else
  146. {
  147. m_number_rows = out_rows;
  148. m_cols_only = false;
  149. }
  150. // Extra interpret level, if found, default never.
  151. // Check only those that are managed.
  152. string level = cfg.parameters["arq"];
  153. int lv = -1;
  154. if (level != "")
  155. {
  156. static const char* levelnames [] = { "never", "onreq", "always" };
  157. for (size_t i = 0; i < Size(levelnames); ++i)
  158. {
  159. if (level == levelnames[i])
  160. {
  161. lv = int(i);
  162. break;
  163. }
  164. }
  165. }
  166. if (lv != -1)
  167. {
  168. m_fallback_level = SRT_ARQLevel(lv);
  169. }
  170. else
  171. {
  172. m_fallback_level = SRT_ARQ_ONREQ;
  173. }
  174. // Required to store in the header when rebuilding
  175. rcv.id = socketID();
  176. // Setup the bit matrix, initialize everything with false.
  177. // Vertical size (y)
  178. rcv.cells.resize(sizeCol() * sizeRow(), false);
  179. // These sequence numbers are both the value of ISN-1 at the moment
  180. // when the handshake is done. The sender ISN is generated here, the
  181. // receiver ISN by the peer. Both should be known after the handshake.
  182. // Later they will be updated as packets are transmitted.
  183. int32_t snd_isn = CSeqNo::incseq(sndISN());
  184. int32_t rcv_isn = CSeqNo::incseq(rcvISN());
  185. // Alright, now we need to get the ISN from m_parent
  186. // to extract the sequence number allowing qualification to the group.
  187. // The base values must be prepared so that feedSource can qualify them.
  188. // SEPARATE FOR SENDING AND RECEIVING!
  189. // Now, assignment of the groups requires:
  190. // For row groups, simply the size of the group suffices.
  191. // For column groups, you need a whole matrix of all sequence
  192. // numbers that are base sequence numbers for the group.
  193. // Sequences that belong to this group are:
  194. // 1. First packet has seq+1 towards the base.
  195. // 2. Every next packet has this value + the size of the row group.
  196. // So: group dispatching is:
  197. // - get the column number
  198. // - extract the group data for that column
  199. // - check if the sequence is later than the group base sequence, if not, report no group for the packet
  200. // - sanity check, if the seqdiff divided by row size gets 0 remainder
  201. // - The result from the above division can't exceed the column size, otherwise
  202. // it's another group. The number of currently collected data should be in 'collected'.
  203. // Now set up the group starting sequences.
  204. // The very first group in both dimensions will have the value of ISN in particular direction.
  205. // Set up sender part.
  206. //
  207. // Size: rows
  208. // Step: 1 (next packet in group is 1 past the previous one)
  209. // Slip: rows (first packet in the next group is distant to first packet in the previous group by 'rows')
  210. HLOGC(pflog.Debug, log << "FEC: INIT: ISN { snd=" << snd_isn << " rcv=" << rcv_isn << " }; sender single row");
  211. ConfigureGroup(snd.row, snd_isn, 1, sizeRow());
  212. // In the beginning we need just one reception group. New reception
  213. // groups will be created in tact with receiving packets outside this one.
  214. // The value of rcv.row[0].base will be used as an absolute base for calculating
  215. // the index of the group for a given received packet.
  216. rcv.rowq.resize(1);
  217. HLOGP(pflog.Debug, "FEC: INIT: receiver first row");
  218. ConfigureGroup(rcv.rowq[0], rcv_isn, 1, sizeRow());
  219. if (sizeCol() > 1)
  220. {
  221. // Size: cols
  222. // Step: rows (the next packet in the group is one row later)
  223. // Slip: rows+1 (the first packet in the next group is later by 1 column + one whole row down)
  224. HLOGP(pflog.Debug, "FEC: INIT: sender first N columns");
  225. ConfigureColumns(snd.cols, snd_isn);
  226. HLOGP(pflog.Debug, "FEC: INIT: receiver first N columns");
  227. ConfigureColumns(rcv.colq, rcv_isn);
  228. }
  229. // The bit markers that mark the received/lost packets will be expanded
  230. // as packets come in.
  231. rcv.cell_base = rcv_isn;
  232. }
  233. template <class Container>
  234. void FECFilterBuiltin::ConfigureColumns(Container& which, int32_t isn)
  235. {
  236. // This is to initialize the first set of groups.
  237. // which: group vector.
  238. // numberCols(): number of packets in one group
  239. // sizeCol(): seqdiff between two packets consecutive in the group
  240. // m_column_slip: seqdiff between the first packet in one group and first packet in the next group
  241. // isn: sequence number of the first packet in the first group
  242. size_t zero = which.size();
  243. // The first series of initialization should embrace:
  244. // - if multiplyer == 1, EVERYTHING (also the case of SOLID matrix)
  245. // - if more, ONLY THE FIRST SQUARE.
  246. which.resize(zero + numberCols());
  247. if (!m_arrangement_staircase)
  248. {
  249. HLOGC(pflog.Debug, log << "ConfigureColumns: new "
  250. << numberCols() << " columns, START AT: " << zero);
  251. // With even arrangement, just use a plain loop.
  252. // Initialize straight way all groups in the size.
  253. int32_t seqno = isn;
  254. for (size_t i = zero; i < which.size(); ++i)
  255. {
  256. // ARGS:
  257. // - seqno: sequence number of the first packet in the group
  258. // - step: distance between two consecutive packets in the group
  259. // - drop: distance between base sequence numbers in groups in consecutive series
  260. // (meaning: with row size 6, group with index 2 and 8 are in the
  261. // same column 2, lying in 0 and 1 series respectively).
  262. ConfigureGroup(which[i], seqno, sizeRow(), sizeCol() * numberCols());
  263. seqno = CSeqNo::incseq(seqno);
  264. }
  265. return;
  266. }
  267. // With staircase, the next column's base sequence is
  268. // shifted by 1 AND the length of the row. When this shift
  269. // becomes below the column 0 bottom, reset it to the row 0
  270. // and continue.
  271. // Start here. The 'isn' is still the absolute base sequence value.
  272. size_t offset = 0;
  273. HLOGC(pflog.Debug, log << "ConfigureColumns: " << (which.size() - zero)
  274. << " columns, START AT: " << zero);
  275. for (size_t i = zero; i < which.size(); ++i)
  276. {
  277. int32_t seq = CSeqNo::incseq(isn, int(offset));
  278. size_t col = i - zero;
  279. HLOGC(pflog.Debug, log << "ConfigureColumns: [" << col << "]: -> ConfigureGroup...");
  280. ConfigureGroup(which[i], seq, sizeRow(), sizeCol() * numberCols());
  281. if (col % numberRows() == numberRows() - 1)
  282. {
  283. offset = col + 1; // +1 because we want it for the next column
  284. HLOGC(pflog.Debug, log << "ConfigureColumns: [" << (col+1) << "]... (resetting to row 0: +"
  285. << offset << " %" << CSeqNo::incseq(isn, (int32_t)offset) << ")");
  286. }
  287. else
  288. {
  289. offset += 1 + sizeRow();
  290. HLOGC(pflog.Debug, log << "ConfigureColumns: [" << (col+1) << "] ... (continue +"
  291. << offset << " %" << CSeqNo::incseq(isn, (int32_t)offset) << ")");
  292. }
  293. }
  294. }
  295. void FECFilterBuiltin::ConfigureGroup(Group& g, int32_t seqno, size_t gstep, size_t drop)
  296. {
  297. g.base = seqno;
  298. g.step = gstep;
  299. // This actually rewrites the size of the group here, but
  300. // by having this value precalculated we simply close the
  301. // group by adding this value to the base sequence.
  302. g.drop = drop;
  303. g.collected = 0;
  304. // Now the buffer spaces for clips.
  305. g.payload_clip.resize(payloadSize());
  306. g.length_clip = 0;
  307. g.flag_clip = 0;
  308. g.timestamp_clip = 0;
  309. HLOGC(pflog.Debug, log << "FEC: ConfigureGroup: base %" << seqno << " step=" << gstep << " drop=" << drop);
  310. // Preallocate the buffer that will be used for storing it for
  311. // the needs of passing the data through the network.
  312. // This will be filled with zeros initially, which is unnecessary,
  313. // but it happeens just once after connection.
  314. }
  315. void FECFilterBuiltin::ResetGroup(Group& g)
  316. {
  317. const int32_t new_seq_base = CSeqNo::incseq(g.base, int(g.drop));
  318. HLOGC(pflog.Debug, log << "FEC: ResetGroup (step=" << g.step << "): base %" << g.base << " -> %" << new_seq_base);
  319. g.base = new_seq_base;
  320. g.collected = 0;
  321. // This isn't necessary for ConfigureGroup because the
  322. // vector after resizing is filled with a given value,
  323. // by default the default value of the type, char(), that is 0.
  324. g.length_clip = 0;
  325. g.flag_clip = 0;
  326. g.timestamp_clip = 0;
  327. memset(&g.payload_clip[0], 0, g.payload_clip.size());
  328. }
  329. void FECFilterBuiltin::feedSource(CPacket& packet)
  330. {
  331. // Hang on the matrix. Find by packet->getSeqNo().
  332. // (The "absolute base" is the cell 0 in vertical groups)
  333. int32_t base = snd.row.base;
  334. // (we are guaranteed that this packet is a data packet, so
  335. // we don't have to check if this isn't a control packet)
  336. int baseoff = CSeqNo::seqoff(base, packet.getSeqNo());
  337. int horiz_pos = baseoff;
  338. if (CheckGroupClose(snd.row, horiz_pos, sizeRow()))
  339. {
  340. HLOGC(pflog.Debug, log << "FEC:... HORIZ group closed, B=%" << snd.row.base);
  341. }
  342. ClipPacket(snd.row, packet);
  343. snd.row.collected++;
  344. // Don't do any column feeding if using column size 1
  345. if (sizeCol() < 2)
  346. {
  347. // The above logging instruction in case of no columns
  348. HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo()
  349. << " B:%" << baseoff << " H:*[" << horiz_pos << "]"
  350. << " size=" << packet.size()
  351. << " TS=" << packet.getMsgTimeStamp()
  352. << " !" << BufferStamp(packet.data(), packet.size()));
  353. HLOGC(pflog.Debug, log << "FEC collected: H: " << snd.row.collected);
  354. return;
  355. }
  356. // 1. Get the number of group in both vertical and horizontal groups:
  357. // - Vertical: offset towards base (% row size, but with updated Base seq unnecessary)
  358. // (Just for a case).
  359. int vert_gx = baseoff % sizeRow();
  360. // 2. Define the position of this packet in the group
  361. // - Horizontal: offset towards base (of the given group, not absolute!)
  362. // - Vertical: (seq-base)/column_size
  363. int32_t vert_base = snd.cols[vert_gx].base;
  364. int vert_off = CSeqNo::seqoff(vert_base, packet.getSeqNo());
  365. // It MAY HAPPEN that the base is newer than the sequence of the packet.
  366. // This may normally happen in the beginning period, where the bases
  367. // set up initially for all columns got the shift, so they are kinda from
  368. // the future, and "this sequence" is in a group that is already closed.
  369. // In this case simply can't clip the packet in the column group.
  370. HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo() << " rowoff=" << baseoff
  371. << " column=" << vert_gx << " .base=%" << vert_base << " coloff=" << vert_off);
  372. // [[assert sizeCol() >= 2]]; // see the condition above.
  373. if (vert_off >= 0)
  374. {
  375. // BEWARE! X % Y with different signedness upgrades int to unsigned!
  376. // SANITY: check if the rule applies on the group
  377. if (vert_off % sizeRow())
  378. {
  379. LOGC(pflog.Fatal, log << "FEC:feedSource: IPE: VGroup #" << vert_gx << " base=%" << vert_base
  380. << " WRONG with horiz base=%" << base << "coloff(" << vert_off
  381. << ") % sizeRow(" << sizeRow() << ") = " << (vert_off % sizeRow()));
  382. // Do not place it, it would be wrong.
  383. return;
  384. }
  385. // [[assert vert_off >= 0]]; // this condition branch
  386. int vert_pos = vert_off / int(sizeRow());
  387. HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo()
  388. << " B:%" << baseoff << " H:*[" << horiz_pos << "] V(B=%" << vert_base
  389. << ")[col=" << vert_gx << "][" << vert_pos << "/" << sizeCol() << "] "
  390. << " size=" << packet.size()
  391. << " TS=" << packet.getMsgTimeStamp()
  392. << " !" << BufferStamp(packet.data(), packet.size()));
  393. // 3. The group should be check for the necessity of being closed.
  394. // Note that FEC packet extraction doesn't change the state of the
  395. // VERTICAL groups (it can be potentially extracted multiple times),
  396. // only the horizontal in order to mark that the vertical FEC is
  397. // extracted already. So, anyway, check if the group limit was reached
  398. // and it wasn't closed.
  399. // 4. Apply the clip
  400. // 5. Increase collected.
  401. if (CheckGroupClose(snd.cols[vert_gx], vert_pos, sizeCol()))
  402. {
  403. HLOGC(pflog.Debug, log << "FEC:... VERT group closed, B=%" << snd.cols[vert_gx].base);
  404. }
  405. ClipPacket(snd.cols[vert_gx], packet);
  406. snd.cols[vert_gx].collected++;
  407. }
  408. else
  409. {
  410. HLOGC(pflog.Debug, log << "FEC:feedSource: %" << packet.getSeqNo()
  411. << " B:%" << baseoff << " H:*[" << horiz_pos << "] V(B=%" << vert_base
  412. << ")[col=" << vert_gx << "]<NO-COLUMN>"
  413. << " size=" << packet.size()
  414. << " TS=" << packet.getMsgTimeStamp()
  415. << " !" << BufferStamp(packet.data(), packet.size()));
  416. }
  417. HLOGC(pflog.Debug, log << "FEC collected: H: " << snd.row.collected << " V[" << vert_gx << "]: " << snd.cols[vert_gx].collected);
  418. }
  419. bool FECFilterBuiltin::CheckGroupClose(Group& g, size_t pos, size_t size)
  420. {
  421. if (pos < size)
  422. return false;
  423. ResetGroup(g);
  424. return true;
  425. }
  426. void FECFilterBuiltin::ClipPacket(Group& g, const CPacket& pkt)
  427. {
  428. // Both length and timestamp must be taken as NETWORK ORDER
  429. // before applying the clip.
  430. uint16_t length_net = htons(uint16_t(pkt.size()));
  431. uint8_t kflg = uint8_t(pkt.getMsgCryptoFlags());
  432. // NOTE: Unlike length, the TIMESTAMP is NOT endian-reordered
  433. // because it will be written into the TIMESTAMP field in the
  434. // header, and header is inverted automatically when sending,
  435. // unlike the contents of the payload, where the length will be written.
  436. uint32_t timestamp_hw = pkt.getMsgTimeStamp();
  437. ClipData(g, length_net, kflg, timestamp_hw, pkt.data(), pkt.size());
  438. HLOGC(pflog.Debug, log << "FEC DATA PKT CLIP: " << hex
  439. << "FLAGS=" << unsigned(kflg) << " LENGTH[ne]=" << (length_net)
  440. << " TS[he]=" << timestamp_hw
  441. << " CLIP STATE: FLAGS=" << unsigned(g.flag_clip)
  442. << " LENGTH[ne]=" << g.length_clip
  443. << " TS[he]=" << g.timestamp_clip
  444. << " PL4=" << (*(uint32_t*)&g.payload_clip[0]));
  445. }
  446. // Clipping a control packet does merely the same, just the packet has
  447. // different contents, so it must be differetly interpreted.
  448. void FECFilterBuiltin::ClipControlPacket(Group& g, const CPacket& pkt)
  449. {
  450. // Both length and timestamp must be taken as NETWORK ORDER
  451. // before applying the clip.
  452. const char* fec_header = pkt.data();
  453. const char* payload = fec_header + 4;
  454. size_t payload_clip_len = pkt.size() - 4;
  455. const uint8_t* flag_clip = (const uint8_t*)(fec_header + 1);
  456. const uint16_t* length_clip = (const uint16_t*)(fec_header + 2);
  457. uint32_t timestamp_hw = pkt.getMsgTimeStamp();
  458. ClipData(g, *length_clip, *flag_clip, timestamp_hw, payload, payload_clip_len);
  459. HLOGC(pflog.Debug, log << "FEC/CTL CLIP: " << hex
  460. << "FLAGS=" << unsigned(*flag_clip) << " LENGTH[ne]=" << (*length_clip)
  461. << " TS[he]=" << timestamp_hw
  462. << " CLIP STATE: FLAGS=" << unsigned(g.flag_clip)
  463. << " LENGTH[ne]=" << g.length_clip
  464. << " TS[he]=" << g.timestamp_clip
  465. << " PL4=" << (*(uint32_t*)&g.payload_clip[0]));
  466. }
  467. void FECFilterBuiltin::ClipRebuiltPacket(Group& g, Receive::PrivPacket& pkt)
  468. {
  469. uint16_t length_net = htons(uint16_t(pkt.length));
  470. uint8_t kflg = MSGNO_ENCKEYSPEC::unwrap(pkt.hdr[SRT_PH_MSGNO]);
  471. // NOTE: Unlike length, the TIMESTAMP is NOT endian-reordered
  472. // because it will be written into the TIMESTAMP field in the
  473. // header, and header is inverted automatically when sending,
  474. // unlike the contents of the payload, where the length will be written.
  475. uint32_t timestamp_hw = pkt.hdr[SRT_PH_TIMESTAMP];
  476. ClipData(g, length_net, kflg, timestamp_hw, pkt.buffer, pkt.length);
  477. HLOGC(pflog.Debug, log << "FEC REBUILT DATA CLIP: " << hex
  478. << "FLAGS=" << unsigned(kflg) << " LENGTH[ne]=" << (length_net)
  479. << " TS[he]=" << timestamp_hw
  480. << " CLIP STATE: FLAGS=" << unsigned(g.flag_clip)
  481. << " LENGTH[ne]=" << g.length_clip
  482. << " TS[he]=" << g.timestamp_clip
  483. << " PL4=" << (*(uint32_t*)&g.payload_clip[0]));
  484. }
  485. void FECFilterBuiltin::ClipData(Group& g, uint16_t length_net, uint8_t kflg,
  486. uint32_t timestamp_hw, const char* payload, size_t payload_size)
  487. {
  488. g.length_clip = g.length_clip ^ length_net;
  489. g.flag_clip = g.flag_clip ^ kflg;
  490. g.timestamp_clip = g.timestamp_clip ^ timestamp_hw;
  491. // Payload goes "as is".
  492. for (size_t i = 0; i < payload_size; ++i)
  493. {
  494. g.payload_clip[i] = g.payload_clip[i] ^ payload[i];
  495. }
  496. // Fill the rest with zeros. When this packet is going to be
  497. // recovered, the payload extracted from this process will have
  498. // the maximum length, but it will be cut to the right length
  499. // and these padding 0s taken out.
  500. for (size_t i = payload_size; i < payloadSize(); ++i)
  501. g.payload_clip[i] = g.payload_clip[i] ^ 0;
  502. }
  503. bool FECFilterBuiltin::packControlPacket(SrtPacket& rpkt, int32_t seq)
  504. {
  505. // If the FEC packet is not yet ready for extraction, do nothing and return false.
  506. // Check if seq is the last sequence of the group.
  507. // Check VERTICAL group first, then HORIZONTAL.
  508. //
  509. // This is because when it happens that HORIZONTAL group is to be
  510. // FEC-CTL reported, it also shifts the base to the next row, whereas
  511. // this base sequence is used to determine the column index that is
  512. // needed to reach the right column group and it must stay unupdated
  513. // until the last packet in this row is checked for VERTICAL groups.
  514. // If it's ready for extraction, extract it, and write into the packet.
  515. //
  516. // NOTE: seq is the sequence number of the LAST PACKET SENT regularly.
  517. // This is only about to be shifted forward by 1 to be placed on the
  518. // data packet. The packet in `r_packet` doesn't have the sequence number
  519. // installed yet
  520. // For BOTH vertical and horizontal snd groups:
  521. // - Check if the "full group" condition is satisfied (all packets from the group are clipped)
  522. // - If not, simply return false and do nothing
  523. // - If so, store the current clip state into the referenced packet, give it the 'seq' sequence
  524. // After packing the FEC packet:
  525. // - update the base sequence in the group for which it's packed
  526. // - make sure that pointers are reset to not suggest the packet is ready
  527. // Handle the special case of m_number_rows == 1, which
  528. // means we don't use columns.
  529. if (m_number_rows <= 1)
  530. {
  531. HLOGC(pflog.Debug, log << "FEC/CTL not checking VERT group - rows only config");
  532. // PASS ON to Horizontal group check
  533. }
  534. else
  535. {
  536. int offset_to_row_base = CSeqNo::seqoff(snd.row.base, seq);
  537. int vert_gx = (offset_to_row_base + int(m_number_cols)) % int(m_number_cols);
  538. // This can actually happen only for the very first sent packet.
  539. // It looks like "following the last packet from the previous group",
  540. // however there was no previous group because this is the first packet.
  541. if (offset_to_row_base < 0)
  542. {
  543. HLOGC(pflog.Debug, log << "FEC/CTL not checking VERT group [" << vert_gx << "] - negative offset_to_row_base %"
  544. << snd.row.base << " -> %" << seq << " (" << offset_to_row_base
  545. << ") (collected " << snd.cols[abs(vert_gx)].collected << "/" << sizeCol() << ")");
  546. // PASS ON to Horizontal group check
  547. }
  548. else
  549. {
  550. if (snd.cols[vert_gx].collected >= m_number_rows)
  551. {
  552. HLOGC(pflog.Debug, log << "FEC/CTL ready for VERT group [" << vert_gx << "]: %" << seq
  553. << " (base %" << snd.cols[vert_gx].base << ")");
  554. // SHIP THE VERTICAL FEC packet.
  555. PackControl(snd.cols[vert_gx], vert_gx, rpkt, seq);
  556. // RESET THE GROUP THAT WAS SENT
  557. ResetGroup(snd.cols[vert_gx]);
  558. return true;
  559. }
  560. HLOGC(pflog.Debug, log << "FEC/CTL NOT ready for VERT group [" << vert_gx << "]: %" << seq
  561. << " (base %" << snd.cols[vert_gx].base << ")"
  562. << " - collected " << snd.cols[vert_gx].collected << "/" << m_number_rows);
  563. }
  564. }
  565. if (snd.row.collected >= m_number_cols)
  566. {
  567. if (!m_cols_only)
  568. {
  569. HLOGC(pflog.Debug, log << "FEC/CTL ready for HORIZ group: %" << seq << " (base %" << snd.row.base << ")");
  570. // SHIP THE HORIZONTAL FEC packet.
  571. PackControl(snd.row, -1, rpkt, seq);
  572. HLOGC(pflog.Debug, log << "...PACKET size=" << rpkt.length
  573. << " TS=" << rpkt.hdr[SRT_PH_TIMESTAMP]
  574. << " !" << BufferStamp(rpkt.buffer, rpkt.length));
  575. }
  576. // RESET THE HORIZONTAL GROUP.
  577. // ALWAYS, even in columns-only.
  578. ResetGroup(snd.row);
  579. if (!m_cols_only)
  580. {
  581. // In columns-only you didn't pack anything, so check
  582. // for column control.
  583. return true;
  584. }
  585. }
  586. else
  587. {
  588. HLOGC(pflog.Debug, log << "FEC/CTL NOT ready for HORIZ group: %" << seq
  589. << " (base %" << snd.row.base << ")"
  590. << " - collected " << snd.row.collected << "/" << m_number_cols);
  591. }
  592. return false;
  593. }
  594. void FECFilterBuiltin::PackControl(const Group& g, signed char index, SrtPacket& pkt, int32_t seq)
  595. {
  596. // Allocate as much space as needed, regardless of the PAYLOADSIZE value.
  597. static const size_t INDEX_SIZE = 1;
  598. size_t total_size =
  599. INDEX_SIZE
  600. + sizeof(g.flag_clip)
  601. + sizeof(g.length_clip)
  602. + g.payload_clip.size();
  603. // Sanity
  604. #if ENABLE_DEBUG
  605. if (g.output_buffer.size() < total_size)
  606. {
  607. LOGC(pflog.Fatal, log << "OUTPUT BUFFER TOO SMALL!");
  608. abort();
  609. }
  610. #endif
  611. char* out = pkt.buffer;
  612. size_t off = 0;
  613. // Spread the index. This is the index of the payload in the vertical group.
  614. // For horizontal group this value is always -1.
  615. out[off++] = index;
  616. // Flags, currently only the encryption flags
  617. out[off++] = g.flag_clip;
  618. // Ok, now the length clip
  619. memcpy((out + off), &g.length_clip, sizeof g.length_clip);
  620. off += sizeof g.length_clip;
  621. // And finally the payload clip
  622. memcpy((out + off), &g.payload_clip[0], g.payload_clip.size());
  623. // Ready. Now fill the header and finalize other data.
  624. pkt.length = total_size;
  625. pkt.hdr[SRT_PH_TIMESTAMP] = g.timestamp_clip;
  626. pkt.hdr[SRT_PH_SEQNO] = seq;
  627. HLOGC(pflog.Debug, log << "FEC: PackControl: hdr("
  628. << (total_size - g.payload_clip.size()) << "): INDEX="
  629. << int(index) << " LENGTH[ne]=" << hex << g.length_clip
  630. << " FLAGS=" << int(g.flag_clip) << " TS=" << g.timestamp_clip
  631. << " PL(" << dec << g.payload_clip.size() << ")[0-4]=" << hex
  632. << (*(uint32_t*)&g.payload_clip[0]));
  633. }
  634. bool FECFilterBuiltin::receive(const CPacket& rpkt, loss_seqs_t& loss_seqs)
  635. {
  636. // Add this packet to the group where it belongs.
  637. // Light up the cell of this packet to mark it received.
  638. // Check if any of the groups to which the packet belongs
  639. // have changed the status into RECOVERABLE.
  640. //
  641. // The group has RECOVERABLE status when it has FEC
  642. // packet received and the number of collected packets counts
  643. // exactly group_size - 1.
  644. bool want_packet = false;
  645. struct IsFec
  646. {
  647. bool row;
  648. bool col;
  649. signed char colx;
  650. } isfec = { false, false, -1 };
  651. // The sequence number must be checked prematurely, or it can otherwise
  652. // cause large resource allocation. This might be even survived, provided
  653. // that this will make the packet seen as exceeding the series 0 matrix,
  654. // so all matrices in previous series should be dismissed thereafter. But
  655. // this short living resource spike may be destructive, so let's do
  656. // matrix dismissal FIRST before this packet is going to be handled.
  657. CheckLargeDrop(rpkt.getSeqNo());
  658. if (rpkt.getMsgSeq() == SRT_MSGNO_CONTROL)
  659. {
  660. // Interpret the first byte of the contents.
  661. const char* payload = rpkt.data();
  662. isfec.colx = payload[0];
  663. if (isfec.colx == -1)
  664. {
  665. isfec.row = true;
  666. }
  667. else
  668. {
  669. isfec.col = true;
  670. }
  671. HLOGC(pflog.Debug, log << "FEC: RECEIVED %" << rpkt.getSeqNo() << " msgno=0, FEC/CTL packet. INDEX=" << int(payload[0]));
  672. // This marks the cell as NOT received, but still does extend the
  673. // cell container up to this sequence. The HangHorizontal and HangVertical
  674. // functions that would also do cell dismissal, RELY ON IT.
  675. MarkCellReceived(rpkt.getSeqNo(), CELL_EXTEND);
  676. }
  677. else
  678. {
  679. // Data packet, check if this packet was already received.
  680. // If so, ignore it. This may happen if you have configured
  681. // FEC and ARQ to cooperate, so a packet once rebuilt might
  682. // be simultaneously also retransmitted. This may confuse the tables.
  683. int celloff = CSeqNo::seqoff(rcv.cell_base, rpkt.getSeqNo());
  684. bool past = celloff < 0;
  685. bool exists = celloff < int(rcv.cells.size()) && !past && rcv.cells[celloff];
  686. if (past || exists)
  687. {
  688. HLOGC(pflog.Debug, log << "FEC: packet %" << rpkt.getSeqNo() << " "
  689. << (past ? "in the PAST" : "already known") << ", IGNORING.");
  690. return true;
  691. }
  692. want_packet = true;
  693. HLOGC(pflog.Debug, log << "FEC: RECEIVED %" << rpkt.getSeqNo() << " msgno=" << rpkt.getMsgSeq() << " DATA PACKET.");
  694. MarkCellReceived(rpkt.getSeqNo());
  695. // Remember this simply every time a packet comes in. In live mode usually
  696. // this flag is ORD_RELAXED (false), but some earlier versions used ORD_REQUIRED.
  697. // Even though this flag is now usually ORD_RELAXED, it's fate in live mode
  698. // isn't completely decided yet, so stay flexible. We believe at least that this
  699. // flag will stay unchanged during whole connection.
  700. rcv.order_required = rpkt.getMsgOrderFlag();
  701. }
  702. loss_seqs_t irrecover_row, irrecover_col;
  703. #if ENABLE_HEAVY_LOGGING
  704. static string hangname [] = {"SUCCESS", "PAST", "CRAZY", "NOT-DONE"};
  705. #endif
  706. // Required for EHangStatus
  707. using namespace std::rel_ops;
  708. EHangStatus okh = HANG_NOTDONE;
  709. if (!isfec.col) // == regular packet or FEC/ROW
  710. {
  711. // Don't manage this packet for horizontal group,
  712. // if it was a vertical FEC/CTL packet.
  713. okh = HangHorizontal(rpkt, isfec.row, irrecover_row);
  714. HLOGC(pflog.Debug, log << "FEC: HangHorizontal %" << rpkt.getSeqNo()
  715. << " msgno=" << rpkt.getMsgSeq()
  716. << " RESULT=" << hangname[okh] << " IRRECOVERABLE: " << Printable(irrecover_row));
  717. }
  718. if (okh > HANG_SUCCESS)
  719. {
  720. // Just informative.
  721. LOGC(pflog.Warn, log << "FEC/H: rebuilding/hanging FAILED.");
  722. }
  723. EHangStatus okv = HANG_NOTDONE;
  724. // Don't do HangVertical in case of row-only configuration
  725. if (!isfec.row && m_number_rows > 1) // == regular packet or FEC/COL
  726. {
  727. // NOTE FOR IPE REPORTING:
  728. // It is allowed that
  729. // - Both HangVertical and HangHorizontal
  730. okv = HangVertical(rpkt, isfec.colx, irrecover_col);
  731. IF_HEAVY_LOGGING(bool discrep = (okv == HANG_CRAZY) ? int(okh) < HANG_CRAZY : false);
  732. HLOGC(pflog.Debug, log << "FEC: HangVertical %" << rpkt.getSeqNo()
  733. << " msgno=" << rpkt.getMsgSeq()
  734. << " RESULT=" << hangname[okh]
  735. << (discrep ? " IPE: H successul and V failed!" : "")
  736. << " IRRECOVERABLE: " << Printable(irrecover_col));
  737. }
  738. if (okv > HANG_SUCCESS)
  739. {
  740. // Just informative.
  741. LOGC(pflog.Warn, log << "FEC/V: rebuilding/hanging FAILED.");
  742. }
  743. if (okv == HANG_CRAZY || okh == HANG_CRAZY)
  744. {
  745. // Mark the cell not received, if it was rejected by the
  746. // FEC group facility, otherwise it will deny to try to rebuild an
  747. // allegedly existing packet.
  748. MarkCellReceived(rpkt.getSeqNo(), CELL_REMOVE);
  749. }
  750. // Pack the following packets as irrecoverable:
  751. if (m_fallback_level == SRT_ARQ_ONREQ)
  752. {
  753. // Use irrecover_row with rows only because there is
  754. // never anything collected in irrecover_col.
  755. if (m_number_rows == 1)
  756. loss_seqs = irrecover_row;
  757. else
  758. loss_seqs = irrecover_col;
  759. }
  760. return want_packet;
  761. // Get the packet from the incoming stream, already recognized
  762. // as data packet, and then:
  763. //
  764. // (Note that the default builtin FEC mechanism uses such rules:
  765. // - allows SRT to get the packet, even if it follows the loss
  766. // - depending on m_fallback_level, confirms or denies the need that SRT handle the loss
  767. // - in loss_seqs we return those that are not recoverable at the current level
  768. // - FEC has no extra header provided, so regular data are passed as is
  769. //)
  770. // So, the needs to implement:
  771. //
  772. // 1. If this is a FEC packet, close the group, check for lost packets, try to recover.
  773. // Check if there is recovery possible, if so, request a new unit and pack the recovered packet there.
  774. // Report the loss to be reported by SRT according to m_fallback_level:
  775. // - ARQ_ALWAYS: N/A for a FEC packet
  776. // - ARQ_EARLY: When Horizontal group is closed and the packet is not recoverable, report this in loss_seqs
  777. // - ARQ_LATELY: When Horizontal and Vertical group is closed and the packet is not recoverable, report it.
  778. // - ARQ_NEVER: Always return empty loss_seqs
  779. //
  780. // 2. If this is a regular packet, use it for building the FEC group.
  781. // - ARQ_ALWAYS: always return true and leave loss_seqs empty.
  782. // - others: return false and return nothing in loss_seqs
  783. }
  784. void FECFilterBuiltin::CheckLargeDrop(int32_t seqno)
  785. {
  786. // Ok, first try to pick up the column and series
  787. int offset = CSeqNo::seqoff(rcv.rowq[0].base, seqno);
  788. if (offset < 0)
  789. {
  790. return;
  791. }
  792. // For row-only configuration, check only parts referring
  793. // to a row.
  794. if (m_number_rows == 1)
  795. {
  796. // We have no columns. So just check if exceeds 5* the row size.
  797. // If so, clear the rows and reconfigure them.
  798. if (offset > int(5 * sizeRow()))
  799. {
  800. // Calculate the new row base, without breaking the current
  801. // layout. Make a skip by some number of rows so that the new
  802. // first row is prepared to receive this packet.
  803. int32_t oldbase = rcv.rowq[0].base;
  804. size_t rowdist = offset / sizeRow();
  805. int32_t newbase = CSeqNo::incseq(oldbase, int(rowdist * sizeRow()));
  806. LOGC(pflog.Warn, log << "FEC: LARGE DROP detected! Resetting row groups. Base: %" << oldbase
  807. << " -> %" << newbase << "(shift by " << CSeqNo::seqoff(oldbase, newbase) << ")");
  808. rcv.rowq.clear();
  809. rcv.cells.clear();
  810. rcv.rowq.resize(1);
  811. HLOGP(pflog.Debug, "FEC: RE-INIT: receiver first row");
  812. ConfigureGroup(rcv.rowq[0], newbase, 1, sizeRow());
  813. }
  814. return;
  815. }
  816. bool reset_anyway = false;
  817. if (offset != CSeqNo::seqoff(rcv.colq[0].base, seqno))
  818. {
  819. reset_anyway = true;
  820. HLOGC(pflog.Debug, log << "FEC: IPE: row.base %" << rcv.rowq[0].base << " != %" << rcv.colq[0].base << " - resetting");
  821. }
  822. // Number of column - regardless of series.
  823. int colx = offset % numberCols();
  824. // Base sequence from the group series 0 in this column
  825. // [[assert rcv.colq.size() >= numberCols()]];
  826. int32_t colbase = rcv.colq[colx].base;
  827. // Offset between this base and seqno
  828. int coloff = CSeqNo::seqoff(colbase, seqno);
  829. // Might be that it's in the row above the column,
  830. // still it's not a large-drop
  831. if (coloff < 0)
  832. {
  833. return;
  834. }
  835. const size_t size_in_packets = colx * numberRows();
  836. const size_t matrix = numberRows() * numberCols();
  837. const int colseries = coloff / int(matrix);
  838. if (size_in_packets > rcvBufferSize()/2 || colseries > SRT_FEC_MAX_RCV_HISTORY || reset_anyway)
  839. {
  840. // Ok, now define the new ABSOLUTE BASE. This is the base of the column 0
  841. // column group from the series previous towards this one.
  842. int32_t oldbase = rcv.colq[0].base;
  843. int32_t newbase = CSeqNo::incseq(oldbase, (colseries-1) * int(matrix));
  844. LOGC(pflog.Warn, log << "FEC: LARGE DROP detected! Resetting all groups. Base: %" << oldbase
  845. << " -> %" << newbase << "(shift by " << CSeqNo::seqoff(oldbase, newbase) << ")");
  846. rcv.rowq.clear();
  847. rcv.colq.clear();
  848. rcv.cells.clear();
  849. rcv.rowq.resize(1);
  850. HLOGP(pflog.Debug, "FEC: RE-INIT: receiver first row");
  851. ConfigureGroup(rcv.rowq[0], newbase, 1, sizeRow());
  852. // Size: cols
  853. // Step: rows (the next packet in the group is one row later)
  854. // Slip: rows+1 (the first packet in the next group is later by 1 column + one whole row down)
  855. HLOGP(pflog.Debug, "FEC: RE-INIT: receiver first N columns");
  856. ConfigureColumns(rcv.colq, newbase);
  857. rcv.cell_base = newbase;
  858. }
  859. }
  860. void FECFilterBuiltin::CollectIrrecoverRow(RcvGroup& g, loss_seqs_t& irrecover) const
  861. {
  862. if (g.dismissed)
  863. return; // already collected
  864. // Obtain the group's packet shift
  865. int32_t base = rcv.cell_base;
  866. int offset = CSeqNo::seqoff(base, g.base);
  867. if (offset < 0)
  868. {
  869. LOGC(pflog.Error, log << "FEC: IPE: row base %" << g.base << " is PAST to cell base %" << base);
  870. return;
  871. }
  872. size_t maxoff = offset + m_number_cols;
  873. // Sanity check, if all cells are really filled.
  874. if (maxoff > rcv.cells.size())
  875. {
  876. LOGC(pflog.Error, log << "FEC: IPE: Collecting loss from row %"
  877. << g.base << "+" << m_number_cols << " while cells <= %"
  878. << CSeqNo::seqoff(rcv.cell_base, int(rcv.cells.size())-1));
  879. return;
  880. }
  881. bool last = true;
  882. loss_seqs_t::value_type val;
  883. for (size_t i = offset; i < maxoff; ++i)
  884. {
  885. bool gone = last;
  886. last = rcv.cells[i];
  887. if (gone && !last)
  888. {
  889. // Switch full -> loss. Store the sequence, as single (for now)
  890. val.first = val.second = CSeqNo::incseq(base, int(i));
  891. }
  892. else if (last && !gone)
  893. {
  894. val.second = CSeqNo::incseq(base, int(i));
  895. irrecover.push_back(val);
  896. }
  897. }
  898. // If it happened that 0 cells were until the end, we are
  899. // sure that we have the val.first set to the first of the loss list
  900. // and we've reached the end. Otherwise 'last' would be true.
  901. if (!last)
  902. {
  903. val.second = CSeqNo::incseq(base, int(maxoff)-1);
  904. irrecover.push_back(val);
  905. }
  906. g.dismissed = true;
  907. }
  908. #if ENABLE_HEAVY_LOGGING
  909. static inline char CellMark(const std::deque<bool>& cells, int index)
  910. {
  911. if (index >= int(cells.size()))
  912. return '/';
  913. return cells[index] ? '#' : '.';
  914. }
  915. static void DebugPrintCells(int32_t base, const std::deque<bool>& cells, size_t row_size)
  916. {
  917. size_t i = 0;
  918. // Shift to the first empty cell
  919. for ( ; i < cells.size(); ++i)
  920. if (cells[i] == false)
  921. break;
  922. if (i == cells.size())
  923. {
  924. LOGC(pflog.Debug, log << "FEC: ... cell[0-" << (cells.size()-1) << "]: ALL CELLS EXIST");
  925. return;
  926. }
  927. // Ok, we have some empty cells, so just adjust to the start of a row.
  928. size_t bstep = i % row_size;
  929. if (i < bstep) // you never know...
  930. i = 0;
  931. else
  932. i -= bstep;
  933. for ( ; i < cells.size(); i += row_size )
  934. {
  935. std::ostringstream os;
  936. os << "cell[" << i << "-" << (i+row_size-1) << "] %" << CSeqNo::incseq(base, (int32_t)i) << ":";
  937. for (size_t y = 0; y < row_size; ++y)
  938. {
  939. os << " " << CellMark(cells, (int)(i+y));
  940. }
  941. LOGP(pflog.Debug, os.str());
  942. }
  943. }
  944. #else
  945. static void DebugPrintCells(int32_t /*base*/, const std::deque<bool>& /*cells*/, size_t /*row_size*/) {}
  946. #endif
  947. FECFilterBuiltin::EHangStatus FECFilterBuiltin::HangHorizontal(const CPacket& rpkt, bool isfec, loss_seqs_t& irrecover)
  948. {
  949. const int32_t seq = rpkt.getSeqNo();
  950. EHangStatus stat;
  951. const int rowx = RcvGetRowGroupIndex(seq, (stat));
  952. if (rowx == -1)
  953. return stat;
  954. RcvGroup& rowg = rcv.rowq[rowx];
  955. // Clip the packet into the horizontal group.
  956. // If this was a regular packet, increase the number of collected.
  957. // If this was a FEC/CTL packet, keep this number, just set the fec flag.
  958. if (isfec)
  959. {
  960. if (!rowg.fec)
  961. {
  962. ClipControlPacket(rowg, rpkt);
  963. rowg.fec = true;
  964. HLOGC(pflog.Debug, log << "FEC/H: FEC/CTL packet clipped, %" << seq << " base=%" << rowg.base);
  965. }
  966. else
  967. {
  968. HLOGC(pflog.Debug, log << "FEC/H: FEC/CTL at %" << seq << " DUPLICATED, skipping.");
  969. }
  970. }
  971. else
  972. {
  973. ClipPacket(rowg, rpkt);
  974. rowg.collected++;
  975. HLOGC(pflog.Debug, log << "FEC/H: DATA packet clipped, %" << seq
  976. << ", received " << rowg.collected << "/" << sizeRow()
  977. << " base=%" << rowg.base);
  978. }
  979. if (rowg.fec && rowg.collected == m_number_cols - 1)
  980. {
  981. HLOGC(pflog.Debug, log << "FEC/H: HAVE " << rowg.collected << " collected & FEC; REBUILDING...");
  982. // The group will provide the information for rebuilding.
  983. // The sequence of the lost packet can be checked in cells.
  984. // With the condition of 'collected == m_number_cols - 1', there
  985. // should be only one lacking packet, so just rely on first found.
  986. RcvRebuild(rowg, RcvGetLossSeqHoriz(rowg),
  987. m_number_rows == 1 ? Group::SINGLE : Group::HORIZ);
  988. #if ENABLE_HEAVY_LOGGING
  989. std::ostringstream os;
  990. for (size_t i = 0; i < rcv.rebuilt.size(); ++i)
  991. {
  992. os << " " << rcv.rebuilt[i].hdr[SRT_PH_SEQNO];
  993. }
  994. LOGC(pflog.Debug, log << "FEC: ... cached rebuilt packets (" << rcv.rebuilt.size() << "):" << os.str());
  995. #endif
  996. }
  997. // When there are only rows, dismiss the oldest row when you have
  998. // collected at least 1 packet in the next group. Do not dismiss
  999. // any groups here otherwise - all will be decided during column
  1000. // processing.
  1001. bool want_collect_irrecover = false;
  1002. bool want_remove_cells = false;
  1003. if (rcv.rowq.size() > 1)
  1004. {
  1005. if (m_number_rows == 1)
  1006. {
  1007. want_remove_cells = true;
  1008. want_collect_irrecover = true;
  1009. }
  1010. else if (m_fallback_level == SRT_ARQ_ONREQ)
  1011. {
  1012. want_collect_irrecover = true;
  1013. }
  1014. }
  1015. if (want_collect_irrecover) // AND rcv.rowq.size() > 1
  1016. {
  1017. int current = int(rcv.rowq.size()) - 2;
  1018. // We know we have at least 2 rows.
  1019. // This value is then 0 or more.
  1020. int past = current - 1;
  1021. // To trigger irrecoverable collection, the current sequence
  1022. // must be further than 1/3 of the row size to start from
  1023. // the previous row. Otherwise, start with the past-previous
  1024. // one, as long as it still exists.
  1025. bool early SRT_ATR_UNUSED = false;
  1026. if (past > 0)
  1027. {
  1028. // If you already have at least 3 rows, sweep starting from
  1029. // the before-previous one (this will become 0 when the number
  1030. // of rows is exactly 3).
  1031. --past;
  1032. }
  1033. else
  1034. {
  1035. // If you have 2 rows, then in the current row (1) there must
  1036. // be the sequence passing already the 1/3 of the size. Otherwise
  1037. // decrease past to make it -1 and not pass the next test.
  1038. if (CSeqNo::seqoff(rcv.rowq[1].base, seq) <= int(m_number_cols/3))
  1039. {
  1040. --past;
  1041. }
  1042. else
  1043. {
  1044. early = true;
  1045. }
  1046. }
  1047. if (past >= 0)
  1048. {
  1049. // Collect irrecoverable since the 'past' index up to 0.
  1050. // If want_remove_cells, also remove these rows and corresponding cells.
  1051. int nrowremove = 1 + past;
  1052. HLOGC(pflog.Debug, log << "Collecting irrecoverable packets from " << nrowremove << " ROWS per offset "
  1053. << CSeqNo::seqoff(rcv.rowq[1].base, seq) << " vs. " << m_number_cols << "/3");
  1054. for (int i = 0; i <= past; ++i)
  1055. {
  1056. CollectIrrecoverRow(rcv.rowq[i], irrecover);
  1057. }
  1058. // Sanity check condition - rcv.rowq must be of size
  1059. // greater than the number of rows to remove so that
  1060. // the rcv.rowq[0] exists after the operation.
  1061. if (want_remove_cells && rcv.rowq.size() > size_t(nrowremove))
  1062. {
  1063. // nrowremove >= 1
  1064. size_t npktremove = sizeRow() * nrowremove;
  1065. size_t ersize = min(npktremove, rcv.cells.size()); // ersize <= rcv.cells.size()
  1066. HLOGC(pflog.Debug, log << "FEC/H: Dismissing rows n=" << nrowremove
  1067. << ", starting at %" << rcv.rowq[0].base
  1068. << " AND " << npktremove << " CELLS, base switch %"
  1069. << rcv.cell_base << " -> %" << rcv.rowq[past].base);
  1070. rcv.rowq.erase(rcv.rowq.begin(), rcv.rowq.begin() + nrowremove);
  1071. rcv.cells.erase(rcv.cells.begin(), rcv.cells.begin() + ersize);
  1072. // We state that we have removed as many cells as for the removed
  1073. // rows. In case when the number of cells proved to be less than that,
  1074. // it will simply remove all cells. So now set the cell base to be
  1075. // in sync with the row base.
  1076. rcv.cell_base = rcv.rowq[0].base;
  1077. DebugPrintCells(rcv.cell_base, rcv.cells, sizeRow());
  1078. }
  1079. }
  1080. else
  1081. {
  1082. HLOGC(pflog.Debug, log << "FEC: NOT collecting irrecover from rows: distance="
  1083. << CSeqNo::seqoff(rcv.rowq[0].base, seq));
  1084. }
  1085. }
  1086. return HANG_SUCCESS;
  1087. }
  1088. int32_t FECFilterBuiltin::RcvGetLossSeqHoriz(Group& g)
  1089. {
  1090. int baseoff = CSeqNo::seqoff(rcv.cell_base, g.base);
  1091. if (baseoff < 0)
  1092. {
  1093. LOGC(pflog.Error, log << "FEC: IPE: negative cell offset, cell_base=%" << rcv.cell_base << " Group's base: %" << g.base << " - NOT ATTEMPTING TO REBUILD");
  1094. return -1;
  1095. }
  1096. // This is a row, so start from the first cell for this group
  1097. // and search lineraly for the first loss.
  1098. int offset = -1;
  1099. for (size_t cix = baseoff; cix < baseoff + m_number_cols; ++cix)
  1100. {
  1101. if (!rcv.CellAt(cix))
  1102. {
  1103. offset = int(cix);
  1104. #if ENABLE_HEAVY_LOGGING
  1105. // For heavy logging case, show all cells in the range
  1106. LOGC(pflog.Debug, log << "FEC/H: cell %" << CSeqNo::incseq(rcv.cell_base, int(cix))
  1107. << " (+" << cix << "): MISSING");
  1108. #else
  1109. // Find just one. No more that just one shall be found
  1110. // because it was checked earlier that we have collected
  1111. // all but just one packet.
  1112. break;
  1113. #endif
  1114. }
  1115. #if ENABLE_HEAVY_LOGGING
  1116. else
  1117. {
  1118. LOGC(pflog.Debug, log << "FEC/H: cell %" << CSeqNo::incseq(rcv.cell_base, int(cix))
  1119. << " (+" << cix << "): exists");
  1120. }
  1121. #endif
  1122. }
  1123. if (offset == -1)
  1124. {
  1125. LOGC(pflog.Fatal, log << "FEC/H: IPE: rebuilding attempt, but no lost packet found");
  1126. return -1; // sanity, shouldn't happen
  1127. }
  1128. // Now that we have an offset towards the first packet in the cells,
  1129. // translate it to the sequence number of the lost packet.
  1130. return CSeqNo::incseq(rcv.cell_base, offset);
  1131. }
  1132. int32_t FECFilterBuiltin::RcvGetLossSeqVert(Group& g)
  1133. {
  1134. int baseoff = CSeqNo::seqoff(rcv.cell_base, g.base);
  1135. if (baseoff < 0)
  1136. {
  1137. LOGC(pflog.Error, log << "FEC: IPE: negative cell offset, cell_base=%" << rcv.cell_base << " Group's base: %" << g.base << " - NOT ATTEMPTING TO REBUILD");
  1138. return -1;
  1139. }
  1140. // This is a row, so start from the first cell for this group
  1141. // and search lineraly for the first loss.
  1142. int offset = -1;
  1143. for (size_t col = 0; col < sizeCol(); ++col)
  1144. {
  1145. size_t cix = baseoff + (col * sizeRow());
  1146. if (!rcv.CellAt(cix))
  1147. {
  1148. offset = int(cix);
  1149. #if ENABLE_HEAVY_LOGGING
  1150. // For heavy logging case, show all cells in the range
  1151. LOGC(pflog.Debug, log << "FEC/V: cell %" << CSeqNo::incseq(rcv.cell_base, int(cix))
  1152. << " (+" << cix << "): MISSING");
  1153. #else
  1154. // Find just one. No more that just one shall be found
  1155. // because it was checked earlier that we have collected
  1156. // all but just one packet.
  1157. break;
  1158. #endif
  1159. }
  1160. #if ENABLE_HEAVY_LOGGING
  1161. else
  1162. {
  1163. LOGC(pflog.Debug, log << "FEC/V: cell %" << CSeqNo::incseq(rcv.cell_base, int(cix))
  1164. << " (+" << cix << "): exists");
  1165. }
  1166. #endif
  1167. }
  1168. if (offset == -1)
  1169. {
  1170. LOGC(pflog.Fatal, log << "FEC/V: IPE: rebuilding attempt, but no lost packet found");
  1171. return -1; // sanity, shouldn't happen
  1172. }
  1173. // Now that we have an offset towards the first packet in the cells,
  1174. // translate it to the sequence number of the lost packet.
  1175. return CSeqNo::incseq(rcv.cell_base, offset);
  1176. }
  1177. void FECFilterBuiltin::RcvRebuild(Group& g, int32_t seqno, Group::Type tp)
  1178. {
  1179. if (seqno == -1)
  1180. return;
  1181. uint16_t length_hw = ntohs(g.length_clip);
  1182. if (length_hw > payloadSize())
  1183. {
  1184. LOGC(pflog.Warn, log << "FEC: DECLIPPED length '" << length_hw << "' exceeds payload size. NOT REBUILDING.");
  1185. return;
  1186. }
  1187. // Rebuild the packet
  1188. // (length_hw is automatically converted through PrivPacket constructor)
  1189. rcv.rebuilt.push_back( length_hw );
  1190. Receive::PrivPacket& p = rcv.rebuilt.back();
  1191. p.hdr[SRT_PH_SEQNO] = seqno;
  1192. // This is for live mode only, for now, so the message
  1193. // number will be always 1, PB_SOLO, INORDER, and flags from clip.
  1194. // The REXMIT flag is set to 1 to fake that the packet was
  1195. // retransmitted. It is necessary because this packet will
  1196. // come out of sequence order, and if such a packet has
  1197. // no rexmit flag set, it's treated as reordered by network,
  1198. // which isn't true here.
  1199. p.hdr[SRT_PH_MSGNO] = 1
  1200. | MSGNO_PACKET_BOUNDARY::wrap(PB_SOLO)
  1201. | MSGNO_PACKET_INORDER::wrap(rcv.order_required)
  1202. | MSGNO_ENCKEYSPEC::wrap(g.flag_clip)
  1203. | MSGNO_REXMIT::wrap(true)
  1204. ;
  1205. p.hdr[SRT_PH_TIMESTAMP] = g.timestamp_clip;
  1206. p.hdr[SRT_PH_ID] = rcv.id;
  1207. // Header ready, now we rebuild the contents
  1208. // First, rebuild the length.
  1209. // Allocate the buffer and assign to a packet.
  1210. // This is only temporary, it will be copied to
  1211. // the target place when needed, with the buffer coming
  1212. // from the unit queue.
  1213. // The payload clip may be longer than length_hw, but it
  1214. // contains only trailing zeros for completion, which are skipped.
  1215. copy(g.payload_clip.begin(), g.payload_clip.end(), p.buffer);
  1216. HLOGC(pflog.Debug, log << "FEC: REBUILT: %" << seqno
  1217. << " msgno=" << MSGNO_SEQ::unwrap(p.hdr[SRT_PH_MSGNO])
  1218. << " flags=" << PacketMessageFlagStr(p.hdr[SRT_PH_MSGNO])
  1219. << " TS=" << p.hdr[SRT_PH_TIMESTAMP] << " ID=" << dec << p.hdr[SRT_PH_ID]
  1220. << " size=" << length_hw
  1221. << " !" << BufferStamp(p.buffer, p.length));
  1222. // Mark this packet received
  1223. MarkCellReceived(seqno);
  1224. // If this is a single request (filled from row and m_number_cols == 1),
  1225. // do not attempt recursive rebuilding
  1226. if (tp == Group::SINGLE)
  1227. return;
  1228. Group::Type crosstype = Group::FlipType(tp);
  1229. EHangStatus stat;
  1230. if (crosstype == Group::HORIZ)
  1231. {
  1232. // Find this packet in the horizontal group
  1233. const int rowx = RcvGetRowGroupIndex(seqno, (stat));
  1234. if (rowx == -1)
  1235. return; // can't access any group to rebuild
  1236. RcvGroup& rowg = rcv.rowq[rowx];
  1237. // Sanity check. It's impossible that the packet was already
  1238. // rebuilt and any attempt to rebuild a lacking packet was made.
  1239. if (rowg.collected > m_number_cols - 1)
  1240. {
  1241. return;
  1242. }
  1243. // Same as ClipPacket for the incoming packet, just this
  1244. // is extracting the data directly from the rebuilt one.
  1245. ClipRebuiltPacket(rowg, p);
  1246. rowg.collected++;
  1247. HLOGC(pflog.Debug, log << "FEC/H: REBUILT packet clipped, %" << seqno
  1248. << ", received " << rowg.collected << "/" << m_number_cols
  1249. << " FOR base=%" << rowg.base);
  1250. // Similar as by HangHorizontal, just don't collect irrecoverable packets.
  1251. // They are already known when the packets were collected.
  1252. if (rowg.fec && rowg.collected == m_number_cols - 1)
  1253. {
  1254. HLOGC(pflog.Debug, log << "FEC/H: with FEC-rebuilt HAVE " << rowg.collected << " collected & FEC; REBUILDING");
  1255. // The group will provide the information for rebuilding.
  1256. // The sequence of the lost packet can be checked in cells.
  1257. // With the condition of 'collected == m_number_cols - 1', there
  1258. // should be only one lacking packet, so just rely on first found.
  1259. // NOTE: RECURSIVE CALL.
  1260. RcvRebuild(rowg, RcvGetLossSeqHoriz(rowg), crosstype);
  1261. }
  1262. }
  1263. else // crosstype == Group::VERT
  1264. {
  1265. // Find this packet in the vertical group
  1266. const int colx = RcvGetColumnGroupIndex(seqno, (stat));
  1267. if (colx == -1)
  1268. return; // can't access any group to rebuild
  1269. RcvGroup& colg = rcv.colq[colx];
  1270. // Sanity check. It's impossible that the packet was already
  1271. // rebuilt and any attempt to rebuild a lacking packet was made.
  1272. if (colg.collected > m_number_rows - 1)
  1273. {
  1274. return;
  1275. }
  1276. // Same as ClipPacket for the incoming packet, just this
  1277. // is extracting the data directly from the rebuilt one.
  1278. ClipRebuiltPacket(colg, p);
  1279. colg.collected++;
  1280. HLOGC(pflog.Debug, log << "FEC/V: REBUILT packet clipped, %" << seqno
  1281. << ", received " << colg.collected << "/" << m_number_rows
  1282. << " FOR base=%" << colg.base);
  1283. // Similar as by HangVertical, just don't collect irrecoverable packets.
  1284. // They are already known when the packets were collected.
  1285. if (colg.fec && colg.collected == m_number_rows - 1)
  1286. {
  1287. HLOGC(pflog.Debug, log << "FEC/V: with FEC-rebuilt HAVE " << colg.collected << " collected & FEC; REBUILDING");
  1288. // The group will provide the information for rebuilding.
  1289. // The sequence of the lost packet can be checked in cells.
  1290. // With the condition of 'collected == m_number_rows - 1', there
  1291. // should be only one lacking packet, so just rely on first found.
  1292. // NOTE: RECURSIVE CALL.
  1293. RcvRebuild(colg, RcvGetLossSeqVert(colg), crosstype);
  1294. }
  1295. }
  1296. }
  1297. size_t FECFilterBuiltin::ExtendRows(size_t rowx)
  1298. {
  1299. // Check if oversize. Oversize is when the
  1300. // index is > 2*m_number_cols. If so, shrink
  1301. // the container first.
  1302. #if ENABLE_HEAVY_LOGGING
  1303. LOGC(pflog.Debug, log << "FEC: ROW STATS BEFORE: n=" << rcv.rowq.size());
  1304. for (size_t i = 0; i < rcv.rowq.size(); ++i)
  1305. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.rowq[i].DisplayStats());
  1306. #endif
  1307. const size_t size_in_packets = rowx * numberCols();
  1308. const int n_series = int(rowx / numberRows());
  1309. if (CheckEmergencyShrink(n_series, size_in_packets))
  1310. {
  1311. HLOGC(pflog.Debug, log << "FEC: DONE Emergency resize, rowx=" << rowx << " series=" << n_series
  1312. << "npackets=" << size_in_packets << " exceeds buf=" << rcvBufferSize());
  1313. }
  1314. // Create and configure next groups.
  1315. size_t old = rcv.rowq.size();
  1316. // First, add the number of groups.
  1317. rcv.rowq.resize(rowx + 1);
  1318. // Starting from old size
  1319. for (size_t i = old; i < rcv.rowq.size(); ++i)
  1320. {
  1321. // Initialize the base for the row group
  1322. int32_t ibase = CSeqNo::incseq(rcv.rowq[0].base, int(i*m_number_cols));
  1323. ConfigureGroup(rcv.rowq[i], ibase, 1, m_number_cols);
  1324. }
  1325. #if ENABLE_HEAVY_LOGGING
  1326. LOGC(pflog.Debug, log << "FEC: ROW STATS AFTER: n=" << rcv.rowq.size());
  1327. for (size_t i = 0; i < rcv.rowq.size(); ++i)
  1328. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.rowq[i].DisplayStats());
  1329. #endif
  1330. return rowx;
  1331. }
  1332. int FECFilterBuiltin::RcvGetRowGroupIndex(int32_t seq, EHangStatus& w_status)
  1333. {
  1334. RcvGroup& head = rcv.rowq[0];
  1335. const int32_t base = head.base;
  1336. const int offset = CSeqNo::seqoff(base, seq);
  1337. // Discard the packet, if older than base.
  1338. if (offset < 0)
  1339. {
  1340. HLOGC(pflog.Debug, log << "FEC/H: Packet %" << seq << " is in the past, ignoring");
  1341. w_status = HANG_PAST;
  1342. return -1;
  1343. }
  1344. // Hang in the receiver group first.
  1345. size_t rowx = offset / m_number_cols;
  1346. /*
  1347. Don't.
  1348. Leaving this code for future if needed, but this check should not be done.
  1349. The resource management for "crazy" sequence numbers is done in the beginning,
  1350. so simply TRUST THIS SEQUENCE, no matter what. After the check it won't do any harm.
  1351. if (rowx > numberRows()*2) // past twice the matrix
  1352. {
  1353. LOGC(pflog.Error, log << "FEC/H: Packet %" << seq << " is in the far future, ignoring");
  1354. return -1;
  1355. }
  1356. */
  1357. // The packet might have come completely out of the blue.
  1358. // The row group container must be prepared to extend
  1359. // itself in order to give place for the packet.
  1360. // First, possibly extend the row container
  1361. if (rowx >= rcv.rowq.size())
  1362. {
  1363. // Never returns -1
  1364. rowx = ExtendRows(rowx);
  1365. }
  1366. w_status = HANG_SUCCESS;
  1367. return int(rowx);
  1368. }
  1369. void FECFilterBuiltin::MarkCellReceived(int32_t seq, ECellReceived is_received)
  1370. {
  1371. // Mark the packet as received. This will allow later to
  1372. // determine, which exactly packet is lost and needs rebuilding.
  1373. const int cellsize = int(rcv.cells.size());
  1374. const int cell_offset = CSeqNo::seqoff(rcv.cell_base, seq);
  1375. bool resized SRT_ATR_UNUSED = false;
  1376. if (cell_offset >= cellsize)
  1377. {
  1378. // Expand the cell container with zeros, excluding the 'cell_offset'.
  1379. // Resize normally up to the required size, just set the lastmost
  1380. // item to true.
  1381. resized = true;
  1382. rcv.cells.resize(cell_offset+1, false);
  1383. }
  1384. if (resized || is_received != CELL_EXTEND)
  1385. {
  1386. // In both RECEIVED and REMOVE cases, forcefully set the value always.
  1387. // In EXTEND, only if it was received
  1388. // Value set should be true only if RECEIVED, false otherwise
  1389. rcv.cells[cell_offset] = (is_received == CELL_RECEIVED);
  1390. }
  1391. #if ENABLE_HEAVY_LOGGING
  1392. static string const cellop [] = { "RECEIVED", "EXTEND", "REMOVE" };
  1393. LOGC(pflog.Debug, log << "FEC: MARK CELL " << cellop[is_received]
  1394. << "(" << (rcv.cells[cell_offset] ? "SET" : "CLR") << ")"
  1395. << ": %" << seq << " - cells base=%"
  1396. << rcv.cell_base << "[" << cell_offset << "]+" << rcv.cells.size()
  1397. << (resized ? "(resized)":"") << " :");
  1398. #endif
  1399. DebugPrintCells(rcv.cell_base, rcv.cells, sizeRow());
  1400. }
  1401. bool FECFilterBuiltin::IsLost(int32_t seq) const
  1402. {
  1403. const int offset = CSeqNo::seqoff(rcv.cell_base, seq);
  1404. if (offset < 0)
  1405. {
  1406. LOGC(pflog.Error, log << "FEC: IsLost: IPE: %" << seq
  1407. << " is earlier than the cell base %" << rcv.cell_base);
  1408. return true; // This might be due to emergency shrinking; pretend the packet is lost
  1409. }
  1410. if (offset >= int(rcv.cells.size()))
  1411. {
  1412. // XXX IPE!
  1413. LOGC(pflog.Error, log << "FEC: IsLost: IPE: %" << seq << " is past the cells %"
  1414. << rcv.cell_base << " + " << rcv.cells.size());
  1415. return false; // Don't notify it yet
  1416. }
  1417. return rcv.cells[offset];
  1418. }
  1419. bool FECFilterBuiltin::CheckEmergencyShrink(size_t n_series, size_t size_in_packets)
  1420. {
  1421. // The minimum required size of the covered sequence range must be such
  1422. // that groups for packets from the previous range must be still reachable.
  1423. // It's then "this and previous" series in case of even arrangement.
  1424. //
  1425. // For staircase arrangement the potential range for a single column series
  1426. // (number of columns equal to a row size) spans for 2 matrices (rows * cols)
  1427. // minus one row. As dismissal is only allowed to be done by one full series
  1428. // of rows and columns, the history must keep as many groups as needed to reach
  1429. // out for this very packet of this group and all packets in the same row.
  1430. // Hence we need two series of columns to cover a similar range as two row, twice.
  1431. const size_t min_series_history = m_arrangement_staircase ? 4 : 2;
  1432. if (n_series <= min_series_history)
  1433. return false;
  1434. if (size_in_packets < rcvBufferSize() && n_series < SRT_FEC_MAX_RCV_HISTORY)
  1435. return false;
  1436. // Shrink is required in order to prepare place for
  1437. // either vertical or horizontal group in series `n_series`.
  1438. // The n_series can be calculated as:
  1439. // n_series = colgx / numberCols()
  1440. // n_series = rowgx / numberRows()
  1441. //
  1442. // The (Column or Row) Group Index value is calculated as
  1443. // the number of column where the desired sequence number
  1444. // should be located towards the very first container item
  1445. // (row/column 0).
  1446. // The task for this function is to leave only one series
  1447. // of groups and therefore initialize the containers. Likely
  1448. // the part that contains the last series should be already
  1449. // there, so in this case just remove some initial items from
  1450. // the container so that only those remain that are intended
  1451. // to remain. However, by various reasons (like e.g. that all
  1452. // packets from the whole series have been lost) particular
  1453. // container (colq, rowq, cell) doesn't contain this last
  1454. // series at all. In that case clear the container completely
  1455. // and just add an initial configuration for the first part
  1456. // (which will be then dynamically extended as packets come in).
  1457. const int32_t oldbase = rcv.colq[0].base;
  1458. const size_t shift_series = n_series - 1;
  1459. // This is simply a situation when the size is so excessive
  1460. // that it couldn't be withstood by the receiver buffer, so
  1461. // even if this isn't an extremely big size for allocation for
  1462. // FEC, it doesn't make sense anyway.
  1463. //
  1464. // Minimum of 2 series must remain in the group container,
  1465. // otherwise there's no need to guard the size.
  1466. // This requires simply resetting all group containers to
  1467. // the very initial state, just take the calculated base seq
  1468. // from the value of colgx reset to column 0.
  1469. // As colgx is calculated by stating that colgx == 0 represents
  1470. // the very first cell in the column groups, take this, shift
  1471. // by the number of series.
  1472. // SHIFT BY: n_series * matrix size
  1473. // n_series is at least 2 (see condition)
  1474. const size_t shift = shift_series * numberCols() * numberRows();
  1475. // Always positive: colgx, and so n_series, and so shift
  1476. const int32_t newbase = CSeqNo::incseq(oldbase, int(shift));
  1477. const size_t shift_rows = shift_series * numberRows();
  1478. bool need_reset = rcv.rowq.size() < shift_rows;
  1479. if (!need_reset)
  1480. {
  1481. // Sanity check - you should have the exact value
  1482. // of `newbase` at the next series beginning position
  1483. if (rcv.rowq[numberRows()].base != newbase)
  1484. {
  1485. LOGC(pflog.Error, log << "FEC: IPE: row start at %" << rcv.rowq[0].base << " next series %" << rcv.rowq[numberRows()].base
  1486. << " (expected %" << newbase << "). RESETTING ROWS.");
  1487. need_reset = true;
  1488. }
  1489. }
  1490. if (need_reset)
  1491. {
  1492. rcv.rowq.clear();
  1493. // This n_series is the number rounded downwards,
  1494. // So you just need to prepare place for ONE series.
  1495. // The procedure below will extend them to the required
  1496. // size for the received colgx.
  1497. rcv.rowq.resize(1);
  1498. HLOGC(pflog.Debug, log << "FEC: Reset recv row %" << oldbase << " -> %" << newbase << ", INIT ROWS:");
  1499. ConfigureGroup(rcv.rowq[0], newbase, 1, sizeRow());
  1500. }
  1501. else
  1502. {
  1503. HLOGC(pflog.Debug, log << "FEC: Shifting rcv row %" << oldbase << " -> %" << newbase);
  1504. rcv.rowq.erase(rcv.rowq.begin(), rcv.rowq.begin() + shift_rows);
  1505. }
  1506. const size_t shift_cols = shift_series * numberCols();
  1507. need_reset = rcv.colq.size() < shift_cols;
  1508. if (!need_reset)
  1509. {
  1510. // Sanity check - you should have the exact value
  1511. // of `newbase` at the next series beginning position
  1512. if (rcv.colq[numberCols()].base != newbase)
  1513. {
  1514. LOGC(pflog.Error, log << "FEC: IPE: col start at %" << rcv.colq[0].base << " next series %" << rcv.colq[numberCols()].base
  1515. << " (expected %" << newbase << "). RESETTING ROWS.");
  1516. need_reset = true;
  1517. }
  1518. }
  1519. if (need_reset)
  1520. {
  1521. rcv.colq.clear();
  1522. HLOGC(pflog.Debug, log << "FEC: Reset recv row %" << oldbase << " -> %" << newbase << ", INIT first " << numberCols() << ":");
  1523. ConfigureColumns(rcv.colq, newbase);
  1524. }
  1525. if (rcv.cells.size() > shift)
  1526. {
  1527. rcv.cells.erase(rcv.cells.begin(), rcv.cells.begin() + shift);
  1528. }
  1529. else
  1530. {
  1531. rcv.cells.clear();
  1532. rcv.cells.push_back(false);
  1533. }
  1534. rcv.cell_base = newbase;
  1535. return true;
  1536. }
  1537. FECFilterBuiltin::EHangStatus FECFilterBuiltin::HangVertical(const CPacket& rpkt, signed char fec_col, loss_seqs_t& irrecover)
  1538. {
  1539. bool fec_ctl = (fec_col != -1);
  1540. // Now hang the packet in the vertical group
  1541. const int32_t seq = rpkt.getSeqNo();
  1542. // Ok, now we have the column index, we know it exists.
  1543. // Apply the packet.
  1544. EHangStatus stat;
  1545. const int colgx = RcvGetColumnGroupIndex(seq, (stat));
  1546. if (colgx == -1)
  1547. return stat;
  1548. RcvGroup& colg = rcv.colq[colgx];
  1549. if (fec_ctl)
  1550. {
  1551. if (!colg.fec)
  1552. {
  1553. ClipControlPacket(colg, rpkt);
  1554. colg.fec = true;
  1555. HLOGC(pflog.Debug, log << "FEC/V: FEC/CTL packet clipped, %" << seq << " FOR COLUMN " << int(fec_col)
  1556. << " base=%" << colg.base);
  1557. }
  1558. else
  1559. {
  1560. HLOGC(pflog.Debug, log << "FEC/V: FEC/CTL at %" << seq << " COLUMN " << int(fec_col) << " DUPLICATED, skipping.");
  1561. }
  1562. }
  1563. else
  1564. {
  1565. // Data packet, clip it as data
  1566. ClipPacket(colg, rpkt);
  1567. colg.collected++;
  1568. HLOGC(pflog.Debug, log << "FEC/V: DATA packet clipped, %" << seq
  1569. << ", received " << colg.collected << "/" << sizeCol()
  1570. << " base=%" << colg.base);
  1571. }
  1572. if (colg.fec && colg.collected == m_number_rows - 1)
  1573. {
  1574. HLOGC(pflog.Debug, log << "FEC/V: HAVE " << colg.collected << " collected & FEC; REBUILDING");
  1575. RcvRebuild(colg, RcvGetLossSeqVert(colg), Group::VERT);
  1576. }
  1577. // Column dismissal takes place under very strictly specified condition,
  1578. // so simply call it in general here. At least it may happen potentially
  1579. // at any time of when a packet has been received.
  1580. RcvCheckDismissColumn(rpkt.getSeqNo(), colgx, irrecover);
  1581. #if ENABLE_HEAVY_LOGGING
  1582. LOGC(pflog.Debug, log << "FEC: COL STATS ATM: n=" << rcv.colq.size());
  1583. for (size_t i = 0; i < rcv.colq.size(); ++i)
  1584. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.colq[i].DisplayStats());
  1585. #endif
  1586. return HANG_SUCCESS;
  1587. }
  1588. void FECFilterBuiltin::RcvCheckDismissColumn(int32_t seq, int colgx, loss_seqs_t& irrecover)
  1589. {
  1590. // The first check we need to do is:
  1591. //
  1592. // - get the column number
  1593. // - get the series for this column
  1594. // - if series is 0, just return
  1595. const size_t series = colgx / numberCols();
  1596. if (series == 0)
  1597. return;
  1598. // - STARTING from the same column series 0:
  1599. // - unless DISMISSED, collect all irrecoverable packets from this group
  1600. // - mark this column DISMISSED
  1601. // - SAME CHECK for previous group, until index 0
  1602. set<int32_t> loss;
  1603. size_t colx SRT_ATR_UNUSED = colgx % numberCols();
  1604. HLOGC(pflog.Debug, log << "FEC/V: going to DISMISS cols past %" << seq
  1605. << " at INDEX=" << colgx << " col=" << colx
  1606. << " series=" << series << " - looking up candidates...");
  1607. // Walk through all column groups in series 0. Collect irrecov's
  1608. // from every group, for which the incoming 'seq' is in future.
  1609. for (size_t i = 0; i < numberCols(); ++i)
  1610. {
  1611. RcvGroup& pg = rcv.colq[i];
  1612. if (pg.dismissed)
  1613. {
  1614. HLOGC(pflog.Debug, log << "FEC/V: ... [" << i << "] base=%"
  1615. << pg.base << " ALREADY DISMISSED, skipping.");
  1616. continue;
  1617. }
  1618. // With multi-staircase it may happen that THIS column contains
  1619. // sequences that are all in the past, but the PREVIOUS column
  1620. // has some in the future, because THIS column is the top of
  1621. // the second staircase, and PREVIOUS is the bottom stair of
  1622. // the first staircase. When this is confirmed, simply skip
  1623. // the columns that have the highest sequence in the future
  1624. // because they can't be dismissed yet. Jump them over, so maybe
  1625. // they can be dismissed in future.
  1626. int this_col_offset = CSeqNo::seqoff(pg.base, seq);
  1627. int last_seq_offset = this_col_offset - int((sizeCol()-1)*sizeRow());
  1628. if (last_seq_offset < 0)
  1629. {
  1630. HLOGC(pflog.Debug, log << "FEC/V: ... [" << i << "] base=%"
  1631. << pg.base << " TOO EARLY (last=%"
  1632. << CSeqNo::incseq(pg.base, (int32_t)((sizeCol()-1)*sizeRow()))
  1633. << ")");
  1634. continue;
  1635. }
  1636. // NOTE: If it was standing on the second staircase top, there's
  1637. // still a chance that it hits the staircase top of the first
  1638. // staircase and will dismiss it as well.
  1639. HLOGC(pflog.Debug, log << "FEC/V: ... [" << i << "] base=%"
  1640. << pg.base << " - PAST last=%"
  1641. << CSeqNo::incseq(pg.base, (int32_t)((sizeCol()-1)*sizeRow()))
  1642. << " - collecting losses.");
  1643. pg.dismissed = true; // mark irrecover already collected
  1644. for (size_t sof = 0; sof < pg.step * sizeCol(); sof += pg.step)
  1645. {
  1646. int32_t lseq = CSeqNo::incseq(pg.base, int(sof));
  1647. if (!IsLost(lseq))
  1648. {
  1649. loss.insert(lseq);
  1650. HLOGC(pflog.Debug, log << "FEC: ... cell +" << sof << " %" << lseq
  1651. << " lost");
  1652. }
  1653. else
  1654. {
  1655. HLOGC(pflog.Debug, log << "FEC: ... cell +" << sof << " %" << lseq
  1656. << " EXISTS");
  1657. }
  1658. }
  1659. }
  1660. // COLUMN DISMISAL:
  1661. // 1. We can only dismiss ONE SERIES OF COLUMNS - OR NOTHING.
  1662. // 2. The triggering 'seq' must be past ANY sequence embraced
  1663. // by any group in the first series of columns.
  1664. // Useful information:
  1665. //
  1666. // 1. It's not known from upside, which column contains a sequence
  1667. // number that reaches FURTHEST. The safe statement is then:
  1668. // - For even arrangement, it must be past BASE0 + matrix size
  1669. // - For staircase arrangement - BASE0 + matrix size * 2.
  1670. int32_t base0 = rcv.colq[0].base;
  1671. int this_off = CSeqNo::seqoff(base0, seq);
  1672. int mindist = int(
  1673. m_arrangement_staircase ?
  1674. (numberCols() * numberRows() * 2)
  1675. :
  1676. (numberCols() * numberRows()));
  1677. bool any_dismiss SRT_ATR_UNUSED = false;
  1678. // Here's a change.
  1679. // The number of existing column groups is supposed to always cover
  1680. // at least one full series, whereas the number of row groups are
  1681. // created always one per necessity, so the number of existing row
  1682. // groups may be less than required for a full series, whereas here
  1683. // it is intended to simply dismiss groups for full series. This may
  1684. // cause that it is aiming for removing more row groups than currently
  1685. // exist. This is completely ok, as the sequence that triggered removal
  1686. // is long past these series anyway, so the groups for packets that will
  1687. // never be received makes no sense. Simply accept this state and delete
  1688. // all row groups and reinitialize them into the new base, where the base
  1689. // is the current base for column 0 group.
  1690. //
  1691. // Therefore dismissal is triggered whenever you have a cover of one column
  1692. // series. If the number of row groups doesn't cover it, simply delete all
  1693. // row groups, that's all.
  1694. // if (base0 +% mindist) <% seq
  1695. if (this_off < mindist) // COND 1: minimum remaining
  1696. {
  1697. HLOGC(pflog.Debug, log << "FEC/V: NOT dismissing any columns at %" << seq
  1698. << ", need to pass %" << CSeqNo::incseq(base0, mindist));
  1699. }
  1700. else if (rcv.colq.size() - 1 < numberCols()) // COND 2: full matrix in columns
  1701. {
  1702. #if ENABLE_HEAVY_LOGGING
  1703. LOGC(pflog.Debug, log << "FEC/V: IPE: about to dismiss past %" << seq
  1704. << " with required %" << CSeqNo::incseq(base0, mindist)
  1705. << " but col container size still " << rcv.colq.size() << "; COL STATS:");
  1706. for (size_t i = 0; i < rcv.colq.size(); ++i)
  1707. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.colq[i].DisplayStats());
  1708. #endif
  1709. }
  1710. else
  1711. {
  1712. // The condition for dismissal is now. The number of dismissed columns
  1713. // is numberCols(), regardless of the required 'mindinst'.
  1714. any_dismiss = true;
  1715. const int32_t newbase = rcv.colq[numberCols()].base;
  1716. int32_t newbase_row SRT_ATR_UNUSED; // For logging only, but including FATAL.
  1717. // Sanity check
  1718. // If sanity check failed OR if the number of existing row
  1719. // groups doesn't enclose those that need to be dismissed,
  1720. // clear row groups completely - these packets are lost and
  1721. // irrecoverable anyway.
  1722. bool insane = false;
  1723. bool undercounted = false;
  1724. if (rcv.rowq.size() - 1 < numberRows()) // COND 3: full matrix in rows
  1725. {
  1726. // Do not reach to index=numberRows() because it doesn't exist.
  1727. // Take the value from the columns as a good deal - actually
  1728. // row base and col base shall be always in sync.
  1729. newbase_row = newbase;
  1730. undercounted = true;
  1731. }
  1732. else
  1733. {
  1734. newbase_row = rcv.rowq[numberRows()].base;
  1735. insane = newbase_row != newbase;
  1736. }
  1737. const size_t matrix_size = numberCols() * numberRows();
  1738. HLOGC(pflog.Debug, log << "FEC/V: DISMISSING " << numberCols() << " COLS. Base %"
  1739. << rcv.colq[0].base << " -> %" << newbase
  1740. << " AND " << numberRows() << " ROWS Base %"
  1741. << rcv.rowq[0].base << " -> %" << newbase_row
  1742. << " AND " << matrix_size << " cells");
  1743. // ensured existence of the removed range: see COND 2 above.
  1744. rcv.colq.erase(rcv.colq.begin(), rcv.colq.begin() + numberCols());
  1745. #if ENABLE_HEAVY_LOGGING
  1746. LOGC(pflog.Debug, log << "FEC: COL STATS BEFORE: n=" << rcv.colq.size());
  1747. for (size_t i = 0; i < rcv.colq.size(); ++i)
  1748. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.colq[i].DisplayStats());
  1749. #endif
  1750. // Now erase accordingly one matrix of rows.
  1751. if (insane || undercounted)
  1752. {
  1753. if (insane)
  1754. {
  1755. LOGC(pflog.Fatal, log << "FEC/V: IPE: DISCREPANCY in new base0 col=%"
  1756. << newbase << " row=%" << newbase_row << " - DELETING ALL ROWS");
  1757. }
  1758. else
  1759. {
  1760. #if ENABLE_HEAVY_LOGGING
  1761. LOGC(pflog.Debug, log << "FEC/V: about to dismiss past %" << seq
  1762. << " with required %" << CSeqNo::incseq(base0, mindist)
  1763. << " but row container size still " << rcv.rowq.size() << " (will clear to %" << newbase << " instead); ROW STATS:");
  1764. for (size_t i = 0; i < rcv.rowq.size(); ++i)
  1765. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.rowq[i].DisplayStats());
  1766. #endif
  1767. }
  1768. // Delete all rows and reinitialize them.
  1769. rcv.rowq.clear();
  1770. rcv.rowq.resize(1);
  1771. ConfigureGroup(rcv.rowq[0], newbase, 1, sizeRow());
  1772. }
  1773. else
  1774. {
  1775. // Remove "legally" a matrix of rows.
  1776. // ensured existence of the removed range: see COND 3 above
  1777. rcv.rowq.erase(rcv.rowq.begin(), rcv.rowq.begin() + numberRows());
  1778. }
  1779. // And now accordingly remove cells. Exactly one matrix of cells.
  1780. // Sanity check first.
  1781. int32_t newbase_cell = CSeqNo::incseq(rcv.cell_base, int32_t(matrix_size));
  1782. if (newbase != newbase_cell)
  1783. {
  1784. LOGC(pflog.Fatal, log << "FEC/V: IPE: DISCREPANCY in new base0 col=%"
  1785. << newbase << " cell_base=%" << newbase_cell << " - DELETING ALL CELLS");
  1786. // Try to shift it gently first. Find the cell that matches the base.
  1787. int shift = CSeqNo::seqoff(rcv.cell_base, newbase);
  1788. if (shift < 0 || size_t(shift) > rcv.cells.size())
  1789. rcv.cells.clear();
  1790. else
  1791. rcv.cells.erase(rcv.cells.begin(), rcv.cells.begin() + shift);
  1792. }
  1793. else
  1794. {
  1795. if (rcv.cells.size() <= size_t(matrix_size))
  1796. rcv.cells.clear();
  1797. else
  1798. rcv.cells.erase(rcv.cells.begin(), rcv.cells.begin() + matrix_size);
  1799. }
  1800. rcv.cell_base = newbase;
  1801. DebugPrintCells(rcv.cell_base, rcv.cells, sizeRow());
  1802. }
  1803. /*
  1804. OLD UNUSED CODE, leaving for historical reasons
  1805. // - check the last sequence of last column in series 0
  1806. // - if passed sequence number is earlier than this, just return
  1807. // - now that seq is newer than the last in the last column,
  1808. // - dismiss whole series 0 column groups
  1809. // First, index of the last column
  1810. size_t lastx = numberCols()-1;
  1811. if (lastx < rcv.colq.size())
  1812. {
  1813. int32_t lastbase = rcv.colq[lastx].base;
  1814. // Compare the base sequence with the sequence that caused the update
  1815. int dist = CSeqNo::seqoff(lastbase, seq);
  1816. // Shift this distance by the distance between the first and last
  1817. // sequence managed by a singled column. This counts (sizeCol()-1)*step.
  1818. dist -= (sizeCol()-1) * rcv.colq[lastx].step;
  1819. // Now, if this value is in the past (negative), it means that the
  1820. // 'seq' number is covered by this group or any earlier group. If so,
  1821. // do nothing. If this value is positive, it means that this
  1822. // sequence is in future towards the group that is in the last
  1823. // column of series 0. If so, whole series 0 may be now dismissed.
  1824. // NOTE: we don't care if lost packets have been collected for
  1825. // the groups being dismissed. They *SHOULD* be, just as a fallback
  1826. // SRT - if needed - will simply send LOSSREPORT request for all
  1827. // packets that are lossreported and all older ones.
  1828. if (dist > 0 && rcv.colq.size() > numberCols() )
  1829. {
  1830. any_dismiss = true;
  1831. int32_t newbase = rcv.colq[numberCols()].base;
  1832. rcv.colq.erase(rcv.colq.begin(), rcv.colq.begin() + numberCols());
  1833. // colgx is INVALIDATED after removal
  1834. int newcolgx SRT_ATR_UNUSED = colgx - numberCols();
  1835. // After a column series was dismissed, now dismiss also
  1836. // the same number of rows.
  1837. // Do some sanity checks first.
  1838. size_t nrowrem = 0;
  1839. int32_t oldrowbase = rcv.rowq[0].base; // before it gets deleted
  1840. if (rcv.rowq.size() > numberRows())
  1841. {
  1842. int32_t newrowbase = rcv.rowq[numberRows()].base;
  1843. if (newbase != newrowbase)
  1844. {
  1845. LOGC(pflog.Error, log << "FEC: IPE: ROW/COL base DISCREPANCY: Looking up lineraly for the right row.");
  1846. // Fallback implementation in order not to break everything
  1847. for (size_t r = 0; r < rcv.rowq.size(); ++r)
  1848. {
  1849. if (CSeqNo::seqoff(newbase, rcv.rowq[r].base) >= 0)
  1850. {
  1851. rcv.rowq.erase(rcv.rowq.begin(), rcv.rowq.begin() + r);
  1852. nrowrem = r;
  1853. break;
  1854. }
  1855. }
  1856. }
  1857. else
  1858. {
  1859. rcv.rowq.erase(rcv.rowq.begin(), rcv.rowq.begin() + numberRows());
  1860. nrowrem = numberRows();
  1861. }
  1862. }
  1863. // If rows were removed, so remove also cells
  1864. if (nrowrem > 0)
  1865. {
  1866. int32_t newbase = rcv.rowq[0].base;
  1867. // This value SHOULD be == nrowrem * sizeRow(), but this
  1868. // calculation is safe against bugs. Report them, if found, though.
  1869. int nrem = CSeqNo::seqoff(rcv.cell_base, newbase);
  1870. if (oldrowbase != rcv.cell_base)
  1871. {
  1872. LOGC(pflog.Error, log << "FEC: CELL/ROW base discrepancy, calculating and resynchronizing");
  1873. }
  1874. else
  1875. {
  1876. HLOGC(pflog.Debug, log << "FEC: will remove " << nrem << " cells, SHOULD BE = "
  1877. << (nrowrem * sizeRow()));
  1878. }
  1879. if (nrem > 0)
  1880. {
  1881. // Now collect losses from all rows about to be dismissed.
  1882. for (int sof = 0; sof < nrem; sof++)
  1883. {
  1884. int32_t lseq = CSeqNo::incseq(rcv.cell_base, sof);
  1885. if (!IsLost(lseq))
  1886. loss.insert(lseq);
  1887. }
  1888. HLOGC(pflog.Debug, log << "FEC: ERASING unused cells (" << nrem << "): %"
  1889. << rcv.cell_base << " - %" << newbase
  1890. << ", losses collected: " << Printable(loss));
  1891. rcv.cells.erase(rcv.cells.begin(), rcv.cells.begin() + nrem);
  1892. rcv.cell_base = newbase;
  1893. DebugPrintCells(rcv.cell_base, rcv.cells, sizeRow());
  1894. }
  1895. else
  1896. {
  1897. HLOGC(pflog.Debug, log << "FEC: NOT ERASING cells, base %" << rcv.cell_base
  1898. << " vs row base %" << rcv.rowq[0].base);
  1899. }
  1900. }
  1901. HLOGC(pflog.Debug, log << "FEC/V: updated g=" << colgx << " -> " << newcolgx << " %"
  1902. << rcv.colq[newcolgx].base << ", DISMISS up to g=" << numberCols()
  1903. << " base=%" << lastbase
  1904. << " ROW=%" << rcv.rowq[0].base << "+" << nrowrem);
  1905. }
  1906. }
  1907. // */
  1908. // Now all collected lost packets translate into the range list format
  1909. TranslateLossRecords(loss, irrecover);
  1910. HLOGC(pflog.Debug, log << "FEC: ... COLLECTED IRRECOVER: " << Printable(loss) << (any_dismiss ? " CELLS DISMISSED" : " nothing dismissed"));
  1911. }
  1912. void FECFilterBuiltin::TranslateLossRecords(const set<int32_t>& loss, loss_seqs_t& irrecover)
  1913. {
  1914. if (loss.empty())
  1915. return;
  1916. // size() >= 1 granted
  1917. set<int32_t>::iterator i = loss.begin();
  1918. int32_t fi_start = *i;
  1919. int32_t fi_end = fi_start;
  1920. ++i;
  1921. for (; i != loss.end(); ++i)
  1922. {
  1923. int dist = CSeqNo::seqoff(fi_end, *i);
  1924. if (dist == 1)
  1925. ++fi_end;
  1926. else
  1927. {
  1928. // Jumped over some sequences, cut the range.
  1929. irrecover.push_back(make_pair(fi_start, fi_end));
  1930. fi_start = fi_end = *i;
  1931. }
  1932. }
  1933. // And ship the last one
  1934. irrecover.push_back(make_pair(fi_start, fi_end));
  1935. }
  1936. int FECFilterBuiltin::RcvGetColumnGroupIndex(int32_t seqno, EHangStatus& w_status)
  1937. {
  1938. // The column is only the column, not yet
  1939. // exactly the index of the column group in the container.
  1940. // It's like:
  1941. // 0 1 2 3 4
  1942. // [A] ' ' ' '
  1943. // [A] [A] ' ' '
  1944. // [A] [A] [A] ' '
  1945. // [A] [A] [A] [A] '++
  1946. // [A]+[A] [A] [A] [A]+
  1947. // [B] [A]+[A] [A] [A]+
  1948. // [B] [B] [A]+[A] [A]+
  1949. // [B] [B] [B] [A]+[A]+
  1950. // [B] [B] [B] [B] [A]++
  1951. // [B]+[B] [B] [B] [B]
  1952. // [B] [B] [B] [B]
  1953. // [B] [B] [B]
  1954. // [B] [B]
  1955. // [B]
  1956. //
  1957. // The same groups laid out in the container:
  1958. //
  1959. // [A]0 [A]1 [A]2 [A]3 [A]4 [B]0 [B]1 [B]2 [B]3 [B]4
  1960. // This means, vert_gx returns the number for the
  1961. // logical column, but we only know this column,
  1962. // not the exact group that is assigned to this
  1963. // packet. That is, in the above picture, if the
  1964. // vert_gx resulted in 3, we still don't know if
  1965. // this is A3 or B3.
  1966. //
  1967. // To know it, we need to first take the base
  1968. // sequence number for the very first column group
  1969. // in the container. Every next group in this
  1970. // container is shifted by the 'slip' factor,
  1971. // which in this case is m_number_cols + 1. The base
  1972. // sequence shifted by m_number_cols*m_number_rows
  1973. // becomes the sequence number of the next
  1974. // group in the same column.
  1975. //
  1976. // If a single column is dismissed, then the
  1977. // column 1 will become column 0, but the column
  1978. // 1 in the next series will also become column 0.
  1979. // All due to that the very base sequence for
  1980. // all groups will be the one in the first series
  1981. // column 1, now 0.
  1982. //
  1983. // Therefore, once we have the column, let's extract
  1984. // the column base sequence.
  1985. // As we can't count on that packets will surely come to close a group
  1986. // or just a particular sequence number will be received, we simply have
  1987. // to check all past groups at the moment when this packet is received:
  1988. //
  1989. // 1. Take the sequence number and determine both the GROUP INDEX and the
  1990. // COLUMN INDEX of this group.
  1991. //
  1992. // Important thing here is that the column group base is the base sequence
  1993. // number of the very first group, which NEED NOT GO HAND IN HAND with the
  1994. // row group sequence base. The rules are then:
  1995. //
  1996. // OFFSET = DISTANCE( colq[0].base TO seq )
  1997. //
  1998. // COLUMN_INDEX = OFFSET % m_number_cols
  1999. //
  2000. // COLUMN_BASE = colq[COLUMN_INDEX].base
  2001. //
  2002. // COLUMN_OFFSET = DISTANCE(COLUMN_BASE TO seq)
  2003. //
  2004. // COLUMN_SERIES = COLUMN_OFFSET / (m_number_cols * m_number_rows)
  2005. //
  2006. // GROUP_INDEX = COLUMN_INDEX + (COLUMN_SERIES * m_number_cols)
  2007. const int offset = CSeqNo::seqoff(rcv.colq[0].base, seqno);
  2008. if (offset < 0)
  2009. {
  2010. HLOGC(pflog.Debug, log << "FEC/V: %" << seqno << " in the past of col ABSOLUTE base %" << rcv.colq[0].base);
  2011. w_status = HANG_PAST;
  2012. return -1;
  2013. }
  2014. if (offset > CSeqNo::m_iSeqNoTH/2)
  2015. {
  2016. LOGC(pflog.Error, log << "FEC/V: IPE/ATTACK: pkt %" << seqno << " has CRAZY OFFSET towards the base %" << rcv.colq[0].base);
  2017. w_status = HANG_CRAZY;
  2018. return -1;
  2019. }
  2020. const int colx = offset % m_number_cols;
  2021. const int32_t colbase = rcv.colq[colx].base;
  2022. const int coloff = CSeqNo::seqoff(colbase, seqno);
  2023. if (coloff < 0)
  2024. {
  2025. HLOGC(pflog.Debug, log << "FEC/V: %" << seqno << " in the past of col #" << colx << " base %" << colbase);
  2026. // This means that this sequence number predates the earliest
  2027. // sequence number supported by the very first column.
  2028. w_status = HANG_PAST;
  2029. return -1;
  2030. }
  2031. const int colseries = coloff / int(m_number_cols * m_number_rows);
  2032. size_t colgx = colx + int(colseries * m_number_cols);
  2033. HLOGC(pflog.Debug, log << "FEC/V: Lookup group for %" << seqno << ": cg_base=%" << rcv.colq[0].base
  2034. << " column=" << colx << " with base %" << colbase << ": SERIES=" << colseries
  2035. << " INDEX:" << colgx);
  2036. // Check oversize. Dismiss some earlier items if it exceeds the size.
  2037. // before you extend the size enormously.
  2038. if (colgx > m_number_rows * m_number_cols * SRT_FEC_MAX_RCV_HISTORY)
  2039. {
  2040. // That's too much
  2041. LOGC(pflog.Error, log << "FEC/V: IPE or ATTACK: offset " << colgx << " is too crazy, ABORTING lookup");
  2042. w_status = HANG_CRAZY;
  2043. return -1;
  2044. }
  2045. if (colgx >= rcv.colq.size())
  2046. {
  2047. colgx = ExtendColumns(colgx);
  2048. }
  2049. w_status = HANG_SUCCESS;
  2050. return int(colgx);
  2051. //
  2052. // Even though column groups are arranged in a "staircase", it only means
  2053. // that DISTANCE(colq[0].base TO colq[1].base) == 1 + m_number_cols, not 1.
  2054. // But still, this DISTANCE(...) % m_number_cols == 1. So:
  2055. //
  2056. // COLUMN_INDEX = GROUP_INDEX % m_number_cols
  2057. //
  2058. // What is special here is that, group base sequence numbers with m_number_cols == 5
  2059. // is, for example, these column groups in order of how they are arranged in
  2060. // the container have their [INDEX] BASE (stating the very first has base == 10):
  2061. //
  2062. // [0] 10, [1] 16, [2] 22, [3] 28, [4] 34, [5] 40, [6] 46
  2063. //
  2064. // Therefore, if we get the sequence number 51, then:
  2065. //
  2066. // OFFSET = 51 - 10 = 41
  2067. //
  2068. // COLUMN_INDEX = 41 % 5[m_number_cols] == 1
  2069. //
  2070. // COLUMN_BASE = colq[1].base == 16
  2071. //
  2072. // COLUMN_OFFSET = DISTANCE(colq[1].base TO 51) = 51 - 16 = 35
  2073. //
  2074. // COLUMN_SERIES = COLUMN_OFFSET / (m_number_cols * m_number_rows)
  2075. // = 35 / (5*5) = 35/25 = 1
  2076. //
  2077. // GROUP_INDEX = COLUMN_INDEX + (COLUMN_SERIES * m_number_cols)
  2078. // = 1 + 1*5 = 6
  2079. //
  2080. // --> We have identified column group with index 6, this one
  2081. // that is designated above as [6] 46. This column group collects
  2082. // the following sequence numbers:
  2083. // - 46
  2084. // - 51 (the one we were searching)
  2085. // - 56
  2086. // - 61
  2087. // - 66
  2088. //
  2089. // We have then column group with index 6. Now we go backward in the column
  2090. // group container starting from the direct previous column up to either
  2091. // the start of container or the size == m_number_cols (5), to see if the
  2092. // group "is closed". So:
  2093. //
  2094. // END = min(m_number_cols, colq.size()) <--- should be 5 or less, if there's less in the container
  2095. //
  2096. // FOR EACH i = 1 TO END:
  2097. // g = colq[GROUP_INDEX - i]
  2098. // gs = SHIFT(seq, -i)
  2099. // gmax = SHIFT(g.base, m_number_cols * m_number_rows)
  2100. // IF ( gs %> gmax )
  2101. // DISMISS COLUMNS from 0 to GROUP_INDEX - i; break
  2102. }
  2103. size_t FECFilterBuiltin::ExtendColumns(size_t colgx)
  2104. {
  2105. // This isn't safe to allow the group container to get expanded to any
  2106. // size, however with some very tolerant settings, such as 10 seconds of
  2107. // latency and very large receiver buffer, this might be tolerable.
  2108. //
  2109. // Therefore put only two conditions here:
  2110. //
  2111. // 1. The group containers must keep at most place for so many
  2112. // packets as it is intended for the receiver buffer. Keeping
  2113. // group cells for more packets doesn't make sense anyway.
  2114. //
  2115. // 2. Existing group containers should contain at least size
  2116. // for two series. If they don't contain that much, there's no
  2117. // need to do any emergency shrinking. Unknown whether this is
  2118. // physically possible, although it may also happen in case when
  2119. // you have very large FEC matrix size not coordinated with the
  2120. // receiver buffer size.
  2121. // colgx is the number of column + NSERIES * numberCols().
  2122. // We can state that for every column we should have a number
  2123. // of packets as many as the number of rows, so simply multiply this.
  2124. const size_t size_in_packets = colgx * numberRows();
  2125. const size_t n_series = colgx / numberCols();
  2126. if (CheckEmergencyShrink(n_series, size_in_packets))
  2127. {
  2128. HLOGC(pflog.Debug, log << "FEC: DONE Emergency resize, colgx=" << colgx << " series=" << n_series
  2129. << "npackets=" << size_in_packets << " exceeds buf=" << rcvBufferSize());
  2130. }
  2131. else
  2132. {
  2133. HLOGC(pflog.Debug, log << "FEC: Will extend up to colgx=" << colgx << " series=" << n_series
  2134. << " for npackets=" << size_in_packets);
  2135. }
  2136. #if ENABLE_HEAVY_LOGGING
  2137. LOGC(pflog.Debug, log << "FEC: COL STATS BEFORE: n=" << rcv.colq.size());
  2138. for (size_t i = 0; i < rcv.colq.size(); ++i)
  2139. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.colq[i].DisplayStats());
  2140. #endif
  2141. // First, obtain the "series" of columns, possibly fixed.
  2142. const int series = int(colgx / numberCols());
  2143. // Now, the base of the series is the base increased by one matrix size.
  2144. const int32_t base = rcv.colq[0].base;
  2145. // This is the base for series 0, but this procedure must be prepared
  2146. // for that the series will not necessarily be 1, may be greater.
  2147. // Extension requires to be done in order to achieve this very index
  2148. // existing in the column, so you need to add whole series in loop
  2149. // until the series covering this shift is created.
  2150. // Check, up to which series the columns are initialized.
  2151. // Start with the series that doesn't exist
  2152. const int old_series = int(rcv.colq.size() / numberCols());
  2153. // Each iteration of this loop adds one series of columns.
  2154. // One series count numberCols() columns.
  2155. for (int s = old_series; s <= series; ++s)
  2156. {
  2157. // We start with the base in series 0, the calculation of the
  2158. // sequence number must happen anew for each one anyway, so it
  2159. // doesn't matter from which start point.
  2160. // Every base sequence for a series of columns is the series 0
  2161. // base increased by one matrix size times series number.
  2162. // THIS REMAINS TRUE NO MATTER IF WE USE STRAIGNT OR STAIRCASE ARRANGEMENT.
  2163. const int32_t sbase = CSeqNo::incseq(base, int(numberCols()*numberRows()) * s);
  2164. HLOGC(pflog.Debug, log << "FEC/V: EXTENDING column groups series " << s
  2165. << ", size " << rcv.colq.size() << " -> "
  2166. << (rcv.colq.size() + numberCols())
  2167. << ", base=%" << base << " -> %" << sbase);
  2168. // Every call to this function extends the given container
  2169. // by 'gsize' number and configures each so added column accordingly.
  2170. ConfigureColumns(rcv.colq, sbase);
  2171. }
  2172. #if ENABLE_HEAVY_LOGGING
  2173. LOGC(pflog.Debug, log << "FEC: COL STATS BEFORE: n=" << rcv.colq.size());
  2174. for (size_t i = 0; i < rcv.colq.size(); ++i)
  2175. LOGC(pflog.Debug, log << "... [" << i << "] " << rcv.colq[i].DisplayStats());
  2176. #endif
  2177. return colgx;
  2178. }
  2179. } // namespace srt