Server NACK retransmit, RPS loss recovery (edith c4111899), adaptive playout, delay-based quality adapt, static frame skip, voice 32k + loss-driven FEC, no voice echo, single-copy frames to GPU
Browse files at this commita2e75c8843d2f1453269d0d3b2f52240d69127a0Parent: a95ba4a- perf
- server NACK retransmit, RPS loss recovery (edith c4111899), adaptive playout, delay-based quality adapt, static frame skip, voice 32k + loss-driven FEC, no voice echo, single-copy frames to GPU
23 changed files +1050 -177
- crates/client/Cargo.toml +11 -11
- crates/client/src/gui/camera_view.rs +5 -5
- crates/client/src/gui/chat.rs +1 -0
- crates/client/src/gui/media_view.rs +6 -0
- crates/client/src/gui/share_view.rs +13 -5
- crates/client/src/gui/wave.rs +5 -0
- crates/client/src/main.rs +9 -1
- crates/client/src/net/media.rs +23 -6
- crates/client/src/net/mod.rs +1 -0
- crates/client/src/share/encode.rs +104 -21
- crates/client/src/share/frame.rs +1 -0
- crates/client/src/share/reassembly.rs +324 -58
- crates/client/src/share/session.rs +237 -42
- crates/client/src/voice/engine.rs +21 -6
- crates/client/src/voice/mod.rs +27 -4
- crates/common/src/call.rs +1 -0
- crates/common/src/constant.rs +1 -1
- crates/common/src/datagram.rs +84 -3
- crates/common/src/event.rs +5 -1
- crates/server/src/call/voice.rs +1 -1
- crates/server/src/rooms.rs +159 -9
- harness/bench.sh +3 -2
- harness/talk.sh +8 -1
crates/client/Cargo.tomlmodified+11 -11
| @@ -12,17 +12,17 @@ tokio.workspace = true | |||
| 12 | quinn = { workspace = true, features = ["rustls-ring"] } | 12 | quinn = { workspace = true, features = ["rustls-ring"] } |
| 13 | 13 | ||
| 14 | gpui-kit = { version = "0.11.0", features = ["syntect"] } | 14 | gpui-kit = { version = "0.11.0", features = ["syntect"] } |
| 15 | -ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 15 | +ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 16 | -ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 16 | +ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 17 | -ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 17 | +ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 18 | -ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 18 | +ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 19 | -ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 19 | +ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 20 | -ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 20 | +ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 21 | -ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 21 | +ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 22 | -ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 22 | +ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 23 | -ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 23 | +ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 24 | -ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 24 | +ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 25 | -ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "299aff6793c2ca5b1b0cd9f192393245e4ee0af6" } | 25 | +ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c41118999fb42403cf9a01e109f8f9a010992ec3" } |
| 26 | ureq = "3.5.2" | 26 | ureq = "3.5.2" |
| 27 | bytes = "1.12.2" | 27 | bytes = "1.12.2" |
| 28 | tracing = "0.1.44" | 28 | tracing = "0.1.44" |
crates/client/src/gui/camera_view.rsmodified+5 -5
| @@ -10,7 +10,7 @@ use gpui_kit::{ | |||
| 10 | 10 | ||
| 11 | use super::{ | 11 | use super::{ |
| 12 | Palette, Tooltip as _, Yumush, avatar, clickable, | 12 | Palette, Tooltip as _, Yumush, avatar, clickable, |
| 13 | - media_view::to_render_image, | 13 | + media_view::into_render_image, |
| 14 | notify_error, | 14 | notify_error, |
| 15 | share_view::{self, FRAME_TICK}, | 15 | share_view::{self, FRAME_TICK}, |
| 16 | text, | 16 | text, |
| @@ -107,14 +107,14 @@ impl Yumush { | |||
| 107 | } | 107 | } |
| 108 | 108 | ||
| 109 | for (&(user_id, kind), tile) in self.chat.tiles.iter_mut() { | 109 | for (&(user_id, kind), tile) in self.chat.tiles.iter_mut() { |
| 110 | + if viewing == Some((user_id, kind)) { | ||
| 111 | + continue; | ||
| 112 | + } | ||
| 110 | let Some(frame) = self.network.share_frame(user_id, kind) else { | 113 | let Some(frame) = self.network.share_frame(user_id, kind) else { |
| 111 | continue; | 114 | continue; |
| 112 | }; | 115 | }; |
| 113 | - if tile.generation == Some(frame.generation) { | ||
| 114 | - continue; | ||
| 115 | - } | ||
| 116 | tile.generation = Some(frame.generation); | 116 | tile.generation = Some(frame.generation); |
| 117 | - let next = to_render_image(&frame); | 117 | + let next = into_render_image(frame); |
| 118 | if let Some(old) = std::mem::replace(&mut tile.frame, next) { | 118 | if let Some(old) = std::mem::replace(&mut tile.frame, next) { |
| 119 | cx.drop_image(old, None); | 119 | cx.drop_image(old, None); |
| 120 | } | 120 | } |
crates/client/src/gui/chat.rsmodified+1 -0
| @@ -1179,6 +1179,7 @@ impl Chat { | |||
| 1179 | loss = stat.loss, | 1179 | loss = stat.loss, |
| 1180 | keyframes = stat.keyframes, | 1180 | keyframes = stat.keyframes, |
| 1181 | latency = stat.latency_ms, | 1181 | latency = stat.latency_ms, |
| 1182 | + nacks = stat.nacks, | ||
| 1182 | "watch" | 1183 | "watch" |
| 1183 | ); | 1184 | ); |
| 1184 | } | 1185 | } |
crates/client/src/gui/media_view.rsmodified+6 -0
| @@ -167,6 +167,12 @@ pub(super) async fn upload_file( | |||
| 167 | uploaded | 167 | uploaded |
| 168 | } | 168 | } |
| 169 | 169 | ||
| 170 | +pub(super) fn into_render_image(frame: crate::media::Frame) -> Option<Arc<RenderImage>> { | ||
| 171 | + let bgra = Arc::try_unwrap(frame.bgra).unwrap_or_else(|shared| (*shared).clone()); | ||
| 172 | + let buffer = image::RgbaImage::from_raw(frame.width, frame.height, bgra)?; | ||
| 173 | + Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) | ||
| 174 | +} | ||
| 175 | + | ||
| 170 | pub(super) fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> { | 176 | pub(super) fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> { |
| 171 | let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; | 177 | let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; |
| 172 | Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) | 178 | Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) |
crates/client/src/gui/share_view.rsmodified+13 -5
| @@ -29,7 +29,7 @@ use super::{ | |||
| 29 | Palette, Tooltip as _, Trigger, Yumush, camera_view, | 29 | Palette, Tooltip as _, Trigger, Yumush, camera_view, |
| 30 | chat::View, | 30 | chat::View, |
| 31 | clickable, entity_action, | 31 | clickable, entity_action, |
| 32 | - media_view::to_render_image, | 32 | + media_view::into_render_image, |
| 33 | notify_error, pop_in, | 33 | notify_error, pop_in, |
| 34 | settings_page::segmented, | 34 | settings_page::segmented, |
| 35 | text, | 35 | text, |
| @@ -367,11 +367,19 @@ impl Yumush { | |||
| 367 | let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else { | 367 | let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else { |
| 368 | return; | 368 | return; |
| 369 | }; | 369 | }; |
| 370 | - if viewer.generation == Some(frame.generation) { | ||
| 371 | - return; | ||
| 372 | - } | ||
| 373 | viewer.generation = Some(frame.generation); | 370 | viewer.generation = Some(frame.generation); |
| 374 | - let next = to_render_image(&frame); | 371 | + let next = into_render_image(frame); |
| 372 | + if let Some(tile) = self.chat.tiles.get_mut(&(viewer.user_id, viewer.kind)) { | ||
| 373 | + tile.generation = viewer.generation; | ||
| 374 | + if let Some(old) = std::mem::replace(&mut tile.frame, next.clone()) | ||
| 375 | + && !viewer | ||
| 376 | + .frame | ||
| 377 | + .as_ref() | ||
| 378 | + .is_some_and(|current| Arc::ptr_eq(current, &old)) | ||
| 379 | + { | ||
| 380 | + cx.drop_image(old, None); | ||
| 381 | + } | ||
| 382 | + } | ||
| 375 | if let Some(old) = std::mem::replace(&mut viewer.frame, next) { | 383 | if let Some(old) = std::mem::replace(&mut viewer.frame, next) { |
| 376 | cx.drop_image(old, None); | 384 | cx.drop_image(old, None); |
| 377 | } | 385 | } |
crates/client/src/gui/wave.rsmodified+5 -0
| @@ -58,6 +58,11 @@ fn advance(waves: &mut HashMap<Id, Wave>, levels: Vec<(Id, Vec<f32>)>) -> bool { | |||
| 58 | impl Waves { | 58 | impl Waves { |
| 59 | pub fn update(&mut self, levels: Levels, me: Option<Id>, silent: bool) -> bool { | 59 | pub fn update(&mut self, levels: Levels, me: Option<Id>, silent: bool) -> bool { |
| 60 | let mut voice = levels.voice; | 60 | let mut voice = levels.voice; |
| 61 | + if let Some(me) = me | ||
| 62 | + && !levels.own.is_empty() | ||
| 63 | + { | ||
| 64 | + voice.push((me, levels.own)); | ||
| 65 | + } | ||
| 61 | if silent { | 66 | if silent { |
| 62 | voice.retain(|(id, _)| Some(*id) != me); | 67 | voice.retain(|(id, _)| Some(*id) != me); |
| 63 | } | 68 | } |
crates/client/src/main.rsmodified+9 -1
| @@ -20,7 +20,15 @@ fn main() { | |||
| 20 | .with( | 20 | .with( |
| 21 | Targets::new() | 21 | Targets::new() |
| 22 | .with_default(Level::INFO) | 22 | .with_default(Level::INFO) |
| 23 | - .with_target("zbus", Level::ERROR), | 23 | + .with_target("zbus", Level::ERROR) |
| 24 | + .with_target( | ||
| 25 | + "metrics", | ||
| 26 | + if std::env::var_os("YUMUSH_METRICS").is_some() { | ||
| 27 | + Level::DEBUG | ||
| 28 | + } else { | ||
| 29 | + Level::INFO | ||
| 30 | + }, | ||
| 31 | + ), | ||
| 24 | ) | 32 | ) |
| 25 | .init(); | 33 | .init(); |
| 26 | 34 | ||
crates/client/src/net/media.rsmodified+23 -6
| @@ -81,10 +81,11 @@ impl Inner { | |||
| 81 | self.want_voice = Some(want); | 81 | self.want_voice = Some(want); |
| 82 | } | 82 | } |
| 83 | 83 | ||
| 84 | - fn watch_requests(&self) -> Vec<((Id, Kind), WatchShare)> { | 84 | + fn watch_requests(&self, connection: &Connection) -> Vec<((Id, Kind), WatchShare)> { |
| 85 | self.watching | 85 | self.watching |
| 86 | .iter() | 86 | .iter() |
| 87 | .map(|((user_id, kind), watching)| { | 87 | .map(|((user_id, kind), watching)| { |
| 88 | + watching.connect(connection.clone()); | ||
| 88 | let request = watch_request(*user_id, *kind, watching.wanted()); | 89 | let request = watch_request(*user_id, *kind, watching.wanted()); |
| 89 | ((*user_id, *kind), request) | 90 | ((*user_id, *kind), request) |
| 90 | }) | 91 | }) |
| @@ -215,7 +216,7 @@ impl Media { | |||
| 215 | && inner.voice.is_none() => | 216 | && inner.voice.is_none() => |
| 216 | { | 217 | { |
| 217 | inner.install_voice(voice, wanted); | 218 | inner.install_voice(voice, wanted); |
| 218 | - Some(inner.watch_requests()) | 219 | + Some(inner.watch_requests(&connection)) |
| 219 | } | 220 | } |
| 220 | _ => return, | 221 | _ => return, |
| 221 | } | 222 | } |
| @@ -254,9 +255,13 @@ impl Media { | |||
| 254 | sharing.set_layers(layers); | 255 | sharing.set_layers(layers); |
| 255 | } | 256 | } |
| 256 | } | 257 | } |
| 257 | - Down::Keyframe { kind, layer } => { | 258 | + Down::Keyframe { |
| 259 | + kind, | ||
| 260 | + layer, | ||
| 261 | + recover, | ||
| 262 | + } => { | ||
| 258 | if let Some(sharing) = inner.sharing.get(kind) { | 263 | if let Some(sharing) = inner.sharing.get(kind) { |
| 259 | - sharing.keyframe(*layer); | 264 | + sharing.keyframe(*layer, *recover); |
| 260 | } | 265 | } |
| 261 | } | 266 | } |
| 262 | Down::Loss { kind, permille } => { | 267 | Down::Loss { kind, permille } => { |
| @@ -284,6 +289,15 @@ impl Media { | |||
| 284 | } | 289 | } |
| 285 | Packet::ScreenAudio { .. } => Kind::Screen, | 290 | Packet::ScreenAudio { .. } => Kind::Screen, |
| 286 | Packet::Video { kind, .. } => kind, | 291 | Packet::Video { kind, .. } => kind, |
| 292 | + Packet::Nack { .. } => return, | ||
| 293 | + Packet::Ack { | ||
| 294 | + kind, layer, ts_ms, .. | ||
| 295 | + } => { | ||
| 296 | + if let Some(sharing) = inner.sharing.get(&kind) { | ||
| 297 | + sharing.ack(layer, ts_ms); | ||
| 298 | + } | ||
| 299 | + return; | ||
| 300 | + } | ||
| 287 | }; | 301 | }; |
| 288 | let key = (Id::from_be_bytes(*from), kind); | 302 | let key = (Id::from_be_bytes(*from), kind); |
| 289 | if let Some(watching) = inner.watching.get(&key) { | 303 | if let Some(watching) = inner.watching.get(&key) { |
| @@ -441,11 +455,12 @@ async fn tick_loop(media: Arc<Media>) { | |||
| 441 | connection, | 455 | connection, |
| 442 | watch_request(*user_id, *kind, quality), | 456 | watch_request(*user_id, *kind, quality), |
| 443 | )), | 457 | )), |
| 444 | - Tick::Keyframe => tokio::spawn(send_quietly( | 458 | + Tick::Keyframe { recover } => tokio::spawn(send_quietly( |
| 445 | connection, | 459 | connection, |
| 446 | RequestKeyframe { | 460 | RequestKeyframe { |
| 447 | user_id: *user_id, | 461 | user_id: *user_id, |
| 448 | kind: *kind, | 462 | kind: *kind, |
| 463 | + recover, | ||
| 449 | }, | 464 | }, |
| 450 | )), | 465 | )), |
| 451 | Tick::Loss(permille) => tokio::spawn(send_quietly( | 466 | Tick::Loss(permille) => tokio::spawn(send_quietly( |
| @@ -569,6 +584,7 @@ impl NetworkHandle { | |||
| 569 | let inner = self.media().lock(); | 584 | let inner = self.media().lock(); |
| 570 | Levels { | 585 | Levels { |
| 571 | voice: inner.voice.as_ref().map(Voice::levels).unwrap_or_default(), | 586 | voice: inner.voice.as_ref().map(Voice::levels).unwrap_or_default(), |
| 587 | + own: inner.voice.as_ref().map(Voice::own_level).unwrap_or_default(), | ||
| 572 | watching: inner | 588 | watching: inner |
| 573 | .watching | 589 | .watching |
| 574 | .iter() | 590 | .iter() |
| @@ -644,7 +660,7 @@ impl NetworkHandle { | |||
| 644 | ) -> Result<(), Fail> { | 660 | ) -> Result<(), Fail> { |
| 645 | let media = self.media().clone(); | 661 | let media = self.media().clone(); |
| 646 | let key = (user_id, kind); | 662 | let key = (user_id, kind); |
| 647 | - let watching = Watching::new(kind, watch, top, volume, choice); | 663 | + let watching = Watching::new(user_id, kind, watch, top, volume, choice); |
| 648 | let quality = watching.wanted(); | 664 | let quality = watching.wanted(); |
| 649 | 665 | ||
| 650 | self.media() | 666 | self.media() |
| @@ -655,6 +671,7 @@ impl NetworkHandle { | |||
| 655 | if !inner.current(epoch) { | 671 | if !inner.current(epoch) { |
| 656 | return Err(Fail::Offline); | 672 | return Err(Fail::Offline); |
| 657 | } | 673 | } |
| 674 | + watching.connect(connection.clone()); | ||
| 658 | inner.watching.insert(key, watching); | 675 | inner.watching.insert(key, watching); |
| 659 | } | 676 | } |
| 660 | let result = call(&connection, watch_request(key.0, kind, quality)).await; | 677 | let result = call(&connection, watch_request(key.0, kind, quality)).await; |
crates/client/src/net/mod.rsmodified+1 -0
| @@ -42,6 +42,7 @@ struct Shared { | |||
| 42 | #[derive(Default)] | 42 | #[derive(Default)] |
| 43 | pub struct Levels { | 43 | pub struct Levels { |
| 44 | pub voice: Vec<(Id, Vec<f32>)>, | 44 | pub voice: Vec<(Id, Vec<f32>)>, |
| 45 | + pub own: Vec<f32>, | ||
| 45 | pub watching: Vec<(Id, Vec<f32>)>, | 46 | pub watching: Vec<(Id, Vec<f32>)>, |
| 46 | pub sharing: Option<Vec<f32>>, | 47 | pub sharing: Option<Vec<f32>>, |
| 47 | } | 48 | } |
crates/client/src/share/encode.rsmodified+104 -21
| @@ -1,5 +1,5 @@ | |||
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; | 2 | +use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering}; |
| 3 | use std::sync::mpsc::{Receiver, Sender, SyncSender, sync_channel}; | 3 | use std::sync::mpsc::{Receiver, Sender, SyncSender, sync_channel}; |
| 4 | use std::sync::{Arc, OnceLock}; | 4 | use std::sync::{Arc, OnceLock}; |
| 5 | use std::thread; | 5 | use std::thread; |
| @@ -54,6 +54,53 @@ pub fn capabilities() -> &'static Capabilities { | |||
| 54 | &probe().capabilities | 54 | &probe().capabilities |
| 55 | } | 55 | } |
| 56 | 56 | ||
| 57 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] | ||
| 58 | +enum Request { | ||
| 59 | + Nothing, | ||
| 60 | + Recover, | ||
| 61 | + Keyframe, | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +impl Request { | ||
| 65 | + fn from_u8(value: u8) -> Self { | ||
| 66 | + match value { | ||
| 67 | + 1 => Self::Recover, | ||
| 68 | + 2 => Self::Keyframe, | ||
| 69 | + _ => Self::Nothing, | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +#[derive(Default)] | ||
| 75 | +struct Control { | ||
| 76 | + request: AtomicU8, | ||
| 77 | + acked: AtomicU64, | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +impl Control { | ||
| 81 | + fn ask(&self, request: Request) { | ||
| 82 | + self.request.fetch_max(request as u8, Ordering::Relaxed); | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + fn take(&self) -> Request { | ||
| 86 | + Request::from_u8(self.request.swap(Request::Nothing as u8, Ordering::Relaxed)) | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + fn pending(&self) -> bool { | ||
| 90 | + self.request.load(Ordering::Relaxed) != Request::Nothing as u8 | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + fn ack(&self, timestamp_ms: u32) { | ||
| 94 | + self.acked | ||
| 95 | + .store(u64::from(timestamp_ms) + 1, Ordering::Relaxed); | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + fn acked(&self) -> Option<u32> { | ||
| 99 | + let value = self.acked.load(Ordering::Relaxed); | ||
| 100 | + (value > 0).then(|| (value - 1) as u32) | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 57 | struct Settings { | 104 | struct Settings { |
| 58 | codec: Codec, | 105 | codec: Codec, |
| 59 | width: u32, | 106 | width: u32, |
| @@ -104,6 +151,12 @@ impl Backend { | |||
| 104 | } | 151 | } |
| 105 | } | 152 | } |
| 106 | 153 | ||
| 154 | + fn ack(&mut self, timestamp_ms: u32) { | ||
| 155 | + if let Self::Hardware(encoder) = self { | ||
| 156 | + encoder.ack(timestamp_ms); | ||
| 157 | + } | ||
| 158 | + } | ||
| 159 | + | ||
| 107 | fn engine(&self) -> Engine { | 160 | fn engine(&self) -> Engine { |
| 108 | match self { | 161 | match self { |
| 109 | Self::Hardware(_) => Engine::Hardware, | 162 | Self::Hardware(_) => Engine::Hardware, |
| @@ -115,10 +168,10 @@ impl Backend { | |||
| 115 | &mut self, | 168 | &mut self, |
| 116 | frame: &Frame, | 169 | frame: &Frame, |
| 117 | settings: &Settings, | 170 | settings: &Settings, |
| 118 | - force: bool, | 171 | + request: Request, |
| 119 | - ) -> Option<(Vec<u8>, bool)> { | 172 | + ) -> Option<(Vec<u8>, bool, bool)> { |
| 120 | match self { | 173 | match self { |
| 121 | - Self::Hardware(encoder) => encoder.encode(frame, settings, force), | 174 | + Self::Hardware(encoder) => encoder.encode(frame, settings, request), |
| 122 | Self::H264(encoder) => { | 175 | Self::H264(encoder) => { |
| 123 | let planes = frame.to_i420(settings.width, settings.height)?; | 176 | let planes = frame.to_i420(settings.width, settings.height)?; |
| 124 | let picture = ec_h264::PictureView::i420( | 177 | let picture = ec_h264::PictureView::i420( |
| @@ -128,8 +181,8 @@ impl Backend { | |||
| 128 | &planes.u, | 181 | &planes.u, |
| 129 | &planes.v, | 182 | &planes.v, |
| 130 | ); | 183 | ); |
| 131 | - report(encoder.encode_with(&picture, force)) | 184 | + report(encoder.encode_with(&picture, request != Request::Nothing)) |
| 132 | - .map(|picture| (picture.au, picture.key_frame)) | 185 | + .map(|picture| (picture.au, picture.key_frame, false)) |
| 133 | } | 186 | } |
| 134 | } | 187 | } |
| 135 | } | 188 | } |
| @@ -144,7 +197,7 @@ fn report<T, E: std::fmt::Debug>(result: Result<T, E>) -> Option<T> { | |||
| 144 | mod hardware { | 197 | mod hardware { |
| 145 | use common::share::Codec; | 198 | use common::share::Codec; |
| 146 | 199 | ||
| 147 | - use super::{Settings, report}; | 200 | + use super::{Request, Settings, report}; |
| 148 | use crate::share::frame::Frame; | 201 | use crate::share::frame::Frame; |
| 149 | 202 | ||
| 150 | pub struct Encoder(ec_hw::HwEncoder); | 203 | pub struct Encoder(ec_hw::HwEncoder); |
| @@ -161,15 +214,22 @@ mod hardware { | |||
| 161 | })); | 214 | })); |
| 162 | } | 215 | } |
| 163 | 216 | ||
| 217 | + pub fn ack(&mut self, timestamp_ms: u32) { | ||
| 218 | + self.0.ack(i64::from(timestamp_ms)); | ||
| 219 | + } | ||
| 220 | + | ||
| 164 | pub fn encode( | 221 | pub fn encode( |
| 165 | &mut self, | 222 | &mut self, |
| 166 | frame: &Frame, | 223 | frame: &Frame, |
| 167 | settings: &Settings, | 224 | settings: &Settings, |
| 168 | - force: bool, | 225 | + request: Request, |
| 169 | - ) -> Option<(Vec<u8>, bool)> { | 226 | + ) -> Option<(Vec<u8>, bool, bool)> { |
| 227 | + if request == Request::Recover { | ||
| 228 | + self.0.recover(); | ||
| 229 | + } | ||
| 170 | let meta = ec_hw::FrameMetadata { | 230 | let meta = ec_hw::FrameMetadata { |
| 171 | timestamp: i64::from(frame.timestamp_ms), | 231 | timestamp: i64::from(frame.timestamp_ms), |
| 172 | - force_keyframe: force, | 232 | + force_keyframe: request == Request::Keyframe, |
| 173 | }; | 233 | }; |
| 174 | let coded = if frame.width.is_multiple_of(2) | 234 | let coded = if frame.width.is_multiple_of(2) |
| 175 | && frame.height.is_multiple_of(2) | 235 | && frame.height.is_multiple_of(2) |
| @@ -194,7 +254,7 @@ mod hardware { | |||
| 194 | }; | 254 | }; |
| 195 | self.0.encode(&picture, meta) | 255 | self.0.encode(&picture, meta) |
| 196 | }; | 256 | }; |
| 197 | - report(coded).map(|coded| (coded.data, coded.is_keyframe)) | 257 | + report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)) |
| 198 | } | 258 | } |
| 199 | } | 259 | } |
| 200 | 260 | ||
| @@ -246,10 +306,11 @@ fn run( | |||
| 246 | layer: Layer, | 306 | layer: Layer, |
| 247 | settings: Settings, | 307 | settings: Settings, |
| 248 | input: Receiver<Arc<Frame>>, | 308 | input: Receiver<Arc<Frame>>, |
| 249 | - request: Arc<AtomicBool>, | 309 | + control: Arc<Control>, |
| 250 | scale: Arc<AtomicU32>, | 310 | scale: Arc<AtomicU32>, |
| 251 | output: Sender<Encoded>, | 311 | output: Sender<Encoded>, |
| 252 | ) { | 312 | ) { |
| 313 | + let mut acked = None; | ||
| 253 | let Some(mut backend) = Backend::open(&settings) else { | 314 | let Some(mut backend) = Backend::open(&settings) else { |
| 254 | return; | 315 | return; |
| 255 | }; | 316 | }; |
| @@ -266,8 +327,15 @@ fn run( | |||
| 266 | applied = wanted; | 327 | applied = wanted; |
| 267 | backend.tune((settings.bitrate as f32 * wanted) as u32, settings.fps); | 328 | backend.tune((settings.bitrate as f32 * wanted) as u32, settings.fps); |
| 268 | } | 329 | } |
| 269 | - let force = request.swap(false, Ordering::Relaxed); | 330 | + let ack = control.acked(); |
| 270 | - let Some((data, keyframe)) = backend.encode(&frame, &settings, force) else { | 331 | + if ack != acked { |
| 332 | + acked = ack; | ||
| 333 | + if let Some(timestamp_ms) = ack { | ||
| 334 | + backend.ack(timestamp_ms); | ||
| 335 | + } | ||
| 336 | + } | ||
| 337 | + let Some((data, keyframe, recovery)) = backend.encode(&frame, &settings, control.take()) | ||
| 338 | + else { | ||
| 271 | continue; | 339 | continue; |
| 272 | }; | 340 | }; |
| 273 | let encoded = Encoded { | 341 | let encoded = Encoded { |
| @@ -275,6 +343,7 @@ fn run( | |||
| 275 | engine: backend.engine(), | 343 | engine: backend.engine(), |
| 276 | data, | 344 | data, |
| 277 | keyframe, | 345 | keyframe, |
| 346 | + recovery, | ||
| 278 | timestamp_ms: frame.timestamp_ms, | 347 | timestamp_ms: frame.timestamp_ms, |
| 279 | }; | 348 | }; |
| 280 | if output.send(encoded).is_err() { | 349 | if output.send(encoded).is_err() { |
| @@ -285,7 +354,7 @@ fn run( | |||
| 285 | 354 | ||
| 286 | struct Lane { | 355 | struct Lane { |
| 287 | input: SyncSender<Arc<Frame>>, | 356 | input: SyncSender<Arc<Frame>>, |
| 288 | - request: Arc<AtomicBool>, | 357 | + control: Arc<Control>, |
| 289 | } | 358 | } |
| 290 | 359 | ||
| 291 | pub struct Encoders { | 360 | pub struct Encoders { |
| @@ -317,12 +386,26 @@ impl Encoders { | |||
| 317 | } | 386 | } |
| 318 | } | 387 | } |
| 319 | 388 | ||
| 320 | - pub fn keyframe(&self, layer: Layer) { | 389 | + pub fn keyframe(&self, layer: Layer, recover: bool) { |
| 390 | + if let Some(lane) = self.lanes.get(&layer) { | ||
| 391 | + lane.control.ask(if recover { | ||
| 392 | + Request::Recover | ||
| 393 | + } else { | ||
| 394 | + Request::Keyframe | ||
| 395 | + }); | ||
| 396 | + } | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + pub fn ack(&self, layer: Layer, timestamp_ms: u32) { | ||
| 321 | if let Some(lane) = self.lanes.get(&layer) { | 400 | if let Some(lane) = self.lanes.get(&layer) { |
| 322 | - lane.request.store(true, Ordering::Relaxed); | 401 | + lane.control.ack(timestamp_ms); |
| 323 | } | 402 | } |
| 324 | } | 403 | } |
| 325 | 404 | ||
| 405 | + pub fn keyframe_pending(&self) -> bool { | ||
| 406 | + self.lanes.values().any(|lane| lane.control.pending()) | ||
| 407 | + } | ||
| 408 | + | ||
| 326 | pub fn bitrate(&self) -> u32 { | 409 | pub fn bitrate(&self) -> u32 { |
| 327 | self.lanes | 410 | self.lanes |
| 328 | .keys() | 411 | .keys() |
| @@ -355,16 +438,16 @@ impl Encoders { | |||
| 355 | gop: fps * KEYFRAME_SECONDS, | 438 | gop: fps * KEYFRAME_SECONDS, |
| 356 | }; | 439 | }; |
| 357 | let (input, receiver) = sync_channel(1); | 440 | let (input, receiver) = sync_channel(1); |
| 358 | - let request = Arc::new(AtomicBool::new(false)); | 441 | + let control = Arc::new(Control::default()); |
| 359 | - let thread_request = Arc::clone(&request); | 442 | + let thread_control = Arc::clone(&control); |
| 360 | let output = self.output.clone(); | 443 | let output = self.output.clone(); |
| 361 | let scale = Arc::clone(&self.scale); | 444 | let scale = Arc::clone(&self.scale); |
| 362 | let spawned = thread::Builder::new() | 445 | let spawned = thread::Builder::new() |
| 363 | .name("share-encode".into()) | 446 | .name("share-encode".into()) |
| 364 | - .spawn(move || run(layer, settings, receiver, thread_request, scale, output)); | 447 | + .spawn(move || run(layer, settings, receiver, thread_control, scale, output)); |
| 365 | if let Err(error) = spawned { | 448 | if let Err(error) = spawned { |
| 366 | tracing::warn!(?error, "share encode thread failed to start"); | 449 | tracing::warn!(?error, "share encode thread failed to start"); |
| 367 | } | 450 | } |
| 368 | - Lane { input, request } | 451 | + Lane { input, control } |
| 369 | } | 452 | } |
| 370 | } | 453 | } |
crates/client/src/share/frame.rsmodified+1 -0
| @@ -31,5 +31,6 @@ pub struct Encoded { | |||
| 31 | pub engine: Engine, | 31 | pub engine: Engine, |
| 32 | pub data: Vec<u8>, | 32 | pub data: Vec<u8>, |
| 33 | pub keyframe: bool, | 33 | pub keyframe: bool, |
| 34 | + pub recovery: bool, | ||
| 34 | pub timestamp_ms: u32, | 35 | pub timestamp_ms: u32, |
| 35 | } | 36 | } |
crates/client/src/share/reassembly.rsmodified+324 -58
| @@ -1,11 +1,17 @@ | |||
| 1 | -use std::collections::HashMap; | 1 | +use std::{ |
| 2 | + collections::HashMap, | ||
| 3 | + time::{Duration, Instant}, | ||
| 4 | +}; | ||
| 2 | 5 | ||
| 3 | use common::{ | 6 | use common::{ |
| 4 | - datagram::{Packet, layout, seq_newer}, | 7 | + datagram::{NACK_MAX, Packet, layout, seq_newer}, |
| 5 | share::Layer, | 8 | share::Layer, |
| 6 | }; | 9 | }; |
| 7 | 10 | ||
| 8 | -const PENDING_LIMIT: usize = 8; | 11 | +const HELD_LIMIT: usize = 16; |
| 12 | +const QUIET: Duration = Duration::from_millis(20); | ||
| 13 | +const NACK_ROUNDS: u8 = 2; | ||
| 14 | +const NACK_SPAN: u32 = 32; | ||
| 9 | 15 | ||
| 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 16 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 11 | enum Phase { | 17 | enum Phase { |
| @@ -21,39 +27,68 @@ pub struct Assembled { | |||
| 21 | pub timestamp_ms: u32, | 27 | pub timestamp_ms: u32, |
| 22 | } | 28 | } |
| 23 | 29 | ||
| 30 | +#[derive(Debug, PartialEq, Eq)] | ||
| 31 | +pub struct Nack { | ||
| 32 | + pub layer: Layer, | ||
| 33 | + pub frame: u32, | ||
| 34 | + pub indices: Vec<u16>, | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +struct Ready { | ||
| 38 | + layer: Layer, | ||
| 39 | + keyframe: bool, | ||
| 40 | + recovery: bool, | ||
| 41 | + timestamp_ms: u32, | ||
| 42 | + data: Option<Vec<u8>>, | ||
| 43 | +} | ||
| 44 | + | ||
| 24 | struct Pending { | 45 | struct Pending { |
| 25 | layer: Layer, | 46 | layer: Layer, |
| 26 | keyframe: bool, | 47 | keyframe: bool, |
| 48 | + recovery: bool, | ||
| 27 | timestamp_ms: u32, | 49 | timestamp_ms: u32, |
| 28 | data: usize, | 50 | data: usize, |
| 29 | length: usize, | 51 | length: usize, |
| 30 | present: usize, | 52 | present: usize, |
| 31 | highest: usize, | 53 | highest: usize, |
| 32 | shards: Vec<Option<Vec<u8>>>, | 54 | shards: Vec<Option<Vec<u8>>>, |
| 55 | + arrived: Instant, | ||
| 56 | + nacks: u8, | ||
| 57 | + nacked: Option<Instant>, | ||
| 58 | + missing_at_nack: Option<usize>, | ||
| 59 | + accounted: bool, | ||
| 33 | } | 60 | } |
| 34 | 61 | ||
| 35 | impl Pending { | 62 | impl Pending { |
| 36 | - fn new(layer: Layer, keyframe: bool, timestamp_ms: u32, length: u32, parity: u16) -> Pending { | 63 | + fn new(packet: (Layer, bool, bool, u32, u32, u16), now: Instant) -> Pending { |
| 64 | + let (layer, keyframe, recovery, timestamp_ms, length, parity) = packet; | ||
| 37 | let layout = layout(length, parity); | 65 | let layout = layout(length, parity); |
| 38 | Pending { | 66 | Pending { |
| 39 | layer, | 67 | layer, |
| 40 | keyframe, | 68 | keyframe, |
| 69 | + recovery, | ||
| 41 | timestamp_ms, | 70 | timestamp_ms, |
| 42 | data: layout.data, | 71 | data: layout.data, |
| 43 | length: length as usize, | 72 | length: length as usize, |
| 44 | present: 0, | 73 | present: 0, |
| 45 | highest: 0, | 74 | highest: 0, |
| 46 | shards: vec![None; layout.count()], | 75 | shards: vec![None; layout.count()], |
| 76 | + arrived: now, | ||
| 77 | + nacks: 0, | ||
| 78 | + nacked: None, | ||
| 79 | + missing_at_nack: None, | ||
| 80 | + accounted: false, | ||
| 47 | } | 81 | } |
| 48 | } | 82 | } |
| 49 | 83 | ||
| 50 | - fn insert(&mut self, index: u16, shard: &[u8]) { | 84 | + fn insert(&mut self, index: u16, shard: &[u8], now: Instant) { |
| 51 | if let Some(slot) = self.shards.get_mut(usize::from(index)) | 85 | if let Some(slot) = self.shards.get_mut(usize::from(index)) |
| 52 | && slot.is_none() | 86 | && slot.is_none() |
| 53 | { | 87 | { |
| 54 | *slot = Some(shard.to_vec()); | 88 | *slot = Some(shard.to_vec()); |
| 55 | self.present += 1; | 89 | self.present += 1; |
| 56 | self.highest = self.highest.max(usize::from(index)); | 90 | self.highest = self.highest.max(usize::from(index)); |
| 91 | + self.arrived = now; | ||
| 57 | } | 92 | } |
| 58 | } | 93 | } |
| 59 | 94 | ||
| @@ -61,6 +96,16 @@ impl Pending { | |||
| 61 | self.present >= self.data | 96 | self.present >= self.data |
| 62 | } | 97 | } |
| 63 | 98 | ||
| 99 | + fn missing(&self) -> Vec<u16> { | ||
| 100 | + self.shards | ||
| 101 | + .iter() | ||
| 102 | + .enumerate() | ||
| 103 | + .filter(|(_, shard)| shard.is_none()) | ||
| 104 | + .map(|(index, _)| index as u16) | ||
| 105 | + .take(NACK_MAX) | ||
| 106 | + .collect() | ||
| 107 | + } | ||
| 108 | + | ||
| 64 | fn assemble(self) -> Option<Vec<u8>> { | 109 | fn assemble(self) -> Option<Vec<u8>> { |
| 65 | let data = self.data; | 110 | let data = self.data; |
| 66 | let mut shards = self.shards; | 111 | let mut shards = self.shards; |
| @@ -88,8 +133,13 @@ impl Pending { | |||
| 88 | pub struct Reassembler { | 133 | pub struct Reassembler { |
| 89 | layer: Option<Layer>, | 134 | layer: Option<Layer>, |
| 90 | pending: HashMap<u32, Pending>, | 135 | pending: HashMap<u32, Pending>, |
| 136 | + ready: HashMap<u32, Ready>, | ||
| 137 | + vanished: HashMap<u32, (u8, Instant)>, | ||
| 91 | last: Option<u32>, | 138 | last: Option<u32>, |
| 139 | + newest: Option<u32>, | ||
| 140 | + gap: Option<(u32, Instant)>, | ||
| 92 | phase: Phase, | 141 | phase: Phase, |
| 142 | + streamed: bool, | ||
| 93 | received_frames: u32, | 143 | received_frames: u32, |
| 94 | lost_frames: u32, | 144 | lost_frames: u32, |
| 95 | expected_shards: u32, | 145 | expected_shards: u32, |
| @@ -108,8 +158,13 @@ impl Reassembler { | |||
| 108 | Reassembler { | 158 | Reassembler { |
| 109 | layer: None, | 159 | layer: None, |
| 110 | pending: HashMap::new(), | 160 | pending: HashMap::new(), |
| 161 | + ready: HashMap::new(), | ||
| 162 | + vanished: HashMap::new(), | ||
| 111 | last: None, | 163 | last: None, |
| 164 | + newest: None, | ||
| 165 | + gap: None, | ||
| 112 | phase: Phase::WaitingKeyframe, | 166 | phase: Phase::WaitingKeyframe, |
| 167 | + streamed: false, | ||
| 113 | received_frames: 0, | 168 | received_frames: 0, |
| 114 | lost_frames: 0, | 169 | lost_frames: 0, |
| 115 | expected_shards: 0, | 170 | expected_shards: 0, |
| @@ -118,10 +173,11 @@ impl Reassembler { | |||
| 118 | } | 173 | } |
| 119 | } | 174 | } |
| 120 | 175 | ||
| 121 | - pub fn push(&mut self, packet: &Packet<'_>) -> Option<Assembled> { | 176 | + pub fn push(&mut self, packet: &Packet<'_>, now: Instant) -> Vec<Assembled> { |
| 122 | let &Packet::Video { | 177 | let &Packet::Video { |
| 123 | layer, | 178 | layer, |
| 124 | keyframe, | 179 | keyframe, |
| 180 | + recovery, | ||
| 125 | frame, | 181 | frame, |
| 126 | index, | 182 | index, |
| 127 | parity, | 183 | parity, |
| @@ -131,83 +187,226 @@ impl Reassembler { | |||
| 131 | .. | 187 | .. |
| 132 | } = packet | 188 | } = packet |
| 133 | else { | 189 | else { |
| 134 | - return None; | 190 | + return Vec::new(); |
| 135 | }; | 191 | }; |
| 136 | if self.layer != Some(layer) { | 192 | if self.layer != Some(layer) { |
| 137 | self.layer = Some(layer); | 193 | self.layer = Some(layer); |
| 138 | self.pending.clear(); | 194 | self.pending.clear(); |
| 195 | + self.ready.clear(); | ||
| 196 | + self.vanished.clear(); | ||
| 139 | self.last = None; | 197 | self.last = None; |
| 198 | + self.newest = None; | ||
| 199 | + self.gap = None; | ||
| 140 | self.phase = Phase::WaitingKeyframe; | 200 | self.phase = Phase::WaitingKeyframe; |
| 201 | + self.streamed = false; | ||
| 141 | } | 202 | } |
| 142 | - if self.last.is_some_and(|last| !seq_newer(frame, last)) { | 203 | + if self.last.is_some_and(|last| !seq_newer(frame, last)) || self.ready.contains_key(&frame) |
| 143 | - return None; | 204 | + { |
| 205 | + return Vec::new(); | ||
| 144 | } | 206 | } |
| 145 | - if !self.pending.contains_key(&frame) && self.pending.len() >= PENDING_LIMIT { | 207 | + if !self.pending.contains_key(&frame) && self.pending.len() + self.ready.len() >= HELD_LIMIT |
| 208 | + { | ||
| 146 | for (_, dropped) in std::mem::take(&mut self.pending) { | 209 | for (_, dropped) in std::mem::take(&mut self.pending) { |
| 147 | self.drop_pending(&dropped); | 210 | self.drop_pending(&dropped); |
| 148 | } | 211 | } |
| 212 | + self.lost_frames += self.ready.len() as u32; | ||
| 213 | + self.ready.clear(); | ||
| 214 | + self.vanished.clear(); | ||
| 215 | + self.gap = None; | ||
| 216 | + self.last = Some(frame.wrapping_sub(1)); | ||
| 149 | self.phase = Phase::WaitingKeyframe; | 217 | self.phase = Phase::WaitingKeyframe; |
| 150 | } | 218 | } |
| 151 | - let pending = self | 219 | + if self.newest.is_none_or(|newest| seq_newer(frame, newest)) { |
| 152 | - .pending | 220 | + self.newest = Some(frame); |
| 153 | - .entry(frame) | 221 | + } |
| 154 | - .or_insert_with(|| Pending::new(layer, keyframe, ts_ms, length, parity)); | 222 | + let accounted = self.vanished.contains_key(&frame); |
| 155 | - pending.insert(index, shard); | 223 | + let pending = self.pending.entry(frame).or_insert_with(|| { |
| 156 | - if !pending.is_complete() { | 224 | + let mut pending = Pending::new((layer, keyframe, recovery, ts_ms, length, parity), now); |
| 157 | - return None; | 225 | + pending.accounted = accounted; |
| 226 | + pending | ||
| 227 | + }); | ||
| 228 | + pending.insert(index, shard, now); | ||
| 229 | + if pending.is_complete() | ||
| 230 | + && let Some(complete) = self.pending.remove(&frame) | ||
| 231 | + { | ||
| 232 | + self.account(&complete); | ||
| 233 | + self.last_count = complete.shards.len() as u32; | ||
| 234 | + let ready = Ready { | ||
| 235 | + layer: complete.layer, | ||
| 236 | + keyframe: complete.keyframe, | ||
| 237 | + recovery: complete.recovery, | ||
| 238 | + timestamp_ms: complete.timestamp_ms, | ||
| 239 | + data: complete.assemble(), | ||
| 240 | + }; | ||
| 241 | + self.ready.insert(frame, ready); | ||
| 158 | } | 242 | } |
| 159 | - let complete = self.pending.remove(&frame)?; | 243 | + self.flush(now) |
| 160 | - self.deliver(frame, complete) | ||
| 161 | } | 244 | } |
| 162 | 245 | ||
| 163 | - fn deliver(&mut self, frame: u32, complete: Pending) -> Option<Assembled> { | 246 | + pub fn expire(&mut self, now: Instant, wait: Duration) -> Vec<Assembled> { |
| 164 | - let skipped = self | 247 | + let mut out = Vec::new(); |
| 165 | - .last | 248 | + while let Some((frame, since)) = self.gap |
| 166 | - .map_or(0, |last| frame.wrapping_sub(last).wrapping_sub(1)); | 249 | + && now.duration_since(since) >= wait |
| 167 | - let (layer, keyframe, timestamp_ms) = | 250 | + { |
| 168 | - (complete.layer, complete.keyframe, complete.timestamp_ms); | 251 | + match self.pending.remove(&frame) { |
| 169 | - let seen = complete.highest + 1; | 252 | + Some(dropped) => self.drop_pending(&dropped), |
| 170 | - self.expected_shards += seen as u32; | 253 | + None if !self.vanished.contains_key(&frame) => { |
| 171 | - self.missing_shards += (seen - complete.present) as u32; | 254 | + self.expected_shards += self.last_count; |
| 172 | - self.last_count = complete.shards.len() as u32; | 255 | + self.missing_shards += self.last_count; |
| 173 | - let data = complete.assemble(); | 256 | + } |
| 174 | - self.last = Some(frame); | 257 | + None => {} |
| 175 | - if skipped > 0 || data.is_none() { | 258 | + } |
| 176 | - self.lost_frames += skipped + u32::from(data.is_none()); | 259 | + self.vanished.remove(&frame); |
| 260 | + self.lost_frames += 1; | ||
| 177 | self.phase = Phase::WaitingKeyframe; | 261 | self.phase = Phase::WaitingKeyframe; |
| 178 | - let (older, newer): (HashMap<u32, Pending>, HashMap<u32, Pending>) = | 262 | + self.last = Some(frame); |
| 179 | - std::mem::take(&mut self.pending) | 263 | + self.gap = None; |
| 180 | - .into_iter() | 264 | + out.extend(self.flush(since)); |
| 181 | - .partition(|&(number, _)| !seq_newer(number, frame)); | 265 | + } |
| 182 | - self.pending = newer; | 266 | + out |
| 183 | - let arrived = older.len() as u32; | 267 | + } |
| 184 | - for dropped in older.values() { | 268 | + |
| 185 | - self.drop_pending(dropped); | 269 | + pub fn nacks(&mut self, now: Instant, rtt: Duration) -> Vec<Nack> { |
| 270 | + let (Some(layer), Some(newest)) = (self.layer, self.newest) else { | ||
| 271 | + return Vec::new(); | ||
| 272 | + }; | ||
| 273 | + let retry = rtt + Duration::from_millis(10); | ||
| 274 | + let frames: Vec<u32> = match self.last { | ||
| 275 | + Some(last) => (1..=newest.wrapping_sub(last).min(NACK_SPAN)) | ||
| 276 | + .map(|step| last.wrapping_add(step)) | ||
| 277 | + .collect(), | ||
| 278 | + None => self.pending.keys().copied().collect(), | ||
| 279 | + }; | ||
| 280 | + let mut out = Vec::new(); | ||
| 281 | + for frame in frames { | ||
| 282 | + if self.ready.contains_key(&frame) { | ||
| 283 | + continue; | ||
| 284 | + } | ||
| 285 | + let behind = seq_newer(newest, frame); | ||
| 286 | + if let Some(pending) = self.pending.get_mut(&frame) { | ||
| 287 | + let quiet = now.duration_since(pending.arrived) >= QUIET; | ||
| 288 | + let due = pending | ||
| 289 | + .nacked | ||
| 290 | + .is_none_or(|at| now.duration_since(at) >= retry); | ||
| 291 | + if !(behind || quiet) || pending.nacks >= NACK_ROUNDS || !due { | ||
| 292 | + continue; | ||
| 293 | + } | ||
| 294 | + if pending.missing_at_nack.is_none() { | ||
| 295 | + pending.missing_at_nack = Some(pending.shards.len() - pending.present); | ||
| 296 | + } | ||
| 297 | + pending.nacks += 1; | ||
| 298 | + pending.nacked = Some(now); | ||
| 299 | + out.push(Nack { | ||
| 300 | + layer: pending.layer, | ||
| 301 | + frame, | ||
| 302 | + indices: pending.missing(), | ||
| 303 | + }); | ||
| 304 | + } else if behind { | ||
| 305 | + let (rounds, at) = self.vanished.entry(frame).or_insert((0, now)); | ||
| 306 | + if *rounds >= NACK_ROUNDS || (*rounds > 0 && now.duration_since(*at) < retry) { | ||
| 307 | + continue; | ||
| 308 | + } | ||
| 309 | + if *rounds == 0 { | ||
| 310 | + self.expected_shards += self.last_count; | ||
| 311 | + self.missing_shards += self.last_count; | ||
| 312 | + } | ||
| 313 | + *rounds += 1; | ||
| 314 | + *at = now; | ||
| 315 | + out.push(Nack { | ||
| 316 | + layer, | ||
| 317 | + frame, | ||
| 318 | + indices: Vec::new(), | ||
| 319 | + }); | ||
| 320 | + } | ||
| 321 | + } | ||
| 322 | + out | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + fn flush(&mut self, since: Instant) -> Vec<Assembled> { | ||
| 326 | + let mut out = Vec::new(); | ||
| 327 | + loop { | ||
| 328 | + let next = match self.last { | ||
| 329 | + Some(last) => last.wrapping_add(1), | ||
| 330 | + None => match self.oldest() { | ||
| 331 | + Some(oldest) if self.ready.contains_key(&oldest) => oldest, | ||
| 332 | + _ => break, | ||
| 333 | + }, | ||
| 334 | + }; | ||
| 335 | + let Some(ready) = self.ready.remove(&next) else { | ||
| 336 | + break; | ||
| 337 | + }; | ||
| 338 | + self.last = Some(next); | ||
| 339 | + self.gap = None; | ||
| 340 | + self.vanished.remove(&next); | ||
| 341 | + out.extend(self.deliver(ready)); | ||
| 342 | + } | ||
| 343 | + if let (Some(last), Some(newest)) = (self.last, self.newest) { | ||
| 344 | + let next = last.wrapping_add(1); | ||
| 345 | + let waiting = next == newest && self.pending.is_empty(); | ||
| 346 | + if seq_newer(newest, last) && !waiting && self.gap.is_none_or(|(at, _)| at != next) { | ||
| 347 | + self.gap = Some((next, since)); | ||
| 186 | } | 348 | } |
| 187 | - let vanished = skipped.saturating_sub(arrived) * self.last_count; | ||
| 188 | - self.expected_shards += vanished; | ||
| 189 | - self.missing_shards += vanished; | ||
| 190 | } | 349 | } |
| 191 | - let data = data?; | 350 | + out |
| 351 | + } | ||
| 352 | + | ||
| 353 | + fn oldest(&self) -> Option<u32> { | ||
| 354 | + self.pending | ||
| 355 | + .keys() | ||
| 356 | + .chain(self.ready.keys()) | ||
| 357 | + .copied() | ||
| 358 | + .reduce(|a, b| if seq_newer(a, b) { b } else { a }) | ||
| 359 | + } | ||
| 360 | + | ||
| 361 | + fn deliver(&mut self, ready: Ready) -> Option<Assembled> { | ||
| 362 | + let Some(data) = ready.data else { | ||
| 363 | + self.lost_frames += 1; | ||
| 364 | + self.phase = Phase::WaitingKeyframe; | ||
| 365 | + return None; | ||
| 366 | + }; | ||
| 192 | self.received_frames += 1; | 367 | self.received_frames += 1; |
| 193 | - if keyframe { | 368 | + if ready.keyframe || (ready.recovery && self.streamed) { |
| 194 | self.phase = Phase::Streaming; | 369 | self.phase = Phase::Streaming; |
| 195 | } | 370 | } |
| 196 | if self.phase == Phase::WaitingKeyframe { | 371 | if self.phase == Phase::WaitingKeyframe { |
| 197 | return None; | 372 | return None; |
| 198 | } | 373 | } |
| 374 | + self.streamed = true; | ||
| 199 | Some(Assembled { | 375 | Some(Assembled { |
| 200 | - layer, | 376 | + layer: ready.layer, |
| 201 | data, | 377 | data, |
| 202 | - keyframe, | 378 | + keyframe: ready.keyframe, |
| 203 | - timestamp_ms, | 379 | + timestamp_ms: ready.timestamp_ms, |
| 204 | }) | 380 | }) |
| 205 | } | 381 | } |
| 206 | 382 | ||
| 383 | + fn account(&mut self, complete: &Pending) { | ||
| 384 | + if complete.accounted { | ||
| 385 | + return; | ||
| 386 | + } | ||
| 387 | + let count = complete.shards.len() as u32; | ||
| 388 | + match complete.missing_at_nack { | ||
| 389 | + Some(missing) => { | ||
| 390 | + self.expected_shards += count; | ||
| 391 | + self.missing_shards += missing as u32; | ||
| 392 | + } | ||
| 393 | + None => { | ||
| 394 | + let seen = complete.highest + 1; | ||
| 395 | + self.expected_shards += seen as u32; | ||
| 396 | + self.missing_shards += (seen - complete.present) as u32; | ||
| 397 | + } | ||
| 398 | + } | ||
| 399 | + } | ||
| 400 | + | ||
| 207 | fn drop_pending(&mut self, dropped: &Pending) { | 401 | fn drop_pending(&mut self, dropped: &Pending) { |
| 402 | + if dropped.accounted { | ||
| 403 | + return; | ||
| 404 | + } | ||
| 208 | let count = dropped.shards.len() as u32; | 405 | let count = dropped.shards.len() as u32; |
| 209 | self.expected_shards += count; | 406 | self.expected_shards += count; |
| 210 | - self.missing_shards += count - dropped.present as u32; | 407 | + self.missing_shards += dropped |
| 408 | + .missing_at_nack | ||
| 409 | + .map_or(count - dropped.present as u32, |missing| missing as u32); | ||
| 211 | } | 410 | } |
| 212 | 411 | ||
| 213 | pub fn packet_loss(&mut self) -> f32 { | 412 | pub fn packet_loss(&mut self) -> f32 { |
| @@ -225,6 +424,10 @@ impl Reassembler { | |||
| 225 | self.phase == Phase::WaitingKeyframe | 424 | self.phase == Phase::WaitingKeyframe |
| 226 | } | 425 | } |
| 227 | 426 | ||
| 427 | + pub fn can_recover(&self) -> bool { | ||
| 428 | + self.streamed | ||
| 429 | + } | ||
| 430 | + | ||
| 228 | pub fn loss_ratio(&mut self) -> f32 { | 431 | pub fn loss_ratio(&mut self) -> f32 { |
| 229 | let total = self.received_frames + self.lost_frames; | 432 | let total = self.received_frames + self.lost_frames; |
| 230 | let ratio = if total == 0 { | 433 | let ratio = if total == 0 { |
| @@ -247,15 +450,72 @@ mod tests { | |||
| 247 | 450 | ||
| 248 | use super::*; | 451 | use super::*; |
| 249 | 452 | ||
| 453 | + const LAYER: Layer = Layer { | ||
| 454 | + quality: Quality { | ||
| 455 | + resolution: Resolution::P1080, | ||
| 456 | + fps: Fps::F60, | ||
| 457 | + }, | ||
| 458 | + codec: Codec::Av1, | ||
| 459 | + }; | ||
| 460 | + | ||
| 461 | + fn packets(frame: u32, data: &[u8]) -> Vec<Vec<u8>> { | ||
| 462 | + let info = FrameInfo { | ||
| 463 | + kind: Kind::Screen, | ||
| 464 | + layer: LAYER, | ||
| 465 | + frame, | ||
| 466 | + keyframe: frame == 0, | ||
| 467 | + recovery: false, | ||
| 468 | + ts_ms: frame, | ||
| 469 | + parity: 1, | ||
| 470 | + }; | ||
| 471 | + let mut out = Vec::new(); | ||
| 472 | + fragments(info, data, |packet| out.push(packet.to_vec())); | ||
| 473 | + out | ||
| 474 | + } | ||
| 475 | + | ||
| 476 | + #[test] | ||
| 477 | + fn nack_recovers_frame_and_holds_newer_ones() { | ||
| 478 | + let data: Vec<u8> = (0..5_000).map(|byte| byte as u8).collect(); | ||
| 479 | + let sent: Vec<Vec<Vec<u8>>> = (0..3).map(|frame| packets(frame, &data)).collect(); | ||
| 480 | + let mut reassembler = Reassembler::new(); | ||
| 481 | + let now = Instant::now(); | ||
| 482 | + let mut delivered = Vec::new(); | ||
| 483 | + for (frame, packets) in sent.iter().enumerate() { | ||
| 484 | + for (index, packet) in packets.iter().enumerate() { | ||
| 485 | + if frame == 1 && index < 2 { | ||
| 486 | + continue; | ||
| 487 | + } | ||
| 488 | + let packet = Packet::decode(packet).unwrap(); | ||
| 489 | + delivered.extend(reassembler.push(&packet, now)); | ||
| 490 | + } | ||
| 491 | + } | ||
| 492 | + assert_eq!(delivered.len(), 1); | ||
| 493 | + let nacks = reassembler.nacks(now, Duration::from_millis(5)); | ||
| 494 | + assert_eq!( | ||
| 495 | + nacks, | ||
| 496 | + vec![Nack { | ||
| 497 | + layer: LAYER, | ||
| 498 | + frame: 1, | ||
| 499 | + indices: vec![0, 1] | ||
| 500 | + }] | ||
| 501 | + ); | ||
| 502 | + for index in nacks[0].indices.iter() { | ||
| 503 | + let packet = Packet::decode(&sent[1][usize::from(*index)]).unwrap(); | ||
| 504 | + delivered.extend(reassembler.push(&packet, now)); | ||
| 505 | + } | ||
| 506 | + let frames: Vec<u32> = delivered.iter().map(|frame| frame.timestamp_ms).collect(); | ||
| 507 | + assert_eq!(frames, vec![0, 1, 2]); | ||
| 508 | + assert!( | ||
| 509 | + reassembler | ||
| 510 | + .expire(now + Duration::from_secs(1), Duration::from_millis(50)) | ||
| 511 | + .is_empty() | ||
| 512 | + ); | ||
| 513 | + assert!(!reassembler.needs_keyframe()); | ||
| 514 | + } | ||
| 515 | + | ||
| 250 | #[test] | 516 | #[test] |
| 251 | fn counts_shard_loss_and_recovers_with_parity() { | 517 | fn counts_shard_loss_and_recovers_with_parity() { |
| 252 | - let layer = Layer { | 518 | + 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(); | 519 | let data: Vec<u8> = (0..10_000).map(|byte| byte as u8).collect(); |
| 260 | let mut reassembler = Reassembler::new(); | 520 | let mut reassembler = Reassembler::new(); |
| 261 | let mut delivered = Vec::new(); | 521 | let mut delivered = Vec::new(); |
| @@ -265,6 +525,7 @@ mod tests { | |||
| 265 | layer, | 525 | layer, |
| 266 | frame, | 526 | frame, |
| 267 | keyframe: true, | 527 | keyframe: true, |
| 528 | + recovery: false, | ||
| 268 | ts_ms: 0, | 529 | ts_ms: 0, |
| 269 | parity: 2, | 530 | parity: 2, |
| 270 | }; | 531 | }; |
| @@ -272,7 +533,12 @@ mod tests { | |||
| 272 | fragments(info, &data, |packet| { | 533 | fragments(info, &data, |packet| { |
| 273 | if index != 3 { | 534 | if index != 3 { |
| 274 | let packet = Packet::decode(packet).unwrap(); | 535 | let packet = Packet::decode(packet).unwrap(); |
| 275 | - delivered.extend(reassembler.push(&packet).map(|frame| frame.data)); | 536 | + delivered.extend( |
| 537 | + reassembler | ||
| 538 | + .push(&packet, Instant::now()) | ||
| 539 | + .into_iter() | ||
| 540 | + .map(|frame| frame.data), | ||
| 541 | + ); | ||
| 276 | } | 542 | } |
| 277 | index += 1; | 543 | index += 1; |
| 278 | }); | 544 | }); |
crates/client/src/share/session.rsmodified+237 -42
| @@ -35,7 +35,7 @@ use super::{ | |||
| 35 | encode::{self, Encoders}, | 35 | encode::{self, Encoders}, |
| 36 | frame::{Encoded, Frame}, | 36 | frame::{Encoded, Frame}, |
| 37 | pacer::Pacer, | 37 | pacer::Pacer, |
| 38 | - reassembly::{Assembled, Reassembler}, | 38 | + reassembly::{Assembled, Nack, Reassembler}, |
| 39 | }; | 39 | }; |
| 40 | use crate::media::{ | 40 | use crate::media::{ |
| 41 | self, | 41 | self, |
| @@ -50,15 +50,27 @@ use crate::voice::{ | |||
| 50 | 50 | ||
| 51 | const CHUNK_MS: u32 = VOICE_FRAME_SAMPLES as u32 * 1000 / VOICE_SAMPLE_RATE; | 51 | const CHUNK_MS: u32 = VOICE_FRAME_SAMPLES as u32 * 1000 / VOICE_SAMPLE_RATE; |
| 52 | const STOP_CHECK: Duration = Duration::from_millis(100); | 52 | const STOP_CHECK: Duration = Duration::from_millis(100); |
| 53 | +const NACK_TICK: Duration = Duration::from_millis(5); | ||
| 54 | +const NACK_SLACK: Duration = Duration::from_millis(40); | ||
| 55 | +const NACK_GIVE_UP: Duration = Duration::from_millis(250); | ||
| 56 | +const DEFAULT_RTT: Duration = Duration::from_millis(50); | ||
| 57 | +const ACK_INTERVAL: Duration = Duration::from_millis(250); | ||
| 53 | const AUDIO_STEP: Duration = Duration::from_millis(5); | 58 | const AUDIO_STEP: Duration = Duration::from_millis(5); |
| 54 | const SAMPLE: Duration = Duration::from_secs(1); | 59 | const SAMPLE: Duration = Duration::from_secs(1); |
| 55 | -const DELAY_MS: i64 = 100; | 60 | +const INITIAL_DELAY_MS: i64 = 100; |
| 61 | +const MIN_DELAY_MS: i64 = 20; | ||
| 62 | +const MAX_DELAY_MS: i64 = 200; | ||
| 63 | +const DELAY_MARGIN_MS: i64 = 8; | ||
| 64 | +const LATENESS_WINDOW: usize = 120; | ||
| 56 | const LATE_MS: i64 = 200; | 65 | const LATE_MS: i64 = 200; |
| 57 | const QUEUE_LIMIT: usize = 8; | 66 | const QUEUE_LIMIT: usize = 8; |
| 58 | const LOSS_LIMIT: f32 = 0.05; | 67 | const LOSS_LIMIT: f32 = 0.05; |
| 59 | const CLEAN_LOSS: f32 = 0.01; | 68 | const CLEAN_LOSS: f32 = 0.01; |
| 60 | const KEYFRAME_INTERVAL: Duration = Duration::from_secs(1); | 69 | const KEYFRAME_INTERVAL: Duration = Duration::from_secs(1); |
| 61 | const CLEAN_SECONDS: u32 = 10; | 70 | const CLEAN_SECONDS: u32 = 10; |
| 71 | +const QUEUING_LIMIT_MS: i64 = 60; | ||
| 72 | +const QUEUING_CLEAN_MS: i64 = 20; | ||
| 73 | +const QUEUING_SAMPLES: usize = 30; | ||
| 62 | const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS; | 74 | const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS; |
| 63 | const DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000 * SHARE_AUDIO_CHANNELS; | 75 | const DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000 * SHARE_AUDIO_CHANNELS; |
| 64 | const AUDIO_RING: usize = VOICE_SAMPLE_RATE as usize * SHARE_AUDIO_CHANNELS / 2; | 76 | const AUDIO_RING: usize = VOICE_SAMPLE_RATE as usize * SHARE_AUDIO_CHANNELS / 2; |
| @@ -72,7 +84,7 @@ pub enum WatchQuality { | |||
| 72 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 84 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 73 | pub enum Tick { | 85 | pub enum Tick { |
| 74 | Quality(Quality), | 86 | Quality(Quality), |
| 75 | - Keyframe, | 87 | + Keyframe { recover: bool }, |
| 76 | Loss(u16), | 88 | Loss(u16), |
| 77 | } | 89 | } |
| 78 | 90 | ||
| @@ -93,6 +105,7 @@ pub struct WatchStats { | |||
| 93 | pub keyframes: u32, | 105 | pub keyframes: u32, |
| 94 | pub buffer_ms: i64, | 106 | pub buffer_ms: i64, |
| 95 | pub latency_ms: Option<i64>, | 107 | pub latency_ms: Option<i64>, |
| 108 | + pub nacks: u32, | ||
| 96 | } | 109 | } |
| 97 | 110 | ||
| 98 | #[derive(Default)] | 111 | #[derive(Default)] |
| @@ -318,8 +331,12 @@ impl Sharing { | |||
| 318 | lock(&self.encoders).set_layers(layers); | 331 | lock(&self.encoders).set_layers(layers); |
| 319 | } | 332 | } |
| 320 | 333 | ||
| 321 | - pub fn keyframe(&self, layer: Layer) { | 334 | + pub fn keyframe(&self, layer: Layer, recover: bool) { |
| 322 | - lock(&self.encoders).keyframe(layer); | 335 | + lock(&self.encoders).keyframe(layer, recover); |
| 336 | + } | ||
| 337 | + | ||
| 338 | + pub fn ack(&self, layer: Layer, timestamp_ms: u32) { | ||
| 339 | + lock(&self.encoders).ack(layer, timestamp_ms); | ||
| 323 | } | 340 | } |
| 324 | 341 | ||
| 325 | pub fn report_loss(&self, permille: u16) { | 342 | pub fn report_loss(&self, permille: u16) { |
| @@ -358,9 +375,31 @@ fn feed( | |||
| 358 | started: Instant, | 375 | started: Instant, |
| 359 | stop: &AtomicBool, | 376 | stop: &AtomicBool, |
| 360 | ) { | 377 | ) { |
| 378 | + let mut previous: Option<Arc<Frame>> = None; | ||
| 379 | + let mut skipped = 0u32; | ||
| 380 | + let mut logged = Instant::now(); | ||
| 361 | while let Some(mut frame) = next(&frames, stop) { | 381 | while let Some(mut frame) = next(&frames, stop) { |
| 362 | frame.timestamp_ms = started.elapsed().as_millis() as u32; | 382 | frame.timestamp_ms = started.elapsed().as_millis() as u32; |
| 363 | - lock(&encoders).push(Arc::new(frame)); | 383 | + let unchanged = previous.as_ref().is_some_and(|last| { |
| 384 | + last.width == frame.width | ||
| 385 | + && last.height == frame.height | ||
| 386 | + && last.bgra == frame.bgra | ||
| 387 | + && frame.timestamp_ms.saturating_sub(last.timestamp_ms) < 1000 | ||
| 388 | + }); | ||
| 389 | + let encoders = lock(&encoders); | ||
| 390 | + if unchanged && !encoders.keyframe_pending() { | ||
| 391 | + skipped += 1; | ||
| 392 | + } else { | ||
| 393 | + let frame = Arc::new(frame); | ||
| 394 | + encoders.push(frame.clone()); | ||
| 395 | + drop(encoders); | ||
| 396 | + previous = Some(frame); | ||
| 397 | + } | ||
| 398 | + if logged.elapsed() >= Duration::from_secs(10) { | ||
| 399 | + tracing::debug!(target: "metrics", skipped, "feed"); | ||
| 400 | + skipped = 0; | ||
| 401 | + logged = Instant::now(); | ||
| 402 | + } | ||
| 364 | } | 403 | } |
| 365 | } | 404 | } |
| 366 | 405 | ||
| @@ -403,6 +442,7 @@ fn send( | |||
| 403 | layer: item.layer, | 442 | layer: item.layer, |
| 404 | frame: number, | 443 | frame: number, |
| 405 | keyframe: item.keyframe, | 444 | keyframe: item.keyframe, |
| 445 | + recovery: item.recovery, | ||
| 406 | ts_ms: item.timestamp_ms, | 446 | ts_ms: item.timestamp_ms, |
| 407 | parity: parity_for(item.data.len() as u32, loss.fec(item.keyframe)), | 447 | parity: parity_for(item.data.len() as u32, loss.fec(item.keyframe)), |
| 408 | }; | 448 | }; |
| @@ -457,6 +497,7 @@ fn encode_audio( | |||
| 457 | struct Clock { | 497 | struct Clock { |
| 458 | started: Instant, | 498 | started: Instant, |
| 459 | offset: AtomicI64, | 499 | offset: AtomicI64, |
| 500 | + delay: AtomicI64, | ||
| 460 | } | 501 | } |
| 461 | 502 | ||
| 462 | impl Clock { | 503 | impl Clock { |
| @@ -469,15 +510,52 @@ impl Clock { | |||
| 469 | .fetch_min(self.now() - i64::from(sharer_ms), Ordering::Relaxed); | 510 | .fetch_min(self.now() - i64::from(sharer_ms), Ordering::Relaxed); |
| 470 | } | 511 | } |
| 471 | 512 | ||
| 513 | + fn origin(&self, sharer_ms: u32) -> i64 { | ||
| 514 | + i64::from(sharer_ms) + self.offset.load(Ordering::Relaxed) | ||
| 515 | + } | ||
| 516 | + | ||
| 472 | fn due(&self, sharer_ms: u32) -> i64 { | 517 | fn due(&self, sharer_ms: u32) -> i64 { |
| 473 | - i64::from(sharer_ms) + self.offset.load(Ordering::Relaxed) + DELAY_MS | 518 | + self.origin(sharer_ms) + self.delay.load(Ordering::Relaxed) |
| 519 | + } | ||
| 520 | +} | ||
| 521 | + | ||
| 522 | +#[derive(Default)] | ||
| 523 | +struct Playout { | ||
| 524 | + lateness: VecDeque<i64>, | ||
| 525 | +} | ||
| 526 | + | ||
| 527 | +impl Playout { | ||
| 528 | + fn observe(&mut self, clock: &Clock, sharer_ms: u32) { | ||
| 529 | + if self.lateness.len() >= LATENESS_WINDOW { | ||
| 530 | + self.lateness.pop_front(); | ||
| 531 | + } | ||
| 532 | + self.lateness | ||
| 533 | + .push_back(clock.now() - clock.origin(sharer_ms)); | ||
| 534 | + let target = self.lateness.iter().copied().max().unwrap_or(0) + DELAY_MARGIN_MS; | ||
| 535 | + let current = clock.delay.load(Ordering::Relaxed); | ||
| 536 | + let next = if target > current { target } else { current - 1 }; | ||
| 537 | + clock | ||
| 538 | + .delay | ||
| 539 | + .store(next.clamp(MIN_DELAY_MS, MAX_DELAY_MS), Ordering::Relaxed); | ||
| 540 | + } | ||
| 541 | + | ||
| 542 | + fn queuing(&self) -> i64 { | ||
| 543 | + let floor = self.lateness.iter().copied().min().unwrap_or(0); | ||
| 544 | + let mut recent: Vec<i64> = self | ||
| 545 | + .lateness | ||
| 546 | + .iter() | ||
| 547 | + .rev() | ||
| 548 | + .take(QUEUING_SAMPLES) | ||
| 549 | + .copied() | ||
| 550 | + .collect(); | ||
| 551 | + recent.sort_unstable(); | ||
| 552 | + recent.get(recent.len() / 2).map_or(0, |median| median - floor) | ||
| 474 | } | 553 | } |
| 475 | } | 554 | } |
| 476 | 555 | ||
| 477 | #[derive(Default)] | 556 | #[derive(Default)] |
| 478 | struct Video { | 557 | struct Video { |
| 479 | - queue: VecDeque<(i64, media::Frame)>, | 558 | + queue: VecDeque<(i64, i64, media::Frame)>, |
| 480 | - shown: Option<media::Frame>, | ||
| 481 | generation: u64, | 559 | generation: u64, |
| 482 | decoded: u32, | 560 | decoded: u32, |
| 483 | engine: Option<Engine>, | 561 | engine: Option<Engine>, |
| @@ -488,13 +566,17 @@ struct Video { | |||
| 488 | #[derive(Default)] | 566 | #[derive(Default)] |
| 489 | struct Health { | 567 | struct Health { |
| 490 | loss: f32, | 568 | loss: f32, |
| 569 | + queuing_ms: i64, | ||
| 491 | packet_loss: Option<f32>, | 570 | packet_loss: Option<f32>, |
| 492 | lost: bool, | 571 | lost: bool, |
| 572 | + recover: bool, | ||
| 493 | served: Option<Layer>, | 573 | served: Option<Layer>, |
| 494 | keyframes: u32, | 574 | keyframes: u32, |
| 575 | + nacks: u32, | ||
| 495 | } | 576 | } |
| 496 | 577 | ||
| 497 | pub struct Watching { | 578 | pub struct Watching { |
| 579 | + link: Arc<Mutex<Option<Connection>>>, | ||
| 498 | clock: Arc<Clock>, | 580 | clock: Arc<Clock>, |
| 499 | video: Arc<Mutex<Video>>, | 581 | video: Arc<Mutex<Video>>, |
| 500 | health: Arc<Mutex<Health>>, | 582 | health: Arc<Mutex<Health>>, |
| @@ -517,6 +599,7 @@ pub struct Watching { | |||
| 517 | 599 | ||
| 518 | impl Watching { | 600 | impl Watching { |
| 519 | pub fn new( | 601 | pub fn new( |
| 602 | + user_id: Id, | ||
| 520 | kind: Kind, | 603 | kind: Kind, |
| 521 | quality: WatchQuality, | 604 | quality: WatchQuality, |
| 522 | top: Quality, | 605 | top: Quality, |
| @@ -527,16 +610,23 @@ impl Watching { | |||
| 527 | let clock = Arc::new(Clock { | 610 | let clock = Arc::new(Clock { |
| 528 | started: Instant::now(), | 611 | started: Instant::now(), |
| 529 | offset: AtomicI64::new(i64::MAX), | 612 | offset: AtomicI64::new(i64::MAX), |
| 613 | + delay: AtomicI64::new(INITIAL_DELAY_MS), | ||
| 530 | }); | 614 | }); |
| 531 | let video = Arc::new(Mutex::new(Video::default())); | 615 | let video = Arc::new(Mutex::new(Video::default())); |
| 532 | let health = Arc::new(Mutex::new(Health::default())); | 616 | let health = Arc::new(Mutex::new(Health::default())); |
| 533 | let volume = Arc::new(AtomicU32::new((volume / 100.0).to_bits())); | 617 | let volume = Arc::new(AtomicU32::new((volume / 100.0).to_bits())); |
| 534 | let (video_tx, video_rx) = mpsc::channel(); | 618 | let (video_tx, video_rx) = mpsc::channel(); |
| 535 | 619 | ||
| 620 | + let link = Arc::new(Mutex::new(None)); | ||
| 536 | let video_worker = { | 621 | let video_worker = { |
| 537 | let (clock, video, health) = (clock.clone(), video.clone(), health.clone()); | 622 | let (clock, video, health) = (clock.clone(), video.clone(), health.clone()); |
| 623 | + let feedback = Feedback { | ||
| 624 | + link: link.clone(), | ||
| 625 | + user_id, | ||
| 626 | + kind, | ||
| 627 | + }; | ||
| 538 | Worker::spawn("share-video", move |stop| { | 628 | Worker::spawn("share-video", move |stop| { |
| 539 | - watch_video(video_rx, &clock, &video, &health, stop) | 629 | + watch_video(video_rx, &feedback, &clock, &video, &health, stop) |
| 540 | }) | 630 | }) |
| 541 | }; | 631 | }; |
| 542 | let meter = Meter::default(); | 632 | let meter = Meter::default(); |
| @@ -568,6 +658,7 @@ impl Watching { | |||
| 568 | received: AtomicU64::new(0), | 658 | received: AtomicU64::new(0), |
| 569 | since: Instant::now(), | 659 | since: Instant::now(), |
| 570 | _video: video_worker, | 660 | _video: video_worker, |
| 661 | + link, | ||
| 571 | _audio: audio_worker, | 662 | _audio: audio_worker, |
| 572 | _output: output, | 663 | _output: output, |
| 573 | quality, | 664 | quality, |
| @@ -595,7 +686,7 @@ impl Watching { | |||
| 595 | let (ts_ms, tx) = match packet { | 686 | let (ts_ms, tx) = match packet { |
| 596 | Packet::Video { ts_ms, .. } => (*ts_ms, Some(&self.video_tx)), | 687 | Packet::Video { ts_ms, .. } => (*ts_ms, Some(&self.video_tx)), |
| 597 | Packet::ScreenAudio { ts_ms, .. } => (*ts_ms, self.audio_tx.as_ref()), | 688 | Packet::ScreenAudio { ts_ms, .. } => (*ts_ms, self.audio_tx.as_ref()), |
| 598 | - Packet::Voice { .. } => return, | 689 | + Packet::Voice { .. } | Packet::Nack { .. } | Packet::Ack { .. } => return, |
| 599 | }; | 690 | }; |
| 600 | self.clock.observe(ts_ms); | 691 | self.clock.observe(ts_ms); |
| 601 | self.received | 692 | self.received |
| @@ -605,6 +696,10 @@ impl Watching { | |||
| 605 | } | 696 | } |
| 606 | } | 697 | } |
| 607 | 698 | ||
| 699 | + pub fn connect(&self, connection: Connection) { | ||
| 700 | + *lock(&self.link) = Some(connection); | ||
| 701 | + } | ||
| 702 | + | ||
| 608 | pub fn stats(&mut self) -> WatchStats { | 703 | pub fn stats(&mut self) -> WatchStats { |
| 609 | let seconds = std::mem::replace(&mut self.since, Instant::now()) | 704 | let seconds = std::mem::replace(&mut self.since, Instant::now()) |
| 610 | .elapsed() | 705 | .elapsed() |
| @@ -614,7 +709,7 @@ impl Watching { | |||
| 614 | let (decoded, engine, buffer_ms, latency_ms) = { | 709 | let (decoded, engine, buffer_ms, latency_ms) = { |
| 615 | let mut video = lock(&self.video); | 710 | let mut video = lock(&self.video); |
| 616 | let buffer_ms = match (video.queue.front(), video.queue.back()) { | 711 | let buffer_ms = match (video.queue.front(), video.queue.back()) { |
| 617 | - (Some((first, _)), Some((last, _))) => last - first, | 712 | + (Some((first, ..)), Some((last, ..))) => last - first, |
| 618 | _ => 0, | 713 | _ => 0, |
| 619 | }; | 714 | }; |
| 620 | let latency_ms = | 715 | let latency_ms = |
| @@ -638,6 +733,7 @@ impl Watching { | |||
| 638 | keyframes: health.keyframes, | 733 | keyframes: health.keyframes, |
| 639 | buffer_ms, | 734 | buffer_ms, |
| 640 | latency_ms, | 735 | latency_ms, |
| 736 | + nacks: health.nacks, | ||
| 641 | } | 737 | } |
| 642 | } | 738 | } |
| 643 | 739 | ||
| @@ -645,17 +741,15 @@ impl Watching { | |||
| 645 | let now = self.clock.now(); | 741 | let now = self.clock.now(); |
| 646 | let mut video = lock(&self.video); | 742 | let mut video = lock(&self.video); |
| 647 | let mut due = None; | 743 | let mut due = None; |
| 648 | - while video.queue.front().is_some_and(|(at, _)| *at <= now) { | 744 | + while video.queue.front().is_some_and(|(at, ..)| *at <= now) { |
| 649 | due = video.queue.pop_front(); | 745 | due = video.queue.pop_front(); |
| 650 | } | 746 | } |
| 651 | - if let Some((at, mut frame)) = due { | 747 | + let (_, origin, mut frame) = due?; |
| 652 | - video.latency_total += now - at + DELAY_MS; | 748 | + video.latency_total += now - origin; |
| 653 | - video.latency_count += 1; | 749 | + video.latency_count += 1; |
| 654 | - video.generation += 1; | 750 | + video.generation += 1; |
| 655 | - frame.generation = video.generation; | 751 | + frame.generation = video.generation; |
| 656 | - video.shown = Some(frame); | 752 | + Some(frame) |
| 657 | - } | ||
| 658 | - video.shown.clone() | ||
| 659 | } | 753 | } |
| 660 | 754 | ||
| 661 | pub fn set_quality(&mut self, quality: WatchQuality) { | 755 | pub fn set_quality(&mut self, quality: WatchQuality) { |
| @@ -673,24 +767,30 @@ impl Watching { | |||
| 673 | } | 767 | } |
| 674 | 768 | ||
| 675 | pub fn tick(&mut self) -> Vec<Tick> { | 769 | pub fn tick(&mut self) -> Vec<Tick> { |
| 676 | - let (loss, served, lost, packet_loss) = { | 770 | + let (loss, queuing_ms, served, lost, packet_loss) = { |
| 677 | let mut health = lock(&self.health); | 771 | let mut health = lock(&self.health); |
| 678 | let due = self | 772 | let due = self |
| 679 | .requested | 773 | .requested |
| 680 | .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); | 774 | .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); |
| 681 | let lost = health.lost && due; | 775 | let lost = health.lost && due; |
| 682 | - (health.loss, health.served, lost, health.packet_loss.take()) | 776 | + ( |
| 777 | + health.loss, | ||
| 778 | + health.queuing_ms, | ||
| 779 | + health.served, | ||
| 780 | + lost.then_some(health.recover), | ||
| 781 | + health.packet_loss.take(), | ||
| 782 | + ) | ||
| 683 | }; | 783 | }; |
| 684 | let mut ticks = Vec::new(); | 784 | let mut ticks = Vec::new(); |
| 685 | if let Some(packet_loss) = packet_loss.filter(|loss| *loss > 0.0) { | 785 | if let Some(packet_loss) = packet_loss.filter(|loss| *loss > 0.0) { |
| 686 | ticks.push(Tick::Loss((packet_loss * 1000.0).ceil() as u16)); | 786 | ticks.push(Tick::Loss((packet_loss * 1000.0).ceil() as u16)); |
| 687 | } | 787 | } |
| 688 | - if lost { | 788 | + if let Some(recover) = lost { |
| 689 | self.requested = Some(Instant::now()); | 789 | self.requested = Some(Instant::now()); |
| 690 | - ticks.push(Tick::Keyframe); | 790 | + ticks.push(Tick::Keyframe { recover }); |
| 691 | } | 791 | } |
| 692 | if self.quality == WatchQuality::Auto { | 792 | if self.quality == WatchQuality::Auto { |
| 693 | - self.adapt(loss, served); | 793 | + self.adapt(loss, queuing_ms, served); |
| 694 | } | 794 | } |
| 695 | let wanted = self.wanted(); | 795 | let wanted = self.wanted(); |
| 696 | if self.emitted != Some(wanted) { | 796 | if self.emitted != Some(wanted) { |
| @@ -700,12 +800,12 @@ impl Watching { | |||
| 700 | ticks | 800 | ticks |
| 701 | } | 801 | } |
| 702 | 802 | ||
| 703 | - fn adapt(&mut self, loss: f32, served: Option<Layer>) { | 803 | + fn adapt(&mut self, loss: f32, queuing_ms: i64, served: Option<Layer>) { |
| 704 | let rung = self.rung; | 804 | let rung = self.rung; |
| 705 | - if loss > LOSS_LIMIT { | 805 | + if loss > LOSS_LIMIT || queuing_ms > QUEUING_LIMIT_MS { |
| 706 | self.rung = (self.rung + 1).min(self.ladder.len() - 1); | 806 | self.rung = (self.rung + 1).min(self.ladder.len() - 1); |
| 707 | self.clean = 0; | 807 | self.clean = 0; |
| 708 | - } else if loss < CLEAN_LOSS { | 808 | + } else if loss < CLEAN_LOSS && queuing_ms < QUEUING_CLEAN_MS { |
| 709 | self.clean += 1; | 809 | self.clean += 1; |
| 710 | if self.clean >= CLEAN_SECONDS | 810 | if self.clean >= CLEAN_SECONDS |
| 711 | && served.is_some_and(|layer| layer.quality == self.ladder[self.rung]) | 811 | && served.is_some_and(|layer| layer.quality == self.ladder[self.rung]) |
| @@ -717,7 +817,7 @@ impl Watching { | |||
| 717 | self.clean = 0; | 817 | self.clean = 0; |
| 718 | } | 818 | } |
| 719 | if self.rung != rung { | 819 | if self.rung != rung { |
| 720 | - tracing::info!(loss, quality = ?self.ladder[self.rung], "share watch quality"); | 820 | + tracing::info!(loss, queuing_ms, quality = ?self.ladder[self.rung], "share watch quality"); |
| 721 | } | 821 | } |
| 722 | } | 822 | } |
| 723 | } | 823 | } |
| @@ -749,8 +849,59 @@ fn rungs() -> &'static [Quality] { | |||
| 749 | &RUNGS | 849 | &RUNGS |
| 750 | } | 850 | } |
| 751 | 851 | ||
| 852 | +struct Feedback { | ||
| 853 | + link: Arc<Mutex<Option<Connection>>>, | ||
| 854 | + user_id: Id, | ||
| 855 | + kind: Kind, | ||
| 856 | +} | ||
| 857 | + | ||
| 858 | +impl Feedback { | ||
| 859 | + fn rtt(&self) -> Duration { | ||
| 860 | + lock(&self.link) | ||
| 861 | + .as_ref() | ||
| 862 | + .map_or(DEFAULT_RTT, Connection::rtt) | ||
| 863 | + } | ||
| 864 | + | ||
| 865 | + fn ack(&self, (layer, ts_ms): (Layer, u32)) { | ||
| 866 | + let Some(connection) = lock(&self.link).clone() else { | ||
| 867 | + return; | ||
| 868 | + }; | ||
| 869 | + let mut out = Vec::new(); | ||
| 870 | + Packet::Ack { | ||
| 871 | + kind: self.kind, | ||
| 872 | + user_id: self.user_id, | ||
| 873 | + layer, | ||
| 874 | + ts_ms, | ||
| 875 | + } | ||
| 876 | + .encode(&mut out); | ||
| 877 | + datagram::send(&connection, Bytes::from(out)); | ||
| 878 | + } | ||
| 879 | + | ||
| 880 | + fn send(&self, nack: &Nack) { | ||
| 881 | + let Some(connection) = lock(&self.link).clone() else { | ||
| 882 | + return; | ||
| 883 | + }; | ||
| 884 | + let indices: Vec<u8> = nack | ||
| 885 | + .indices | ||
| 886 | + .iter() | ||
| 887 | + .flat_map(|index| index.to_le_bytes()) | ||
| 888 | + .collect(); | ||
| 889 | + let mut out = Vec::new(); | ||
| 890 | + Packet::Nack { | ||
| 891 | + kind: self.kind, | ||
| 892 | + user_id: self.user_id, | ||
| 893 | + layer: nack.layer, | ||
| 894 | + frame: nack.frame, | ||
| 895 | + indices: &indices, | ||
| 896 | + } | ||
| 897 | + .encode(&mut out); | ||
| 898 | + datagram::send(&connection, Bytes::from(out)); | ||
| 899 | + } | ||
| 900 | +} | ||
| 901 | + | ||
| 752 | fn watch_video( | 902 | fn watch_video( |
| 753 | rx: Receiver<Bytes>, | 903 | rx: Receiver<Bytes>, |
| 904 | + feedback: &Feedback, | ||
| 754 | clock: &Clock, | 905 | clock: &Clock, |
| 755 | video: &Mutex<Video>, | 906 | video: &Mutex<Video>, |
| 756 | health: &Mutex<Health>, | 907 | health: &Mutex<Health>, |
| @@ -759,24 +910,62 @@ fn watch_video( | |||
| 759 | let mut reassembler = Reassembler::new(); | 910 | let mut reassembler = Reassembler::new(); |
| 760 | let mut decoder: Option<(Codec, VideoDecoder)> = None; | 911 | let mut decoder: Option<(Codec, VideoDecoder)> = None; |
| 761 | let mut sampled = Instant::now(); | 912 | let mut sampled = Instant::now(); |
| 913 | + let mut playout = Playout::default(); | ||
| 914 | + let mut decoded: Option<(Layer, u32)> = None; | ||
| 915 | + let mut acked_at = Instant::now(); | ||
| 916 | + let mut show = |assembled: Assembled| { | ||
| 917 | + { | ||
| 918 | + let mut health = lock(health); | ||
| 919 | + health.served = Some(assembled.layer); | ||
| 920 | + health.keyframes += u32::from(assembled.keyframe); | ||
| 921 | + } | ||
| 922 | + decode_video(&mut decoder, &assembled, clock, &mut playout, video); | ||
| 923 | + lock(health).queuing_ms = playout.queuing(); | ||
| 924 | + (assembled.layer, assembled.timestamp_ms) | ||
| 925 | + }; | ||
| 762 | while !stop.load(Ordering::Relaxed) { | 926 | while !stop.load(Ordering::Relaxed) { |
| 763 | - match rx.recv_timeout(STOP_CHECK) { | 927 | + match rx.recv_timeout(NACK_TICK) { |
| 764 | Ok(bytes) => { | 928 | Ok(bytes) => { |
| 765 | if let Some((_, packet)) = split(&bytes) | 929 | if let Some((_, packet)) = split(&bytes) |
| 766 | - && let Some(assembled) = reassembler.push(&packet) | 930 | + && let Some(last) = reassembler |
| 931 | + .push(&packet, Instant::now()) | ||
| 932 | + .into_iter() | ||
| 933 | + .map(&mut show) | ||
| 934 | + .last() | ||
| 767 | { | 935 | { |
| 768 | - { | 936 | + decoded = Some(last); |
| 769 | - let mut health = lock(health); | ||
| 770 | - health.served = Some(assembled.layer); | ||
| 771 | - health.keyframes += u32::from(assembled.keyframe); | ||
| 772 | - } | ||
| 773 | - decode_video(&mut decoder, &assembled, clock, video); | ||
| 774 | } | 937 | } |
| 775 | } | 938 | } |
| 776 | Err(RecvTimeoutError::Timeout) => {} | 939 | Err(RecvTimeoutError::Timeout) => {} |
| 777 | Err(RecvTimeoutError::Disconnected) => break, | 940 | Err(RecvTimeoutError::Disconnected) => break, |
| 778 | } | 941 | } |
| 779 | - lock(health).lost = reassembler.needs_keyframe(); | 942 | + let now = Instant::now(); |
| 943 | + let rtt = feedback.rtt(); | ||
| 944 | + let wait = (rtt * 2 + NACK_SLACK).clamp(NACK_SLACK, NACK_GIVE_UP); | ||
| 945 | + if let Some(last) = reassembler | ||
| 946 | + .expire(now, wait) | ||
| 947 | + .into_iter() | ||
| 948 | + .map(&mut show) | ||
| 949 | + .last() | ||
| 950 | + { | ||
| 951 | + decoded = Some(last); | ||
| 952 | + } | ||
| 953 | + let nacks = reassembler.nacks(now, rtt); | ||
| 954 | + lock(health).nacks += nacks.len() as u32; | ||
| 955 | + for nack in &nacks { | ||
| 956 | + feedback.send(nack); | ||
| 957 | + } | ||
| 958 | + { | ||
| 959 | + let mut health = lock(health); | ||
| 960 | + health.lost = reassembler.needs_keyframe(); | ||
| 961 | + health.recover = reassembler.can_recover(); | ||
| 962 | + } | ||
| 963 | + if acked_at.elapsed() >= ACK_INTERVAL | ||
| 964 | + && let Some(ack) = decoded.take() | ||
| 965 | + { | ||
| 966 | + feedback.ack(ack); | ||
| 967 | + acked_at = Instant::now(); | ||
| 968 | + } | ||
| 780 | if sampled.elapsed() >= SAMPLE { | 969 | if sampled.elapsed() >= SAMPLE { |
| 781 | let mut health = lock(health); | 970 | let mut health = lock(health); |
| 782 | health.loss = reassembler.loss_ratio(); | 971 | health.loss = reassembler.loss_ratio(); |
| @@ -790,6 +979,7 @@ fn decode_video( | |||
| 790 | decoder: &mut Option<(Codec, VideoDecoder)>, | 979 | decoder: &mut Option<(Codec, VideoDecoder)>, |
| 791 | assembled: &Assembled, | 980 | assembled: &Assembled, |
| 792 | clock: &Clock, | 981 | clock: &Clock, |
| 982 | + playout: &mut Playout, | ||
| 793 | video: &Mutex<Video>, | 983 | video: &Mutex<Video>, |
| 794 | ) { | 984 | ) { |
| 795 | let codec = assembled.layer.codec; | 985 | let codec = assembled.layer.codec; |
| @@ -799,16 +989,20 @@ fn decode_video( | |||
| 799 | let Some((_, active)) = decoder.as_mut() else { | 989 | let Some((_, active)) = decoder.as_mut() else { |
| 800 | return; | 990 | return; |
| 801 | }; | 991 | }; |
| 802 | - let due = clock.due(assembled.timestamp_ms); | ||
| 803 | let engine = active.engine(); | 992 | let engine = active.engine(); |
| 804 | let pictures = active.decode(&assembled.data, assembled.timestamp_ms); | 993 | let pictures = active.decode(&assembled.data, assembled.timestamp_ms); |
| 994 | + playout.observe(clock, assembled.timestamp_ms); | ||
| 995 | + let (origin, due) = ( | ||
| 996 | + clock.origin(assembled.timestamp_ms), | ||
| 997 | + clock.due(assembled.timestamp_ms), | ||
| 998 | + ); | ||
| 805 | let mut video = lock(video); | 999 | let mut video = lock(video); |
| 806 | video.engine = Some(engine); | 1000 | video.engine = Some(engine); |
| 807 | for picture in pictures { | 1001 | for picture in pictures { |
| 808 | let Some(frame) = picture.into_frame(media::convert::SHARE_WIDTH) else { | 1002 | let Some(frame) = picture.into_frame(media::convert::SHARE_WIDTH) else { |
| 809 | continue; | 1003 | continue; |
| 810 | }; | 1004 | }; |
| 811 | - video.queue.push_back((due, frame)); | 1005 | + video.queue.push_back((due, origin, frame)); |
| 812 | video.decoded += 1; | 1006 | video.decoded += 1; |
| 813 | while video.queue.len() > QUEUE_LIMIT { | 1007 | while video.queue.len() > QUEUE_LIMIT { |
| 814 | video.queue.pop_front(); | 1008 | video.queue.pop_front(); |
| @@ -918,6 +1112,7 @@ mod tests { | |||
| 918 | layer: encoded.layer, | 1112 | layer: encoded.layer, |
| 919 | frame: number as u32, | 1113 | frame: number as u32, |
| 920 | keyframe: encoded.keyframe, | 1114 | keyframe: encoded.keyframe, |
| 1115 | + recovery: false, | ||
| 921 | ts_ms: encoded.timestamp_ms, | 1116 | ts_ms: encoded.timestamp_ms, |
| 922 | parity: 1, | 1117 | parity: 1, |
| 923 | }; | 1118 | }; |
| @@ -925,7 +1120,7 @@ mod tests { | |||
| 925 | let Some(packet) = Packet::decode(packet) else { | 1120 | let Some(packet) = Packet::decode(packet) else { |
| 926 | panic!("fragment"); | 1121 | panic!("fragment"); |
| 927 | }; | 1122 | }; |
| 928 | - if let Some(assembled) = reassembler.push(&packet) { | 1123 | + for assembled in reassembler.push(&packet, Instant::now()) { |
| 929 | pictures.extend( | 1124 | pictures.extend( |
| 930 | decoder.decode(&assembled.data, assembled.timestamp_ms), | 1125 | decoder.decode(&assembled.data, assembled.timestamp_ms), |
| 931 | ); | 1126 | ); |
crates/client/src/voice/engine.rsmodified+21 -6
| @@ -29,7 +29,9 @@ const RESTART_AFTER: Duration = Duration::from_secs(1); | |||
| 29 | const MAX_DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000; | 29 | const MAX_DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000; |
| 30 | const HANGOVER_FRAMES: u32 = 15; | 30 | const HANGOVER_FRAMES: u32 = 15; |
| 31 | const FADE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 5 / 1000; | 31 | const FADE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 5 / 1000; |
| 32 | -const EXPECTED_LOSS_PERC: u8 = 10; | 32 | +const INITIAL_LOSS_PERC: u8 = 3; |
| 33 | +const MIN_LOSS_PERC: u8 = 3; | ||
| 34 | +const MAX_LOSS_PERC: u8 = 25; | ||
| 33 | 35 | ||
| 34 | fn soft_clip(sample: f32) -> f32 { | 36 | fn soft_clip(sample: f32) -> f32 { |
| 35 | const KNEE: f32 = 0.8; | 37 | const KNEE: f32 = 0.8; |
| @@ -52,7 +54,7 @@ fn bitrate(profile: Profile) -> u32 { | |||
| 52 | } | 54 | } |
| 53 | } | 55 | } |
| 54 | 56 | ||
| 55 | -fn encoder(profile: Profile) -> Encoder { | 57 | +fn encoder(profile: Profile, loss_perc: u8) -> Encoder { |
| 56 | let application = match profile { | 58 | let application = match profile { |
| 57 | Profile::Voice => Application::Voip, | 59 | Profile::Voice => Application::Voip, |
| 58 | Profile::Music => Application::Audio, | 60 | Profile::Music => Application::Audio, |
| @@ -62,7 +64,7 @@ fn encoder(profile: Profile) -> Encoder { | |||
| 62 | encoder.set_bandwidth(Some(Bandwidth::Full)); | 64 | encoder.set_bandwidth(Some(Bandwidth::Full)); |
| 63 | encoder.set_analysis(true); | 65 | encoder.set_analysis(true); |
| 64 | encoder.set_inband_fec(true); | 66 | encoder.set_inband_fec(true); |
| 65 | - encoder.set_packet_loss_perc(EXPECTED_LOSS_PERC); | 67 | + encoder.set_packet_loss_perc(loss_perc); |
| 66 | encoder | 68 | encoder |
| 67 | } | 69 | } |
| 68 | 70 | ||
| @@ -168,6 +170,7 @@ impl Speaker { | |||
| 168 | 170 | ||
| 169 | pub struct Engine { | 171 | pub struct Engine { |
| 170 | encoder: Encoder, | 172 | encoder: Encoder, |
| 173 | + loss_perc: u8, | ||
| 171 | profile: Profile, | 174 | profile: Profile, |
| 172 | capture_buffer: Vec<f32>, | 175 | capture_buffer: Vec<f32>, |
| 173 | sequence: u32, | 176 | sequence: u32, |
| @@ -200,7 +203,8 @@ impl Default for Engine { | |||
| 200 | impl Engine { | 203 | impl Engine { |
| 201 | pub fn new() -> Self { | 204 | pub fn new() -> Self { |
| 202 | Self { | 205 | Self { |
| 203 | - encoder: encoder(Profile::Voice), | 206 | + encoder: encoder(Profile::Voice, INITIAL_LOSS_PERC), |
| 207 | + loss_perc: INITIAL_LOSS_PERC, | ||
| 204 | profile: Profile::Voice, | 208 | profile: Profile::Voice, |
| 205 | capture_buffer: Vec::new(), | 209 | capture_buffer: Vec::new(), |
| 206 | sequence: 0, | 210 | sequence: 0, |
| @@ -304,7 +308,6 @@ impl Engine { | |||
| 304 | } | 308 | } |
| 305 | speaker.last_heard = now; | 309 | speaker.last_heard = now; |
| 306 | if payload.is_empty() { | 310 | if payload.is_empty() { |
| 307 | - speaker.spectrum.absorb(&mut self.sent); | ||
| 308 | return; | 311 | return; |
| 309 | } | 312 | } |
| 310 | if sequence < speaker.next { | 313 | if sequence < speaker.next { |
| @@ -426,15 +429,27 @@ impl Engine { | |||
| 426 | self.output_gain = output_volume / 100.0; | 429 | self.output_gain = output_volume / 100.0; |
| 427 | self.activation = activation; | 430 | self.activation = activation; |
| 428 | if profile != self.profile { | 431 | if profile != self.profile { |
| 429 | - self.encoder = encoder(profile); | 432 | + self.encoder = encoder(profile, self.loss_perc); |
| 430 | self.profile = profile; | 433 | self.profile = profile; |
| 431 | } | 434 | } |
| 432 | } | 435 | } |
| 433 | 436 | ||
| 437 | + pub fn set_uplink_loss(&mut self, loss: f32) { | ||
| 438 | + let perc = ((loss * 100.0 * 2.0).ceil() as u8).clamp(MIN_LOSS_PERC, MAX_LOSS_PERC); | ||
| 439 | + if perc != self.loss_perc { | ||
| 440 | + self.encoder.set_packet_loss_perc(perc); | ||
| 441 | + self.loss_perc = perc; | ||
| 442 | + } | ||
| 443 | + } | ||
| 444 | + | ||
| 434 | pub fn set_talking(&mut self, talking: bool) { | 445 | pub fn set_talking(&mut self, talking: bool) { |
| 435 | self.talking = talking; | 446 | self.talking = talking; |
| 436 | } | 447 | } |
| 437 | 448 | ||
| 449 | + pub fn own_level(&mut self) -> Vec<f32> { | ||
| 450 | + self.sent.take() | ||
| 451 | + } | ||
| 452 | + | ||
| 438 | pub fn level_db(&self) -> f32 { | 453 | pub fn level_db(&self) -> f32 { |
| 439 | self.level_db | 454 | self.level_db |
| 440 | } | 455 | } |
crates/client/src/voice/mod.rsmodified+27 -4
| @@ -49,6 +49,7 @@ pub struct Voice { | |||
| 49 | playback: Playback, | 49 | playback: Playback, |
| 50 | choice: Choice, | 50 | choice: Choice, |
| 51 | audio: Audio, | 51 | audio: Audio, |
| 52 | + last_path: Mutex<(u64, u64)>, | ||
| 52 | } | 53 | } |
| 53 | 54 | ||
| 54 | pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice { | 55 | pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice { |
| @@ -85,6 +86,7 @@ pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice | |||
| 85 | playback, | 86 | playback, |
| 86 | choice: settings.choice.clone(), | 87 | choice: settings.choice.clone(), |
| 87 | audio, | 88 | audio, |
| 89 | + last_path: Mutex::new((0, 0)), | ||
| 88 | }; | 90 | }; |
| 89 | voice.apply(settings); | 91 | voice.apply(settings); |
| 90 | voice | 92 | voice |
| @@ -298,6 +300,10 @@ impl Voice { | |||
| 298 | self.with_engine(Vec::new(), Engine::levels) | 300 | self.with_engine(Vec::new(), Engine::levels) |
| 299 | } | 301 | } |
| 300 | 302 | ||
| 303 | + pub fn own_level(&self) -> Vec<f32> { | ||
| 304 | + self.with_engine(Vec::new(), Engine::own_level) | ||
| 305 | + } | ||
| 306 | + | ||
| 301 | pub fn level_db(&self) -> f32 { | 307 | pub fn level_db(&self) -> f32 { |
| 302 | self.with_engine(SILENT_DB, |engine| engine.level_db()) | 308 | self.with_engine(SILENT_DB, |engine| engine.level_db()) |
| 303 | } | 309 | } |
| @@ -307,10 +313,27 @@ impl Voice { | |||
| 307 | .connection | 313 | .connection |
| 308 | .as_ref() | 314 | .as_ref() |
| 309 | .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0); | 315 | .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0); |
| 310 | - self.with_engine(VoiceSample::default(), |engine| VoiceSample { | 316 | + let (lost, sent) = self.connection.as_ref().map_or((0, 0), |connection| { |
| 311 | - ping_ms, | 317 | + let path = connection.stats().path; |
| 312 | - traffic: engine.take_traffic(), | 318 | + (path.lost_packets, path.sent_packets) |
| 313 | - bitrate_kbps: engine.bitrate_kbps(), | 319 | + }); |
| 320 | + let loss = { | ||
| 321 | + let mut last = self | ||
| 322 | + .last_path | ||
| 323 | + .lock() | ||
| 324 | + .unwrap_or_else(|poisoned| poisoned.into_inner()); | ||
| 325 | + let lost_delta = lost.saturating_sub(last.0); | ||
| 326 | + let sent_delta = sent.saturating_sub(last.1); | ||
| 327 | + *last = (lost, sent); | ||
| 328 | + lost_delta as f32 / sent_delta.max(1) as f32 | ||
| 329 | + }; | ||
| 330 | + self.with_engine(VoiceSample::default(), |engine| { | ||
| 331 | + engine.set_uplink_loss(loss); | ||
| 332 | + VoiceSample { | ||
| 333 | + ping_ms, | ||
| 334 | + traffic: engine.take_traffic(), | ||
| 335 | + bitrate_kbps: engine.bitrate_kbps(), | ||
| 336 | + } | ||
| 314 | }) | 337 | }) |
| 315 | } | 338 | } |
| 316 | 339 | ||
crates/common/src/call.rsmodified+1 -0
| @@ -393,6 +393,7 @@ pub struct UnwatchShare { | |||
| 393 | pub struct RequestKeyframe { | 393 | pub struct RequestKeyframe { |
| 394 | pub user_id: Id, | 394 | pub user_id: Id, |
| 395 | pub kind: Kind, | 395 | pub kind: Kind, |
| 396 | + pub recover: bool, | ||
| 396 | } | 397 | } |
| 397 | 398 | ||
| 398 | #[derive(Debug, Clone, Encode, Decode)] | 399 | #[derive(Debug, Clone, Encode, Decode)] |
crates/common/src/constant.rsmodified+1 -1
| @@ -20,7 +20,7 @@ pub const MAXIMUM_STATUS_LENGTH: usize = 64; | |||
| 20 | pub const MAXIMUM_DEVICE_NAME_LENGTH: usize = 64; | 20 | pub const MAXIMUM_DEVICE_NAME_LENGTH: usize = 64; |
| 21 | pub const VOICE_SAMPLE_RATE: u32 = 48_000; | 21 | pub const VOICE_SAMPLE_RATE: u32 = 48_000; |
| 22 | pub const VOICE_FRAME_SAMPLES: usize = 960; | 22 | pub const VOICE_FRAME_SAMPLES: usize = 960; |
| 23 | -pub const VOICE_BITRATE: i32 = 48_000; | 23 | +pub const VOICE_BITRATE: i32 = 32_000; |
| 24 | pub const MUSIC_BITRATE: i32 = 96_000; | 24 | pub const MUSIC_BITRATE: i32 = 96_000; |
| 25 | pub const VOICE_MAX_PAYLOAD: usize = 1000; | 25 | pub const VOICE_MAX_PAYLOAD: usize = 1000; |
| 26 | pub const MINIMUM_ATTACHMENT_LIMIT_BYTES: u64 = 1024 * 1024; | 26 | pub const MINIMUM_ATTACHMENT_LIMIT_BYTES: u64 = 1024 * 1024; |
crates/common/src/datagram.rsmodified+84 -3
| @@ -19,6 +19,7 @@ pub const VOICE_HEADER: usize = 5; | |||
| 19 | const SHARE_AUDIO_HEADER: usize = 9; | 19 | const SHARE_AUDIO_HEADER: usize = 9; |
| 20 | const VIDEO_HEADER: usize = 19; | 20 | const VIDEO_HEADER: usize = 19; |
| 21 | const KEYFRAME_FLAG: u8 = 1; | 21 | const KEYFRAME_FLAG: u8 = 1; |
| 22 | +const RECOVERY_FLAG: u8 = 2; | ||
| 22 | 23 | ||
| 23 | const _: () = assert!(RELAY_PREFIX + VIDEO_HEADER + VIDEO_FRAGMENT_BYTES <= MAX_DATAGRAM); | 24 | const _: () = assert!(RELAY_PREFIX + VIDEO_HEADER + VIDEO_FRAGMENT_BYTES <= MAX_DATAGRAM); |
| 24 | const _: () = assert!(RELAY_PREFIX + SHARE_AUDIO_HEADER + VOICE_MAX_PAYLOAD <= MAX_DATAGRAM); | 25 | const _: () = assert!(RELAY_PREFIX + SHARE_AUDIO_HEADER + VOICE_MAX_PAYLOAD <= MAX_DATAGRAM); |
| @@ -27,6 +28,10 @@ const TAG_VOICE: u8 = 0; | |||
| 27 | const TAG_SCREEN_AUDIO: u8 = 1; | 28 | const TAG_SCREEN_AUDIO: u8 = 1; |
| 28 | const TAG_SCREEN: u8 = 2; | 29 | const TAG_SCREEN: u8 = 2; |
| 29 | const TAG_CAMERA: u8 = 3; | 30 | const TAG_CAMERA: u8 = 3; |
| 31 | +const TAG_NACK: u8 = 4; | ||
| 32 | +const TAG_ACK: u8 = 5; | ||
| 33 | +const NACK_HEADER: usize = 15; | ||
| 34 | +pub const NACK_MAX: usize = 64; | ||
| 30 | 35 | ||
| 31 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 36 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 32 | pub enum Packet<'a> { | 37 | pub enum Packet<'a> { |
| @@ -43,6 +48,7 @@ pub enum Packet<'a> { | |||
| 43 | kind: Kind, | 48 | kind: Kind, |
| 44 | layer: Layer, | 49 | layer: Layer, |
| 45 | keyframe: bool, | 50 | keyframe: bool, |
| 51 | + recovery: bool, | ||
| 46 | frame: u32, | 52 | frame: u32, |
| 47 | index: u16, | 53 | index: u16, |
| 48 | parity: u16, | 54 | parity: u16, |
| @@ -50,6 +56,19 @@ pub enum Packet<'a> { | |||
| 50 | ts_ms: u32, | 56 | ts_ms: u32, |
| 51 | shard: &'a [u8], | 57 | shard: &'a [u8], |
| 52 | }, | 58 | }, |
| 59 | + Nack { | ||
| 60 | + kind: Kind, | ||
| 61 | + user_id: i64, | ||
| 62 | + layer: Layer, | ||
| 63 | + frame: u32, | ||
| 64 | + indices: &'a [u8], | ||
| 65 | + }, | ||
| 66 | + Ack { | ||
| 67 | + kind: Kind, | ||
| 68 | + user_id: i64, | ||
| 69 | + layer: Layer, | ||
| 70 | + ts_ms: u32, | ||
| 71 | + }, | ||
| 53 | } | 72 | } |
| 54 | 73 | ||
| 55 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -122,6 +141,7 @@ impl<'a> Packet<'a> { | |||
| 122 | kind, | 141 | kind, |
| 123 | layer, | 142 | layer, |
| 124 | keyframe, | 143 | keyframe, |
| 144 | + recovery, | ||
| 125 | frame, | 145 | frame, |
| 126 | index, | 146 | index, |
| 127 | parity, | 147 | parity, |
| @@ -131,7 +151,10 @@ impl<'a> Packet<'a> { | |||
| 131 | } => { | 151 | } => { |
| 132 | out.push(video_tag(*kind)); | 152 | out.push(video_tag(*kind)); |
| 133 | out.push(layer.to_byte()); | 153 | out.push(layer.to_byte()); |
| 134 | - out.push(if *keyframe { KEYFRAME_FLAG } else { 0 }); | 154 | + out.push( |
| 155 | + if *keyframe { KEYFRAME_FLAG } else { 0 } | ||
| 156 | + | if *recovery { RECOVERY_FLAG } else { 0 }, | ||
| 157 | + ); | ||
| 135 | out.extend_from_slice(&frame.to_le_bytes()); | 158 | out.extend_from_slice(&frame.to_le_bytes()); |
| 136 | out.extend_from_slice(&index.to_le_bytes()); | 159 | out.extend_from_slice(&index.to_le_bytes()); |
| 137 | out.extend_from_slice(&length.to_le_bytes()); | 160 | out.extend_from_slice(&length.to_le_bytes()); |
| @@ -139,9 +162,43 @@ impl<'a> Packet<'a> { | |||
| 139 | out.extend_from_slice(&parity.to_le_bytes()); | 162 | out.extend_from_slice(&parity.to_le_bytes()); |
| 140 | out.extend_from_slice(shard); | 163 | out.extend_from_slice(shard); |
| 141 | } | 164 | } |
| 165 | + Self::Nack { | ||
| 166 | + kind, | ||
| 167 | + user_id, | ||
| 168 | + layer, | ||
| 169 | + frame, | ||
| 170 | + indices, | ||
| 171 | + } => { | ||
| 172 | + out.push(TAG_NACK); | ||
| 173 | + out.push(video_tag(*kind)); | ||
| 174 | + out.extend_from_slice(&user_id.to_be_bytes()); | ||
| 175 | + out.push(layer.to_byte()); | ||
| 176 | + out.extend_from_slice(&frame.to_le_bytes()); | ||
| 177 | + out.extend_from_slice(indices); | ||
| 178 | + } | ||
| 179 | + Self::Ack { | ||
| 180 | + kind, | ||
| 181 | + user_id, | ||
| 182 | + layer, | ||
| 183 | + ts_ms, | ||
| 184 | + } => { | ||
| 185 | + out.push(TAG_ACK); | ||
| 186 | + out.push(video_tag(*kind)); | ||
| 187 | + out.extend_from_slice(&user_id.to_be_bytes()); | ||
| 188 | + out.push(layer.to_byte()); | ||
| 189 | + out.extend_from_slice(&ts_ms.to_le_bytes()); | ||
| 190 | + } | ||
| 142 | } | 191 | } |
| 143 | } | 192 | } |
| 144 | 193 | ||
| 194 | + pub fn nack_indices(indices: &[u8]) -> impl Iterator<Item = u16> + '_ { | ||
| 195 | + indices | ||
| 196 | + .as_chunks::<2>() | ||
| 197 | + .0 | ||
| 198 | + .iter() | ||
| 199 | + .map(|pair| u16::from_le_bytes(*pair)) | ||
| 200 | + } | ||
| 201 | + | ||
| 145 | pub fn decode(b: &'a [u8]) -> Option<Self> { | 202 | pub fn decode(b: &'a [u8]) -> Option<Self> { |
| 146 | match *b.first()? { | 203 | match *b.first()? { |
| 147 | TAG_VOICE => { | 204 | TAG_VOICE => { |
| @@ -159,6 +216,25 @@ impl<'a> Packet<'a> { | |||
| 159 | opus, | 216 | opus, |
| 160 | }) | 217 | }) |
| 161 | } | 218 | } |
| 219 | + TAG_NACK => { | ||
| 220 | + let indices = b.get(NACK_HEADER..)?; | ||
| 221 | + (indices.len() % 2 == 0 && indices.len() <= NACK_MAX * 2).then_some(())?; | ||
| 222 | + Some(Self::Nack { | ||
| 223 | + kind: video_kind(*b.get(1)?)?, | ||
| 224 | + user_id: i64::from_be_bytes(b[2..10].try_into().ok()?), | ||
| 225 | + layer: Layer::from_byte(b[10])?, | ||
| 226 | + frame: u32_at(b, 11), | ||
| 227 | + indices, | ||
| 228 | + }) | ||
| 229 | + } | ||
| 230 | + TAG_ACK => (b.len() == NACK_HEADER).then(|| { | ||
| 231 | + Some(Self::Ack { | ||
| 232 | + kind: video_kind(b[1])?, | ||
| 233 | + user_id: i64::from_be_bytes(b[2..10].try_into().ok()?), | ||
| 234 | + layer: Layer::from_byte(b[10])?, | ||
| 235 | + ts_ms: u32_at(b, 11), | ||
| 236 | + }) | ||
| 237 | + })?, | ||
| 162 | tag => { | 238 | tag => { |
| 163 | let kind = video_kind(tag)?; | 239 | let kind = video_kind(tag)?; |
| 164 | let shard = b.get(VIDEO_HEADER..)?; | 240 | let shard = b.get(VIDEO_HEADER..)?; |
| @@ -177,6 +253,7 @@ impl<'a> Packet<'a> { | |||
| 177 | kind, | 253 | kind, |
| 178 | layer, | 254 | layer, |
| 179 | keyframe: b[2] & KEYFRAME_FLAG != 0, | 255 | keyframe: b[2] & KEYFRAME_FLAG != 0, |
| 256 | + recovery: b[2] & RECOVERY_FLAG != 0, | ||
| 180 | frame: u32_at(b, 3), | 257 | frame: u32_at(b, 3), |
| 181 | index, | 258 | index, |
| 182 | parity, | 259 | parity, |
| @@ -210,6 +287,7 @@ pub struct FrameInfo { | |||
| 210 | pub layer: Layer, | 287 | pub layer: Layer, |
| 211 | pub frame: u32, | 288 | pub frame: u32, |
| 212 | pub keyframe: bool, | 289 | pub keyframe: bool, |
| 290 | + pub recovery: bool, | ||
| 213 | pub ts_ms: u32, | 291 | pub ts_ms: u32, |
| 214 | pub parity: u16, | 292 | pub parity: u16, |
| 215 | } | 293 | } |
| @@ -220,6 +298,7 @@ pub fn fragments(info: FrameInfo, data: &[u8], mut emit: impl FnMut(&[u8])) { | |||
| 220 | layer, | 298 | layer, |
| 221 | frame, | 299 | frame, |
| 222 | keyframe, | 300 | keyframe, |
| 301 | + recovery, | ||
| 223 | ts_ms, | 302 | ts_ms, |
| 224 | parity, | 303 | parity, |
| 225 | } = info; | 304 | } = info; |
| @@ -231,14 +310,14 @@ pub fn fragments(info: FrameInfo, data: &[u8], mut emit: impl FnMut(&[u8])) { | |||
| 231 | } = layout(length, parity); | 310 | } = layout(length, parity); |
| 232 | let mut padded = data.to_vec(); | 311 | let mut padded = data.to_vec(); |
| 233 | padded.resize(data_count * shard, 0); | 312 | padded.resize(data_count * shard, 0); |
| 234 | - let Ok(recovery) = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard)) | 313 | + let Ok(repair) = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard)) |
| 235 | else { | 314 | else { |
| 236 | return; | 315 | return; |
| 237 | }; | 316 | }; |
| 238 | let mut out = Vec::with_capacity(VIDEO_HEADER + shard); | 317 | let mut out = Vec::with_capacity(VIDEO_HEADER + shard); |
| 239 | for (index, shard) in padded | 318 | for (index, shard) in padded |
| 240 | .chunks(shard) | 319 | .chunks(shard) |
| 241 | - .chain(recovery.iter().map(Vec::as_slice)) | 320 | + .chain(repair.iter().map(Vec::as_slice)) |
| 242 | .enumerate() | 321 | .enumerate() |
| 243 | { | 322 | { |
| 244 | out.clear(); | 323 | out.clear(); |
| @@ -246,6 +325,7 @@ pub fn fragments(info: FrameInfo, data: &[u8], mut emit: impl FnMut(&[u8])) { | |||
| 246 | kind, | 325 | kind, |
| 247 | layer, | 326 | layer, |
| 248 | keyframe, | 327 | keyframe, |
| 328 | + recovery, | ||
| 249 | frame, | 329 | frame, |
| 250 | index: index as u16, | 330 | index: index as u16, |
| 251 | parity, | 331 | parity, |
| @@ -346,6 +426,7 @@ mod tests { | |||
| 346 | layer, | 426 | layer, |
| 347 | frame: 3, | 427 | frame: 3, |
| 348 | keyframe: true, | 428 | keyframe: true, |
| 429 | + recovery: false, | ||
| 349 | ts_ms: 99, | 430 | ts_ms: 99, |
| 350 | parity: 1, | 431 | parity: 1, |
| 351 | }; | 432 | }; |
crates/common/src/event.rsmodified+5 -1
| @@ -85,7 +85,11 @@ pub enum Event { | |||
| 85 | #[derive(Debug, Clone, Encode, Decode)] | 85 | #[derive(Debug, Clone, Encode, Decode)] |
| 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 { |
| 89 | + kind: Kind, | ||
| 90 | + layer: Layer, | ||
| 91 | + recover: bool, | ||
| 92 | + }, | ||
| 89 | Loss { kind: Kind, permille: u16 }, | 93 | Loss { kind: Kind, permille: u16 }, |
| 90 | VoiceEnded, | 94 | VoiceEnded, |
| 91 | } | 95 | } |
crates/server/src/call/voice.rsmodified+1 -1
| @@ -161,7 +161,7 @@ impl Handle for RequestKeyframe { | |||
| 161 | .sh | 161 | .sh |
| 162 | .services | 162 | .services |
| 163 | .rooms | 163 | .rooms |
| 164 | - .keyframe(cx.client.id, self.user_id, self.kind) | 164 | + .keyframe(cx.client.id, self.user_id, self.kind, self.recover) |
| 165 | .ok_or(Error::NotFound)?; | 165 | .ok_or(Error::NotFound)?; |
| 166 | cx.out.push(keyframe); | 166 | cx.out.push(keyframe); |
| 167 | 167 | ||
crates/server/src/rooms.rsmodified+159 -9
| @@ -1,9 +1,10 @@ | |||
| 1 | use std::{ | 1 | use std::{ |
| 2 | - collections::{BTreeMap, BTreeSet, HashMap}, | 2 | + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, |
| 3 | sync::{Arc, Mutex, atomic::Ordering}, | 3 | sync::{Arc, Mutex, atomic::Ordering}, |
| 4 | time::Instant, | 4 | time::Instant, |
| 5 | }; | 5 | }; |
| 6 | 6 | ||
| 7 | +use bytes::Bytes; | ||
| 7 | use common::{ | 8 | use common::{ |
| 8 | datagram::{self, Packet, RELAY_PREFIX, relayed}, | 9 | datagram::{self, Packet, RELAY_PREFIX, relayed}, |
| 9 | error::Error, | 10 | error::Error, |
| @@ -72,11 +73,42 @@ struct Viewer { | |||
| 72 | quality: Quality, | 73 | quality: Quality, |
| 73 | decode: Vec<Codec>, | 74 | decode: Vec<Codec>, |
| 74 | forward: Forward, | 75 | forward: Forward, |
| 76 | + acked: Option<(Layer, u32)>, | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +const RECENT_PACKETS: usize = 4096; | ||
| 80 | + | ||
| 81 | +#[derive(Default)] | ||
| 82 | +struct Recent { | ||
| 83 | + order: VecDeque<(Layer, u32, u16)>, | ||
| 84 | + packets: HashMap<(Layer, u32, u16), Bytes>, | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +impl Recent { | ||
| 88 | + fn insert(&mut self, key: (Layer, u32, u16), bytes: Bytes) { | ||
| 89 | + if self.packets.insert(key, bytes).is_none() { | ||
| 90 | + self.order.push_back(key); | ||
| 91 | + } | ||
| 92 | + while self.order.len() > RECENT_PACKETS { | ||
| 93 | + if let Some(old) = self.order.pop_front() { | ||
| 94 | + self.packets.remove(&old); | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + fn frame(&self, layer: Layer, frame: u32) -> impl Iterator<Item = &Bytes> { | ||
| 100 | + self.order | ||
| 101 | + .iter() | ||
| 102 | + .filter(move |(l, f, _)| *l == layer && *f == frame) | ||
| 103 | + .filter_map(|key| self.packets.get(key)) | ||
| 104 | + } | ||
| 75 | } | 105 | } |
| 76 | 106 | ||
| 77 | struct Sharing { | 107 | struct Sharing { |
| 78 | source: Source, | 108 | source: Source, |
| 79 | viewers: Vec<Viewer>, | 109 | viewers: Vec<Viewer>, |
| 110 | + recent: Recent, | ||
| 111 | + acked: HashMap<Layer, u32>, | ||
| 80 | } | 112 | } |
| 81 | 113 | ||
| 82 | impl Sharing { | 114 | impl Sharing { |
| @@ -120,7 +152,9 @@ struct Sharer { | |||
| 120 | 152 | ||
| 121 | fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec<Broadcast> { | 153 | fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec<Broadcast> { |
| 122 | let before = sharing.layers(); | 154 | let before = sharing.layers(); |
| 123 | - let Sharing { source, viewers } = sharing; | 155 | + let Sharing { |
| 156 | + source, viewers, .. | ||
| 157 | + } = sharing; | ||
| 124 | let mut used: Vec<Layer> = Vec::new(); | 158 | let mut used: Vec<Layer> = Vec::new(); |
| 125 | let mut keyframes = Vec::new(); | 159 | let mut keyframes = Vec::new(); |
| 126 | let mut stopped = Vec::new(); | 160 | let mut stopped = Vec::new(); |
| @@ -145,6 +179,7 @@ fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec<Broadcast> { | |||
| 145 | Media::Keyframe { | 179 | Media::Keyframe { |
| 146 | kind: sharer.kind, | 180 | kind: sharer.kind, |
| 147 | layer, | 181 | layer, |
| 182 | + recover: false, | ||
| 148 | }, | 183 | }, |
| 149 | )); | 184 | )); |
| 150 | } | 185 | } |
| @@ -539,6 +574,8 @@ impl Rooms { | |||
| 539 | let sharing = seat.shares.entry(kind).or_insert_with(|| Sharing { | 574 | let sharing = seat.shares.entry(kind).or_insert_with(|| Sharing { |
| 540 | source: source.clone(), | 575 | source: source.clone(), |
| 541 | viewers: Vec::new(), | 576 | viewers: Vec::new(), |
| 577 | + recent: Recent::default(), | ||
| 578 | + acked: HashMap::new(), | ||
| 542 | }); | 579 | }); |
| 543 | sharing.source = source; | 580 | sharing.source = source; |
| 544 | 581 | ||
| @@ -582,11 +619,16 @@ impl Rooms { | |||
| 582 | quality, | 619 | quality, |
| 583 | decode: decode.to_vec(), | 620 | decode: decode.to_vec(), |
| 584 | forward, | 621 | forward, |
| 622 | + acked: None, | ||
| 585 | }); | 623 | }); |
| 586 | let mut broadcasts = Vec::from_iter(layers_changed(sharer_conn, kind, sharing, before)); | 624 | let mut broadcasts = Vec::from_iter(layers_changed(sharer_conn, kind, sharing, before)); |
| 587 | broadcasts.push(Broadcast::media( | 625 | broadcasts.push(Broadcast::media( |
| 588 | sharer_conn, | 626 | sharer_conn, |
| 589 | - Media::Keyframe { kind, layer }, | 627 | + Media::Keyframe { |
| 628 | + kind, | ||
| 629 | + layer, | ||
| 630 | + recover: false, | ||
| 631 | + }, | ||
| 590 | )); | 632 | )); |
| 591 | 633 | ||
| 592 | Some(broadcasts) | 634 | Some(broadcasts) |
| @@ -602,7 +644,13 @@ impl Rooms { | |||
| 602 | remove_viewer(sharer_conn, kind, sharing, viewer_id) | 644 | remove_viewer(sharer_conn, kind, sharing, viewer_id) |
| 603 | } | 645 | } |
| 604 | 646 | ||
| 605 | - pub fn keyframe(&self, id: ConnId, sharer_id: Id, kind: Kind) -> Option<Broadcast> { | 647 | + pub fn keyframe( |
| 648 | + &self, | ||
| 649 | + id: ConnId, | ||
| 650 | + sharer_id: Id, | ||
| 651 | + kind: Kind, | ||
| 652 | + recover: bool, | ||
| 653 | + ) -> Option<Broadcast> { | ||
| 606 | let mut inner = self.0.lock().unwrap(); | 654 | let mut inner = self.0.lock().unwrap(); |
| 607 | let sharer_conn = inner.seat_conn(sharer_id)?; | 655 | let sharer_conn = inner.seat_conn(sharer_id)?; |
| 608 | let (_, room) = inner.seat_mut(id)?; | 656 | let (_, room) = inner.seat_mut(id)?; |
| @@ -619,6 +667,7 @@ impl Rooms { | |||
| 619 | Media::Keyframe { | 667 | Media::Keyframe { |
| 620 | kind, | 668 | kind, |
| 621 | layer: viewer.forward.target(), | 669 | layer: viewer.forward.target(), |
| 670 | + recover: recover && viewer.forward.live().is_some(), | ||
| 622 | }, | 671 | }, |
| 623 | )) | 672 | )) |
| 624 | } | 673 | } |
| @@ -649,7 +698,20 @@ impl Rooms { | |||
| 649 | return relay_video(room, from.id, kind, layer, keyframe, packet); | 698 | return relay_video(room, from.id, kind, layer, keyframe, packet); |
| 650 | } | 699 | } |
| 651 | match Packet::decode(packet) { | 700 | match Packet::decode(packet) { |
| 652 | - Some(Packet::Voice { seq, .. }) => relay_voice(room, from.id, seq, packet), | 701 | + Some(Packet::Nack { |
| 702 | + kind, | ||
| 703 | + user_id, | ||
| 704 | + layer, | ||
| 705 | + frame, | ||
| 706 | + indices, | ||
| 707 | + }) => resend(room, from.id, user_id, kind, layer, frame, indices), | ||
| 708 | + Some(Packet::Ack { | ||
| 709 | + kind, | ||
| 710 | + user_id, | ||
| 711 | + layer, | ||
| 712 | + ts_ms, | ||
| 713 | + }) => ack(room, from.id, user_id, kind, layer, ts_ms), | ||
| 714 | + Some(Packet::Voice { .. }) => relay_voice(room, from.id, packet), | ||
| 653 | Some(Packet::ScreenAudio { .. }) => relay_share_audio(room, from.id, packet), | 715 | Some(Packet::ScreenAudio { .. }) => relay_share_audio(room, from.id, packet), |
| 654 | _ => {} | 716 | _ => {} |
| 655 | } | 717 | } |
| @@ -658,16 +720,13 @@ impl Rooms { | |||
| 658 | } | 720 | } |
| 659 | } | 721 | } |
| 660 | 722 | ||
| 661 | -fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) { | 723 | +fn relay_voice(room: &Room, id: ConnId, packet: &[u8]) { |
| 662 | let Some(sender) = room.seats.get(&id) else { | 724 | let Some(sender) = room.seats.get(&id) else { |
| 663 | return; | 725 | return; |
| 664 | }; | 726 | }; |
| 665 | if sender.muted { | 727 | if sender.muted { |
| 666 | return; | 728 | return; |
| 667 | } | 729 | } |
| 668 | - let mut echo = Vec::new(); | ||
| 669 | - Packet::Voice { seq, opus: &[] }.encode(&mut echo); | ||
| 670 | - datagram::send(&sender.connection, relayed(&sender.prefix, &echo)); | ||
| 671 | let bytes = relayed(&sender.prefix, packet); | 730 | let bytes = relayed(&sender.prefix, packet); |
| 672 | for (other_id, seat) in &room.seats { | 731 | for (other_id, seat) in &room.seats { |
| 673 | if *other_id != id { | 732 | if *other_id != id { |
| @@ -676,6 +735,94 @@ fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) { | |||
| 676 | } | 735 | } |
| 677 | } | 736 | } |
| 678 | 737 | ||
| 738 | +fn ack(room: &mut Room, id: ConnId, sharer_id: Id, kind: Kind, layer: Layer, ts_ms: u32) { | ||
| 739 | + let Some(viewer_id) = room.seats.get(&id).map(|seat| seat.user_id) else { | ||
| 740 | + return; | ||
| 741 | + }; | ||
| 742 | + let Some(seat) = room | ||
| 743 | + .seats | ||
| 744 | + .values_mut() | ||
| 745 | + .find(|seat| seat.user_id == sharer_id) | ||
| 746 | + else { | ||
| 747 | + return; | ||
| 748 | + }; | ||
| 749 | + let (connection, prefix) = (seat.connection.clone(), seat.prefix); | ||
| 750 | + let Some(sharing) = seat.shares.get_mut(&kind) else { | ||
| 751 | + return; | ||
| 752 | + }; | ||
| 753 | + let Some(viewer) = sharing | ||
| 754 | + .viewers | ||
| 755 | + .iter_mut() | ||
| 756 | + .find(|viewer| viewer.user_id == viewer_id) | ||
| 757 | + else { | ||
| 758 | + return; | ||
| 759 | + }; | ||
| 760 | + if viewer.forward.live() != Some(layer) { | ||
| 761 | + return; | ||
| 762 | + } | ||
| 763 | + viewer.acked = Some((layer, ts_ms)); | ||
| 764 | + let lowest = sharing | ||
| 765 | + .viewers | ||
| 766 | + .iter() | ||
| 767 | + .filter(|viewer| viewer.forward.live() == Some(layer)) | ||
| 768 | + .map(|viewer| match viewer.acked { | ||
| 769 | + Some((acked_layer, ts)) if acked_layer == layer => Some(ts), | ||
| 770 | + _ => None, | ||
| 771 | + }) | ||
| 772 | + .try_fold(u32::MAX, |lowest, ts| ts.map(|ts| lowest.min(ts))); | ||
| 773 | + let Some(lowest) = lowest.filter(|lowest| *lowest != u32::MAX) else { | ||
| 774 | + return; | ||
| 775 | + }; | ||
| 776 | + if sharing.acked.insert(layer, lowest) == Some(lowest) { | ||
| 777 | + return; | ||
| 778 | + } | ||
| 779 | + let mut out = Vec::new(); | ||
| 780 | + Packet::Ack { | ||
| 781 | + kind, | ||
| 782 | + user_id: sharer_id, | ||
| 783 | + layer, | ||
| 784 | + ts_ms: lowest, | ||
| 785 | + } | ||
| 786 | + .encode(&mut out); | ||
| 787 | + datagram::send(&connection, relayed(&prefix, &out)); | ||
| 788 | +} | ||
| 789 | + | ||
| 790 | +fn resend( | ||
| 791 | + room: &Room, | ||
| 792 | + id: ConnId, | ||
| 793 | + sharer_id: Id, | ||
| 794 | + kind: Kind, | ||
| 795 | + layer: Layer, | ||
| 796 | + frame: u32, | ||
| 797 | + indices: &[u8], | ||
| 798 | +) { | ||
| 799 | + let Some(viewer) = room.seats.get(&id) else { | ||
| 800 | + return; | ||
| 801 | + }; | ||
| 802 | + let Some(sharing) = room | ||
| 803 | + .seats | ||
| 804 | + .values() | ||
| 805 | + .find(|seat| seat.user_id == sharer_id) | ||
| 806 | + .and_then(|seat| seat.shares.get(&kind)) | ||
| 807 | + else { | ||
| 808 | + return; | ||
| 809 | + }; | ||
| 810 | + if sharing.viewer(viewer.user_id).is_none() { | ||
| 811 | + return; | ||
| 812 | + } | ||
| 813 | + if indices.is_empty() { | ||
| 814 | + for bytes in sharing.recent.frame(layer, frame) { | ||
| 815 | + datagram::send(&viewer.connection, bytes.clone()); | ||
| 816 | + } | ||
| 817 | + return; | ||
| 818 | + } | ||
| 819 | + for index in Packet::nack_indices(indices) { | ||
| 820 | + if let Some(bytes) = sharing.recent.packets.get(&(layer, frame, index)) { | ||
| 821 | + datagram::send(&viewer.connection, bytes.clone()); | ||
| 822 | + } | ||
| 823 | + } | ||
| 824 | +} | ||
| 825 | + | ||
| 679 | fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) { | 826 | fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) { |
| 680 | let Some(seat) = room.seats.get(&id) else { | 827 | let Some(seat) = room.seats.get(&id) else { |
| 681 | return; | 828 | return; |
| @@ -704,6 +851,9 @@ fn relay_video( | |||
| 704 | return Vec::new(); | 851 | return Vec::new(); |
| 705 | }; | 852 | }; |
| 706 | let bytes = relayed(&seat.prefix, packet); | 853 | let bytes = relayed(&seat.prefix, packet); |
| 854 | + if let Some(Packet::Video { frame, index, .. }) = Packet::decode(packet) { | ||
| 855 | + sharing.recent.insert((layer, frame, index), bytes.clone()); | ||
| 856 | + } | ||
| 707 | let before = keyframe.then(|| sharing.layers()); | 857 | let before = keyframe.then(|| sharing.layers()); |
| 708 | for viewer in &mut sharing.viewers { | 858 | for viewer in &mut sharing.viewers { |
| 709 | if keyframe { | 859 | if keyframe { |
harness/bench.shmodified+3 -2
| @@ -8,7 +8,7 @@ DROP="${DROP:-0}" | |||
| 8 | WARM="${WARM:-60}" | 8 | WARM="${WARM:-60}" |
| 9 | SPAN="${SPAN:-20}" | 9 | SPAN="${SPAN:-20}" |
| 10 | export HARNESS_STATE="$STATE" | 10 | export HARNESS_STATE="$STATE" |
| 11 | -export RUST_LOG="info,metrics=debug" | 11 | +export YUMUSH_METRICS=1 |
| 12 | E="$STATE/env2" | 12 | E="$STATE/env2" |
| 13 | lo() { awk '/^ *lo:/ {print $2}' /proc/net/dev; } | 13 | lo() { awk '/^ *lo:/ {print $2}' /proc/net/dev; } |
| 14 | drops() { awk '/^Udp:/ {v=$6} END {print v}' /proc/net/snmp; } | 14 | drops() { awk '/^Udp:/ {v=$6} END {print v}' /proc/net/snmp; } |
| @@ -55,7 +55,8 @@ echo "cpu %: alice $(cpu "$ta" "$TA") bob $(cpu "$tb" "$TB") server $(cpu "$ts | |||
| 55 | echo "voice kbps: alice up $(echo "$alice" | avg up voice) down $(echo "$alice" | avg down voice) loss $(echo "$bob" | avg loss voice)" | 55 | echo "voice kbps: alice up $(echo "$alice" | avg up voice) down $(echo "$alice" | avg down voice) loss $(echo "$bob" | avg loss voice)" |
| 56 | if [ "$MODE" = share ]; then | 56 | if [ "$MODE" = share ]; then |
| 57 | k=$(echo "$bob" | grep "metrics: watch " | grep -o "keyframes=[0-9]*" | cut -d= -f2 | sed -n '1p;$p' | paste -sd' ') | 57 | k=$(echo "$bob" | grep "metrics: watch " | grep -o "keyframes=[0-9]*" | cut -d= -f2 | sed -n '1p;$p' | paste -sd' ') |
| 58 | - echo "send kbps: $(echo "$alice" | avg kbps send)" | 58 | + n=$(echo "$bob" | grep "metrics: watch " | grep -o "nacks=[0-9]*" | cut -d= -f2 | sed -n '1p;$p' | paste -sd' ' || true) |
| 59 | + echo "send kbps: $(echo "$alice" | avg kbps send) nacks ${n:-}" | ||
| 59 | echo "watch: kbps $(echo "$bob" | avg kbps watch) fps $(echo "$bob" | avg fps watch) latency ms $(echo "$bob" | avg latency watch) frame loss $(echo "$bob" | avg loss watch) keyframes $k" | 60 | echo "watch: kbps $(echo "$bob" | avg kbps watch) fps $(echo "$bob" | avg fps watch) latency ms $(echo "$bob" | avg latency watch) frame loss $(echo "$bob" | avg loss watch) keyframes $k" |
| 60 | grep -h "share watch quality" "$STATE/bob.log" | sed 's/\x1b\[[0-9;]*m//g' | tail -1 || true | 61 | grep -h "share watch quality" "$STATE/bob.log" | sed 's/\x1b\[[0-9;]*m//g' | tail -1 || true |
| 61 | fi | 62 | fi |
harness/talk.shmodified+8 -1
| @@ -22,4 +22,11 @@ for i in range(rate * seconds): | |||
| 22 | frames.append(struct.pack("<h", int(max(-1, min(1, 0.35 * v)) * 32767))) | 22 | frames.append(struct.pack("<h", int(max(-1, min(1, 0.35 * v)) * 32767))) |
| 23 | w.writeframes(b"".join(frames)) | 23 | w.writeframes(b"".join(frames)) |
| 24 | PY | 24 | PY |
| 25 | -while true; do pw-play --target harness-mic "$out"; done | 25 | +while true; do |
| 26 | + pw-play --target 0 -P '{ node.name = harness-talk }' "$out" & | ||
| 27 | + player=$! | ||
| 28 | + sleep 0.3 | ||
| 29 | + pw-link harness-talk:output_MONO harness-mic:input_FL || true | ||
| 30 | + pw-link harness-talk:output_MONO harness-mic:input_FR || true | ||
| 31 | + wait "$player" || true | ||
| 32 | +done | ||