Address review on the XDamage capture PR

- Viewer PLI/FIR: dedupe only while an IDR is pending; drop the 1 s gap so a lost IDR cannot block recovery.
- XShm: release the local mapping on every attach failure; mark the segment for removal in all cases.
- Damage events no longer defer an overdue capture.
- After idle, the next tick is one frame after now instead of now.
This commit is contained in:
ferstar authored and VallierDev committed 2026-10-15 08:22:14 +08:00
1 parent a870f7d041
commit 59a45e092b
3 files changed
+20 -47

No files matched your search

+12 -8
View File
@@ -45,7 +45,12 @@ impl DamageCapture {
if format.bits_per_pixel != 32 { return Err(format!("root depth {depth} is not 32 bits per pixel")); }
let len = width as usize * height as usize * 4;
// The segment is marked for removal once attached; the kernel frees it after the last detach.
// NonEmpty: one event each time the root goes from clean to damaged; re-armed in `wait`.
let damage = conn.generate_id().map_err(text)?;
conn.damage_create(damage, root, ReportLevel::NON_EMPTY).map_err(text)?.check().map_err(text)?;
// Nothing below can fail without also releasing the local mapping, so every error path is covered here.
let seg = conn.generate_id().map_err(text)?;
let shmid = unsafe { libc::shmget(libc::IPC_PRIVATE, len, libc::IPC_CREAT | 0o600) };
if shmid < 0 { return Err("shmget failed".into()); }
let shm_ptr = unsafe { libc::shmat(shmid, std::ptr::null(), 0) } as *mut u8;
@@ -53,14 +58,13 @@ impl DamageCapture {
unsafe { libc::shmctl(shmid, libc::IPC_RMID, std::ptr::null_mut()) };
return Err("shmat failed".into());
}
let seg = conn.generate_id().map_err(text)?;
conn.shm_attach(seg, shmid as u32, false).map_err(text)?.check().map_err(text)?;
let attach = conn.shm_attach(seg, shmid as u32, false).map_err(text).and_then(|c| c.check().map_err(text));
// Marked for removal either way; the kernel frees it after the last detach.
unsafe { libc::shmctl(shmid, libc::IPC_RMID, std::ptr::null_mut()) };
// NonEmpty: one event each time the root goes from clean to damaged; re-armed in `wait`.
let damage = conn.generate_id().map_err(text)?;
conn.damage_create(damage, root, ReportLevel::NON_EMPTY).map_err(text)?.check().map_err(text)?;
conn.flush().map_err(text)?;
if let Err(error) = attach {
unsafe { libc::shmdt(shm_ptr as *const libc::c_void) };
return Err(error);
}
Ok(Self { conn, root, damage, damage_event: damage_info.first_event, width, height, seg, shm_ptr, len })
}
+5 -5
View File
@@ -214,10 +214,9 @@ fn run_damage(config: Config, mut capture: DamageCapture, units: mpsc::Sender<Ve
if stop.load(Ordering::Relaxed) { return Ok(()); }
let deadline = if dirty { next_tick } else { last_send + keepalive };
let wait = deadline.saturating_duration_since(Instant::now());
if capture.wait(wait.max(Duration::from_millis(1)))? {
dirty = true;
continue;
}
// A change marks the picture dirty and falls through, so a client that damages the root constantly
// cannot keep an overdue tick waiting.
if capture.wait(wait.max(Duration::from_millis(1)))? { dirty = true; }
let now = Instant::now();
if dirty && now < next_tick { continue; }
if !dirty && now < last_send + keepalive { continue; }
@@ -250,7 +249,8 @@ fn run_damage(config: Config, mut capture: DamageCapture, units: mpsc::Sender<Ve
let now = Instant::now();
if dirty {
// Keep the tick phase; after a long idle, restart the phase from now instead of bursting to catch up.
next_tick = (next_tick + frame_interval).max(now);
let next = next_tick + frame_interval;
next_tick = if next > now { next } else { now + frame_interval };
dirty = false;
}
last_send = now;
+3 -34
View File
@@ -193,13 +193,14 @@ impl WebRtcSession {
let mut feedback = [0u8; 1500];
let mut reports = 0usize;
let mut feedback_counts = FeedbackCounts::default();
let mut keyframe_gate = KeyframeGate::new();
while let Ok((packets, _)) = sender.read(&mut feedback).await {
for packet in packets {
feedback_counts.observe(packet.as_any());
if packet.as_any().is::<webrtc::rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication>()
|| packet.as_any().is::<webrtc::rtcp::payload_feedbacks::full_intra_request::FullIntraRequest>() {
if keyframe_gate.allow(&idr_on_feedback, std::time::Instant::now()) {
// Dedupe only while an IDR is pending; the encoder clears the flag when it emits one,
// so a lost IDR does not block the next recovery request.
if !idr_on_feedback.load(std::sync::atomic::Ordering::Acquire) {
idr_on_feedback.store(true, std::sync::atomic::Ordering::Release);
}
}
@@ -994,21 +995,6 @@ impl FeedbackCounts {
}
}
/// Keyframe requests from viewer feedback: at most one accepted per `KEYFRAME_MIN_GAP`, and none while the
/// previous request still waits for the encoder. Without this, every PLI/FIR forced an IDR, and a lossy link
/// turned into an IDR storm. The idea follows live777's PLI backoff, written from scratch.
pub(crate) struct KeyframeGate { last: Option<std::time::Instant> }
const KEYFRAME_MIN_GAP: std::time::Duration = std::time::Duration::from_secs(1);
impl KeyframeGate {
pub(crate) fn new() -> Self { Self { last: None } }
pub(crate) fn allow(&mut self, pending: &std::sync::atomic::AtomicBool, now: std::time::Instant) -> bool {
if pending.load(std::sync::atomic::Ordering::Acquire) { return false; }
if self.last.is_some_and(|last| now.duration_since(last) < KEYFRAME_MIN_GAP) { return false; }
self.last = Some(now);
true
}
}
#[cfg(test)]
mod network_tests {
use super::*;
@@ -1025,21 +1011,4 @@ mod network_tests {
counts.observe(&PictureLossIndication::default());
assert_eq!((counts.nack_packets, counts.pli, counts.fir), (3, 1, 0));
}
#[test]
fn keyframe_gate_drops_request_storms() {
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};
let pending = AtomicBool::new(false);
let start = Instant::now();
let mut gate = KeyframeGate::new();
// A burst of 100 PLIs within one second yields a single accepted request.
let accepted = (0..100).filter(|i| gate.allow(&pending, start + Duration::from_millis(*i * 10))).count();
assert_eq!(accepted, 1);
// While the previous request is still waiting for the encoder, nothing gets through, even after the gap.
pending.store(true, std::sync::atomic::Ordering::Release);
assert!(!gate.allow(&pending, start + Duration::from_secs(5)));
// Once the encoder has answered, the next request is accepted after the gap again.
pending.store(false, std::sync::atomic::Ordering::Release);
assert!(gate.allow(&pending, start + Duration::from_secs(5)));
}
}