forge
Explore
Log in

Don't you dare go Hollow

Add share test harness, fake capture and windows capture

Browse files at this commit

f550e1a266771465621d2c50bf8db5094a6efa16Ahmet Kaan GümüşParent: e06b4ef
  • feat
    • add share test harness, fake capture and windows capture
Show full message
✨ feat: add share test harness, fake capture and windows capture

A headless niri harness (private D-Bus, own server and clients, wlrctl
and wtype input, grim screenshots) drives the app end to end, and a
YUMUSH_TEST_CAPTURE source feeds a numbered test pattern so frame
progress can be read back from screenshots.

Windows gets screen capture through Windows Graphics Capture and share
audio through WASAPI process loopback that excludes our own process.

Bumps edith_codecs for zero-reorder H.264, patches cros-libva with its
VPP fix, adds an optimized harness profile and shows the playout buffer
instead of a skew-dependent delay.
Cargo.tomlmodified+7 -0
@@ -8,6 +8,10 @@ debug = "line-tables-only"
8 [profile.dev.package."*"]8 [profile.dev.package."*"]
9 opt-level = 39 opt-level = 3
10 10
11+[profile.harness]
12+inherits = "dev"
13+opt-level = 3
14+
11 [profile.release]15 [profile.release]
12 opt-level = 316 opt-level = 3
13 lto = "fat"17 lto = "fat"
@@ -28,3 +32,6 @@ quinn = { version = "0.11.12", default-features = false, features = [
28 "runtime-tokio",32 "runtime-tokio",
29 ] }33 ] }
30 rustls = "0.23.45"34 rustls = "0.23.45"
35+
36+[patch."https://github.com/chromeos/cros-libva"]
37+cros-libva = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
crates/client/Cargo.tomlmodified+17 -16
@@ -9,20 +9,20 @@ tokio.workspace = true
9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
10 10
11 gpui-kit = { version = "0.11.0", features = ["syntect"] }11 gpui-kit = { version = "0.11.0", features = ["syntect"] }
12-ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }12+ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
13-ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }13+ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
14-ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }14+ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
15-ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }15+ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
16-ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }16+ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
17-ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }17+ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
18-ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }18+ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
19-ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }19+ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
20-ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }20+ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
21-ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }21+ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
22-ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }22+ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
23-ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }23+ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
24-ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }24+ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
25-ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }25+ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
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"
@@ -37,11 +37,12 @@ rtrb = "0.4.1"
37 pipewire = { version = "0.10.1", features = ["v0_3_49"] }37 pipewire = { version = "0.10.1", features = ["v0_3_49"] }
38 ksni = "0.3.7"38 ksni = "0.3.7"
39 ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] }39 ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] }
40-ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }40+ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
41-ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }41+ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" }
42 42
43 [target.'cfg(target_os = "windows")'.dependencies]43 [target.'cfg(target_os = "windows")'.dependencies]
44 wasapi = "0.27.0"44 wasapi = "0.27.0"
45+windows-capture = "2.0.1"
45 46
46 [target.'cfg(target_os = "macos")'.dependencies]47 [target.'cfg(target_os = "macos")'.dependencies]
47 coreaudio-rs = "0.14.2"48 coreaudio-rs = "0.14.2"
crates/client/src/gui.rsmodified+1 -1
@@ -602,7 +602,7 @@ pub struct Yumush {
602 deferred: Vec<NetworkEvent>,602 deferred: Vec<NetworkEvent>,
603 backups: Vec<BackupInfo>,603 backups: Vec<BackupInfo>,
604 pending_backup_delete: Option<String>,604 pending_backup_delete: Option<String>,
605- share_apps: Vec<crate::share::audio_capture::AudioApp>,605+ share_apps: Vec<crate::share::audio::AudioApp>,
606 }606 }
607 607
608 impl Yumush {608 impl Yumush {
crates/client/src/gui/share_view.rsmodified+1 -1
@@ -23,7 +23,7 @@ use super::{
23 use crate::{23 use crate::{
24 settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings},24 settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings},
25 share::{25 share::{
26- audio_capture::{AudioApp, AudioKind},26+ audio::{AudioApp, AudioKind},
27 encode::capabilities,27 encode::capabilities,
28 session::WatchQuality,28 session::WatchQuality,
29 },29 },
crates/client/src/gui/voice_stats.rsmodified+1 -1
@@ -244,7 +244,7 @@ fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palett
244 ("Bitrate", format!("{} kbps", stats.kbps)),244 ("Bitrate", format!("{} kbps", stats.kbps)),
245 ("FPS", format!("{:.0}", stats.fps)),245 ("FPS", format!("{:.0}", stats.fps)),
246 ("Loss", format!("{:.1} %", stats.loss * 100.)),246 ("Loss", format!("{:.1} %", stats.loss * 100.)),
247- ("Delay", format!("{} ms", stats.delay_ms)),247+ ("Buffer", format!("{} ms", stats.buffer_ms)),
248 ("Keyframes", stats.keyframes.to_string()),248 ("Keyframes", stats.keyframes.to_string()),
249 ];249 ];
250 column()250 column()
crates/client/src/network.rsmodified+2 -1
@@ -49,7 +49,8 @@ use crate::{
49 ClientConfig,49 ClientConfig,
50 settings::{SHARE_QUALITY, ShareSettings, VoiceSettings},50 settings::{SHARE_QUALITY, ShareSettings, VoiceSettings},
51 share::{51 share::{
52- audio_capture::{self, AudioApp},52+ audio::AudioApp,
53+ audio_capture,
53 encode::capabilities,54 encode::capabilities,
54 session::{ShareSample, Sharing, Tick, WatchQuality, Watching},55 session::{ShareSample, Sharing, Tick, WatchQuality, Watching},
55 },56 },
crates/client/src/settings.rsmodified+1 -1
@@ -14,7 +14,7 @@ use tracing::warn;
14 14
15 use crate::{15 use crate::{
16 config_file,16 config_file,
17- share::{audio_capture::AudioMode, encode::capabilities, session::WatchQuality},17+ share::{audio::AudioMode, encode::capabilities, session::WatchQuality},
18 voice::audio::Choice,18 voice::audio::Choice,
19 };19 };
20 20
crates/client/src/share/audio.rsadded+18 -0
@@ -0,0 +1,18 @@
1+pub enum AudioMode {
2+ Everything { excluded: Vec<String> },
3+ Source(String),
4+}
5+
6+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7+pub enum AudioKind {
8+ App,
9+ Output,
10+ Input,
11+}
12+
13+#[derive(Debug, Clone)]
14+pub struct AudioApp {
15+ pub name: String,
16+ pub node: String,
17+ pub kind: AudioKind,
18+}
crates/client/src/share/audio_capture.rsmodified+2 -19
@@ -27,24 +27,14 @@ use pw::{
27 use spa::{pod::Pod, utils::dict::DictRef};27 use spa::{pod::Pod, utils::dict::DictRef};
28 use tracing::warn;28 use tracing::warn;
29 29
30+use super::audio::{AudioApp, AudioKind, AudioMode};
31+
30 const STOP_CHECK: Duration = Duration::from_millis(100);32 const STOP_CHECK: Duration = Duration::from_millis(100);
31 const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);33 const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);
32 const OWN_PREFIX: &str = "yumush";34 const OWN_PREFIX: &str = "yumush";
33 const APP_CLASS: &str = "Stream/Output/Audio";35 const APP_CLASS: &str = "Stream/Output/Audio";
34 const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"];36 const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"];
35 37
36-pub enum AudioMode {
37- Everything { excluded: Vec<String> },
38- Source(String),
39-}
40-
41-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42-pub enum AudioKind {
43- App,
44- Output,
45- Input,
46-}
47-
48 impl AudioKind {38 impl AudioKind {
49 fn of(class: &str) -> Option<Self> {39 fn of(class: &str) -> Option<Self> {
50 match class {40 match class {
@@ -56,13 +46,6 @@ impl AudioKind {
56 }46 }
57 }47 }
58 48
59-#[derive(Debug, Clone)]
60-pub struct AudioApp {
61- pub name: String,
62- pub node: String,
63- pub kind: AudioKind,
64-}
65-
66 pub struct AudioCapture {49 pub struct AudioCapture {
67 stop: Arc<AtomicBool>,50 stop: Arc<AtomicBool>,
68 thread: Option<JoinHandle<()>>,51 thread: Option<JoinHandle<()>>,
crates/client/src/share/audio_capture_windows.rsadded+191 -0
@@ -0,0 +1,191 @@
1+use std::{
2+ collections::{HashMap, VecDeque},
3+ error::Error,
4+ process,
5+ sync::{
6+ Arc,
7+ atomic::{AtomicBool, Ordering},
8+ },
9+ thread::JoinHandle,
10+ time::Duration,
11+};
12+
13+use common::constant::VOICE_SAMPLE_RATE;
14+use rtrb::Producer;
15+use tracing::warn;
16+use wasapi::{
17+ AudioCaptureClient, AudioClient, DeviceEnumerator, Direction, Handle, Role, SampleType,
18+ StreamMode, WaveFormat, deinitialize, initialize_mta,
19+};
20+
21+use super::audio::{AudioApp, AudioKind, AudioMode};
22+
23+const STOP_CHECK: Duration = Duration::from_millis(100);
24+const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);
25+const BUFFER_HNS: i64 = 200_000;
26+const BYTES_PER_SAMPLE: usize = 4;
27+
28+pub struct AudioCapture {
29+ stop: Arc<AtomicBool>,
30+ thread: Option<JoinHandle<()>>,
31+}
32+
33+impl Drop for AudioCapture {
34+ fn drop(&mut self) {
35+ self.stop.store(true, Ordering::Relaxed);
36+ if let Some(thread) = self.thread.take() {
37+ let _ = thread.join();
38+ }
39+ }
40+}
41+
42+fn with_com<T: Default>(body: impl FnOnce() -> T) -> T {
43+ if let Err(error) = initialize_mta().ok() {
44+ warn!("COM not initialized: {error}");
45+ return T::default();
46+ }
47+ let value = body();
48+ deinitialize();
49+ value
50+}
51+
52+pub fn apps() -> Vec<AudioApp> {
53+ std::thread::spawn(|| {
54+ with_com(|| {
55+ sessions().unwrap_or_else(|error| {
56+ warn!("share apps: {error}");
57+ Vec::new()
58+ })
59+ })
60+ })
61+ .join()
62+ .unwrap_or_default()
63+}
64+
65+fn sessions() -> Result<Vec<AudioApp>, Box<dyn Error>> {
66+ let enumerator = DeviceEnumerator::new()?;
67+ let device = enumerator.get_default_device_for_role(Direction::Render, Role::Console)?;
68+ let enumeration = device
69+ .get_iaudiosessionmanager()?
70+ .get_audiosessionenumerator()?;
71+ let own = process::id();
72+ let mut named: HashMap<u32, String> = HashMap::new();
73+ for index in 0..enumeration.get_count()? {
74+ let session = enumeration.get_session(index)?;
75+ let Ok(pid) = session.get_process_id() else {
76+ continue;
77+ };
78+ if pid == 0 || pid == own {
79+ continue;
80+ }
81+ let name = session.get_display_name().unwrap_or_default();
82+ let name = if name.is_empty() {
83+ format!("pid {pid}")
84+ } else {
85+ name
86+ };
87+ named.entry(pid).or_insert(name);
88+ }
89+ let mut apps: Vec<AudioApp> = named
90+ .into_iter()
91+ .map(|(pid, name)| AudioApp {
92+ name,
93+ node: pid.to_string(),
94+ kind: AudioKind::App,
95+ })
96+ .collect();
97+ apps.sort_by(|a, b| a.name.cmp(&b.name));
98+ Ok(apps)
99+}
100+
101+pub fn start(mode: AudioMode, output: Producer<f32>) -> AudioCapture {
102+ let stop = Arc::new(AtomicBool::new(false));
103+ let thread = {
104+ let stop = stop.clone();
105+ std::thread::Builder::new()
106+ .name("share-audio".to_string())
107+ .spawn(move || {
108+ with_com(|| {
109+ let mut output = output;
110+ while !stop.load(Ordering::Relaxed) {
111+ if let Err(error) = run(&mode, &mut output, &stop) {
112+ warn!("share audio: {error}, retrying");
113+ std::thread::sleep(RETRY_AFTER_ERROR);
114+ }
115+ }
116+ })
117+ })
118+ .inspect_err(|error| warn!("share audio not started: {error}"))
119+ .ok()
120+ };
121+
122+ AudioCapture { stop, thread }
123+}
124+
125+fn wave_format() -> WaveFormat {
126+ WaveFormat::new(
127+ 32,
128+ 32,
129+ SampleType::Float,
130+ VOICE_SAMPLE_RATE as usize,
131+ 2,
132+ None,
133+ )
134+}
135+
136+fn run(
137+ mode: &AudioMode,
138+ output: &mut Producer<f32>,
139+ stop: &AtomicBool,
140+) -> Result<(), Box<dyn Error>> {
141+ let mut client = match mode {
142+ AudioMode::Everything { .. } => {
143+ AudioClient::new_application_loopback_client(process::id(), false)?
144+ }
145+ AudioMode::Source(node) => {
146+ AudioClient::new_application_loopback_client(node.parse()?, true)?
147+ }
148+ };
149+ client.initialize_client(
150+ &wave_format(),
151+ Direction::Capture,
152+ StreamMode::EventsShared {
153+ autoconvert: true,
154+ buffer_duration_hns: BUFFER_HNS,
155+ },
156+ None,
157+ )?;
158+ let event = client.set_get_eventhandle()?;
159+ let reader = client.get_audiocaptureclient()?;
160+
161+ client.start_stream()?;
162+ let result = capture(&event, &reader, output, stop);
163+ client.stop_stream()?;
164+ result
165+}
166+
167+fn capture(
168+ event: &Handle,
169+ reader: &AudioCaptureClient,
170+ output: &mut Producer<f32>,
171+ stop: &AtomicBool,
172+) -> Result<(), Box<dyn Error>> {
173+ let mut bytes = VecDeque::new();
174+ while !stop.load(Ordering::Relaxed) {
175+ let _ = event.wait_for_event(STOP_CHECK.as_millis() as u32);
176+ while reader.get_next_packet_size()?.unwrap_or(0) > 0 {
177+ reader.read_from_device_to_deque(&mut bytes)?;
178+ }
179+ for sample in bytes
180+ .make_contiguous()
181+ .as_chunks::<BYTES_PER_SAMPLE>()
182+ .0
183+ .iter()
184+ .map(|chunk| f32::from_le_bytes(*chunk))
185+ {
186+ let _ = output.push(sample);
187+ }
188+ bytes.clear();
189+ }
190+ Ok(())
191+}
crates/client/src/share/capture.rsmodified+64 -2
@@ -47,7 +47,7 @@ pub struct Capture {
47 pub frames: Receiver<Frame>,47 pub frames: Receiver<Frame>,
48 stop: Arc<AtomicBool>,48 stop: Arc<AtomicBool>,
49 thread: Option<JoinHandle<()>>,49 thread: Option<JoinHandle<()>>,
50- _session: Session<Screencast>,50+ _session: Option<Session<Screencast>>,
51 }51 }
52 52
53 impl Drop for Capture {53 impl Drop for Capture {
@@ -60,6 +60,9 @@ impl Drop for Capture {
60 }60 }
61 61
62 pub async fn open() -> Result<Capture, String> {62 pub async fn open() -> Result<Capture, String> {
63+ if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") {
64+ return Ok(fake(&spec));
65+ }
63 let screencast = Screencast::new().await.map_err(text)?;66 let screencast = Screencast::new().await.map_err(text)?;
64 let session = screencast67 let session = screencast
65 .create_session(Default::default())68 .create_session(Default::default())
@@ -122,10 +125,69 @@ pub async fn open() -> Result<Capture, String> {
122 frames: frames_rx,125 frames: frames_rx,
123 stop,126 stop,
124 thread: Some(thread),127 thread: Some(thread),
125- _session: session,128+ _session: Some(session),
126 })129 })
127 }130 }
128 131
132+fn fake(spec: &str) -> Capture {
133+ let parsed: Option<(u32, u32, u32)> = spec.split_once('@').and_then(|(size, fps)| {
134+ let (width, height) = size.split_once('x')?;
135+ Some((width.parse().ok()?, height.parse().ok()?, fps.parse().ok()?))
136+ });
137+ let (width, height, refresh) = parsed
138+ .filter(|(width, height, fps)| *width > 0 && *height > 0 && *fps > 0)
139+ .unwrap_or((1280, 720, DEFAULT_REFRESH));
140+ let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE);
141+ let stop = Arc::new(AtomicBool::new(false));
142+ let thread = {
143+ let stop = stop.clone();
144+ std::thread::Builder::new()
145+ .name("share-capture-fake".to_string())
146+ .spawn(move || {
147+ let started = Instant::now();
148+ let interval = Duration::from_secs_f64(1.0 / f64::from(refresh));
149+ let mut number: u64 = 0;
150+ while !stop.load(Ordering::Relaxed) {
151+ let bar = (number as usize * 8) % width as usize;
152+ let mut bgra = vec![40u8; (width * height) as usize * BYTES_PER_PIXEL];
153+ for y in 0..height as usize {
154+ let row = y * width as usize;
155+ for x in bar..(bar + 32).min(width as usize) {
156+ bgra[(row + x) * BYTES_PER_PIXEL..][..3].fill(255);
157+ }
158+ if y < 16 {
159+ for x in 0..(32 * 16).min(width as usize) {
160+ let value = if (number >> (x / 16)) & 1 == 1 { 255 } else { 0 };
161+ bgra[(row + x) * BYTES_PER_PIXEL..][..3].fill(value);
162+ }
163+ }
164+ }
165+ let frame = Frame {
166+ width,
167+ height,
168+ stride: width * BYTES_PER_PIXEL as u32,
169+ timestamp_ms: u32::try_from(started.elapsed().as_millis())
170+ .unwrap_or(u32::MAX),
171+ bgra,
172+ };
173+ let _ = frames_tx.try_send(frame);
174+ number += 1;
175+ std::thread::sleep(interval);
176+ }
177+ })
178+ .ok()
179+ };
180+ Capture {
181+ width,
182+ height,
183+ refresh,
184+ frames: frames_rx,
185+ stop,
186+ thread,
187+ _session: None,
188+ }
189+}
190+
129 fn text(error: impl std::fmt::Display) -> String {191 fn text(error: impl std::fmt::Display) -> String {
130 error.to_string()192 error.to_string()
131 }193 }
crates/client/src/share/capture_windows.rsadded+117 -0
@@ -0,0 +1,117 @@
1+use std::{
2+ sync::mpsc::{Receiver, SyncSender, sync_channel},
3+ time::Instant,
4+};
5+
6+use windows_capture::{
7+ capture::{CaptureControl, Context, GraphicsCaptureApiHandler},
8+ frame::Frame as CaptureFrame,
9+ graphics_capture_api::InternalCaptureControl,
10+ monitor::Monitor,
11+ settings::{
12+ ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
13+ MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
14+ },
15+};
16+
17+use super::frame::Frame;
18+
19+const DEFAULT_REFRESH: u32 = 60;
20+const FRAME_QUEUE: usize = 2;
21+const BYTES_PER_PIXEL: usize = 4;
22+
23+pub struct Capture {
24+ pub width: u32,
25+ pub height: u32,
26+ pub refresh: u32,
27+ pub frames: Receiver<Frame>,
28+ control: Option<CaptureControl<Handler, String>>,
29+}
30+
31+impl Drop for Capture {
32+ fn drop(&mut self) {
33+ if let Some(control) = self.control.take() {
34+ let _ = control.stop();
35+ }
36+ }
37+}
38+
39+pub async fn open() -> Result<Capture, String> {
40+ let monitor = Monitor::primary().map_err(text)?;
41+ let width = monitor.width().map_err(text)?;
42+ let height = monitor.height().map_err(text)?;
43+ let refresh = monitor
44+ .refresh_rate()
45+ .ok()
46+ .filter(|refresh| *refresh > 1)
47+ .unwrap_or(DEFAULT_REFRESH);
48+
49+ let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE);
50+ let settings = Settings::new(
51+ monitor,
52+ CursorCaptureSettings::WithCursor,
53+ DrawBorderSettings::WithoutBorder,
54+ SecondaryWindowSettings::Default,
55+ MinimumUpdateIntervalSettings::Default,
56+ DirtyRegionSettings::Default,
57+ ColorFormat::Bgra8,
58+ (frames_tx, Instant::now()),
59+ );
60+ let control = Handler::start_free_threaded(settings).map_err(text)?;
61+
62+ Ok(Capture {
63+ width,
64+ height,
65+ refresh,
66+ frames: frames_rx,
67+ control: Some(control),
68+ })
69+}
70+
71+fn text(error: impl std::fmt::Display) -> String {
72+ error.to_string()
73+}
74+
75+struct Handler {
76+ frames: SyncSender<Frame>,
77+ started: Instant,
78+}
79+
80+impl GraphicsCaptureApiHandler for Handler {
81+ type Flags = (SyncSender<Frame>, Instant);
82+ type Error = String;
83+
84+ fn new(context: Context<Self::Flags>) -> Result<Self, Self::Error> {
85+ let (frames, started) = context.flags;
86+ Ok(Self { frames, started })
87+ }
88+
89+ fn on_frame_arrived(
90+ &mut self,
91+ frame: &mut CaptureFrame,
92+ _: InternalCaptureControl,
93+ ) -> Result<(), Self::Error> {
94+ let (width, height) = (frame.width(), frame.height());
95+ let mut buffer = frame.buffer().map_err(text)?;
96+ let pitch = buffer.row_pitch() as usize;
97+ let row = width as usize * BYTES_PER_PIXEL;
98+ let raw = buffer.as_raw_buffer();
99+
100+ let mut bgra = Vec::with_capacity(row * height as usize);
101+ for line in 0..height as usize {
102+ let Some(pixels) = raw.get(line * pitch..line * pitch + row) else {
103+ return Ok(());
104+ };
105+ bgra.extend_from_slice(pixels);
106+ }
107+
108+ let _ = self.frames.try_send(Frame {
109+ width,
110+ height,
111+ stride: row as u32,
112+ timestamp_ms: u32::try_from(self.started.elapsed().as_millis()).unwrap_or(u32::MAX),
113+ bgra,
114+ });
115+ Ok(())
116+ }
117+}
crates/client/src/share/mod.rsmodified+7 -0
@@ -1,7 +1,14 @@
1+pub mod audio;
1 #[cfg(target_os = "linux")]2 #[cfg(target_os = "linux")]
2 pub mod audio_capture;3 pub mod audio_capture;
4+#[cfg(target_os = "windows")]
5+#[path = "audio_capture_windows.rs"]
6+pub mod audio_capture;
3 #[cfg(target_os = "linux")]7 #[cfg(target_os = "linux")]
4 pub mod capture;8 pub mod capture;
9+#[cfg(target_os = "windows")]
10+#[path = "capture_windows.rs"]
11+pub mod capture;
5 pub mod convert;12 pub mod convert;
6 pub mod encode;13 pub mod encode;
7 pub mod frame;14 pub mod frame;
crates/client/src/share/session.rsmodified+15 -18
@@ -24,7 +24,8 @@ use rtrb::{Consumer, Producer, RingBuffer};
24 use tracing::warn;24 use tracing::warn;
25 25
26 use super::{26 use super::{
27- audio_capture::{self, AudioCapture, AudioMode},27+ audio::AudioMode,
28+ audio_capture::{self, AudioCapture},
28 capture::{self, Capture},29 capture::{self, Capture},
29 encode::{self, Encoders},30 encode::{self, Encoders},
30 frame::{Encoded, Frame},31 frame::{Encoded, Frame},
@@ -80,7 +81,7 @@ pub struct WatchStats {
80 pub fps: f32,81 pub fps: f32,
81 pub loss: f32,82 pub loss: f32,
82 pub keyframes: u32,83 pub keyframes: u32,
83- pub delay_ms: i64,84+ pub buffer_ms: i64,
84 }85 }
85 86
86 #[derive(Default)]87 #[derive(Default)]
@@ -141,10 +142,10 @@ fn next<T>(rx: &Receiver<T>, stop: &AtomicBool) -> Option<T> {
141 None142 None
142 }143 }
143 144
144-#[cfg(not(target_os = "linux"))]145+#[cfg(not(any(target_os = "linux", target_os = "windows")))]
145 pub struct Sharing {}146 pub struct Sharing {}
146 147
147-#[cfg(target_os = "linux")]148+#[cfg(any(target_os = "linux", target_os = "windows"))]
148 pub struct Sharing {149 pub struct Sharing {
149 encoders: Arc<Mutex<Encoders>>,150 encoders: Arc<Mutex<Encoders>>,
150 _feed: Worker,151 _feed: Worker,
@@ -155,7 +156,7 @@ pub struct Sharing {
155 sent: Arc<Mutex<Sent>>,156 sent: Arc<Mutex<Sent>>,
156 }157 }
157 158
158-#[cfg(not(target_os = "linux"))]159+#[cfg(not(any(target_os = "linux", target_os = "windows")))]
159 impl Sharing {160 impl Sharing {
160 pub async fn start(161 pub async fn start(
161 _: Connection,162 _: Connection,
@@ -175,7 +176,7 @@ impl Sharing {
175 }176 }
176 }177 }
177 178
178-#[cfg(target_os = "linux")]179+#[cfg(any(target_os = "linux", target_os = "windows"))]
179 impl Sharing {180 impl Sharing {
180 pub async fn start(181 pub async fn start(
181 connection: Connection,182 connection: Connection,
@@ -354,13 +355,6 @@ impl Clock {
354 self.started.elapsed().as_millis() as i64355 self.started.elapsed().as_millis() as i64
355 }356 }
356 357
357- fn delay(&self) -> i64 {
358- match self.offset.load(Ordering::Relaxed) {
359- i64::MAX => 0,
360- offset => offset + DELAY_MS,
361- }
362- }
363-
364 fn observe(&self, sharer_ms: u32) {358 fn observe(&self, sharer_ms: u32) {
365 self.offset359 self.offset
366 .fetch_min(self.now() - i64::from(sharer_ms), Ordering::Relaxed);360 .fetch_min(self.now() - i64::from(sharer_ms), Ordering::Relaxed);
@@ -476,9 +470,13 @@ impl Watching {
476 .as_secs_f32()470 .as_secs_f32()
477 .max(f32::EPSILON);471 .max(f32::EPSILON);
478 let bytes = self.received.swap(0, Ordering::Relaxed);472 let bytes = self.received.swap(0, Ordering::Relaxed);
479- let (decoded, engine) = {473+ let (decoded, engine, buffer_ms) = {
480 let mut video = lock(&self.video);474 let mut video = lock(&self.video);
481- (std::mem::take(&mut video.decoded), video.engine)475+ let buffer_ms = match (video.queue.front(), video.queue.back()) {
476+ (Some((first, _)), Some((last, _))) => last - first,
477+ _ => 0,
478+ };
479+ (std::mem::take(&mut video.decoded), video.engine, buffer_ms)
482 };480 };
483 let health = lock(&self.health);481 let health = lock(&self.health);
484 WatchStats {482 WatchStats {
@@ -488,7 +486,7 @@ impl Watching {
488 fps: decoded as f32 / seconds,486 fps: decoded as f32 / seconds,
489 loss: health.loss,487 loss: health.loss,
490 keyframes: self.keyframes,488 keyframes: self.keyframes,
491- delay_ms: self.clock.delay(),489+ buffer_ms,
492 }490 }
493 }491 }
494 492
@@ -762,8 +760,7 @@ mod tests {
762 }760 }
763 }761 }
764 }762 }
765- eprintln!("{codec:?}: {pictures} pictures");763+ assert_eq!(pictures, 10, "{codec:?}");
766- assert!(pictures > 0, "{codec:?} decoded nothing");
767 }764 }
768 }765 }
769 }766 }
harness/client.shadded+11 -0
@@ -0,0 +1,11 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+HERE="$(cd "$(dirname "$0")" && pwd)"
4+ROOT="$(dirname "$HERE")"
5+STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
6+NAME="$1"
7+source "$STATE/env"
8+mkdir -p "$STATE/clients/$NAME"
9+XDG_CONFIG_HOME="$STATE/clients/$NAME" RUST_LOG="${RUST_LOG:-info}" "$ROOT/target/${PROFILE:-harness}/client" >"$STATE/$NAME.log" 2>&1 &
10+echo "$NAME $!" >> "$STATE/pids"
11+echo "$NAME $!"
harness/codec.shadded+11 -0
@@ -0,0 +1,11 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+cd "$(dirname "$0")"
4+./ui.sh click 600 400
5+./ui.sh click 172 981; sleep 0.8; ./ui.sh click "$1" 835; sleep 0.5; ./ui.sh click 600 400
6+./ui.sh click 144 980; sleep 2; ./ui.sh click 144 980; sleep 3
7+./ui.sh click 1740 28; sleep 6
8+./ui.sh click 1020 1000 right; sleep 0.6; ./ui.sh click 1087 598; sleep 2.5
9+./shot.sh "codec-$2" >/dev/null
10+magick "/tmp/claude-1000/yumush-harness/shots/codec-$2.png" -crop 300x200+970+600 "/tmp/claude-1000/yumush-harness/shots/c-$2.png"
11+./ui.sh click 1500 300
harness/down.shadded+5 -0
@@ -0,0 +1,5 @@
1+#!/usr/bin/env bash
2+STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
3+[ -f "$STATE/pids" ] || exit 0
4+tac "$STATE/pids" | while read -r name pid; do kill "$pid" 2>/dev/null && echo "stopped $name $pid"; done
5+rm -f "$STATE/pids" "$STATE/env"
harness/fps.pyadded+32 -0
@@ -0,0 +1,32 @@
1+import subprocess, sys, time, os
2+from PIL import Image
3+state = os.environ.get("HARNESS_STATE", "/tmp/claude-1000/yumush-harness")
4+env = dict(os.environ)
5+for line in open(f"{state}/env"):
6+ k, v = line.split()[1].split("=", 1)
7+ env[k] = v
8+x0, y0, x1, y1, src_w = [int(a) for a in sys.argv[1:6]]
9+seconds = float(sys.argv[6]) if len(sys.argv) > 6 else 3
10+def find_video(im):
11+ for y in range(y0, y1):
12+ if im.getpixel((x0 + (x1 - x0) // 2, y))[0] > 20:
13+ return y
14+def read(path):
15+ im = Image.open(path).convert("RGB")
16+ top = find_video(im)
17+ s = (x1 - x0) / src_w
18+ n = 0
19+ for i in range(32):
20+ px = im.getpixel((int(x0 + (i * 16 + 8) * s), int(top + 4 * s)))
21+ if px[0] > 128:
22+ n |= 1 << i
23+ return n
24+samples = []
25+end = time.time() + seconds
26+while time.time() < end:
27+ p = f"{state}/shots/fps.png"
28+ t = time.time()
29+ subprocess.run(["grim", p], env=env, check=True)
30+ samples.append((t, read(p)))
31+(t0, n0), (t1, n1) = samples[0], samples[-1]
32+print(f"frames {n0}->{n1} in {t1-t0:.2f}s = {(n1-n0)/(t1-t0):.1f} fps, {len(samples)} shots")
harness/niri.kdladded+20 -0
@@ -0,0 +1,20 @@
1+debug {
2+ dbus-interfaces-in-non-session-instances
3+}
4+hotkey-overlay {
5+ skip-at-startup
6+}
7+animations {
8+ off
9+}
10+prefer-no-csd
11+screenshot-path null
12+layout {
13+ gaps 0
14+ default-column-width { proportion 0.5; }
15+}
16+gestures {
17+ hot-corners {
18+ off
19+ }
20+}
harness/portals.confadded+3 -0
@@ -0,0 +1,3 @@
1+[preferred]
2+default=gtk
3+org.freedesktop.impl.portal.ScreenCast=gnome
harness/session.shadded+23 -0
@@ -0,0 +1,23 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+HERE="$(cd "$(dirname "$0")" && pwd)"
4+STATE="$1"
5+before="$(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' || true)"
6+niri --headless -c "$HERE/niri.kdl" >"$STATE/niri.log" 2>&1 &
7+echo "niri $!" >> "$STATE/pids"
8+socket=""
9+for _ in $(seq 100); do
10+ socket="$(comm -13 <(echo "$before" | sort) <(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' | sort) | head -1)"
11+ [ -n "$socket" ] && break
12+ sleep 0.1
13+done
14+export WAYLAND_DISPLAY="$socket" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland
15+export NIRI_SOCKET="$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)"
16+dbus-update-activation-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE NIRI_SOCKET XDG_CONFIG_HOME="$STATE/xdg"
17+{
18+ echo "export WAYLAND_DISPLAY=$WAYLAND_DISPLAY"
19+ echo "export NIRI_SOCKET=$NIRI_SOCKET"
20+ echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS"
21+ echo "export XDG_CURRENT_DESKTOP=niri"
22+} > "$STATE/env"
23+wait
harness/share.shadded+10 -0
@@ -0,0 +1,10 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+HERE="$(cd "$(dirname "$0")" && pwd)"
4+cd "$HERE"
5+./ui.sh click 825 29; sleep 2
6+./ui.sh click 1785 29; sleep 2
7+./ui.sh click 144 980; sleep 3
8+./ui.sh click 1740 28; sleep "${SETTLE:-6}"
9+./shot.sh watch
10+python3 fps.py 1193 54 1911 1015 "${SRC_W:-1280}" "${SECONDS_MEASURE:-5}"
harness/shot.shadded+5 -0
@@ -0,0 +1,5 @@
1+#!/usr/bin/env bash
2+STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
3+source "$STATE/env"
4+out="$STATE/shots/${1:-shot}.png"
5+grim "$out" && echo "$out"
harness/ui.shadded+16 -0
@@ -0,0 +1,16 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
4+source "$STATE/env"
5+to() { wlrctl pointer move -4000 -4000; wlrctl pointer move "$1" "$2"; sleep 0.1; }
6+case "$1" in
7+ click) to "$2" "$3"; wlrctl pointer click "${4:-left}";;
8+ move) to "$2" "$3";;
9+ type) wtype "$2";;
10+ key) wtype -k "$2";;
11+ clear) args=(); for _ in $(seq "${2:-30}"); do args+=(-k BackSpace); done; wtype "${args[@]}";;
12+ field) to "$2" "$3"; wlrctl pointer click left; sleep 0.2; wlrctl pointer click left; sleep 0.2
13+ args=(); for _ in $(seq 30); do args+=(-k BackSpace); done; wtype "${args[@]}"; sleep 0.2; wtype "$4";;
14+ scroll) wlrctl pointer scroll "$2" "${3:-0}";;
15+esac
16+sleep "${UI_DELAY:-0.3}"
harness/up.shadded+15 -0
@@ -0,0 +1,15 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+HERE="$(cd "$(dirname "$0")" && pwd)"
4+ROOT="$(dirname "$HERE")"
5+STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}"
6+[ -e "$STATE/pids" ] && { echo "harness already up: $STATE"; exit 1; }
7+mkdir -p "$STATE/server" "$STATE/xdg/xdg-desktop-portal" "$STATE/shots"
8+cp "$ROOT/fullchain.pem" "$ROOT/privkey.pem" "$STATE/server/"
9+cp "$HERE/portals.conf" "$STATE/xdg/xdg-desktop-portal/niri-portals.conf"
10+(cd "$STATE/server" && exec "$ROOT/target/${PROFILE:-harness}/server" >"$STATE/server.log" 2>&1) &
11+echo "server $!" >> "$STATE/pids"
12+dbus-run-session -- "$HERE/session.sh" "$STATE" >"$STATE/session.log" 2>&1 &
13+echo "session $!" >> "$STATE/pids"
14+for _ in $(seq 100); do [ -s "$STATE/env" ] && break; sleep 0.2; done
15+cat "$STATE/env"