Share adaptation. Random loss no longer cuts the rate: the uplink controller only backs off on quinn congestion events, a low send buffer or RTT growth, and FEC parity is sized per frame from the binomial tail of the reported loss (frame miss under 0.1%, keyframes 0.01%), so 5% uplink drop no longer leaves ~1% of frames unrecoverable (sender-side drops never reach the server cache NACKs resend from). Encoder lanes that can't keep up step down (fps to 30, then 2/3 size to 360p) and lower a shared pixel-rate budget that new lanes start within
Browse files at this commite5ae8bc9167c8d0072cf0b136da8bb667e909cfbParent: c258f52- fix
- share adaptation. Random loss no longer cuts the rate: the uplink controller only backs off on quinn congestion events, a low send buffer or RTT growth, and FEC parity is sized per frame from the binomial tail of the reported loss (frame miss under 0.1%, keyframes 0.01%), so 5% uplink drop no longer leaves ~1% of frames unrecoverable (sender-side drops never reach the server cache NACKs resend from). Encoder lanes that can't keep up step down (fps to 30, then 2/3 size to 360p) and lower a shared pixel-rate budget that new lanes start within
- a step that doesn't cut encode time stops the descent (software 2160p60: 1.5 -> 10-14 fps). A new watch waits a keyframe interval before asking for one, so the ask can't beat WatchShare to the server (NotFound)
- failed media requests name the request
5 changed files +131 -29
- crates/client/src/net/media.rs +5 -1
- crates/client/src/share/congestion.rs +7 -12
- crates/client/src/share/encode.rs +96 -3
- crates/client/src/share/session.rs +6 -11
- crates/common/src/datagram.rs +17 -2
crates/client/src/net/media.rsmodified+5 -1
| @@ -467,7 +467,11 @@ async fn join(connection: &Connection, community_id: Id) -> Result<Vec<Id>, Fail | ||
| 467 | 467 | |
| 468 | 468 | async fn send_quietly<C: Call>(connection: Connection, request: C) { |
| 469 | 469 | if let Err(error) = call(&connection, request).await { |
| 470 | - warn!("media request failed: {error}"); | |
| 470 | + let name = std::any::type_name::<C>() | |
| 471 | + .rsplit("::") | |
| 472 | + .next() | |
| 473 | + .unwrap_or_default(); | |
| 474 | + warn!("media request {name} failed: {error}"); | |
| 471 | 475 | } |
| 472 | 476 | } |
| 473 | 477 |
crates/client/src/share/congestion.rsmodified+7 -12
| @@ -3,21 +3,19 @@ use std::{ | ||
| 3 | 3 | time::Duration, |
| 4 | 4 | }; |
| 5 | 5 | |
| 6 | +use common::datagram::parity_for; | |
| 6 | 7 | use quinn::Connection; |
| 7 | 8 | |
| 8 | 9 | pub const PERIOD: Duration = Duration::from_millis(500); |
| 9 | 10 | const MIN_SCALE: f32 = 0.25; |
| 10 | 11 | const DECREASE: f32 = 0.75; |
| 11 | 12 | const INCREASE: f32 = 0.05; |
| 12 | -const LOSS_LIMIT: f32 = 0.02; | |
| 13 | 13 | const QUEUE_DELAY: Duration = Duration::from_millis(60); |
| 14 | 14 | const BUFFER_LOW: usize = 256 * 1024; |
| 15 | 15 | const INITIAL_LOSS: f32 = 0.05; |
| 16 | 16 | const LOSS_DECAY: f32 = 0.9; |
| 17 | -const FEC_FLOOR: f32 = 0.05; | |
| 18 | -const FEC_GAIN: f32 = 4.0; | |
| 19 | -const FEC_MAX: f32 = 0.5; | |
| 20 | -const KEYFRAME_FEC: f32 = 0.1; | |
| 17 | +const MISS: f32 = 0.001; | |
| 18 | +const KEYFRAME_MISS: f32 = 0.0001; | |
| 21 | 19 | |
| 22 | 20 | pub struct Loss(AtomicU32); |
| 23 | 21 | |
| @@ -37,10 +35,10 @@ impl Loss { | ||
| 37 | 35 | self.0.store(loss.to_bits(), Ordering::Relaxed); |
| 38 | 36 | } |
| 39 | 37 | |
| 40 | - pub fn fec(&self, keyframe: bool) -> f32 { | |
| 38 | + pub fn parity(&self, length: u32, keyframe: bool) -> u16 { | |
| 41 | 39 | let loss = f32::from_bits(self.0.load(Ordering::Relaxed)); |
| 42 | - let extra = if keyframe { KEYFRAME_FEC } else { 0.0 }; | |
| 43 | - (FEC_FLOOR + FEC_GAIN * loss + extra).min(FEC_MAX) | |
| 40 | + let miss = if keyframe { KEYFRAME_MISS } else { MISS }; | |
| 41 | + parity_for(length, loss, miss) | |
| 44 | 42 | } |
| 45 | 43 | } |
| 46 | 44 | |
| @@ -95,10 +93,7 @@ impl Controller { | ||
| 95 | 93 | .saturating_sub(self.last.congestion_events); |
| 96 | 94 | self.last = now; |
| 97 | 95 | self.loss = lost as f32 / sent.max(1) as f32; |
| 98 | - let congested = events > 0 | |
| 99 | - || now.buffer_low | |
| 100 | - || lost as f32 > sent.max(1) as f32 * LOSS_LIMIT | |
| 101 | - || now.rtt > base + QUEUE_DELAY; | |
| 96 | + let congested = events > 0 || now.buffer_low || now.rtt > base + QUEUE_DELAY; | |
| 102 | 97 | self.scale = match congested { |
| 103 | 98 | true => (self.scale * DECREASE).max(MIN_SCALE), |
| 104 | 99 | false => (self.scale + INCREASE).min(1.0), |
crates/client/src/share/encode.rsmodified+96 -3
| @@ -3,6 +3,7 @@ use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering}; | ||
| 3 | 3 | use std::sync::mpsc::{Receiver, Sender, SyncSender, sync_channel}; |
| 4 | 4 | use std::sync::{Arc, OnceLock}; |
| 5 | 5 | use std::thread; |
| 6 | +use std::time::Instant; | |
| 6 | 7 | |
| 7 | 8 | use common::share::{Codec, Layer}; |
| 8 | 9 | |
| @@ -13,6 +14,11 @@ const SOFTWARE: Codec = Codec::H264; | ||
| 13 | 14 | const DEFAULT_MAX_HEIGHT: u32 = 2160; |
| 14 | 15 | const KEYFRAME_SECONDS: u32 = 3600; |
| 15 | 16 | const SLACK_MS: u32 = 4; |
| 17 | +const OVERLOAD: f32 = 1.2; | |
| 18 | +const GAIN: f32 = 0.8; | |
| 19 | +const SETTLE_FRAMES: u32 = 4; | |
| 20 | +const MIN_FPS: u32 = 30; | |
| 21 | +const MIN_HEIGHT: u32 = 360; | |
| 16 | 22 | |
| 17 | 23 | pub struct Capabilities { |
| 18 | 24 | pub encode: Vec<Codec>, |
| @@ -112,6 +118,43 @@ struct Settings { | ||
| 112 | 118 | gop: u32, |
| 113 | 119 | } |
| 114 | 120 | |
| 121 | +impl Settings { | |
| 122 | + fn rate(&self) -> u64 { | |
| 123 | + u64::from(self.width) * u64::from(self.height) * u64::from(self.fps) | |
| 124 | + } | |
| 125 | + | |
| 126 | + fn within(mut self, budget: u64) -> Settings { | |
| 127 | + while self.rate() > budget | |
| 128 | + && let Some(lighter) = self.lighter() | |
| 129 | + { | |
| 130 | + self = lighter; | |
| 131 | + } | |
| 132 | + self | |
| 133 | + } | |
| 134 | + | |
| 135 | + fn lighter(&self) -> Option<Settings> { | |
| 136 | + let (width, height, fps) = if self.fps > MIN_FPS { | |
| 137 | + (self.width, self.height, (self.fps / 2).max(MIN_FPS)) | |
| 138 | + } else if self.height * 2 / 3 >= MIN_HEIGHT { | |
| 139 | + ( | |
| 140 | + (self.width * 2 / 3) & !1, | |
| 141 | + (self.height * 2 / 3) & !1, | |
| 142 | + self.fps, | |
| 143 | + ) | |
| 144 | + } else { | |
| 145 | + return None; | |
| 146 | + }; | |
| 147 | + Some(Settings { | |
| 148 | + codec: self.codec, | |
| 149 | + width, | |
| 150 | + height, | |
| 151 | + fps, | |
| 152 | + bitrate: self.bitrate, | |
| 153 | + gop: fps * KEYFRAME_SECONDS, | |
| 154 | + }) | |
| 155 | + } | |
| 156 | +} | |
| 157 | + | |
| 115 | 158 | enum Backend { |
| 116 | 159 | Hardware(Box<hardware::Encoder>), |
| 117 | 160 | H264(Box<ec_h264::Encoder>), |
| @@ -387,15 +430,20 @@ fn run( | ||
| 387 | 430 | input: Receiver<Arc<Frame>>, |
| 388 | 431 | control: Arc<Control>, |
| 389 | 432 | scale: Arc<AtomicU32>, |
| 433 | + budget: Arc<AtomicU64>, | |
| 390 | 434 | output: Sender<Encoded>, |
| 391 | 435 | ) { |
| 392 | 436 | let mut acked = None; |
| 393 | 437 | let Some(mut backend) = Backend::open(&settings) else { |
| 394 | 438 | return; |
| 395 | 439 | }; |
| 440 | + let mut settings = settings; | |
| 396 | 441 | let mut applied = 1.0; |
| 397 | - let interval = 1000 / settings.fps; | |
| 442 | + let mut interval = 1000 / settings.fps; | |
| 398 | 443 | let mut due = 0u32; |
| 444 | + let mut busy_ms = 0.0; | |
| 445 | + let mut settled = 0u32; | |
| 446 | + let mut before = f32::INFINITY; | |
| 399 | 447 | for frame in input { |
| 400 | 448 | crate::usage::tick(crate::usage::Group::Encode); |
| 401 | 449 | if frame.timestamp_ms + SLACK_MS < due { |
| @@ -414,10 +462,41 @@ fn run( | ||
| 414 | 462 | backend.ack(timestamp_ms); |
| 415 | 463 | } |
| 416 | 464 | } |
| 465 | + let started = Instant::now(); | |
| 417 | 466 | let Some((data, keyframe, recovery)) = backend.encode(&frame, &settings, control.take()) |
| 418 | 467 | else { |
| 419 | 468 | continue; |
| 420 | 469 | }; |
| 470 | + if !keyframe { | |
| 471 | + let spent = started.elapsed().as_secs_f32() * 1000.0; | |
| 472 | + busy_ms = if settled == 0 { | |
| 473 | + spent | |
| 474 | + } else { | |
| 475 | + 0.75 * busy_ms + 0.25 * spent | |
| 476 | + }; | |
| 477 | + settled += 1; | |
| 478 | + } | |
| 479 | + if settled >= SETTLE_FRAMES | |
| 480 | + && busy_ms > interval as f32 * OVERLOAD | |
| 481 | + && busy_ms < before * GAIN | |
| 482 | + && let Some(lighter) = settings.lighter() | |
| 483 | + && let Some(opened) = Backend::open(&lighter) | |
| 484 | + { | |
| 485 | + tracing::info!( | |
| 486 | + busy_ms, | |
| 487 | + width = lighter.width, | |
| 488 | + height = lighter.height, | |
| 489 | + fps = lighter.fps, | |
| 490 | + "share encoder overloaded" | |
| 491 | + ); | |
| 492 | + budget.fetch_min(lighter.rate(), Ordering::Relaxed); | |
| 493 | + backend = opened; | |
| 494 | + settings = lighter; | |
| 495 | + interval = 1000 / settings.fps; | |
| 496 | + applied = 1.0; | |
| 497 | + settled = 0; | |
| 498 | + before = busy_ms; | |
| 499 | + } | |
| 421 | 500 | let encoded = Encoded { |
| 422 | 501 | layer, |
| 423 | 502 | engine: backend.engine(), |
| @@ -443,6 +522,7 @@ pub struct Encoders { | ||
| 443 | 522 | output: Sender<Encoded>, |
| 444 | 523 | lanes: HashMap<Layer, Lane>, |
| 445 | 524 | scale: Arc<AtomicU32>, |
| 525 | + budget: Arc<AtomicU64>, | |
| 446 | 526 | } |
| 447 | 527 | |
| 448 | 528 | impl Encoders { |
| @@ -453,6 +533,7 @@ impl Encoders { | ||
| 453 | 533 | output, |
| 454 | 534 | lanes: HashMap::new(), |
| 455 | 535 | scale: Arc::new(AtomicU32::new(1f32.to_bits())), |
| 536 | + budget: Arc::new(AtomicU64::new(u64::MAX)), | |
| 456 | 537 | } |
| 457 | 538 | } |
| 458 | 539 | |
| @@ -513,15 +594,27 @@ impl Encoders { | ||
| 513 | 594 | fps, |
| 514 | 595 | bitrate: layer.bitrate(self.source_width, self.source_height), |
| 515 | 596 | gop: fps * KEYFRAME_SECONDS, |
| 516 | - }; | |
| 597 | + } | |
| 598 | + .within(self.budget.load(Ordering::Relaxed)); | |
| 517 | 599 | let (input, receiver) = sync_channel(1); |
| 518 | 600 | let control = Arc::new(Control::default()); |
| 519 | 601 | let thread_control = Arc::clone(&control); |
| 520 | 602 | let output = self.output.clone(); |
| 521 | 603 | let scale = Arc::clone(&self.scale); |
| 604 | + let budget = Arc::clone(&self.budget); | |
| 522 | 605 | let spawned = thread::Builder::new() |
| 523 | 606 | .name("share-encode".into()) |
| 524 | - .spawn(move || run(layer, settings, receiver, thread_control, scale, output)); | |
| 607 | + .spawn(move || { | |
| 608 | + run( | |
| 609 | + layer, | |
| 610 | + settings, | |
| 611 | + receiver, | |
| 612 | + thread_control, | |
| 613 | + scale, | |
| 614 | + budget, | |
| 615 | + output, | |
| 616 | + ) | |
| 617 | + }); | |
| 525 | 618 | if let Err(error) = spawned { |
| 526 | 619 | tracing::warn!(?error, "share encode thread failed to start"); |
| 527 | 620 | } |
crates/client/src/share/session.rsmodified+6 -11
| @@ -15,9 +15,7 @@ use common::{ | ||
| 15 | 15 | SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, |
| 16 | 16 | VOICE_SAMPLE_RATE, |
| 17 | 17 | }, |
| 18 | - datagram::{ | |
| 19 | - self, FrameInfo, Packet, RELAY_PREFIX, fragments, parity_for, split, warn_if_small, | |
| 20 | - }, | |
| 18 | + datagram::{self, FrameInfo, Packet, RELAY_PREFIX, fragments, split, warn_if_small}, | |
| 21 | 19 | model::Id, |
| 22 | 20 | share::{Codec, Fps, Kind, Layer, Mode, Quality, Resolution, Source, clamp}, |
| 23 | 21 | }; |
| @@ -493,7 +491,7 @@ fn send_layer( | ||
| 493 | 491 | keyframe: item.keyframe, |
| 494 | 492 | recovery: item.recovery, |
| 495 | 493 | ts_ms: item.timestamp_ms, |
| 496 | - parity: parity_for(item.data.len() as u32, loss.fec(item.keyframe)), | |
| 494 | + parity: loss.parity(item.data.len() as u32, item.keyframe), | |
| 497 | 495 | }; |
| 498 | 496 | number = number.wrapping_add(1); |
| 499 | 497 | fragments(info, &item.data, |packet| { |
| @@ -706,7 +704,7 @@ pub struct Watching { | ||
| 706 | 704 | rung: usize, |
| 707 | 705 | clean: u32, |
| 708 | 706 | hold: u32, |
| 709 | - requested: Option<Instant>, | |
| 707 | + requested: Instant, | |
| 710 | 708 | } |
| 711 | 709 | |
| 712 | 710 | impl Watching { |
| @@ -781,7 +779,7 @@ impl Watching { | ||
| 781 | 779 | ladder, |
| 782 | 780 | clean: 0, |
| 783 | 781 | hold: 0, |
| 784 | - requested: None, | |
| 782 | + requested: Instant::now(), | |
| 785 | 783 | }; |
| 786 | 784 | watching.emitted = Some(watching.wanted()); |
| 787 | 785 | watching |
| @@ -913,10 +911,7 @@ impl Watching { | ||
| 913 | 911 | pub fn tick(&mut self) -> Vec<Tick> { |
| 914 | 912 | let (loss, queuing_ms, served, lost, packet_loss) = { |
| 915 | 913 | let mut health = lock(&self.health); |
| 916 | - let due = self | |
| 917 | - .requested | |
| 918 | - .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); | |
| 919 | - let lost = health.lost && due; | |
| 914 | + let lost = health.lost && self.requested.elapsed() >= KEYFRAME_INTERVAL; | |
| 920 | 915 | ( |
| 921 | 916 | health.loss, |
| 922 | 917 | health.queuing_ms, |
| @@ -930,7 +925,7 @@ impl Watching { | ||
| 930 | 925 | ticks.push(Tick::Loss((packet_loss * 1000.0).ceil() as u16)); |
| 931 | 926 | } |
| 932 | 927 | if let Some(recover) = lost { |
| 933 | - self.requested = Some(Instant::now()); | |
| 928 | + self.requested = Instant::now(); | |
| 934 | 929 | ticks.push(Tick::Keyframe { recover }); |
| 935 | 930 | } |
| 936 | 931 | if self.quality == WatchQuality::Auto { |
crates/common/src/datagram.rsmodified+17 -2
| @@ -94,9 +94,24 @@ pub fn layout(length: u32, parity: u16) -> Layout { | ||
| 94 | 94 | } |
| 95 | 95 | } |
| 96 | 96 | |
| 97 | -pub fn parity_for(length: u32, ratio: f32) -> u16 { | |
| 97 | +pub fn parity_for(length: u32, loss: f32, miss: f32) -> u16 { | |
| 98 | 98 | let data = (length as usize).div_ceil(VIDEO_FRAGMENT_BYTES).max(1); |
| 99 | - ((data as f32 * ratio).ceil() as u16).max(1) | |
| 99 | + let loss = f64::from(loss.clamp(0.001, 0.3)); | |
| 100 | + let most = data.max(2); | |
| 101 | + (1..most) | |
| 102 | + .find(|&parity| unrecoverable(data + parity, parity, loss) < f64::from(miss)) | |
| 103 | + .unwrap_or(most) as u16 | |
| 104 | +} | |
| 105 | + | |
| 106 | +fn unrecoverable(total: usize, parity: usize, loss: f64) -> f64 { | |
| 107 | + let kept = 1.0 - loss; | |
| 108 | + let mut term = kept.powi(total as i32); | |
| 109 | + let mut recoverable = term; | |
| 110 | + for lost in 0..parity { | |
| 111 | + term *= (total - lost) as f64 / (lost + 1) as f64 * loss / kept; | |
| 112 | + recoverable += term; | |
| 113 | + } | |
| 114 | + (1.0 - recoverable).max(0.0) | |
| 100 | 115 | } |
| 101 | 116 | |
| 102 | 117 | pub fn seq_newer(a: u32, b: u32) -> bool { |