forge
Explore
Log in

Don't you dare go Hollow

Add reed-solomon fec to screen share video

Browse files at this commit

55b5cdf250bd36847ecc5e88b1c8ce30ebc63ba3Ahmet Kaan GümüşParent: 96addff
  • feat
    • add reed-solomon fec to screen share video
Show full message
✨ feat: add reed-solomon fec to screen share video

Each frame gets 25% parity shards, so a frame survives the loss of any
shards up to that count. Keyframe requests are paced to one per second
and the relay starts a waiting viewer on any shard of a keyframe.
With 10% datagram loss the viewer now sees no frame loss.
crates/client/Cargo.tomlmodified+1 -0
@@ -5,6 +5,7 @@ edition = "2024"
5 5
6 [dependencies]6 [dependencies]
7 common.workspace = true7 common.workspace = true
8+reed-solomon-simd = "3.1.0"
8 tokio.workspace = true9 tokio.workspace = true
9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }10 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
10 11
crates/client/src/share/reassembly.rsmodified+50 -14
@@ -22,7 +22,10 @@ struct Pending {
22 layer: Layer,22 layer: Layer,
23 keyframe: bool,23 keyframe: bool,
24 timestamp_ms: u32,24 timestamp_ms: u32,
25- parts: Vec<Option<Vec<u8>>>,25+ data: usize,
26+ length: usize,
27+ present: usize,
28+ shards: Vec<Option<Vec<u8>>>,
26 }29 }
27 30
28 impl Pending {31 impl Pending {
@@ -31,18 +34,47 @@ impl Pending {
31 layer: fragment.layer,34 layer: fragment.layer,
32 keyframe: fragment.keyframe,35 keyframe: fragment.keyframe,
33 timestamp_ms: fragment.timestamp_ms,36 timestamp_ms: fragment.timestamp_ms,
34- parts: vec![None; usize::from(fragment.count)],37+ data: usize::from(fragment.data),
38+ length: fragment.length as usize,
39+ present: 0,
40+ shards: vec![None; usize::from(fragment.count)],
35 }41 }
36 }42 }
37 43
38 fn insert(&mut self, fragment: Fragment<'_>) {44 fn insert(&mut self, fragment: Fragment<'_>) {
39- if let Some(part) = self.parts.get_mut(usize::from(fragment.index)) {45+ if let Some(shard) = self.shards.get_mut(usize::from(fragment.index))
40- part.get_or_insert_with(|| fragment.payload.to_vec());46+ && shard.is_none()
47+ {
48+ *shard = Some(fragment.payload.to_vec());
49+ self.present += 1;
41 }50 }
42 }51 }
43 52
44 fn is_complete(&self) -> bool {53 fn is_complete(&self) -> bool {
45- self.parts.iter().all(Option::is_some)54+ self.present >= self.data
55+ }
56+
57+ fn assemble(self) -> Option<Vec<u8>> {
58+ let data = self.data;
59+ let mut shards = self.shards;
60+ if shards[..data].iter().any(Option::is_none) {
61+ let originals = shards[..data]
62+ .iter()
63+ .enumerate()
64+ .filter_map(|(index, shard)| Some((index, shard.as_deref()?)));
65+ let recovery = shards[data..]
66+ .iter()
67+ .enumerate()
68+ .filter_map(|(index, shard)| Some((index, shard.as_deref()?)));
69+ let restored =
70+ reed_solomon_simd::decode(data, shards.len() - data, originals, recovery).ok()?;
71+ for (index, shard) in restored {
72+ shards[index] = Some(shard);
73+ }
74+ }
75+ let mut bytes: Vec<u8> = shards.into_iter().take(data).flatten().flatten().collect();
76+ bytes.truncate(self.length);
77+ (bytes.len() == self.length).then_some(bytes)
46 }78 }
47 }79 }
48 80
@@ -105,28 +137,32 @@ impl Reassembler {
105 }137 }
106 138
107 fn deliver(&mut self, frame: u32, complete: Pending) -> Option<Assembled> {139 fn deliver(&mut self, frame: u32, complete: Pending) -> Option<Assembled> {
108- self.received_frames += 1;
109 let skipped = self140 let skipped = self
110 .last141 .last
111 .map_or(0, |last| frame.wrapping_sub(last).wrapping_sub(1));142 .map_or(0, |last| frame.wrapping_sub(last).wrapping_sub(1));
112- if skipped > 0 {143+ let (layer, keyframe, timestamp_ms) =
113- self.lost_frames += skipped;144+ (complete.layer, complete.keyframe, complete.timestamp_ms);
145+ let data = complete.assemble();
146+ self.last = Some(frame);
147+ if skipped > 0 || data.is_none() {
148+ self.lost_frames += skipped + u32::from(data.is_none());
114 self.lost = true;149 self.lost = true;
115 self.phase = Phase::WaitingKeyframe;150 self.phase = Phase::WaitingKeyframe;
116 self.pending.retain(|&older, _| is_newer(older, frame));151 self.pending.retain(|&older, _| is_newer(older, frame));
117 }152 }
118- self.last = Some(frame);153+ let data = data?;
119- if complete.keyframe {154+ self.received_frames += 1;
155+ if keyframe {
120 self.phase = Phase::Streaming;156 self.phase = Phase::Streaming;
121 }157 }
122 if self.phase == Phase::WaitingKeyframe {158 if self.phase == Phase::WaitingKeyframe {
123 return None;159 return None;
124 }160 }
125 Some(Assembled {161 Some(Assembled {
126- layer: complete.layer,162+ layer,
127- data: complete.parts.into_iter().flatten().flatten().collect(),163+ data,
128- keyframe: complete.keyframe,164+ keyframe,
129- timestamp_ms: complete.timestamp_ms,165+ timestamp_ms,
130 })166 })
131 }167 }
132 168
crates/client/src/share/session.rsmodified+13 -2
@@ -49,6 +49,7 @@ const DELAY_MS: i64 = 100;
49 const LATE_MS: i64 = 200;49 const LATE_MS: i64 = 200;
50 const QUEUE_LIMIT: usize = 8;50 const QUEUE_LIMIT: usize = 8;
51 const LOSS_LIMIT: f32 = 0.05;51 const LOSS_LIMIT: f32 = 0.05;
52+const KEYFRAME_INTERVAL: Duration = Duration::from_secs(1);
52 const CLEAN_SECONDS: u32 = 10;53 const CLEAN_SECONDS: u32 = 10;
53 const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS;54 const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS;
54 const DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000 * SHARE_AUDIO_CHANNELS;55 const DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000 * SHARE_AUDIO_CHANNELS;
@@ -443,6 +444,7 @@ pub struct Watching {
443 emitted: Option<Quality>,444 emitted: Option<Quality>,
444 rung: usize,445 rung: usize,
445 clean: u32,446 clean: u32,
447+ requested: Option<Instant>,
446 }448 }
447 449
448 impl Watching {450 impl Watching {
@@ -492,6 +494,7 @@ impl Watching {
492 .position(|quality| *quality == SHARE_QUALITY)494 .position(|quality| *quality == SHARE_QUALITY)
493 .unwrap_or(0),495 .unwrap_or(0),
494 clean: 0,496 clean: 0,
497+ requested: None,
495 }498 }
496 }499 }
497 500
@@ -560,12 +563,20 @@ impl Watching {
560 }563 }
561 564
562 pub fn tick(&mut self) -> Vec<Tick> {565 pub fn tick(&mut self) -> Vec<Tick> {
563- let (loss, lost, served) = {566+ let (loss, served, lost) = {
564 let mut health = lock(&self.health);567 let mut health = lock(&self.health);
565- (health.loss, std::mem::take(&mut health.lost), health.served)568+ let due = self
569+ .requested
570+ .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL);
571+ let lost = health.lost && due;
572+ if lost {
573+ health.lost = false;
574+ }
575+ (health.loss, health.served, lost)
566 };576 };
567 let mut ticks = Vec::new();577 let mut ticks = Vec::new();
568 if lost {578 if lost {
579+ self.requested = Some(Instant::now());
569 ticks.push(Tick::Keyframe);580 ticks.push(Tick::Keyframe);
570 }581 }
571 let wanted = match self.quality {582 let wanted = match self.quality {
crates/common/Cargo.tomlmodified+1 -0
@@ -8,6 +8,7 @@ bitcode.workspace = true
8 quinn.workspace = true8 quinn.workspace = true
9 thiserror = "2.0.21"9 thiserror = "2.0.21"
10 uuid = { version = "1.29.3", features = ["v7"] }10 uuid = { version = "1.29.3", features = ["v7"] }
11+reed-solomon-simd = "3.1.0"
11 12
12 [lints]13 [lints]
13 workspace = true14 workspace = true
crates/common/src/constant.rsmodified+1 -0
@@ -37,6 +37,7 @@ pub const DEFAULT_MAX_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;
37 pub const DEFAULT_MESSAGES_PER_MINUTE: u32 = 30;37 pub const DEFAULT_MESSAGES_PER_MINUTE: u32 = 30;
38 pub const DEFAULT_LOGINS_PER_MINUTE: u32 = 10;38 pub const DEFAULT_LOGINS_PER_MINUTE: u32 = 10;
39 pub const VIDEO_FRAGMENT_BYTES: usize = 1100;39 pub const VIDEO_FRAGMENT_BYTES: usize = 1100;
40+pub const VIDEO_FEC_DATA_PER_PARITY: usize = 4;
40 pub const MAXIMUM_SHARE_LAYERS: usize = 4;41 pub const MAXIMUM_SHARE_LAYERS: usize = 4;
41 pub const SHARE_AUDIO_BITRATE: i32 = 128_000;42 pub const SHARE_AUDIO_BITRATE: i32 = 128_000;
42 pub const SHARE_AUDIO_CHANNELS: usize = 2;43 pub const SHARE_AUDIO_CHANNELS: usize = 2;
crates/common/src/datagram.rsmodified+34 -9
@@ -1,7 +1,7 @@
1 use uuid::Uuid;1 use uuid::Uuid;
2 2
3 use crate::{3 use crate::{
4- constant::{VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD},4+ constant::{VIDEO_FEC_DATA_PER_PARITY, VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD},
5 share::Layer,5 share::Layer,
6 };6 };
7 7
@@ -32,6 +32,8 @@ pub struct Fragment<'a> {
32 pub frame: u32,32 pub frame: u32,
33 pub index: u16,33 pub index: u16,
34 pub count: u16,34 pub count: u16,
35+ pub data: u16,
36+ pub length: u32,
35 pub keyframe: bool,37 pub keyframe: bool,
36 pub timestamp_ms: u32,38 pub timestamp_ms: u32,
37 pub payload: &'a [u8],39 pub payload: &'a [u8],
@@ -66,6 +68,8 @@ impl<'a> Datagram<'a> {
66 bytes.extend_from_slice(&fragment.frame.to_be_bytes());68 bytes.extend_from_slice(&fragment.frame.to_be_bytes());
67 bytes.extend_from_slice(&fragment.index.to_be_bytes());69 bytes.extend_from_slice(&fragment.index.to_be_bytes());
68 bytes.extend_from_slice(&fragment.count.to_be_bytes());70 bytes.extend_from_slice(&fragment.count.to_be_bytes());
71+ bytes.extend_from_slice(&fragment.data.to_be_bytes());
72+ bytes.extend_from_slice(&fragment.length.to_be_bytes());
69 bytes.push(fragment.keyframe as u8);73 bytes.push(fragment.keyframe as u8);
70 bytes.extend_from_slice(&fragment.timestamp_ms.to_be_bytes());74 bytes.extend_from_slice(&fragment.timestamp_ms.to_be_bytes());
71 bytes.extend_from_slice(fragment.payload);75 bytes.extend_from_slice(fragment.payload);
@@ -99,6 +103,8 @@ impl<'a> Datagram<'a> {
99 let (frame, rest) = rest.split_first_chunk::<4>()?;103 let (frame, rest) = rest.split_first_chunk::<4>()?;
100 let (index, rest) = rest.split_first_chunk::<2>()?;104 let (index, rest) = rest.split_first_chunk::<2>()?;
101 let (count, rest) = rest.split_first_chunk::<2>()?;105 let (count, rest) = rest.split_first_chunk::<2>()?;
106+ let (data, rest) = rest.split_first_chunk::<2>()?;
107+ let (length, rest) = rest.split_first_chunk::<4>()?;
102 let (keyframe, rest) = rest.split_first()?;108 let (keyframe, rest) = rest.split_first()?;
103 let (timestamp_ms, payload) = rest.split_first_chunk::<4>()?;109 let (timestamp_ms, payload) = rest.split_first_chunk::<4>()?;
104 let fragment = Fragment {110 let fragment = Fragment {
@@ -106,11 +112,16 @@ impl<'a> Datagram<'a> {
106 frame: u32::from_be_bytes(*frame),112 frame: u32::from_be_bytes(*frame),
107 index: u16::from_be_bytes(*index),113 index: u16::from_be_bytes(*index),
108 count: u16::from_be_bytes(*count),114 count: u16::from_be_bytes(*count),
115+ data: u16::from_be_bytes(*data),
116+ length: u32::from_be_bytes(*length),
109 keyframe: *keyframe != 0,117 keyframe: *keyframe != 0,
110 timestamp_ms: u32::from_be_bytes(*timestamp_ms),118 timestamp_ms: u32::from_be_bytes(*timestamp_ms),
111 payload,119 payload,
112 };120 };
113- if fragment.index >= fragment.count {121+ if fragment.index >= fragment.count
122+ || fragment.data == 0
123+ || fragment.data > fragment.count
124+ {
114 return None;125 return None;
115 }126 }
116 Self::Video(fragment)127 Self::Video(fragment)
@@ -140,6 +151,12 @@ impl<'a> Datagram<'a> {
140 }151 }
141 }152 }
142 153
154+fn layout(length: usize) -> (usize, usize, usize) {
155+ let shard = length.clamp(2, VIDEO_FRAGMENT_BYTES).next_multiple_of(2);
156+ let data = length.div_ceil(shard).max(1);
157+ (shard, data, data.div_ceil(VIDEO_FEC_DATA_PER_PARITY).max(1))
158+}
159+
143 pub fn fragments(160 pub fn fragments(
144 layer: Layer,161 layer: Layer,
145 frame: u32,162 frame: u32,
@@ -147,10 +164,15 @@ pub fn fragments(
147 timestamp_ms: u32,164 timestamp_ms: u32,
148 data: &[u8],165 data: &[u8],
149 ) -> Vec<Vec<u8>> {166 ) -> Vec<Vec<u8>> {
150- let chunks: Vec<&[u8]> = data.chunks(VIDEO_FRAGMENT_BYTES).collect();167+ let (shard, data_count, parity_count) = layout(data.len());
151- let count = chunks.len() as u16;168+ let count = (data_count + parity_count) as u16;
152- chunks169+ let mut padded = data.to_vec();
153- .into_iter()170+ padded.resize(data_count * shard, 0);
171+ let parity = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard))
172+ .expect("reed-solomon encode");
173+ padded
174+ .chunks(shard)
175+ .chain(parity.iter().map(Vec::as_slice))
154 .enumerate()176 .enumerate()
155 .map(|(index, payload)| {177 .map(|(index, payload)| {
156 Datagram::Video(Fragment {178 Datagram::Video(Fragment {
@@ -158,6 +180,8 @@ pub fn fragments(
158 frame,180 frame,
159 index: index as u16,181 index: index as u16,
160 count,182 count,
183+ data: data_count as u16,
184+ length: data.len() as u32,
161 keyframe,185 keyframe,
162 timestamp_ms,186 timestamp_ms,
163 payload,187 payload,
@@ -201,7 +225,7 @@ mod tests {
201 };225 };
202 let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5];226 let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5];
203 let packets = fragments(layer, 3, true, 99, &data);227 let packets = fragments(layer, 3, true, 99, &data);
204- assert_eq!(packets.len(), 2);228+ assert_eq!(packets.len(), 3);
205 229
206 let relay = encode_relay(&user_id, &packets[1]).unwrap();230 let relay = encode_relay(&user_id, &packets[1]).unwrap();
207 let (decoded_id, datagram) = decode_relay(&relay).unwrap();231 let (decoded_id, datagram) = decode_relay(&relay).unwrap();
@@ -210,7 +234,8 @@ mod tests {
210 panic!("not video");234 panic!("not video");
211 };235 };
212 assert_eq!(fragment.layer, layer);236 assert_eq!(fragment.layer, layer);
213- assert_eq!((fragment.index, fragment.count), (1, 2));237+ assert_eq!((fragment.index, fragment.count), (1, 3));
214- assert_eq!(fragment.payload.len(), 5);238+ assert_eq!((fragment.data, fragment.length), (2, data.len() as u32));
239+ assert_eq!(fragment.payload.len(), VIDEO_FRAGMENT_BYTES);
215 }240 }
216 }241 }
crates/server/src/share.rsmodified+1 -1
@@ -285,7 +285,7 @@ impl Shares {
285 Some(Datagram::Video(fragment)) => {285 Some(Datagram::Video(fragment)) => {
286 let before = sharing.layers();286 let before = sharing.layers();
287 for viewer in &mut sharing.viewers {287 for viewer in &mut sharing.viewers {
288- if fragment.keyframe && fragment.index == 0 {288+ if fragment.keyframe {
289 viewer.forward = viewer.forward.on_keyframe(fragment.layer);289 viewer.forward = viewer.forward.on_keyframe(fragment.layer);
290 }290 }
291 if viewer.forward.live() == Some(fragment.layer) {291 if viewer.forward.live() == Some(fragment.layer) {