forge
Explore
Log in

Don't you dare go Hollow

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 commit

e5ae8bc9167c8d0072cf0b136da8bb667e909cfbAhmet Kaan GümüşParent: 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
Show full message
🐛 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
crates/client/src/net/media.rsmodified+5 -1
@@ -467,7 +467,11 @@ async fn join(connection: &Connection, community_id: Id) -> Result<Vec<Id>, Fail
467467
468468 async fn send_quietly<C: Call>(connection: Connection, request: C) {
469469 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}");
471475 }
472476 }
473477
crates/client/src/share/congestion.rsmodified+7 -12
@@ -3,21 +3,19 @@ use std::{
33 time::Duration,
44 };
55
6+use common::datagram::parity_for;
67 use quinn::Connection;
78
89 pub const PERIOD: Duration = Duration::from_millis(500);
910 const MIN_SCALE: f32 = 0.25;
1011 const DECREASE: f32 = 0.75;
1112 const INCREASE: f32 = 0.05;
12-const LOSS_LIMIT: f32 = 0.02;
1313 const QUEUE_DELAY: Duration = Duration::from_millis(60);
1414 const BUFFER_LOW: usize = 256 * 1024;
1515 const INITIAL_LOSS: f32 = 0.05;
1616 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;
2119
2220 pub struct Loss(AtomicU32);
2321
@@ -37,10 +35,10 @@ impl Loss {
3735 self.0.store(loss.to_bits(), Ordering::Relaxed);
3836 }
3937
40- pub fn fec(&self, keyframe: bool) -> f32 {
38+ pub fn parity(&self, length: u32, keyframe: bool) -> u16 {
4139 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)
4442 }
4543 }
4644
@@ -95,10 +93,7 @@ impl Controller {
9593 .saturating_sub(self.last.congestion_events);
9694 self.last = now;
9795 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;
10297 self.scale = match congested {
10398 true => (self.scale * DECREASE).max(MIN_SCALE),
10499 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};
33 use std::sync::mpsc::{Receiver, Sender, SyncSender, sync_channel};
44 use std::sync::{Arc, OnceLock};
55 use std::thread;
6+use std::time::Instant;
67
78 use common::share::{Codec, Layer};
89
@@ -13,6 +14,11 @@ const SOFTWARE: Codec = Codec::H264;
1314 const DEFAULT_MAX_HEIGHT: u32 = 2160;
1415 const KEYFRAME_SECONDS: u32 = 3600;
1516 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;
1622
1723 pub struct Capabilities {
1824 pub encode: Vec<Codec>,
@@ -112,6 +118,43 @@ struct Settings {
112118 gop: u32,
113119 }
114120
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+
115158 enum Backend {
116159 Hardware(Box<hardware::Encoder>),
117160 H264(Box<ec_h264::Encoder>),
@@ -387,15 +430,20 @@ fn run(
387430 input: Receiver<Arc<Frame>>,
388431 control: Arc<Control>,
389432 scale: Arc<AtomicU32>,
433+ budget: Arc<AtomicU64>,
390434 output: Sender<Encoded>,
391435 ) {
392436 let mut acked = None;
393437 let Some(mut backend) = Backend::open(&settings) else {
394438 return;
395439 };
440+ let mut settings = settings;
396441 let mut applied = 1.0;
397- let interval = 1000 / settings.fps;
442+ let mut interval = 1000 / settings.fps;
398443 let mut due = 0u32;
444+ let mut busy_ms = 0.0;
445+ let mut settled = 0u32;
446+ let mut before = f32::INFINITY;
399447 for frame in input {
400448 crate::usage::tick(crate::usage::Group::Encode);
401449 if frame.timestamp_ms + SLACK_MS < due {
@@ -414,10 +462,41 @@ fn run(
414462 backend.ack(timestamp_ms);
415463 }
416464 }
465+ let started = Instant::now();
417466 let Some((data, keyframe, recovery)) = backend.encode(&frame, &settings, control.take())
418467 else {
419468 continue;
420469 };
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+ }
421500 let encoded = Encoded {
422501 layer,
423502 engine: backend.engine(),
@@ -443,6 +522,7 @@ pub struct Encoders {
443522 output: Sender<Encoded>,
444523 lanes: HashMap<Layer, Lane>,
445524 scale: Arc<AtomicU32>,
525+ budget: Arc<AtomicU64>,
446526 }
447527
448528 impl Encoders {
@@ -453,6 +533,7 @@ impl Encoders {
453533 output,
454534 lanes: HashMap::new(),
455535 scale: Arc::new(AtomicU32::new(1f32.to_bits())),
536+ budget: Arc::new(AtomicU64::new(u64::MAX)),
456537 }
457538 }
458539
@@ -513,15 +594,27 @@ impl Encoders {
513594 fps,
514595 bitrate: layer.bitrate(self.source_width, self.source_height),
515596 gop: fps * KEYFRAME_SECONDS,
516- };
597+ }
598+ .within(self.budget.load(Ordering::Relaxed));
517599 let (input, receiver) = sync_channel(1);
518600 let control = Arc::new(Control::default());
519601 let thread_control = Arc::clone(&control);
520602 let output = self.output.clone();
521603 let scale = Arc::clone(&self.scale);
604+ let budget = Arc::clone(&self.budget);
522605 let spawned = thread::Builder::new()
523606 .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+ });
525618 if let Err(error) = spawned {
526619 tracing::warn!(?error, "share encode thread failed to start");
527620 }
crates/client/src/share/session.rsmodified+6 -11
@@ -15,9 +15,7 @@ use common::{
1515 SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD,
1616 VOICE_SAMPLE_RATE,
1717 },
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},
2119 model::Id,
2220 share::{Codec, Fps, Kind, Layer, Mode, Quality, Resolution, Source, clamp},
2321 };
@@ -493,7 +491,7 @@ fn send_layer(
493491 keyframe: item.keyframe,
494492 recovery: item.recovery,
495493 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),
497495 };
498496 number = number.wrapping_add(1);
499497 fragments(info, &item.data, |packet| {
@@ -706,7 +704,7 @@ pub struct Watching {
706704 rung: usize,
707705 clean: u32,
708706 hold: u32,
709- requested: Option<Instant>,
707+ requested: Instant,
710708 }
711709
712710 impl Watching {
@@ -781,7 +779,7 @@ impl Watching {
781779 ladder,
782780 clean: 0,
783781 hold: 0,
784- requested: None,
782+ requested: Instant::now(),
785783 };
786784 watching.emitted = Some(watching.wanted());
787785 watching
@@ -913,10 +911,7 @@ impl Watching {
913911 pub fn tick(&mut self) -> Vec<Tick> {
914912 let (loss, queuing_ms, served, lost, packet_loss) = {
915913 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;
920915 (
921916 health.loss,
922917 health.queuing_ms,
@@ -930,7 +925,7 @@ impl Watching {
930925 ticks.push(Tick::Loss((packet_loss * 1000.0).ceil() as u16));
931926 }
932927 if let Some(recover) = lost {
933- self.requested = Some(Instant::now());
928+ self.requested = Instant::now();
934929 ticks.push(Tick::Keyframe { recover });
935930 }
936931 if self.quality == WatchQuality::Auto {
crates/common/src/datagram.rsmodified+17 -2
@@ -94,9 +94,24 @@ pub fn layout(length: u32, parity: u16) -> Layout {
9494 }
9595 }
9696
97-pub fn parity_for(length: u32, ratio: f32) -> u16 {
97+pub fn parity_for(length: u32, loss: f32, miss: f32) -> u16 {
9898 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)
100115 }
101116
102117 pub fn seq_newer(a: u32, b: u32) -> bool {