Loss-adaptive video FEC driven by viewer shard-loss reports, evenly sized shards without tail padding, bench harness script
Browse files at this commit8cbbd6ce657a48d542fda21ed684ee954f7bc933Parent: 7acf9fc- perf
- loss-adaptive video FEC driven by viewer shard-loss reports, evenly sized shards without tail padding, bench harness script
17 changed files +369 -83
- crates/client/src/gui/share_view.rs +5 -1
- crates/client/src/net/link.rs +2 -1
- crates/client/src/net/media.rs +15 -2
- crates/client/src/share/congestion.rs +42 -1
- crates/client/src/share/reassembly.rs +94 -5
- crates/client/src/share/session.rs +59 -40
- crates/common/src/call.rs +8 -0
- crates/common/src/constant.rs +0 -1
- crates/common/src/datagram.rs +49 -23
- crates/common/src/event.rs +1 -0
- crates/common/src/transport.rs +6 -2
- crates/server/src/call/mod.rs +1 -0
- crates/server/src/call/voice.rs +17 -2
- crates/server/src/network.rs +5 -1
- crates/server/src/request.rs +11 -4
- crates/server/src/rooms.rs +17 -0
- harness/bench.sh +37 -0
crates/client/src/gui/share_view.rsmodified+5 -1
| @@ -515,7 +515,11 @@ impl Yumush { | |||
| 515 | icon_button( | 515 | icon_button( |
| 516 | format!("share_mute_{muted}"), | 516 | format!("share_mute_{muted}"), |
| 517 | palette, | 517 | palette, |
| 518 | - if muted { IconName::VolumeX } else { IconName::Volume2 }, | 518 | + if muted { |
| 519 | + IconName::VolumeX | ||
| 520 | + } else { | ||
| 521 | + IconName::Volume2 | ||
| 522 | + }, | ||
| 519 | if muted { "Unmute" } else { "Mute" }, | 523 | if muted { "Unmute" } else { "Mute" }, |
| 520 | entity_action(entity, |yumush, window, cx| { | 524 | entity_action(entity, |yumush, window, cx| { |
| 521 | yumush.toggle_share_mute(window, cx) | 525 | yumush.toggle_share_mute(window, cx) |
crates/client/src/net/link.rsmodified+2 -1
| @@ -81,7 +81,8 @@ impl Endpoints { | |||
| 81 | 81 | ||
| 82 | let bind: SocketAddr = bind.parse().map_err(|_| LinkError::Unreachable)?; | 82 | let bind: SocketAddr = bind.parse().map_err(|_| LinkError::Unreachable)?; |
| 83 | let mut endpoint = | 83 | let mut endpoint = |
| 84 | - common::transport::endpoint(bind, None).map_err(|_| LinkError::Unreachable)?; | 84 | + common::transport::endpoint(bind, quinn::EndpointConfig::default(), None) |
| 85 | + .map_err(|_| LinkError::Unreachable)?; | ||
| 85 | endpoint.set_default_client_config(config()?); | 86 | endpoint.set_default_client_config(config()?); |
| 86 | *slot = Some(endpoint.clone()); | 87 | *slot = Some(endpoint.clone()); |
| 87 | 88 | ||
crates/client/src/net/media.rsmodified+15 -2
| @@ -7,8 +7,8 @@ use std::{ | |||
| 7 | use bytes::Bytes; | 7 | use bytes::Bytes; |
| 8 | use common::{ | 8 | use common::{ |
| 9 | call::{ | 9 | call::{ |
| 10 | - Call, JoinVoice, LeaveVoice, ListShares, RequestKeyframe, StartShare, StopShare, | 10 | + Call, JoinVoice, LeaveVoice, ListShares, ReportLoss, RequestKeyframe, StartShare, |
| 11 | - UnwatchShare, WatchShare, | 11 | + StopShare, UnwatchShare, WatchShare, |
| 12 | }, | 12 | }, |
| 13 | datagram::{Packet, RELAY_PREFIX}, | 13 | datagram::{Packet, RELAY_PREFIX}, |
| 14 | event::{Event, Media as Down}, | 14 | event::{Event, Media as Down}, |
| @@ -264,6 +264,11 @@ impl Media { | |||
| 264 | sharing.keyframe(*layer); | 264 | sharing.keyframe(*layer); |
| 265 | } | 265 | } |
| 266 | } | 266 | } |
| 267 | + Down::Loss { kind, permille } => { | ||
| 268 | + if let Some(sharing) = inner.sharing.get(kind) { | ||
| 269 | + sharing.report_loss(*permille); | ||
| 270 | + } | ||
| 271 | + } | ||
| 267 | Down::VoiceEnded => { | 272 | Down::VoiceEnded => { |
| 268 | inner.end_voice(); | 273 | inner.end_voice(); |
| 269 | return true; | 274 | return true; |
| @@ -447,6 +452,14 @@ async fn tick_loop(media: Arc<Media>) { | |||
| 447 | kind: *kind, | 452 | kind: *kind, |
| 448 | }, | 453 | }, |
| 449 | )), | 454 | )), |
| 455 | + Tick::Loss(permille) => tokio::spawn(send_quietly( | ||
| 456 | + connection, | ||
| 457 | + ReportLoss { | ||
| 458 | + user_id: *user_id, | ||
| 459 | + kind: *kind, | ||
| 460 | + permille, | ||
| 461 | + }, | ||
| 462 | + )), | ||
| 450 | }; | 463 | }; |
| 451 | } | 464 | } |
| 452 | } | 465 | } |
crates/client/src/share/congestion.rsmodified+42 -1
| @@ -1,4 +1,7 @@ | |||
| 1 | -use std::time::Duration; | 1 | +use std::{ |
| 2 | + sync::atomic::{AtomicU32, Ordering}, | ||
| 3 | + time::Duration, | ||
| 4 | +}; | ||
| 2 | 5 | ||
| 3 | use quinn::Connection; | 6 | use quinn::Connection; |
| 4 | 7 | ||
| @@ -9,6 +12,37 @@ const INCREASE: f32 = 0.05; | |||
| 9 | const LOSS_LIMIT: f32 = 0.02; | 12 | const LOSS_LIMIT: f32 = 0.02; |
| 10 | const QUEUE_DELAY: Duration = Duration::from_millis(60); | 13 | const QUEUE_DELAY: Duration = Duration::from_millis(60); |
| 11 | const BUFFER_LOW: usize = 256 * 1024; | 14 | const BUFFER_LOW: usize = 256 * 1024; |
| 15 | +const INITIAL_LOSS: f32 = 0.05; | ||
| 16 | +const LOSS_DECAY: f32 = 0.9; | ||
| 17 | +const FEC_FLOOR: f32 = 0.05; | ||
| 18 | +const FEC_GAIN: f32 = 4.0; | ||
| 19 | +const FEC_MAX: f32 = 0.5; | ||
| 20 | +const KEYFRAME_FEC: f32 = 0.1; | ||
| 21 | + | ||
| 22 | +pub struct Loss(AtomicU32); | ||
| 23 | + | ||
| 24 | +impl Default for Loss { | ||
| 25 | + fn default() -> Self { | ||
| 26 | + Self(AtomicU32::new(INITIAL_LOSS.to_bits())) | ||
| 27 | + } | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +impl Loss { | ||
| 31 | + pub fn report(&self, loss: f32) { | ||
| 32 | + self.0.fetch_max(loss.max(0.0).to_bits(), Ordering::Relaxed); | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + pub fn decay(&self) { | ||
| 36 | + let loss = f32::from_bits(self.0.load(Ordering::Relaxed)) * LOSS_DECAY; | ||
| 37 | + self.0.store(loss.to_bits(), Ordering::Relaxed); | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + pub fn fec(&self, keyframe: bool) -> f32 { | ||
| 41 | + let loss = f32::from_bits(self.0.load(Ordering::Relaxed)); | ||
| 42 | + let extra = if keyframe { KEYFRAME_FEC } else { 0.0 }; | ||
| 43 | + (FEC_FLOOR + FEC_GAIN * loss + extra).min(FEC_MAX) | ||
| 44 | + } | ||
| 45 | +} | ||
| 12 | 46 | ||
| 13 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | 47 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 14 | pub struct Uplink { | 48 | pub struct Uplink { |
| @@ -34,6 +68,7 @@ impl Uplink { | |||
| 34 | 68 | ||
| 35 | pub struct Controller { | 69 | pub struct Controller { |
| 36 | scale: f32, | 70 | scale: f32, |
| 71 | + loss: f32, | ||
| 37 | base_rtt: Option<Duration>, | 72 | base_rtt: Option<Duration>, |
| 38 | last: Uplink, | 73 | last: Uplink, |
| 39 | } | 74 | } |
| @@ -42,6 +77,7 @@ impl Default for Controller { | |||
| 42 | fn default() -> Self { | 77 | fn default() -> Self { |
| 43 | Self { | 78 | Self { |
| 44 | scale: 1.0, | 79 | scale: 1.0, |
| 80 | + loss: 0.0, | ||
| 45 | base_rtt: None, | 81 | base_rtt: None, |
| 46 | last: Uplink::default(), | 82 | last: Uplink::default(), |
| 47 | } | 83 | } |
| @@ -58,6 +94,7 @@ impl Controller { | |||
| 58 | .congestion_events | 94 | .congestion_events |
| 59 | .saturating_sub(self.last.congestion_events); | 95 | .saturating_sub(self.last.congestion_events); |
| 60 | self.last = now; | 96 | self.last = now; |
| 97 | + self.loss = lost as f32 / sent.max(1) as f32; | ||
| 61 | let congested = events > 0 | 98 | let congested = events > 0 |
| 62 | || now.buffer_low | 99 | || now.buffer_low |
| 63 | || lost as f32 > sent.max(1) as f32 * LOSS_LIMIT | 100 | || lost as f32 > sent.max(1) as f32 * LOSS_LIMIT |
| @@ -68,6 +105,10 @@ impl Controller { | |||
| 68 | }; | 105 | }; |
| 69 | self.scale | 106 | self.scale |
| 70 | } | 107 | } |
| 108 | + | ||
| 109 | + pub fn loss(&self) -> f32 { | ||
| 110 | + self.loss | ||
| 111 | + } | ||
| 71 | } | 112 | } |
| 72 | 113 | ||
| 73 | #[cfg(test)] | 114 | #[cfg(test)] |
crates/client/src/share/reassembly.rsmodified+94 -5
| @@ -28,12 +28,13 @@ struct Pending { | |||
| 28 | data: usize, | 28 | data: usize, |
| 29 | length: usize, | 29 | length: usize, |
| 30 | present: usize, | 30 | present: usize, |
| 31 | + highest: usize, | ||
| 31 | shards: Vec<Option<Vec<u8>>>, | 32 | shards: Vec<Option<Vec<u8>>>, |
| 32 | } | 33 | } |
| 33 | 34 | ||
| 34 | impl Pending { | 35 | impl Pending { |
| 35 | - fn new(layer: Layer, keyframe: bool, timestamp_ms: u32, length: u32) -> Pending { | 36 | + fn new(layer: Layer, keyframe: bool, timestamp_ms: u32, length: u32, parity: u16) -> Pending { |
| 36 | - let layout = layout(length); | 37 | + let layout = layout(length, parity); |
| 37 | Pending { | 38 | Pending { |
| 38 | layer, | 39 | layer, |
| 39 | keyframe, | 40 | keyframe, |
| @@ -41,6 +42,7 @@ impl Pending { | |||
| 41 | data: layout.data, | 42 | data: layout.data, |
| 42 | length: length as usize, | 43 | length: length as usize, |
| 43 | present: 0, | 44 | present: 0, |
| 45 | + highest: 0, | ||
| 44 | shards: vec![None; layout.count()], | 46 | shards: vec![None; layout.count()], |
| 45 | } | 47 | } |
| 46 | } | 48 | } |
| @@ -51,6 +53,7 @@ impl Pending { | |||
| 51 | { | 53 | { |
| 52 | *slot = Some(shard.to_vec()); | 54 | *slot = Some(shard.to_vec()); |
| 53 | self.present += 1; | 55 | self.present += 1; |
| 56 | + self.highest = self.highest.max(usize::from(index)); | ||
| 54 | } | 57 | } |
| 55 | } | 58 | } |
| 56 | 59 | ||
| @@ -89,6 +92,9 @@ pub struct Reassembler { | |||
| 89 | phase: Phase, | 92 | phase: Phase, |
| 90 | received_frames: u32, | 93 | received_frames: u32, |
| 91 | lost_frames: u32, | 94 | lost_frames: u32, |
| 95 | + expected_shards: u32, | ||
| 96 | + missing_shards: u32, | ||
| 97 | + last_count: u32, | ||
| 92 | } | 98 | } |
| 93 | 99 | ||
| 94 | impl Default for Reassembler { | 100 | impl Default for Reassembler { |
| @@ -106,6 +112,9 @@ impl Reassembler { | |||
| 106 | phase: Phase::WaitingKeyframe, | 112 | phase: Phase::WaitingKeyframe, |
| 107 | received_frames: 0, | 113 | received_frames: 0, |
| 108 | lost_frames: 0, | 114 | lost_frames: 0, |
| 115 | + expected_shards: 0, | ||
| 116 | + missing_shards: 0, | ||
| 117 | + last_count: 1, | ||
| 109 | } | 118 | } |
| 110 | } | 119 | } |
| 111 | 120 | ||
| @@ -115,6 +124,7 @@ impl Reassembler { | |||
| 115 | keyframe, | 124 | keyframe, |
| 116 | frame, | 125 | frame, |
| 117 | index, | 126 | index, |
| 127 | + parity, | ||
| 118 | length, | 128 | length, |
| 119 | ts_ms, | 129 | ts_ms, |
| 120 | shard, | 130 | shard, |
| @@ -133,13 +143,15 @@ impl Reassembler { | |||
| 133 | return None; | 143 | return None; |
| 134 | } | 144 | } |
| 135 | if !self.pending.contains_key(&frame) && self.pending.len() >= PENDING_LIMIT { | 145 | if !self.pending.contains_key(&frame) && self.pending.len() >= PENDING_LIMIT { |
| 136 | - self.pending.clear(); | 146 | + for (_, dropped) in std::mem::take(&mut self.pending) { |
| 147 | + self.drop_pending(&dropped); | ||
| 148 | + } | ||
| 137 | self.phase = Phase::WaitingKeyframe; | 149 | self.phase = Phase::WaitingKeyframe; |
| 138 | } | 150 | } |
| 139 | let pending = self | 151 | let pending = self |
| 140 | .pending | 152 | .pending |
| 141 | .entry(frame) | 153 | .entry(frame) |
| 142 | - .or_insert_with(|| Pending::new(layer, keyframe, ts_ms, length)); | 154 | + .or_insert_with(|| Pending::new(layer, keyframe, ts_ms, length, parity)); |
| 143 | pending.insert(index, shard); | 155 | pending.insert(index, shard); |
| 144 | if !pending.is_complete() { | 156 | if !pending.is_complete() { |
| 145 | return None; | 157 | return None; |
| @@ -154,12 +166,27 @@ impl Reassembler { | |||
| 154 | .map_or(0, |last| frame.wrapping_sub(last).wrapping_sub(1)); | 166 | .map_or(0, |last| frame.wrapping_sub(last).wrapping_sub(1)); |
| 155 | let (layer, keyframe, timestamp_ms) = | 167 | let (layer, keyframe, timestamp_ms) = |
| 156 | (complete.layer, complete.keyframe, complete.timestamp_ms); | 168 | (complete.layer, complete.keyframe, complete.timestamp_ms); |
| 169 | + let seen = complete.highest + 1; | ||
| 170 | + self.expected_shards += seen as u32; | ||
| 171 | + self.missing_shards += (seen - complete.present) as u32; | ||
| 172 | + self.last_count = complete.shards.len() as u32; | ||
| 157 | let data = complete.assemble(); | 173 | let data = complete.assemble(); |
| 158 | self.last = Some(frame); | 174 | self.last = Some(frame); |
| 159 | if skipped > 0 || data.is_none() { | 175 | if skipped > 0 || data.is_none() { |
| 160 | self.lost_frames += skipped + u32::from(data.is_none()); | 176 | self.lost_frames += skipped + u32::from(data.is_none()); |
| 161 | self.phase = Phase::WaitingKeyframe; | 177 | self.phase = Phase::WaitingKeyframe; |
| 162 | - self.pending.retain(|&older, _| seq_newer(older, frame)); | 178 | + let (older, newer): (HashMap<u32, Pending>, HashMap<u32, Pending>) = |
| 179 | + std::mem::take(&mut self.pending) | ||
| 180 | + .into_iter() | ||
| 181 | + .partition(|&(number, _)| !seq_newer(number, frame)); | ||
| 182 | + self.pending = newer; | ||
| 183 | + let arrived = older.len() as u32; | ||
| 184 | + for dropped in older.values() { | ||
| 185 | + self.drop_pending(dropped); | ||
| 186 | + } | ||
| 187 | + let vanished = skipped.saturating_sub(arrived) * self.last_count; | ||
| 188 | + self.expected_shards += vanished; | ||
| 189 | + self.missing_shards += vanished; | ||
| 163 | } | 190 | } |
| 164 | let data = data?; | 191 | let data = data?; |
| 165 | self.received_frames += 1; | 192 | self.received_frames += 1; |
| @@ -177,6 +204,23 @@ impl Reassembler { | |||
| 177 | }) | 204 | }) |
| 178 | } | 205 | } |
| 179 | 206 | ||
| 207 | + fn drop_pending(&mut self, dropped: &Pending) { | ||
| 208 | + let count = dropped.shards.len() as u32; | ||
| 209 | + self.expected_shards += count; | ||
| 210 | + self.missing_shards += count - dropped.present as u32; | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + pub fn packet_loss(&mut self) -> f32 { | ||
| 214 | + let ratio = if self.expected_shards == 0 { | ||
| 215 | + 0.0 | ||
| 216 | + } else { | ||
| 217 | + self.missing_shards as f32 / self.expected_shards as f32 | ||
| 218 | + }; | ||
| 219 | + self.expected_shards = 0; | ||
| 220 | + self.missing_shards = 0; | ||
| 221 | + ratio | ||
| 222 | + } | ||
| 223 | + | ||
| 180 | pub fn needs_keyframe(&self) -> bool { | 224 | pub fn needs_keyframe(&self) -> bool { |
| 181 | self.phase == Phase::WaitingKeyframe | 225 | self.phase == Phase::WaitingKeyframe |
| 182 | } | 226 | } |
| @@ -193,3 +237,48 @@ impl Reassembler { | |||
| 193 | ratio | 237 | ratio |
| 194 | } | 238 | } |
| 195 | } | 239 | } |
| 240 | + | ||
| 241 | +#[cfg(test)] | ||
| 242 | +mod tests { | ||
| 243 | + use common::{ | ||
| 244 | + datagram::{FrameInfo, fragments}, | ||
| 245 | + share::{Codec, Fps, Kind, Quality, Resolution}, | ||
| 246 | + }; | ||
| 247 | + | ||
| 248 | + use super::*; | ||
| 249 | + | ||
| 250 | + #[test] | ||
| 251 | + fn counts_shard_loss_and_recovers_with_parity() { | ||
| 252 | + let layer = Layer { | ||
| 253 | + quality: Quality { | ||
| 254 | + resolution: Resolution::P1080, | ||
| 255 | + fps: Fps::F60, | ||
| 256 | + }, | ||
| 257 | + codec: Codec::Av1, | ||
| 258 | + }; | ||
| 259 | + let data: Vec<u8> = (0..10_000).map(|byte| byte as u8).collect(); | ||
| 260 | + let mut reassembler = Reassembler::new(); | ||
| 261 | + let mut delivered = Vec::new(); | ||
| 262 | + for frame in 0..2 { | ||
| 263 | + let info = FrameInfo { | ||
| 264 | + kind: Kind::Screen, | ||
| 265 | + layer, | ||
| 266 | + frame, | ||
| 267 | + keyframe: true, | ||
| 268 | + ts_ms: 0, | ||
| 269 | + parity: 2, | ||
| 270 | + }; | ||
| 271 | + let mut index = 0; | ||
| 272 | + fragments(info, &data, |packet| { | ||
| 273 | + if index != 3 { | ||
| 274 | + let packet = Packet::decode(packet).unwrap(); | ||
| 275 | + delivered.extend(reassembler.push(&packet).map(|frame| frame.data)); | ||
| 276 | + } | ||
| 277 | + index += 1; | ||
| 278 | + }); | ||
| 279 | + } | ||
| 280 | + assert_eq!(delivered, vec![data.clone(), data]); | ||
| 281 | + let loss = reassembler.packet_loss(); | ||
| 282 | + assert!(loss > 0.05 && loss < 0.15, "{loss}"); | ||
| 283 | + } | ||
| 284 | +} | ||
crates/client/src/share/session.rsmodified+59 -40
| @@ -15,7 +15,9 @@ use common::{ | |||
| 15 | SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, | 15 | SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, |
| 16 | VOICE_SAMPLE_RATE, | 16 | VOICE_SAMPLE_RATE, |
| 17 | }, | 17 | }, |
| 18 | - datagram::{self, Packet, RELAY_PREFIX, fragments, split, warn_if_small}, | 18 | + datagram::{ |
| 19 | + self, FrameInfo, Packet, RELAY_PREFIX, fragments, parity_for, split, warn_if_small, | ||
| 20 | + }, | ||
| 19 | model::Id, | 21 | model::Id, |
| 20 | share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options}, | 22 | share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options}, |
| 21 | }; | 23 | }; |
| @@ -29,7 +31,7 @@ use super::{ | |||
| 29 | audio_capture::{self, AudioCapture}, | 31 | audio_capture::{self, AudioCapture}, |
| 30 | camera::{self, Camera}, | 32 | camera::{self, Camera}, |
| 31 | capture::{self, Capture}, | 33 | capture::{self, Capture}, |
| 32 | - congestion::{self, Controller, Uplink}, | 34 | + congestion::{self, Controller, Loss, Uplink}, |
| 33 | encode::{self, Encoders}, | 35 | encode::{self, Encoders}, |
| 34 | frame::{Encoded, Frame}, | 36 | frame::{Encoded, Frame}, |
| 35 | pacer::Pacer, | 37 | pacer::Pacer, |
| @@ -71,6 +73,7 @@ pub enum WatchQuality { | |||
| 71 | pub enum Tick { | 73 | pub enum Tick { |
| 72 | Quality(Quality), | 74 | Quality(Quality), |
| 73 | Keyframe, | 75 | Keyframe, |
| 76 | + Loss(u16), | ||
| 74 | } | 77 | } |
| 75 | 78 | ||
| 76 | pub struct LayerStats { | 79 | pub struct LayerStats { |
| @@ -184,6 +187,7 @@ pub struct Sharing { | |||
| 184 | meter: Meter, | 187 | meter: Meter, |
| 185 | _sender: Worker, | 188 | _sender: Worker, |
| 186 | _congestion: Worker, | 189 | _congestion: Worker, |
| 190 | + loss: Arc<Loss>, | ||
| 187 | sent: Arc<Mutex<Sent>>, | 191 | sent: Arc<Mutex<Sent>>, |
| 188 | } | 192 | } |
| 189 | 193 | ||
| @@ -252,16 +256,17 @@ impl Sharing { | |||
| 252 | since: Instant::now(), | 256 | since: Instant::now(), |
| 253 | tallies: HashMap::new(), | 257 | tallies: HashMap::new(), |
| 254 | })); | 258 | })); |
| 259 | + let loss = Arc::new(Loss::default()); | ||
| 255 | let congestion = { | 260 | let congestion = { |
| 256 | - let (connection, encoders) = (connection.clone(), encoders.clone()); | 261 | + let (connection, encoders, loss) = (connection.clone(), encoders.clone(), loss.clone()); |
| 257 | Worker::spawn("share-congestion", move |stop| { | 262 | Worker::spawn("share-congestion", move |stop| { |
| 258 | - control(&connection, &encoders, stop) | 263 | + control(&connection, &encoders, &loss, stop) |
| 259 | }) | 264 | }) |
| 260 | }; | 265 | }; |
| 261 | let sender = { | 266 | let sender = { |
| 262 | - let (sent, encoders) = (sent.clone(), encoders.clone()); | 267 | + let (sent, encoders, loss) = (sent.clone(), encoders.clone(), loss.clone()); |
| 263 | Worker::spawn("share-send", move |stop| { | 268 | Worker::spawn("share-send", move |stop| { |
| 264 | - send(kind, encoded, connection, encoders, sent, stop) | 269 | + send(kind, encoded, connection, encoders, &loss, sent, stop) |
| 265 | }) | 270 | }) |
| 266 | }; | 271 | }; |
| 267 | 272 | ||
| @@ -279,6 +284,7 @@ impl Sharing { | |||
| 279 | _sender: sender, | 284 | _sender: sender, |
| 280 | _congestion: congestion, | 285 | _congestion: congestion, |
| 281 | sent, | 286 | sent, |
| 287 | + loss, | ||
| 282 | }) | 288 | }) |
| 283 | } | 289 | } |
| 284 | 290 | ||
| @@ -315,6 +321,10 @@ impl Sharing { | |||
| 315 | lock(&self.encoders).keyframe(layer); | 321 | lock(&self.encoders).keyframe(layer); |
| 316 | } | 322 | } |
| 317 | 323 | ||
| 324 | + pub fn report_loss(&self, permille: u16) { | ||
| 325 | + self.loss.report(f32::from(permille) / 1000.0); | ||
| 326 | + } | ||
| 327 | + | ||
| 318 | pub fn stats(&self) -> Vec<LayerStats> { | 328 | pub fn stats(&self) -> Vec<LayerStats> { |
| 319 | lock(&self.sent).take() | 329 | lock(&self.sent).take() |
| 320 | } | 330 | } |
| @@ -353,11 +363,13 @@ fn feed( | |||
| 353 | } | 363 | } |
| 354 | } | 364 | } |
| 355 | 365 | ||
| 356 | -fn control(connection: &Connection, encoders: &Mutex<Encoders>, stop: &AtomicBool) { | 366 | +fn control(connection: &Connection, encoders: &Mutex<Encoders>, loss: &Loss, stop: &AtomicBool) { |
| 357 | let mut controller = Controller::default(); | 367 | let mut controller = Controller::default(); |
| 358 | let mut scale = 1.0; | 368 | let mut scale = 1.0; |
| 359 | while wait(stop, congestion::PERIOD) { | 369 | while wait(stop, congestion::PERIOD) { |
| 360 | let next = controller.observe(Uplink::read(connection)); | 370 | let next = controller.observe(Uplink::read(connection)); |
| 371 | + loss.decay(); | ||
| 372 | + loss.report(controller.loss()); | ||
| 361 | if next < scale { | 373 | if next < scale { |
| 362 | tracing::info!(scale = next, "share uplink congested"); | 374 | tracing::info!(scale = next, "share uplink congested"); |
| 363 | } | 375 | } |
| @@ -373,6 +385,7 @@ fn send( | |||
| 373 | rx: Receiver<Encoded>, | 385 | rx: Receiver<Encoded>, |
| 374 | connection: Connection, | 386 | connection: Connection, |
| 375 | encoders: Arc<Mutex<Encoders>>, | 387 | encoders: Arc<Mutex<Encoders>>, |
| 388 | + loss: &Loss, | ||
| 376 | sent: Arc<Mutex<Sent>>, | 389 | sent: Arc<Mutex<Sent>>, |
| 377 | stop: &AtomicBool, | 390 | stop: &AtomicBool, |
| 378 | ) { | 391 | ) { |
| @@ -384,18 +397,18 @@ fn send( | |||
| 384 | let counter = counters.entry(item.layer).or_default(); | 397 | let counter = counters.entry(item.layer).or_default(); |
| 385 | let number = *counter; | 398 | let number = *counter; |
| 386 | *counter = counter.wrapping_add(1); | 399 | *counter = counter.wrapping_add(1); |
| 387 | - fragments( | 400 | + let info = FrameInfo { |
| 388 | kind, | 401 | kind, |
| 389 | - item.layer, | 402 | + layer: item.layer, |
| 390 | - number, | 403 | + frame: number, |
| 391 | - item.keyframe, | 404 | + keyframe: item.keyframe, |
| 392 | - item.timestamp_ms, | 405 | + ts_ms: item.timestamp_ms, |
| 393 | - &item.data, | 406 | + parity: parity_for(item.data.len() as u32, loss.fec(item.keyframe)), |
| 394 | - |packet| { | 407 | + }; |
| 395 | - pacer.wait(packet.len(), bitrate); | 408 | + fragments(info, &item.data, |packet| { |
| 396 | - datagram::send(&connection, Bytes::copy_from_slice(packet)); | 409 | + pacer.wait(packet.len(), bitrate); |
| 397 | - }, | 410 | + datagram::send(&connection, Bytes::copy_from_slice(packet)); |
| 398 | - ); | 411 | + }); |
| 399 | } | 412 | } |
| 400 | } | 413 | } |
| 401 | 414 | ||
| @@ -472,6 +485,7 @@ struct Video { | |||
| 472 | #[derive(Default)] | 485 | #[derive(Default)] |
| 473 | struct Health { | 486 | struct Health { |
| 474 | loss: f32, | 487 | loss: f32, |
| 488 | + packet_loss: Option<f32>, | ||
| 475 | lost: bool, | 489 | lost: bool, |
| 476 | served: Option<Layer>, | 490 | served: Option<Layer>, |
| 477 | keyframes: u32, | 491 | keyframes: u32, |
| @@ -644,15 +658,18 @@ impl Watching { | |||
| 644 | } | 658 | } |
| 645 | 659 | ||
| 646 | pub fn tick(&mut self) -> Vec<Tick> { | 660 | pub fn tick(&mut self) -> Vec<Tick> { |
| 647 | - let (loss, served, lost) = { | 661 | + let (loss, served, lost, packet_loss) = { |
| 648 | - let health = lock(&self.health); | 662 | + let mut health = lock(&self.health); |
| 649 | let due = self | 663 | let due = self |
| 650 | .requested | 664 | .requested |
| 651 | .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); | 665 | .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); |
| 652 | let lost = health.lost && due; | 666 | let lost = health.lost && due; |
| 653 | - (health.loss, health.served, lost) | 667 | + (health.loss, health.served, lost, health.packet_loss.take()) |
| 654 | }; | 668 | }; |
| 655 | let mut ticks = Vec::new(); | 669 | let mut ticks = Vec::new(); |
| 670 | + if let Some(packet_loss) = packet_loss.filter(|loss| *loss > 0.0) { | ||
| 671 | + ticks.push(Tick::Loss((packet_loss * 1000.0).ceil() as u16)); | ||
| 672 | + } | ||
| 656 | if lost { | 673 | if lost { |
| 657 | self.requested = Some(Instant::now()); | 674 | self.requested = Some(Instant::now()); |
| 658 | ticks.push(Tick::Keyframe); | 675 | ticks.push(Tick::Keyframe); |
| @@ -746,7 +763,9 @@ fn watch_video( | |||
| 746 | } | 763 | } |
| 747 | lock(health).lost = reassembler.needs_keyframe(); | 764 | lock(health).lost = reassembler.needs_keyframe(); |
| 748 | if sampled.elapsed() >= SAMPLE { | 765 | if sampled.elapsed() >= SAMPLE { |
| 749 | - lock(health).loss = reassembler.loss_ratio(); | 766 | + let mut health = lock(health); |
| 767 | + health.loss = reassembler.loss_ratio(); | ||
| 768 | + health.packet_loss = Some(reassembler.packet_loss()); | ||
| 750 | sampled = Instant::now(); | 769 | sampled = Instant::now(); |
| 751 | } | 770 | } |
| 752 | } | 771 | } |
| @@ -879,24 +898,24 @@ mod tests { | |||
| 879 | let mut reassembler = Reassembler::new(); | 898 | let mut reassembler = Reassembler::new(); |
| 880 | let mut pictures = Vec::new(); | 899 | let mut pictures = Vec::new(); |
| 881 | for (number, encoded) in encoded.iter().enumerate() { | 900 | for (number, encoded) in encoded.iter().enumerate() { |
| 882 | - fragments( | 901 | + let info = FrameInfo { |
| 883 | - Kind::Screen, | 902 | + kind: Kind::Screen, |
| 884 | - encoded.layer, | 903 | + layer: encoded.layer, |
| 885 | - number as u32, | 904 | + frame: number as u32, |
| 886 | - encoded.keyframe, | 905 | + keyframe: encoded.keyframe, |
| 887 | - encoded.timestamp_ms, | 906 | + ts_ms: encoded.timestamp_ms, |
| 888 | - &encoded.data, | 907 | + parity: 1, |
| 889 | - |packet| { | 908 | + }; |
| 890 | - let Some(packet) = Packet::decode(packet) else { | 909 | + fragments(info, &encoded.data, |packet| { |
| 891 | - panic!("fragment"); | 910 | + let Some(packet) = Packet::decode(packet) else { |
| 892 | - }; | 911 | + panic!("fragment"); |
| 893 | - if let Some(assembled) = reassembler.push(&packet) { | 912 | + }; |
| 894 | - pictures.extend( | 913 | + if let Some(assembled) = reassembler.push(&packet) { |
| 895 | - decoder.decode(&assembled.data, assembled.timestamp_ms), | 914 | + pictures.extend( |
| 896 | - ); | 915 | + decoder.decode(&assembled.data, assembled.timestamp_ms), |
| 897 | - } | 916 | + ); |
| 898 | - }, | 917 | + } |
| 899 | - ); | 918 | + }); |
| 900 | } | 919 | } |
| 901 | assert_eq!(pictures.len(), 10, "{codec:?} {:?}", decoder.engine()); | 920 | assert_eq!(pictures.len(), 10, "{codec:?} {:?}", decoder.engine()); |
| 902 | let last = pictures.pop().expect("picture"); | 921 | let last = pictures.pop().expect("picture"); |
crates/common/src/call.rsmodified+8 -0
| @@ -395,6 +395,13 @@ pub struct RequestKeyframe { | |||
| 395 | pub kind: Kind, | 395 | pub kind: Kind, |
| 396 | } | 396 | } |
| 397 | 397 | ||
| 398 | +#[derive(Debug, Clone, Encode, Decode)] | ||
| 399 | +pub struct ReportLoss { | ||
| 400 | + pub user_id: Id, | ||
| 401 | + pub kind: Kind, | ||
| 402 | + pub permille: u16, | ||
| 403 | +} | ||
| 404 | + | ||
| 398 | #[derive(Debug, Clone, Encode, Decode)] | 405 | #[derive(Debug, Clone, Encode, Decode)] |
| 399 | pub struct DeclineCall { | 406 | pub struct DeclineCall { |
| 400 | pub community_id: Id, | 407 | pub community_id: Id, |
| @@ -686,6 +693,7 @@ calls! { | |||
| 686 | WatchShare: User -> (); | 693 | WatchShare: User -> (); |
| 687 | UnwatchShare: User -> (); | 694 | UnwatchShare: User -> (); |
| 688 | RequestKeyframe: User -> (); | 695 | RequestKeyframe: User -> (); |
| 696 | + ReportLoss: User -> (); | ||
| 689 | DeclineCall: User -> (); | 697 | DeclineCall: User -> (); |
| 690 | ListVoiceParticipants: User -> Vec<Id>; | 698 | ListVoiceParticipants: User -> Vec<Id>; |
| 691 | ListVoiceRooms: Builder -> Vec<VoiceRoom>; | 699 | ListVoiceRooms: Builder -> Vec<VoiceRoom>; |
crates/common/src/constant.rsmodified+0 -1
| @@ -37,7 +37,6 @@ 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; | ||
| 41 | pub const MAXIMUM_SHARE_LAYERS: usize = 4; | 40 | pub const MAXIMUM_SHARE_LAYERS: usize = 4; |
| 42 | pub const SHARE_AUDIO_BITRATE: i32 = 128_000; | 41 | pub const SHARE_AUDIO_BITRATE: i32 = 128_000; |
| 43 | pub const SHARE_AUDIO_CHANNELS: usize = 2; | 42 | pub const SHARE_AUDIO_CHANNELS: usize = 2; |
crates/common/src/datagram.rsmodified+49 -23
| @@ -5,9 +5,7 @@ use quinn::{Connection, SendDatagramError}; | |||
| 5 | use tracing::warn; | 5 | use tracing::warn; |
| 6 | 6 | ||
| 7 | use crate::{ | 7 | use crate::{ |
| 8 | - constant::{ | 8 | + constant::{MAX_FRAME_BYTES, VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD}, |
| 9 | - MAX_FRAME_BYTES, VIDEO_FEC_DATA_PER_PARITY, VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD, | ||
| 10 | - }, | ||
| 11 | share::{Kind, Layer}, | 9 | share::{Kind, Layer}, |
| 12 | }; | 10 | }; |
| 13 | 11 | ||
| @@ -16,7 +14,7 @@ const MAX_DATAGRAM: usize = 1200 - 48; | |||
| 16 | 14 | ||
| 17 | pub const VOICE_HEADER: usize = 5; | 15 | pub const VOICE_HEADER: usize = 5; |
| 18 | const SHARE_AUDIO_HEADER: usize = 9; | 16 | const SHARE_AUDIO_HEADER: usize = 9; |
| 19 | -const VIDEO_HEADER: usize = 17; | 17 | +const VIDEO_HEADER: usize = 19; |
| 20 | const KEYFRAME_FLAG: u8 = 1; | 18 | const KEYFRAME_FLAG: u8 = 1; |
| 21 | 19 | ||
| 22 | const _: () = assert!(RELAY_PREFIX + VIDEO_HEADER + VIDEO_FRAGMENT_BYTES <= MAX_DATAGRAM); | 20 | const _: () = assert!(RELAY_PREFIX + VIDEO_HEADER + VIDEO_FRAGMENT_BYTES <= MAX_DATAGRAM); |
| @@ -44,6 +42,7 @@ pub enum Packet<'a> { | |||
| 44 | keyframe: bool, | 42 | keyframe: bool, |
| 45 | frame: u32, | 43 | frame: u32, |
| 46 | index: u16, | 44 | index: u16, |
| 45 | + parity: u16, | ||
| 47 | length: u32, | 46 | length: u32, |
| 48 | ts_ms: u32, | 47 | ts_ms: u32, |
| 49 | shard: &'a [u8], | 48 | shard: &'a [u8], |
| @@ -63,17 +62,21 @@ impl Layout { | |||
| 63 | } | 62 | } |
| 64 | } | 63 | } |
| 65 | 64 | ||
| 66 | -pub fn layout(length: u32) -> Layout { | 65 | +pub fn layout(length: u32, parity: u16) -> Layout { |
| 67 | let length = length as usize; | 66 | let length = length as usize; |
| 68 | - let shard = length.clamp(2, VIDEO_FRAGMENT_BYTES).next_multiple_of(2); | 67 | + let data = length.div_ceil(VIDEO_FRAGMENT_BYTES).max(1); |
| 69 | - let data = length.div_ceil(shard).max(1); | ||
| 70 | Layout { | 68 | Layout { |
| 71 | - shard, | 69 | + shard: length.div_ceil(data).max(2).next_multiple_of(2), |
| 72 | data, | 70 | data, |
| 73 | - parity: data.div_ceil(VIDEO_FEC_DATA_PER_PARITY).max(1), | 71 | + parity: usize::from(parity), |
| 74 | } | 72 | } |
| 75 | } | 73 | } |
| 76 | 74 | ||
| 75 | +pub fn parity_for(length: u32, ratio: f32) -> u16 { | ||
| 76 | + let data = (length as usize).div_ceil(VIDEO_FRAGMENT_BYTES).max(1); | ||
| 77 | + ((data as f32 * ratio).ceil() as u16).max(1) | ||
| 78 | +} | ||
| 79 | + | ||
| 77 | pub fn seq_newer(a: u32, b: u32) -> bool { | 80 | pub fn seq_newer(a: u32, b: u32) -> bool { |
| 78 | let distance = a.wrapping_sub(b); | 81 | let distance = a.wrapping_sub(b); |
| 79 | distance != 0 && distance < u32::MAX / 2 | 82 | distance != 0 && distance < u32::MAX / 2 |
| @@ -118,6 +121,7 @@ impl<'a> Packet<'a> { | |||
| 118 | keyframe, | 121 | keyframe, |
| 119 | frame, | 122 | frame, |
| 120 | index, | 123 | index, |
| 124 | + parity, | ||
| 121 | length, | 125 | length, |
| 122 | ts_ms, | 126 | ts_ms, |
| 123 | shard, | 127 | shard, |
| @@ -129,6 +133,7 @@ impl<'a> Packet<'a> { | |||
| 129 | out.extend_from_slice(&index.to_le_bytes()); | 133 | out.extend_from_slice(&index.to_le_bytes()); |
| 130 | out.extend_from_slice(&length.to_le_bytes()); | 134 | out.extend_from_slice(&length.to_le_bytes()); |
| 131 | out.extend_from_slice(&ts_ms.to_le_bytes()); | 135 | out.extend_from_slice(&ts_ms.to_le_bytes()); |
| 136 | + out.extend_from_slice(&parity.to_le_bytes()); | ||
| 132 | out.extend_from_slice(shard); | 137 | out.extend_from_slice(shard); |
| 133 | } | 138 | } |
| 134 | } | 139 | } |
| @@ -160,7 +165,8 @@ impl<'a> Packet<'a> { | |||
| 160 | if length as usize > MAX_FRAME_BYTES { | 165 | if length as usize > MAX_FRAME_BYTES { |
| 161 | return None; | 166 | return None; |
| 162 | } | 167 | } |
| 163 | - let layout = layout(length); | 168 | + let parity = u16::from_le_bytes([b[17], b[18]]); |
| 169 | + let layout = layout(length, parity); | ||
| 164 | if usize::from(index) >= layout.count() || shard.len() != layout.shard { | 170 | if usize::from(index) >= layout.count() || shard.len() != layout.shard { |
| 165 | return None; | 171 | return None; |
| 166 | } | 172 | } |
| @@ -170,6 +176,7 @@ impl<'a> Packet<'a> { | |||
| 170 | keyframe: b[2] & KEYFRAME_FLAG != 0, | 176 | keyframe: b[2] & KEYFRAME_FLAG != 0, |
| 171 | frame: u32_at(b, 3), | 177 | frame: u32_at(b, 3), |
| 172 | index, | 178 | index, |
| 179 | + parity, | ||
| 173 | length, | 180 | length, |
| 174 | ts_ms: u32_at(b, 13), | 181 | ts_ms: u32_at(b, 13), |
| 175 | shard, | 182 | shard, |
| @@ -194,31 +201,41 @@ pub fn split(b: &[u8]) -> Option<(&[u8; RELAY_PREFIX], Packet<'_>)> { | |||
| 194 | Some((from, Packet::decode(rest)?)) | 201 | Some((from, Packet::decode(rest)?)) |
| 195 | } | 202 | } |
| 196 | 203 | ||
| 197 | -pub fn fragments( | 204 | +#[derive(Debug, Clone, Copy)] |
| 198 | - kind: Kind, | 205 | +pub struct FrameInfo { |
| 199 | - layer: Layer, | 206 | + pub kind: Kind, |
| 200 | - frame: u32, | 207 | + pub layer: Layer, |
| 201 | - keyframe: bool, | 208 | + pub frame: u32, |
| 202 | - ts_ms: u32, | 209 | + pub keyframe: bool, |
| 203 | - data: &[u8], | 210 | + pub ts_ms: u32, |
| 204 | - mut emit: impl FnMut(&[u8]), | 211 | + pub parity: u16, |
| 205 | -) { | 212 | +} |
| 213 | + | ||
| 214 | +pub fn fragments(info: FrameInfo, data: &[u8], mut emit: impl FnMut(&[u8])) { | ||
| 215 | + let FrameInfo { | ||
| 216 | + kind, | ||
| 217 | + layer, | ||
| 218 | + frame, | ||
| 219 | + keyframe, | ||
| 220 | + ts_ms, | ||
| 221 | + parity, | ||
| 222 | + } = info; | ||
| 206 | let length = data.len() as u32; | 223 | let length = data.len() as u32; |
| 207 | let Layout { | 224 | let Layout { |
| 208 | shard, | 225 | shard, |
| 209 | data: data_count, | 226 | data: data_count, |
| 210 | parity: parity_count, | 227 | parity: parity_count, |
| 211 | - } = layout(length); | 228 | + } = layout(length, parity); |
| 212 | let mut padded = data.to_vec(); | 229 | let mut padded = data.to_vec(); |
| 213 | padded.resize(data_count * shard, 0); | 230 | padded.resize(data_count * shard, 0); |
| 214 | - let Ok(parity) = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard)) | 231 | + let Ok(recovery) = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard)) |
| 215 | else { | 232 | else { |
| 216 | return; | 233 | return; |
| 217 | }; | 234 | }; |
| 218 | let mut out = Vec::with_capacity(VIDEO_HEADER + shard); | 235 | let mut out = Vec::with_capacity(VIDEO_HEADER + shard); |
| 219 | for (index, shard) in padded | 236 | for (index, shard) in padded |
| 220 | .chunks(shard) | 237 | .chunks(shard) |
| 221 | - .chain(parity.iter().map(Vec::as_slice)) | 238 | + .chain(recovery.iter().map(Vec::as_slice)) |
| 222 | .enumerate() | 239 | .enumerate() |
| 223 | { | 240 | { |
| 224 | out.clear(); | 241 | out.clear(); |
| @@ -228,6 +245,7 @@ pub fn fragments( | |||
| 228 | keyframe, | 245 | keyframe, |
| 229 | frame, | 246 | frame, |
| 230 | index: index as u16, | 247 | index: index as u16, |
| 248 | + parity, | ||
| 231 | length, | 249 | length, |
| 232 | ts_ms, | 250 | ts_ms, |
| 233 | shard, | 251 | shard, |
| @@ -297,7 +315,15 @@ mod tests { | |||
| 297 | 315 | ||
| 298 | let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5]; | 316 | let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5]; |
| 299 | let mut count = 0; | 317 | let mut count = 0; |
| 300 | - fragments(Kind::Camera, layer, 3, true, 99, &data, |packet| { | 318 | + let info = FrameInfo { |
| 319 | + kind: Kind::Camera, | ||
| 320 | + layer, | ||
| 321 | + frame: 3, | ||
| 322 | + keyframe: true, | ||
| 323 | + ts_ms: 99, | ||
| 324 | + parity: 1, | ||
| 325 | + }; | ||
| 326 | + fragments(info, &data, |packet| { | ||
| 301 | let Some(Packet::Video { | 327 | let Some(Packet::Video { |
| 302 | kind, | 328 | kind, |
| 303 | keyframe, | 329 | keyframe, |
crates/common/src/event.rsmodified+1 -0
| @@ -86,6 +86,7 @@ pub enum Event { | |||
| 86 | pub enum Media { | 86 | pub enum Media { |
| 87 | Layers { kind: Kind, layers: Vec<Layer> }, | 87 | Layers { kind: Kind, layers: Vec<Layer> }, |
| 88 | Keyframe { kind: Kind, layer: Layer }, | 88 | Keyframe { kind: Kind, layer: Layer }, |
| 89 | + Loss { kind: Kind, permille: u16 }, | ||
| 89 | VoiceEnded, | 90 | VoiceEnded, |
| 90 | } | 91 | } |
| 91 | 92 | ||
crates/common/src/transport.rsmodified+6 -2
| @@ -21,12 +21,16 @@ pub fn transport() -> TransportConfig { | |||
| 21 | config | 21 | config |
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | -pub fn endpoint(bind: SocketAddr, server: Option<ServerConfig>) -> io::Result<Endpoint> { | 24 | +pub fn endpoint( |
| 25 | + bind: SocketAddr, | ||
| 26 | + config: EndpointConfig, | ||
| 27 | + server: Option<ServerConfig>, | ||
| 28 | +) -> io::Result<Endpoint> { | ||
| 25 | let socket = Socket::new(Domain::for_address(bind), Type::DGRAM, Some(Protocol::UDP))?; | 29 | let socket = Socket::new(Domain::for_address(bind), Type::DGRAM, Some(Protocol::UDP))?; |
| 26 | let _ = socket.set_recv_buffer_size(SOCKET_BUFFER_BYTES); | 30 | let _ = socket.set_recv_buffer_size(SOCKET_BUFFER_BYTES); |
| 27 | let _ = socket.set_send_buffer_size(SOCKET_BUFFER_BYTES); | 31 | let _ = socket.set_send_buffer_size(SOCKET_BUFFER_BYTES); |
| 28 | socket.bind(&bind.into())?; | 32 | socket.bind(&bind.into())?; |
| 29 | - Endpoint::new(EndpointConfig::default(), server, socket.into(), Arc::new(TokioRuntime)) | 33 | + Endpoint::new(config, server, socket.into(), Arc::new(TokioRuntime)) |
| 30 | } | 34 | } |
| 31 | 35 | ||
| 32 | #[repr(u32)] | 36 | #[repr(u32)] |
crates/server/src/call/mod.rsmodified+1 -0
| @@ -169,6 +169,7 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> { | |||
| 169 | Request::WatchShare(call) => serve(call, cx).await, | 169 | Request::WatchShare(call) => serve(call, cx).await, |
| 170 | Request::UnwatchShare(call) => serve(call, cx).await, | 170 | Request::UnwatchShare(call) => serve(call, cx).await, |
| 171 | Request::RequestKeyframe(call) => serve(call, cx).await, | 171 | Request::RequestKeyframe(call) => serve(call, cx).await, |
| 172 | + Request::ReportLoss(call) => serve(call, cx).await, | ||
| 172 | Request::DeclineCall(call) => serve(call, cx).await, | 173 | Request::DeclineCall(call) => serve(call, cx).await, |
| 173 | Request::ListVoiceParticipants(call) => serve(call, cx).await, | 174 | Request::ListVoiceParticipants(call) => serve(call, cx).await, |
| 174 | Request::ListVoiceRooms(call) => serve(call, cx).await, | 175 | Request::ListVoiceRooms(call) => serve(call, cx).await, |
crates/server/src/call/voice.rsmodified+17 -2
| @@ -1,8 +1,8 @@ | |||
| 1 | use common::{ | 1 | use common::{ |
| 2 | call::{ | 2 | call::{ |
| 3 | DeclineCall, JoinVoice, KickFromVoice, LeaveVoice, ListShares, ListVoiceParticipants, | 3 | DeclineCall, JoinVoice, KickFromVoice, LeaveVoice, ListShares, ListVoiceParticipants, |
| 4 | - ListVoiceRooms, RequestKeyframe, ServerMute, StartShare, StopShare, UnwatchShare, | 4 | + ListVoiceRooms, ReportLoss, RequestKeyframe, ServerMute, StartShare, StopShare, |
| 5 | - WatchShare, | 5 | + UnwatchShare, WatchShare, |
| 6 | }, | 6 | }, |
| 7 | error::Error, | 7 | error::Error, |
| 8 | event::Event, | 8 | event::Event, |
| @@ -169,6 +169,21 @@ impl Handle for RequestKeyframe { | |||
| 169 | } | 169 | } |
| 170 | } | 170 | } |
| 171 | 171 | ||
| 172 | +impl Handle for ReportLoss { | ||
| 173 | + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | ||
| 174 | + me.user()?; | ||
| 175 | + let loss = cx | ||
| 176 | + .sh | ||
| 177 | + .services | ||
| 178 | + .rooms | ||
| 179 | + .loss(cx.client.id, self.user_id, self.kind, self.permille) | ||
| 180 | + .ok_or(Error::NotFound)?; | ||
| 181 | + cx.out.push(loss); | ||
| 182 | + | ||
| 183 | + Ok(()) | ||
| 184 | + } | ||
| 185 | +} | ||
| 186 | + | ||
| 172 | impl Handle for DeclineCall { | 187 | impl Handle for DeclineCall { |
| 173 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 188 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 174 | let me = me.user()?; | 189 | let me = me.user()?; |
crates/server/src/network.rsmodified+5 -1
| @@ -59,7 +59,11 @@ pub async fn serve( | |||
| 59 | directory: PathBuf, | 59 | directory: PathBuf, |
| 60 | backups: PathBuf, | 60 | backups: PathBuf, |
| 61 | ) -> Result<(), ServerError> { | 61 | ) -> Result<(), ServerError> { |
| 62 | - let endpoint = transport::endpoint(server_address.parse()?, Some(server_config))?; | 62 | + let endpoint = transport::endpoint( |
| 63 | + server_address.parse()?, | ||
| 64 | + quinn::EndpointConfig::default(), | ||
| 65 | + Some(server_config), | ||
| 66 | + )?; | ||
| 63 | info!("listening on {server_address}"); | 67 | info!("listening on {server_address}"); |
| 64 | 68 | ||
| 65 | let shared = Shared { | 69 | let shared = Shared { |
crates/server/src/request.rsmodified+11 -4
| @@ -55,7 +55,11 @@ pub async fn presence_changed( | |||
| 55 | Ok(vec![Broadcast::new(To::Related(user_id), event)]) | 55 | Ok(vec![Broadcast::new(To::Related(user_id), event)]) |
| 56 | } | 56 | } |
| 57 | 57 | ||
| 58 | -pub(crate) async fn introduce(user_id: Id, others: &[Id], cx: &mut Cx<'_>) -> Result<(), ServerError> { | 58 | +pub(crate) async fn introduce( |
| 59 | + user_id: Id, | ||
| 60 | + others: &[Id], | ||
| 61 | + cx: &mut Cx<'_>, | ||
| 62 | +) -> Result<(), ServerError> { | ||
| 59 | let hub = &cx.sh.services.hub; | 63 | let hub = &cx.sh.services.hub; |
| 60 | let presence = effective_presence(hub, user_id, cx.db).await?; | 64 | let presence = effective_presence(hub, user_id, cx.db).await?; |
| 61 | for &other in others { | 65 | for &other in others { |
| @@ -63,7 +67,10 @@ pub(crate) async fn introduce(user_id: Id, others: &[Id], cx: &mut Cx<'_>) -> Re | |||
| 63 | continue; | 67 | continue; |
| 64 | } | 68 | } |
| 65 | let theirs = effective_presence(hub, other, cx.db).await?; | 69 | let theirs = effective_presence(hub, other, cx.db).await?; |
| 66 | - cx.emit(To::User(other), Event::PresenceChanged { user_id, presence }); | 70 | + cx.emit( |
| 71 | + To::User(other), | ||
| 72 | + Event::PresenceChanged { user_id, presence }, | ||
| 73 | + ); | ||
| 67 | cx.emit( | 74 | cx.emit( |
| 68 | To::User(user_id), | 75 | To::User(user_id), |
| 69 | Event::PresenceChanged { | 76 | Event::PresenceChanged { |
| @@ -333,8 +340,8 @@ mod tests { | |||
| 333 | use common::{ | 340 | use common::{ |
| 334 | call::{ | 341 | call::{ |
| 335 | AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, | 342 | AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, |
| 336 | - DeleteCommunity, FindUser, Invite, Kick, LeaveCommunity, ListCommunities, | 343 | + DeleteCommunity, FindUser, Invite, Kick, LeaveCommunity, ListCommunities, ListFriends, |
| 337 | - ListFriends, UpdateCommunity, | 344 | + UpdateCommunity, |
| 338 | }, | 345 | }, |
| 339 | error::Error as CommonError, | 346 | error::Error as CommonError, |
| 340 | model::{Id, Role}, | 347 | model::{Id, Role}, |
crates/server/src/rooms.rsmodified+17 -0
| @@ -623,6 +623,23 @@ impl Rooms { | |||
| 623 | )) | 623 | )) |
| 624 | } | 624 | } |
| 625 | 625 | ||
| 626 | + pub fn loss(&self, id: ConnId, sharer_id: Id, kind: Kind, permille: u16) -> Option<Broadcast> { | ||
| 627 | + let mut inner = self.0.lock().unwrap(); | ||
| 628 | + let sharer_conn = inner.seat_conn(sharer_id)?; | ||
| 629 | + let (_, room) = inner.seat_mut(id)?; | ||
| 630 | + let viewer_id = room.seats.get(&id)?.user_id; | ||
| 631 | + room.seats | ||
| 632 | + .get(&sharer_conn)? | ||
| 633 | + .shares | ||
| 634 | + .get(&kind)? | ||
| 635 | + .viewer(viewer_id)?; | ||
| 636 | + | ||
| 637 | + Some(Broadcast::media( | ||
| 638 | + sharer_conn, | ||
| 639 | + Media::Loss { kind, permille }, | ||
| 640 | + )) | ||
| 641 | + } | ||
| 642 | + | ||
| 626 | pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec<Broadcast> { | 643 | pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec<Broadcast> { |
| 627 | let mut inner = self.0.lock().unwrap(); | 644 | let mut inner = self.0.lock().unwrap(); |
| 628 | let Some((_, room)) = inner.seat_mut(from.id) else { | 645 | let Some((_, room)) = inner.seat_mut(from.id) else { |
harness/bench.shadded+37 -0
| @@ -0,0 +1,37 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +set -euo pipefail | ||
| 3 | +HERE="$(cd "$(dirname "$0")" && pwd)" | ||
| 4 | +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" | ||
| 5 | +CAPTURE="${CAPTURE:-2560x1440@60}" | ||
| 6 | +WARM="${WARM:-60}" | ||
| 7 | +SPAN="${SPAN:-20}" | ||
| 8 | +export HARNESS_STATE="$STATE" | ||
| 9 | +E="$STATE/env2" | ||
| 10 | +lo() { awk '/^ *lo:/ {print $2}' /proc/net/dev; } | ||
| 11 | +drops() { awk '/^Udp:/ {v=$6} END {print v}' /proc/net/snmp; } | ||
| 12 | + | ||
| 13 | +"$HERE/up.sh" >/dev/null | ||
| 14 | +YUMUSH_TEST_CAMERA=1 YUMUSH_TEST_CAPTURE="$CAPTURE" "$HERE/client.sh" alice >/dev/null | ||
| 15 | +ENV_FILE="$E" "$HERE/client.sh" bob >/dev/null | ||
| 16 | +sleep 6 | ||
| 17 | +"$HERE/ui.sh" click 877 456 | ||
| 18 | +ENV_FILE="$E" "$HERE/ui.sh" click 877 456 | ||
| 19 | +sleep 4 | ||
| 20 | +(source "$STATE/env"; niri msg action maximize-column) | ||
| 21 | +(source "$E"; niri msg action maximize-column) | ||
| 22 | +sleep 2 | ||
| 23 | +"$HERE/ui.sh" click 1820 29 | ||
| 24 | +sleep 2 | ||
| 25 | +ENV_FILE="$E" "$HERE/ui.sh" click 1820 29 | ||
| 26 | +sleep 3 | ||
| 27 | +"$HERE/ui.sh" click 144 998 | ||
| 28 | +sleep 4 | ||
| 29 | +ENV_FILE="$E" "$HERE/ui.sh" click 320 105 | ||
| 30 | +sleep "$WARM" | ||
| 31 | +b=$(lo); d=$(drops) | ||
| 32 | +sleep "$SPAN" | ||
| 33 | +a=$(lo); D=$(drops) | ||
| 34 | +echo "loopback kbps: $(( (a - b) * 8 / 1000 / SPAN )) udp drops: $((D - d))" | ||
| 35 | +grep -h "share watch quality" "$STATE/bob.log" | sed 's/\x1b\[[0-9;]*m//g' | tail -1 || true | ||
| 36 | +ENV_FILE="$E" "$HERE/shot.sh" bench >/dev/null | ||
| 37 | +"$HERE/down.sh" >/dev/null 2>&1 | ||