//! Reed-Solomon erasure coding over GF(2^8), polynomial `0x11D` (`docs/PROTOCOL.md` 5.3, 6.4). //! //! Systematic code: `data` shards pass through unchanged, `parity` shards are linear combinations of them, and any //! `data` of the `data + parity` shards rebuild the rest. Every byte position is coded on its own, so all shards of //! a block have the same length. //! //! Two matrices are needed: video ([`ReedSolomon::new`]: the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`, from //! fec-rs, U14 settled pending the Day 1 check) and audio (a fixed 2 × 4 parity matrix, UNKNOWN U16, passed in //! with [`ReedSolomon::with_parity_matrix`] until it is measured). use crate::util::{cap, malformed}; use crate::{Error, Result}; /// Maximum shards in one block (data + parity). pub const MAX_SHARDS: usize = 255; /// Maximum length of one shard, in bytes. pub const MAX_SHARD_BYTES: usize = 4096; /// Square submatrices checked exhaustively for the MDS property; bigger matrices get the 1 × 1 and, if cheap /// enough, the 2 × 2 checks only. const MDS_EXHAUSTIVE_BUDGET: u64 = 200_000; const MDS_PAIRS_BUDGET: u64 = 1_000_000; // ------------------------------------------------------------------------------------------------ GF(2^8) /// `EXP[i] = 2^i` (doubled so a sum of two logarithms needs no reduction) and `LOG[x] = log2(x)`. #[allow(clippy::indexing_slicing, reason = "compile-time table: any out-of-bounds index fails the build")] const fn tables() -> ([u8; 512], [u8; 256]) { let mut exp = [0u8; 512]; let mut log = [0u8; 256]; let mut x: u16 = 1; let mut i = 0; while i < 255 { exp[i] = x as u8; log[x as usize] = i as u8; x <<= 1; if x & 0x100 != 0 { x ^= 0x11D; } i += 1; } while i < 512 { exp[i] = exp[i - 255]; i += 1; } (exp, log) } const TABLES: ([u8; 512], [u8; 256]) = tables(); fn log(x: u8) -> usize { usize::from(TABLES.1.get(usize::from(x)).copied().unwrap_or(0)) } fn exp(i: usize) -> u8 { TABLES.0.get(i).copied().unwrap_or(0) } fn mul(a: u8, b: u8) -> u8 { if a == 0 || b == 0 { 0 } else { exp(log(a) + log(b)) } } /// Multiplicative inverse; `inv(0)` is 0 (never used as a divisor). fn inv(a: u8) -> u8 { if a == 0 { 0 } else { exp(255 - log(a)) } } /// `dst ^= c · src`, byte by byte. fn mul_add(dst: &mut [u8], src: &[u8], c: u8) { if c == 0 { return; } let lc = log(c); for (d, &s) in dst.iter_mut().zip(src) { if s != 0 { *d ^= exp(lc + log(s)); } } } /// Inverse of a row-major `n × n` matrix by Gauss-Jordan elimination; `None` when singular. fn invert(mut a: Vec, n: usize) -> Option> { let mut out = vec![0u8; n * n]; for i in 0..n { *out.get_mut(i * n + i)? = 1; } for col in 0..n { let pivot = (col..n).find(|&r| a.get(r * n + col).is_some_and(|v| *v != 0))?; if pivot != col { for c in 0..n { a.swap(pivot * n + c, col * n + c); out.swap(pivot * n + c, col * n + c); } } let scale = inv(*a.get(col * n + col)?); for c in 0..n { let v = a.get_mut(col * n + c)?; *v = mul(*v, scale); let w = out.get_mut(col * n + c)?; *w = mul(*w, scale); } for r in 0..n { if r == col { continue; } let factor = *a.get(r * n + col)?; if factor == 0 { continue; } for c in 0..n { let ac = mul(factor, *a.get(col * n + c)?); *a.get_mut(r * n + c)? ^= ac; let oc = mul(factor, *out.get(col * n + c)?); *out.get_mut(r * n + c)? ^= oc; } } } Some(out) } /// `n choose k`, saturating. fn choose(n: usize, k: usize) -> u64 { let mut r: u64 = 1; for i in 0..k.min(n) { // Exact while it fits (r * (n - i) is divisible by i + 1); once it saturates it stays saturated. r = match r.checked_mul(n.saturating_sub(i) as u64) { Some(v) => v / (i as u64 + 1), None => return u64::MAX, }; } if k > n { 0 } else { r } } /// All `size`-element subsets of `0..n`, in lexicographic order, passed to `f` until it returns false. fn each_subset(n: usize, size: usize, mut f: impl FnMut(&[usize]) -> bool) -> bool { if size > n { return true; } let mut idx: Vec = (0..size).collect(); loop { if !f(&idx) { return false; } // The rightmost position that can still move right. let Some(i) = (0..size).rev().find(|&i| idx.get(i).is_some_and(|&v| v < n - size + i)) else { return true; }; let start = idx.get(i).copied().unwrap_or(0) + 1; for (off, slot) in idx.iter_mut().enumerate().skip(i) { *slot = start + (off - i); } } } /// Whether `[I; P]` is MDS, i.e. every square submatrix of `P` is invertible (see the budgets above). fn is_mds(p: &[u8], data: usize, parity: usize) -> bool { if p.contains(&0) { return false; } let total: u64 = (2..=data.min(parity)) .map(|s| choose(data, s).saturating_mul(choose(parity, s))) .fold(0u64, u64::saturating_add); let max_size = if total <= MDS_EXHAUSTIVE_BUDGET { data.min(parity) } else if choose(data, 2).saturating_mul(choose(parity, 2)) <= MDS_PAIRS_BUDGET { 2 } else { 1 }; for s in 2..=max_size { let ok = each_subset(parity, s, |rows| { each_subset(data, s, |cols| { let sub: Vec = rows .iter() .flat_map(|&r| cols.iter().map(move |&c| p.get(r * data + c).copied().unwrap_or(0))) .collect(); invert(sub, s).is_some() }) }); if !ok { return false; } } true } // ------------------------------------------------------------------------------------------------ the code /// Parity shards for `data_shards` at `fec_percentage`: `ceil(data × percentage / 100)`. /// /// # Errors /// [`Error::UnexpectedValue`] when `data_shards` is 0 or data + parity would exceed [`MAX_SHARDS`]. pub fn parity_count(data_shards: usize, fec_percentage: u8) -> Result { let k = u64::try_from(data_shards).unwrap_or(u64::MAX); let m = k.saturating_mul(u64::from(fec_percentage)).div_ceil(100); let m = usize::try_from(m).unwrap_or(usize::MAX); if data_shards == 0 || data_shards.saturating_add(m) > MAX_SHARDS { return Err(Error::UnexpectedValue { what: "fec shard count", value: k }); } Ok(m) } /// One code: shard counts and its parity matrix. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ReedSolomon { data_shards: usize, parity_shards: usize, /// `parity_shards × data_shards` coefficients, row-major. parity_matrix: Vec, } fn check_counts(data_shards: usize, parity_shards: usize) -> Result<()> { let sum = data_shards.checked_add(parity_shards); if data_shards == 0 || parity_shards == 0 || sum.is_none_or(|s| s > MAX_SHARDS) { return Err(Error::UnexpectedValue { what: "fec shard counts", value: u64::try_from(data_shards).unwrap_or(u64::MAX), }); } Ok(()) } impl ReedSolomon { /// The code GameStream video uses for `data_shards` + `parity_shards`: parity row `j` is the Cauchy row /// `1 / ((parity_shards + i) XOR j)` (`docs/PROTOCOL.md` 5.3). /// /// # Errors /// [`Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`]. pub fn new(data_shards: usize, parity_shards: usize) -> Result { check_counts(data_shards, parity_shards)?; let mut parity_matrix = Vec::with_capacity(data_shards * parity_shards); for j in 0..parity_shards { for i in 0..data_shards { // parity + i <= 254 and j < parity, so the XOR is never zero. parity_matrix.push(inv(((parity_shards + i) ^ j) as u8)); } } Ok(Self { data_shards, parity_shards, parity_matrix }) } /// A code with an explicit parity matrix (`parity_shards × data_shards`, row-major). The matrix must make every /// square submatrix of `[I; P]` invertible, or some loss patterns cannot be rebuilt; this is checked /// exhaustively for small matrices and by its 1 × 1 and 2 × 2 minors for large ones. /// /// # Errors /// As [`Self::new`]; [`Error::Malformed`] for a matrix of the wrong size or one that is not MDS. pub fn with_parity_matrix(data_shards: usize, parity_shards: usize, parity_matrix: &[u8]) -> Result { check_counts(data_shards, parity_shards)?; if parity_matrix.len() != data_shards * parity_shards { return Err(malformed("fec parity matrix size")); } if !is_mds(parity_matrix, data_shards, parity_shards) { return Err(malformed("fec parity matrix is not MDS")); } Ok(Self { data_shards, parity_shards, parity_matrix: parity_matrix.to_vec() }) } /// Number of data shards. #[must_use] pub const fn data_shards(&self) -> usize { self.data_shards } /// Number of parity shards. #[must_use] pub const fn parity_shards(&self) -> usize { self.parity_shards } /// The parity matrix, row-major. #[must_use] pub fn parity_matrix(&self) -> &[u8] { &self.parity_matrix } fn coefficient(&self, row: usize, col: usize) -> u8 { self.parity_matrix.get(row * self.data_shards + col).copied().unwrap_or(0) } /// One parity row over the given data shards. fn parity_row(&self, row: usize, data: &[&[u8]], len: usize) -> Vec { let mut out = vec![0u8; len]; for (i, d) in data.iter().enumerate() { mul_add(&mut out, d, self.coefficient(row, i)); } out } /// Computes the parity shards from the data shards. `shards` holds `data + parity` buffers of equal length; /// the parity ones are overwritten. /// /// # Errors /// [`Error::Malformed`] for the wrong shard count or unequal lengths, [`Error::TooLarge`] over /// [`MAX_SHARD_BYTES`]. pub fn encode(&self, shards: &mut [Vec]) -> Result<()> { if shards.len() != self.data_shards + self.parity_shards { return Err(malformed("fec shard count")); } let len = shards.first().map_or(0, Vec::len); if shards.iter().any(|s| s.len() != len) { return Err(malformed("fec shards of unequal length")); } cap("fec shard", MAX_SHARD_BYTES, len)?; let (data, parity) = shards.split_at_mut(self.data_shards); let data: Vec<&[u8]> = data.iter().map(Vec::as_slice).collect(); for (j, p) in parity.iter_mut().enumerate() { *p = self.parity_row(j, &data, len); } Ok(()) } /// Rebuilds missing shards in place. `shards` holds `data + parity` entries, `None` for lost ones; on success /// every entry is `Some`, and present entries are never changed. /// /// # Errors /// [`Error::Malformed`] for the wrong count, unequal lengths, or a singular system (a matrix that was not /// MDS), [`Error::TooLarge`] over [`MAX_SHARD_BYTES`], [`Error::Truncated`] when fewer than `data` shards are /// present. pub fn reconstruct(&self, shards: &mut [Option>]) -> Result<()> { let k = self.data_shards; if shards.len() != k + self.parity_shards { return Err(malformed("fec shard count")); } let len = shards.iter().flatten().next().map_or(0, Vec::len); if shards.iter().flatten().any(|s| s.len() != len) { return Err(malformed("fec shards of unequal length")); } cap("fec shard", MAX_SHARD_BYTES, len)?; let present = shards.iter().flatten().count(); if present < k { return Err(Error::Truncated { what: "fec shards", needed: k, actual: present }); } let missing: Vec = (0..k).filter(|&i| shards.get(i).is_some_and(Option::is_none)).collect(); if !missing.is_empty() { let rows: Vec = (0..self.parity_shards) .filter(|&j| shards.get(k + j).is_some_and(Option::is_some)) .take(missing.len()) .collect(); let e = missing.len(); let a: Vec = rows .iter() .flat_map(|&r| missing.iter().map(move |&c| (r, c))) .map(|(r, c)| self.coefficient(r, c)) .collect(); let a_inv = invert(a, e).ok_or(malformed("fec system is singular (matrix not MDS)"))?; // rhs_r = parity_r - sum over present data of P[r][i] * d_i let mut rhs: Vec> = Vec::with_capacity(e); for &r in &rows { let mut v = shards.get(k + r).and_then(Option::as_ref).cloned().unwrap_or_default(); for i in (0..k).filter(|i| !missing.contains(i)) { if let Some(Some(d)) = shards.get(i) { mul_add(&mut v, d, self.coefficient(r, i)); } } rhs.push(v); } for (c, &slot) in missing.iter().enumerate() { let mut out = vec![0u8; len]; for (r, v) in rhs.iter().enumerate() { mul_add(&mut out, v, a_inv.get(c * e + r).copied().unwrap_or(0)); } if let Some(s) = shards.get_mut(slot) { *s = Some(out); } } } let parity_missing: Vec = (0..self.parity_shards).filter(|&j| shards.get(k + j).is_some_and(Option::is_none)).collect(); if !parity_missing.is_empty() { let data: Vec<&[u8]> = shards.iter().take(k).flatten().map(Vec::as_slice).collect(); let rebuilt: Vec<(usize, Vec)> = parity_missing.iter().map(|&j| (j, self.parity_row(j, &data, len))).collect(); for (j, p) in rebuilt { if let Some(s) = shards.get_mut(k + j) { *s = Some(p); } } } Ok(()) } }