//! Two FEC measurements the sitting settles from real traffic, with our own arithmetic: //! //! - **U14** (video, live): for each complete block, DomiStream's Cauchy encoder must reproduce the parity packets //! the host sent (offset 32 on). Two readings are checked: parity over whole data packets (PROTOCOL.md 5.3) and //! over data packets with their 32 header bytes zeroed. //! - **U16** (audio, offline from `audio-packets.bin`): each parity byte is a linear combination over GF(2^8) //! (polynomial `0x11D`) of the four data bytes at the same offset, so a few offsets give the 2 × 4 matrix; every //! other byte of every block then checks it. use std::collections::BTreeMap; use domistream::audio::{AudioPacket, parse_audio_packet}; use domistream::fec::{ReedSolomon, parity_count}; /// GF(2^8) with polynomial `0x11D`, generator 2. pub struct Gf { exp: [u8; 512], log: [u8; 256], } impl Gf { pub fn new() -> Self { let (mut exp, mut log) = ([0u8; 512], [0u8; 256]); let mut x: u16 = 1; for (i, e) in exp.iter_mut().take(255).enumerate() { *e = x as u8; log[usize::from(x)] = i as u8; x <<= 1; if x & 0x100 != 0 { x ^= 0x11D; } } // exp[i + 255] = exp[i], so a product's log sum (at most 508) needs no reduction. exp.copy_within(0..255, 255); Self { exp, log } } pub fn mul(&self, a: u8, b: u8) -> u8 { if a == 0 || b == 0 { 0 } else { self.exp[usize::from(self.log[usize::from(a)]) + usize::from(self.log[usize::from(b)])] } } /// `1 / a`; `a` must not be 0. pub fn inv(&self, a: u8) -> u8 { self.exp[255 - usize::from(self.log[usize::from(a)])] } } /// What the audio solver found for one parity row. #[derive(Clone, Debug, PartialEq, Eq)] pub enum RowResult { /// The four coefficients, and how many byte equations agreed and disagreed with them. Solved { coefficients: [u8; 4], equations: u64, mismatches: u64 }, /// Not enough independent equations (rank below 4). Underdetermined { rank: usize, equations: u64 }, } /// The audio parity matrix from captured blocks. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AudioFecReport { pub data_packets: u64, pub parity_packets: u64, pub unparsed: u64, pub blocks: usize, /// Blocks with all 4 data packets and parity row 0 / row 1, all of one length. pub complete: [usize; 2], pub rows: [RowResult; 2], } impl AudioFecReport { /// The 2 × 4 matrix, row-major, when both rows solved without a single mismatch. pub fn matrix(&self) -> Option<[u8; 8]> { match (&self.rows[0], &self.rows[1]) { ( RowResult::Solved { coefficients: a, mismatches: 0, .. }, RowResult::Solved { coefficients: b, mismatches: 0, .. }, ) => Some([a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]]), _ => None, } } /// Whether DomiStream accepts the solved matrix as an MDS code (`AudioFec::ParityMatrix`). pub fn matrix_is_mds(&self) -> Option { self.matrix().map(|m| ReedSolomon::with_parity_matrix(4, 2, &m).is_ok()) } } #[derive(Default)] struct AudioBlock { data: [Option>; 4], parity: [Option>; 2], } /// Solves U16 from raw audio datagrams (as received: encrypted payloads are the shards). pub fn solve_audio(datagrams: &[Vec]) -> AudioFecReport { let gf = Gf::new(); let mut blocks: BTreeMap = BTreeMap::new(); let (mut data_packets, mut parity_packets, mut unparsed) = (0, 0, 0); for d in datagrams { match parse_audio_packet(d) { Ok(AudioPacket::Data { rtp, payload }) => { data_packets += 1; let b = blocks.entry(rtp.sequence & !3).or_default(); b.data[usize::from(rtp.sequence & 3)] = Some(payload.to_vec()); } Ok(AudioPacket::Parity { fec, parity, .. }) => { parity_packets += 1; let b = blocks.entry(fec.base_sequence).or_default(); b.parity[usize::from(fec.shard_index & 1)] = Some(parity.to_vec()); } Err(_) => unparsed += 1, } } let mut complete = [0usize; 2]; let rows = [0usize, 1].map(|row| { let mut basis: Vec<(usize, [u8; 5])> = Vec::new(); let mut equations: Vec<[u8; 5]> = Vec::new(); for b in blocks.values() { let (Some(d0), Some(d1), Some(d2), Some(d3), Some(p)) = (&b.data[0], &b.data[1], &b.data[2], &b.data[3], &b.parity[row]) else { continue; }; let len = p.len(); if [d0, d1, d2, d3].iter().any(|d| d.len() != len) { continue; } complete[row] += 1; for o in 0..len { let eq = [d0[o], d1[o], d2[o], d3[o], p[o]]; equations.push(eq); if basis.len() < 4 { add_to_basis(&gf, &mut basis, eq); } } } let count = equations.len() as u64; if basis.len() < 4 { return RowResult::Underdetermined { rank: basis.len(), equations: count }; } let mut c = [0u8; 4]; for (pc, r) in &basis { c[*pc] = r[4]; } let mismatches = equations.iter().filter(|e| (0..4).fold(0u8, |acc, i| acc ^ gf.mul(c[i], e[i])) != e[4]).count() as u64; RowResult::Solved { coefficients: c, equations: count, mismatches } }); AudioFecReport { data_packets, parity_packets, unparsed, blocks: blocks.len(), complete, rows } } /// Adds one augmented equation to a reduced row-echelon basis (pivot 1, zero in other rows' pivot columns). fn add_to_basis(gf: &Gf, basis: &mut Vec<(usize, [u8; 5])>, mut row: [u8; 5]) { for (pc, b) in basis.iter() { let f = row[*pc]; if f != 0 { for i in 0..5 { row[i] ^= gf.mul(f, b[i]); } } } let Some(pc) = (0..4).find(|&i| row[i] != 0) else { return }; let inv = gf.inv(row[pc]); for v in &mut row { *v = gf.mul(*v, inv); } for (_, b) in basis.iter_mut() { let f = b[pc]; if f != 0 { for i in 0..5 { b[i] ^= gf.mul(f, row[i]); } } } basis.push((pc, row)); } /// How a complete video block compared with our encoder. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum VideoOutcome { /// Parity over whole data packets (PROTOCOL.md 5.3) matches. Whole, /// Only parity over data packets with zeroed 32-byte headers matches. PayloadOnly, /// Neither reading matches. Neither, /// Not comparable (shards of different lengths, or a code DomiStream refuses). Skipped, } struct VideoBlock { k: u16, m: usize, shards: BTreeMap>, } /// The live U14 check: collects each block's packets (plaintext) and compares the parity once it is complete. pub struct VideoFecCheck { pending: BTreeMap<(u32, u8), VideoBlock>, limit: u64, pub checked: u64, pub whole: u64, pub payload_only: u64, pub neither: u64, pub skipped: u64, } /// Blocks kept open at once; the oldest is dropped beyond this (a lost packet means it never completes). const MAX_PENDING_BLOCKS: usize = 64; impl VideoFecCheck { /// Checks at most `limit` blocks. pub fn new(limit: u64) -> Self { Self { pending: BTreeMap::new(), limit, checked: 0, whole: 0, payload_only: 0, neither: 0, skipped: 0 } } /// One plaintext packet of block `block` of frame `frame`: shard `shard` of `k` data shards at `pct` percent. pub fn push(&mut self, frame: u32, block: u8, shard: u16, k: u16, pct: u8, packet: &[u8]) -> Option { if self.checked >= self.limit { return None; } let m = parity_count(usize::from(k), pct).ok()?; if m == 0 { return None; } let entry = self.pending.entry((frame, block)).or_insert_with(|| VideoBlock { k, m, shards: BTreeMap::new() }); if entry.k != k || entry.m != m { return None; } entry.shards.insert(shard, packet.to_vec()); if entry.shards.len() < usize::from(k) + m { while self.pending.len() > MAX_PENDING_BLOCKS { self.pending.pop_first(); } return None; } let b = self.pending.remove(&(frame, block))?; self.checked += 1; let outcome = compare(&b); match outcome { VideoOutcome::Whole => self.whole += 1, VideoOutcome::PayloadOnly => self.payload_only += 1, VideoOutcome::Neither => self.neither += 1, VideoOutcome::Skipped => self.skipped += 1, } Some(outcome) } } fn compare(b: &VideoBlock) -> VideoOutcome { let k = usize::from(b.k); let shards: Vec<&Vec> = b.shards.values().collect(); let len = shards.first().map_or(0, |s| s.len()); if len <= 32 || shards.iter().any(|s| s.len() != len) { return VideoOutcome::Skipped; } let Ok(rs) = ReedSolomon::new(k, b.m) else { return VideoOutcome::Skipped }; let parity_matches = |zero_headers: bool| -> Option { let mut work: Vec> = Vec::with_capacity(k + b.m); for s in shards.iter().take(k) { let mut d = (*s).clone(); if zero_headers { d.iter_mut().take(32).for_each(|x| *x = 0); } work.push(d); } work.extend((0..b.m).map(|_| vec![0u8; len])); rs.encode(&mut work).ok()?; Some(work.iter().skip(k).zip(shards.iter().skip(k)).all(|(ours, theirs)| ours.get(32..) == theirs.get(32..))) }; match (parity_matches(false), parity_matches(true)) { (Some(true), _) => VideoOutcome::Whole, (_, Some(true)) => VideoOutcome::PayloadOnly, (Some(false), _) | (_, Some(false)) => VideoOutcome::Neither, _ => VideoOutcome::Skipped, } } #[cfg(test)] mod tests { use super::*; fn rtp(pt: u8, seq: u16, payload: &[u8]) -> Vec { let mut p = vec![0x80, pt]; p.extend_from_slice(&seq.to_be_bytes()); p.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); p.extend_from_slice(payload); p } fn parity_packet(seq: u16, shard: u8, base: u16, parity: &[u8]) -> Vec { let mut fec = vec![shard, 97]; fec.extend_from_slice(&base.to_be_bytes()); fec.extend_from_slice(&[0; 8]); fec.extend_from_slice(parity); rtp(127, seq, &fec) } /// Blocks made with a known matrix; the solver must find it and every byte must agree. #[test] fn audio_matrix_is_recovered() { let gf = Gf::new(); let m = [0x77, 0x40, 0x38, 0x0e, 0xc7, 0xa7, 0x0d, 0x6c]; let mut datagrams = Vec::new(); let mut x: u32 = 12345; for block in 0..6u16 { let base = block * 4; let data: Vec> = (0..4) .map(|_| { (0..32) .map(|_| { x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); (x >> 16) as u8 }) .collect() }) .collect(); for (i, d) in data.iter().enumerate() { datagrams.push(rtp(97, base + i as u16, d)); } for row in 0..2 { let p: Vec = (0..32).map(|o| (0..4).fold(0u8, |acc, i| acc ^ gf.mul(m[row * 4 + i], data[i][o]))).collect(); datagrams.push(parity_packet(1000 + block * 2 + row as u16, row as u8, base, &p)); } } datagrams.push(vec![0x00, 0x01]); let r = solve_audio(&datagrams); assert_eq!((r.data_packets, r.parity_packets, r.unparsed, r.blocks, r.complete), (24, 12, 1, 6, [6, 6])); assert_eq!(r.matrix(), Some(m), "{r:?}"); } #[test] fn too_little_audio_is_underdetermined() { let r = solve_audio(&[rtp(97, 0, &[1, 2]), rtp(97, 1, &[3, 4])]); assert!(matches!(r.rows[0], RowResult::Underdetermined { rank: 0, equations: 0 })); assert_eq!(r.matrix(), None); } #[test] fn gf_inverse() { let gf = Gf::new(); for a in 1..=255u8 { assert_eq!(gf.mul(a, gf.inv(a)), 1); } // 2 * 0x80 wraps through the polynomial. assert_eq!(gf.mul(2, 0x80), 0x1D); } fn packet(shard: u16, fill: u8, len: usize) -> Vec { let mut p = vec![fill; len]; p[0] = 0x90; p[2..4].copy_from_slice(&shard.to_be_bytes()); p } #[test] fn video_parity_from_our_encoder_matches_whole_packets() { let (k, m, len) = (4usize, 2usize, 64usize); let rs = ReedSolomon::new(k, m).unwrap(); let mut shards: Vec> = (0..k).map(|i| packet(i as u16, 0x10 + i as u8, len)).collect(); shards.extend((0..m).map(|_| vec![0u8; len])); rs.encode(&mut shards).unwrap(); // The host overwrites parity bytes 0-31 with headers after computing the parity. for s in shards.iter_mut().skip(k) { s[..32].fill(0xEE); } let mut check = VideoFecCheck::new(10); let mut last = None; for (i, s) in shards.iter().enumerate() { last = check.push(9, 0, i as u16, k as u16, 50, s); } assert_eq!(last, Some(VideoOutcome::Whole)); assert_eq!((check.checked, check.whole), (1, 1)); } #[test] fn foreign_video_parity_is_reported() { let mut check = VideoFecCheck::new(10); let mut last = None; for i in 0..6u16 { last = check.push(1, 0, i, 4, 50, &packet(i, 0x33 + i as u8, 64)); } assert_eq!(last, Some(VideoOutcome::Neither)); assert_eq!(check.neither, 1); } }