Skip to content
All tools
Tool

Check how many FEC sets each shred feed delivers in full

Group two feeds' shreds into FEC sets and see, per feed and for both combined, how many arrived complete, recoverable or short.

Download fec_check.pyPython 3, standard library only. Edit the two ports in FEEDS, then run it on the receiving machine.
fec_check.pypy
#!/usr/bin/env python3# fec_check.py: how many FEC sets does each feed deliver in full?# Point one destination at each port below, then run this on that one machine: python3 fec_check.py [seconds]import selectors, socket, struct, sys, timefrom collections import Counter FEEDS = {"current": 20001, "premium": 20002}   # feed name -> UDP port on this machineSECONDS = int(sys.argv[1]) if len(sys.argv) > 1 else 60HEADER = 83   # common shred header; a coding shred adds num_data, num_coding and position (u16 each) def kind(variant):   # "data", "code", or None for a variant this script does not know    if variant == 0xA5 or variant & 0xF0 in (0x80, 0x90, 0xB0):        return "data"    if variant == 0x5A or variant & 0xF0 in (0x40, 0x60, 0x70):        return "code" sel = selectors.DefaultSelector()for name, port in FEEDS.items():    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8 << 20)    sock.bind(("0.0.0.0", port))    sock.setblocking(False)    sel.register(sock, selectors.EVENT_READ, name) new = lambda: {"data": set(), "code": set(), "need": None}   # data indexes, coding positions, data shreds in the setsets = {name: {} for name in FEEDS}                          # feed -> (slot, fec set) -> new()end = time.monotonic() + SECONDSwhile time.monotonic() < end:    for key, _ in sel.select(timeout=1):        while True:            try:                pkt = key.fileobj.recv(2048)            except BlockingIOError:                break            if len(pkt) < HEADER or pkt.startswith(b"SHREDCAST-VERIFY") or not kind(pkt[64]):                continue            slot, index = struct.unpack_from("<QI", pkt, 65)            (fec_set,) = struct.unpack_from("<I", pkt, 79)            fec = sets[key.data].setdefault((slot, fec_set), new())            if kind(pkt[64]) == "data":                fec["data"].add(index)            elif len(pkt) >= HEADER + 6:                need, _, position = struct.unpack_from("<HHH", pkt, HEADER)                fec["code"].add(position)                fec["need"] = need def verdict(fec):    if fec["need"] is None:        return "unknown"       # no coding shred seen, so the size of the set is not known    if len(fec["data"]) >= fec["need"]:        return "complete"      # every data shred arrived    if len(fec["data"]) + len(fec["code"]) >= fec["need"]:        return "recoverable"   # some are missing, but enough shreds arrived to rebuild them    return "incomplete" both = {}                      # what you would hold if you ran both feeds and combined themfor view in sets.values():    for key, fec in view.items():        merged = both.setdefault(key, new())        merged["data"] |= fec["data"]        merged["code"] |= fec["code"]        merged["need"] = merged["need"] or fec["need"] slots = {key[0] for key in both}partial = {min(slots), max(slots)} if slots else set()   # the first and last slots are only partly capturedprint(f"{'':13}{'sets':>6}{'complete':>10}{'recoverable':>13}{'incomplete':>12}{'unknown':>9}")for name, view in {**sets, "both feeds": both}.items():    kept = [fec for key, fec in view.items() if key[0] not in partial]    count = Counter(verdict(fec) for fec in kept)    share = lambda v: f"{count[v] / len(kept):.0%}" if kept else "-"    print(f"{name:13}{len(kept):6}{share('complete'):>10}{share('recoverable'):>13}{share('incomplete'):>12}{share('unknown'):>9}")

Speed is half the question

A feed that wins every race can still hurt you when it leaves holes. A block can only be rebuilt from an FEC set once enough of its shreds arrive, so a fast feed with many short sets hands your decoder work it cannot finish.

This script counts that directly. It listens to two feeds at once, sorts every shred into its FEC set, and tells you how many sets each feed delivered in full. It also shows what you would hold if you merged both feeds, which is the case for running two sources side by side.

Set it up

The ports match our race script, so one setup serves both: your current feed on UDP port 20001 and a Premium Shreds trial on UDP port 20002, both aimed at the same machine.

sh

python3 fec_check.py 60

Other ports work too; set them in the FEEDS dictionary. Python 3 with its standard library is all it needs.

Read the table

There is one row per feed and a final row for both feeds combined. Each row shows how many sets were counted and what share fell into each verdict:

  • complete: every data shred in the set arrived.
  • recoverable: some data shreds are missing, but enough coding shreds arrived to rebuild them.
  • incomplete: too few shreds arrived to rebuild the set.
  • unknown: no coding shred arrived, so the size of the set could not be read.

Complete plus recoverable is the share of sets your decoder can turn back into entries. If the combined row is clearly better than either feed alone, the two feeds are missing different shreds.

Limits of a short run

The first and last slots of the run are left out because the capture starts and stops part of the way through them. A sixty second sample covers about 150 slots, which is enough to see a pattern. Run it for several minutes when the result is close.

How it works out the answer

Classify each packet as data or coding from its variant byte, then group it by slot and the FEC set index at byte offset 79. Coding shreds also carry the set's data count, coding count and their own position as 16-bit values after the header. A set is complete when every data shred arrived, recoverable when data plus coding shreds reach the data count, incomplete below that, and unknown when no coding shred was seen. The first and last slots are dropped because the capture window cuts them.

Questions

What is the difference between complete and recoverable?
A complete set arrived with every data shred, so your decoder reads it straight away. A recoverable set is missing some data shreds but holds enough coding shreds to rebuild them with Reed-Solomon recovery. Both end up decodable; recoverable ones cost a little CPU and time first.
Why would a set be marked unknown?
Only coding shreds carry the number of data shreds in their set. When a run sees data shreds from a set but none of its coding shreds, the script cannot tell whether the set is whole, so it says so rather than guessing. A high unknown share usually points to coding shreds being dropped.
Can I run this alongside the first shred race script?
Not on the same ports at the same time, because each script binds both UDP ports for itself. Run them one after the other on the same setup. Both use ports 20001 and 20002 by default, so no reconfiguration is needed between the two runs.