From f550e1a266771465621d2c50bf8db5094a6efa16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 08:04:37 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20add=20share=20test=20harnes?= =?UTF-8?q?s,=20fake=20capture=20and=20windows=20capture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.toml | 7 + crates/client/Cargo.toml | 33 +-- crates/client/src/gui.rs | 2 +- crates/client/src/gui/share_view.rs | 2 +- crates/client/src/gui/voice_stats.rs | 2 +- crates/client/src/network.rs | 3 +- crates/client/src/settings.rs | 2 +- crates/client/src/share/audio.rs | 18 ++ crates/client/src/share/audio_capture.rs | 21 +- .../client/src/share/audio_capture_windows.rs | 191 ++++++++++++++++++ crates/client/src/share/capture.rs | 66 +++++- crates/client/src/share/capture_windows.rs | 117 +++++++++++ crates/client/src/share/mod.rs | 7 + crates/client/src/share/session.rs | 33 ++- harness/client.sh | 11 + harness/codec.sh | 11 + harness/down.sh | 5 + harness/fps.py | 32 +++ harness/niri.kdl | 20 ++ harness/portals.conf | 3 + harness/session.sh | 23 +++ harness/share.sh | 10 + harness/shot.sh | 5 + harness/ui.sh | 16 ++ harness/up.sh | 15 ++ 25 files changed, 595 insertions(+), 60 deletions(-) create mode 100644 crates/client/src/share/audio.rs create mode 100644 crates/client/src/share/audio_capture_windows.rs create mode 100644 crates/client/src/share/capture_windows.rs create mode 100755 harness/client.sh create mode 100755 harness/codec.sh create mode 100755 harness/down.sh create mode 100644 harness/fps.py create mode 100644 harness/niri.kdl create mode 100644 harness/portals.conf create mode 100755 harness/session.sh create mode 100755 harness/share.sh create mode 100755 harness/shot.sh create mode 100755 harness/ui.sh create mode 100755 harness/up.sh diff --git a/Cargo.toml b/Cargo.toml index 6b38424..aed1d73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,10 @@ debug = "line-tables-only" [profile.dev.package."*"] opt-level = 3 +[profile.harness] +inherits = "dev" +opt-level = 3 + [profile.release] opt-level = 3 lto = "fat" @@ -28,3 +32,6 @@ quinn = { version = "0.11.12", default-features = false, features = [ "runtime-tokio", ] } rustls = "0.23.45" + +[patch."https://github.com/chromeos/cros-libva"] +cros-libva = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 2dcef8d..5b829e6 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -9,20 +9,20 @@ tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } gpui-kit = { version = "0.11.0", features = ["syntect"] } -ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } ureq = "3.5.2" bytes = "1.12.2" tracing = "0.1.44" @@ -37,11 +37,12 @@ rtrb = "0.4.1" pipewire = { version = "0.10.1", features = ["v0_3_49"] } ksni = "0.3.7" ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } -ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } -ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } +ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "19320a9deb61d27aaaedf2f18948184ca7838730" } [target.'cfg(target_os = "windows")'.dependencies] wasapi = "0.27.0" +windows-capture = "2.0.1" [target.'cfg(target_os = "macos")'.dependencies] coreaudio-rs = "0.14.2" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index ae19651..8eaa93d 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -602,7 +602,7 @@ pub struct Yumush { deferred: Vec, backups: Vec, pending_backup_delete: Option, - share_apps: Vec, + share_apps: Vec, } impl Yumush { diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index 9b9411c..180ec7c 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -23,7 +23,7 @@ use super::{ use crate::{ settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings}, share::{ - audio_capture::{AudioApp, AudioKind}, + audio::{AudioApp, AudioKind}, encode::capabilities, session::WatchQuality, }, diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index 91eb84d..1d0bc12 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -244,7 +244,7 @@ fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palett ("Bitrate", format!("{} kbps", stats.kbps)), ("FPS", format!("{:.0}", stats.fps)), ("Loss", format!("{:.1} %", stats.loss * 100.)), - ("Delay", format!("{} ms", stats.delay_ms)), + ("Buffer", format!("{} ms", stats.buffer_ms)), ("Keyframes", stats.keyframes.to_string()), ]; column() diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index 5227efb..526cdfe 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -49,7 +49,8 @@ use crate::{ ClientConfig, settings::{SHARE_QUALITY, ShareSettings, VoiceSettings}, share::{ - audio_capture::{self, AudioApp}, + audio::AudioApp, + audio_capture, encode::capabilities, session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, }, diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index e5f0b42..ea15898 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -14,7 +14,7 @@ use tracing::warn; use crate::{ config_file, - share::{audio_capture::AudioMode, encode::capabilities, session::WatchQuality}, + share::{audio::AudioMode, encode::capabilities, session::WatchQuality}, voice::audio::Choice, }; diff --git a/crates/client/src/share/audio.rs b/crates/client/src/share/audio.rs new file mode 100644 index 0000000..36e6d67 --- /dev/null +++ b/crates/client/src/share/audio.rs @@ -0,0 +1,18 @@ +pub enum AudioMode { + Everything { excluded: Vec }, + Source(String), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AudioKind { + App, + Output, + Input, +} + +#[derive(Debug, Clone)] +pub struct AudioApp { + pub name: String, + pub node: String, + pub kind: AudioKind, +} diff --git a/crates/client/src/share/audio_capture.rs b/crates/client/src/share/audio_capture.rs index a22e37b..3893768 100644 --- a/crates/client/src/share/audio_capture.rs +++ b/crates/client/src/share/audio_capture.rs @@ -27,24 +27,14 @@ use pw::{ use spa::{pod::Pod, utils::dict::DictRef}; use tracing::warn; +use super::audio::{AudioApp, AudioKind, AudioMode}; + const STOP_CHECK: Duration = Duration::from_millis(100); const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); const OWN_PREFIX: &str = "yumush"; const APP_CLASS: &str = "Stream/Output/Audio"; const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"]; -pub enum AudioMode { - Everything { excluded: Vec }, - Source(String), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AudioKind { - App, - Output, - Input, -} - impl AudioKind { fn of(class: &str) -> Option { match class { @@ -56,13 +46,6 @@ impl AudioKind { } } -#[derive(Debug, Clone)] -pub struct AudioApp { - pub name: String, - pub node: String, - pub kind: AudioKind, -} - pub struct AudioCapture { stop: Arc, thread: Option>, diff --git a/crates/client/src/share/audio_capture_windows.rs b/crates/client/src/share/audio_capture_windows.rs new file mode 100644 index 0000000..1e3aa97 --- /dev/null +++ b/crates/client/src/share/audio_capture_windows.rs @@ -0,0 +1,191 @@ +use std::{ + collections::{HashMap, VecDeque}, + error::Error, + process, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::Duration, +}; + +use common::constant::VOICE_SAMPLE_RATE; +use rtrb::Producer; +use tracing::warn; +use wasapi::{ + AudioCaptureClient, AudioClient, DeviceEnumerator, Direction, Handle, Role, SampleType, + StreamMode, WaveFormat, deinitialize, initialize_mta, +}; + +use super::audio::{AudioApp, AudioKind, AudioMode}; + +const STOP_CHECK: Duration = Duration::from_millis(100); +const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); +const BUFFER_HNS: i64 = 200_000; +const BYTES_PER_SAMPLE: usize = 4; + +pub struct AudioCapture { + stop: Arc, + thread: Option>, +} + +impl Drop for AudioCapture { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn with_com(body: impl FnOnce() -> T) -> T { + if let Err(error) = initialize_mta().ok() { + warn!("COM not initialized: {error}"); + return T::default(); + } + let value = body(); + deinitialize(); + value +} + +pub fn apps() -> Vec { + std::thread::spawn(|| { + with_com(|| { + sessions().unwrap_or_else(|error| { + warn!("share apps: {error}"); + Vec::new() + }) + }) + }) + .join() + .unwrap_or_default() +} + +fn sessions() -> Result, Box> { + let enumerator = DeviceEnumerator::new()?; + let device = enumerator.get_default_device_for_role(Direction::Render, Role::Console)?; + let enumeration = device + .get_iaudiosessionmanager()? + .get_audiosessionenumerator()?; + let own = process::id(); + let mut named: HashMap = HashMap::new(); + for index in 0..enumeration.get_count()? { + let session = enumeration.get_session(index)?; + let Ok(pid) = session.get_process_id() else { + continue; + }; + if pid == 0 || pid == own { + continue; + } + let name = session.get_display_name().unwrap_or_default(); + let name = if name.is_empty() { + format!("pid {pid}") + } else { + name + }; + named.entry(pid).or_insert(name); + } + let mut apps: Vec = named + .into_iter() + .map(|(pid, name)| AudioApp { + name, + node: pid.to_string(), + kind: AudioKind::App, + }) + .collect(); + apps.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(apps) +} + +pub fn start(mode: AudioMode, output: Producer) -> AudioCapture { + let stop = Arc::new(AtomicBool::new(false)); + let thread = { + let stop = stop.clone(); + std::thread::Builder::new() + .name("share-audio".to_string()) + .spawn(move || { + with_com(|| { + let mut output = output; + while !stop.load(Ordering::Relaxed) { + if let Err(error) = run(&mode, &mut output, &stop) { + warn!("share audio: {error}, retrying"); + std::thread::sleep(RETRY_AFTER_ERROR); + } + } + }) + }) + .inspect_err(|error| warn!("share audio not started: {error}")) + .ok() + }; + + AudioCapture { stop, thread } +} + +fn wave_format() -> WaveFormat { + WaveFormat::new( + 32, + 32, + SampleType::Float, + VOICE_SAMPLE_RATE as usize, + 2, + None, + ) +} + +fn run( + mode: &AudioMode, + output: &mut Producer, + stop: &AtomicBool, +) -> Result<(), Box> { + let mut client = match mode { + AudioMode::Everything { .. } => { + AudioClient::new_application_loopback_client(process::id(), false)? + } + AudioMode::Source(node) => { + AudioClient::new_application_loopback_client(node.parse()?, true)? + } + }; + client.initialize_client( + &wave_format(), + Direction::Capture, + StreamMode::EventsShared { + autoconvert: true, + buffer_duration_hns: BUFFER_HNS, + }, + None, + )?; + let event = client.set_get_eventhandle()?; + let reader = client.get_audiocaptureclient()?; + + client.start_stream()?; + let result = capture(&event, &reader, output, stop); + client.stop_stream()?; + result +} + +fn capture( + event: &Handle, + reader: &AudioCaptureClient, + output: &mut Producer, + stop: &AtomicBool, +) -> Result<(), Box> { + let mut bytes = VecDeque::new(); + while !stop.load(Ordering::Relaxed) { + let _ = event.wait_for_event(STOP_CHECK.as_millis() as u32); + while reader.get_next_packet_size()?.unwrap_or(0) > 0 { + reader.read_from_device_to_deque(&mut bytes)?; + } + for sample in bytes + .make_contiguous() + .as_chunks::() + .0 + .iter() + .map(|chunk| f32::from_le_bytes(*chunk)) + { + let _ = output.push(sample); + } + bytes.clear(); + } + Ok(()) +} diff --git a/crates/client/src/share/capture.rs b/crates/client/src/share/capture.rs index 1f08048..4ac27d5 100644 --- a/crates/client/src/share/capture.rs +++ b/crates/client/src/share/capture.rs @@ -47,7 +47,7 @@ pub struct Capture { pub frames: Receiver, stop: Arc, thread: Option>, - _session: Session, + _session: Option>, } impl Drop for Capture { @@ -60,6 +60,9 @@ impl Drop for Capture { } pub async fn open() -> Result { + if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") { + return Ok(fake(&spec)); + } let screencast = Screencast::new().await.map_err(text)?; let session = screencast .create_session(Default::default()) @@ -122,10 +125,69 @@ pub async fn open() -> Result { frames: frames_rx, stop, thread: Some(thread), - _session: session, + _session: Some(session), }) } +fn fake(spec: &str) -> Capture { + let parsed: Option<(u32, u32, u32)> = spec.split_once('@').and_then(|(size, fps)| { + let (width, height) = size.split_once('x')?; + Some((width.parse().ok()?, height.parse().ok()?, fps.parse().ok()?)) + }); + let (width, height, refresh) = parsed + .filter(|(width, height, fps)| *width > 0 && *height > 0 && *fps > 0) + .unwrap_or((1280, 720, DEFAULT_REFRESH)); + let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); + let stop = Arc::new(AtomicBool::new(false)); + let thread = { + let stop = stop.clone(); + std::thread::Builder::new() + .name("share-capture-fake".to_string()) + .spawn(move || { + let started = Instant::now(); + let interval = Duration::from_secs_f64(1.0 / f64::from(refresh)); + let mut number: u64 = 0; + while !stop.load(Ordering::Relaxed) { + let bar = (number as usize * 8) % width as usize; + let mut bgra = vec![40u8; (width * height) as usize * BYTES_PER_PIXEL]; + for y in 0..height as usize { + let row = y * width as usize; + for x in bar..(bar + 32).min(width as usize) { + bgra[(row + x) * BYTES_PER_PIXEL..][..3].fill(255); + } + if y < 16 { + for x in 0..(32 * 16).min(width as usize) { + let value = if (number >> (x / 16)) & 1 == 1 { 255 } else { 0 }; + bgra[(row + x) * BYTES_PER_PIXEL..][..3].fill(value); + } + } + } + let frame = Frame { + width, + height, + stride: width * BYTES_PER_PIXEL as u32, + timestamp_ms: u32::try_from(started.elapsed().as_millis()) + .unwrap_or(u32::MAX), + bgra, + }; + let _ = frames_tx.try_send(frame); + number += 1; + std::thread::sleep(interval); + } + }) + .ok() + }; + Capture { + width, + height, + refresh, + frames: frames_rx, + stop, + thread, + _session: None, + } +} + fn text(error: impl std::fmt::Display) -> String { error.to_string() } diff --git a/crates/client/src/share/capture_windows.rs b/crates/client/src/share/capture_windows.rs new file mode 100644 index 0000000..01a18ff --- /dev/null +++ b/crates/client/src/share/capture_windows.rs @@ -0,0 +1,117 @@ +use std::{ + sync::mpsc::{Receiver, SyncSender, sync_channel}, + time::Instant, +}; + +use windows_capture::{ + capture::{CaptureControl, Context, GraphicsCaptureApiHandler}, + frame::Frame as CaptureFrame, + graphics_capture_api::InternalCaptureControl, + monitor::Monitor, + settings::{ + ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings, + MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings, + }, +}; + +use super::frame::Frame; + +const DEFAULT_REFRESH: u32 = 60; +const FRAME_QUEUE: usize = 2; +const BYTES_PER_PIXEL: usize = 4; + +pub struct Capture { + pub width: u32, + pub height: u32, + pub refresh: u32, + pub frames: Receiver, + control: Option>, +} + +impl Drop for Capture { + fn drop(&mut self) { + if let Some(control) = self.control.take() { + let _ = control.stop(); + } + } +} + +pub async fn open() -> Result { + let monitor = Monitor::primary().map_err(text)?; + let width = monitor.width().map_err(text)?; + let height = monitor.height().map_err(text)?; + let refresh = monitor + .refresh_rate() + .ok() + .filter(|refresh| *refresh > 1) + .unwrap_or(DEFAULT_REFRESH); + + let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); + let settings = Settings::new( + monitor, + CursorCaptureSettings::WithCursor, + DrawBorderSettings::WithoutBorder, + SecondaryWindowSettings::Default, + MinimumUpdateIntervalSettings::Default, + DirtyRegionSettings::Default, + ColorFormat::Bgra8, + (frames_tx, Instant::now()), + ); + let control = Handler::start_free_threaded(settings).map_err(text)?; + + Ok(Capture { + width, + height, + refresh, + frames: frames_rx, + control: Some(control), + }) +} + +fn text(error: impl std::fmt::Display) -> String { + error.to_string() +} + +struct Handler { + frames: SyncSender, + started: Instant, +} + +impl GraphicsCaptureApiHandler for Handler { + type Flags = (SyncSender, Instant); + type Error = String; + + fn new(context: Context) -> Result { + let (frames, started) = context.flags; + Ok(Self { frames, started }) + } + + fn on_frame_arrived( + &mut self, + frame: &mut CaptureFrame, + _: InternalCaptureControl, + ) -> Result<(), Self::Error> { + let (width, height) = (frame.width(), frame.height()); + let mut buffer = frame.buffer().map_err(text)?; + let pitch = buffer.row_pitch() as usize; + let row = width as usize * BYTES_PER_PIXEL; + let raw = buffer.as_raw_buffer(); + + let mut bgra = Vec::with_capacity(row * height as usize); + for line in 0..height as usize { + let Some(pixels) = raw.get(line * pitch..line * pitch + row) else { + return Ok(()); + }; + bgra.extend_from_slice(pixels); + } + + let _ = self.frames.try_send(Frame { + width, + height, + stride: row as u32, + timestamp_ms: u32::try_from(self.started.elapsed().as_millis()).unwrap_or(u32::MAX), + bgra, + }); + Ok(()) + } +} diff --git a/crates/client/src/share/mod.rs b/crates/client/src/share/mod.rs index f1ca648..4c037cc 100644 --- a/crates/client/src/share/mod.rs +++ b/crates/client/src/share/mod.rs @@ -1,7 +1,14 @@ +pub mod audio; #[cfg(target_os = "linux")] pub mod audio_capture; +#[cfg(target_os = "windows")] +#[path = "audio_capture_windows.rs"] +pub mod audio_capture; #[cfg(target_os = "linux")] pub mod capture; +#[cfg(target_os = "windows")] +#[path = "capture_windows.rs"] +pub mod capture; pub mod convert; pub mod encode; pub mod frame; diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index 86ecc69..dde4567 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -24,7 +24,8 @@ use rtrb::{Consumer, Producer, RingBuffer}; use tracing::warn; use super::{ - audio_capture::{self, AudioCapture, AudioMode}, + audio::AudioMode, + audio_capture::{self, AudioCapture}, capture::{self, Capture}, encode::{self, Encoders}, frame::{Encoded, Frame}, @@ -80,7 +81,7 @@ pub struct WatchStats { pub fps: f32, pub loss: f32, pub keyframes: u32, - pub delay_ms: i64, + pub buffer_ms: i64, } #[derive(Default)] @@ -141,10 +142,10 @@ fn next(rx: &Receiver, stop: &AtomicBool) -> Option { None } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "windows")))] pub struct Sharing {} -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "windows"))] pub struct Sharing { encoders: Arc>, _feed: Worker, @@ -155,7 +156,7 @@ pub struct Sharing { sent: Arc>, } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "windows")))] impl Sharing { pub async fn start( _: Connection, @@ -175,7 +176,7 @@ impl Sharing { } } -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "windows"))] impl Sharing { pub async fn start( connection: Connection, @@ -354,13 +355,6 @@ impl Clock { self.started.elapsed().as_millis() as i64 } - fn delay(&self) -> i64 { - match self.offset.load(Ordering::Relaxed) { - i64::MAX => 0, - offset => offset + DELAY_MS, - } - } - fn observe(&self, sharer_ms: u32) { self.offset .fetch_min(self.now() - i64::from(sharer_ms), Ordering::Relaxed); @@ -476,9 +470,13 @@ impl Watching { .as_secs_f32() .max(f32::EPSILON); let bytes = self.received.swap(0, Ordering::Relaxed); - let (decoded, engine) = { + let (decoded, engine, buffer_ms) = { let mut video = lock(&self.video); - (std::mem::take(&mut video.decoded), video.engine) + let buffer_ms = match (video.queue.front(), video.queue.back()) { + (Some((first, _)), Some((last, _))) => last - first, + _ => 0, + }; + (std::mem::take(&mut video.decoded), video.engine, buffer_ms) }; let health = lock(&self.health); WatchStats { @@ -488,7 +486,7 @@ impl Watching { fps: decoded as f32 / seconds, loss: health.loss, keyframes: self.keyframes, - delay_ms: self.clock.delay(), + buffer_ms, } } @@ -762,8 +760,7 @@ mod tests { } } } - eprintln!("{codec:?}: {pictures} pictures"); - assert!(pictures > 0, "{codec:?} decoded nothing"); + assert_eq!(pictures, 10, "{codec:?}"); } } } diff --git a/harness/client.sh b/harness/client.sh new file mode 100755 index 0000000..5a221d8 --- /dev/null +++ b/harness/client.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(dirname "$HERE")" +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +NAME="$1" +source "$STATE/env" +mkdir -p "$STATE/clients/$NAME" +XDG_CONFIG_HOME="$STATE/clients/$NAME" RUST_LOG="${RUST_LOG:-info}" "$ROOT/target/${PROFILE:-harness}/client" >"$STATE/$NAME.log" 2>&1 & +echo "$NAME $!" >> "$STATE/pids" +echo "$NAME $!" diff --git a/harness/codec.sh b/harness/codec.sh new file mode 100755 index 0000000..d887260 --- /dev/null +++ b/harness/codec.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +./ui.sh click 600 400 +./ui.sh click 172 981; sleep 0.8; ./ui.sh click "$1" 835; sleep 0.5; ./ui.sh click 600 400 +./ui.sh click 144 980; sleep 2; ./ui.sh click 144 980; sleep 3 +./ui.sh click 1740 28; sleep 6 +./ui.sh click 1020 1000 right; sleep 0.6; ./ui.sh click 1087 598; sleep 2.5 +./shot.sh "codec-$2" >/dev/null +magick "/tmp/claude-1000/yumush-harness/shots/codec-$2.png" -crop 300x200+970+600 "/tmp/claude-1000/yumush-harness/shots/c-$2.png" +./ui.sh click 1500 300 diff --git a/harness/down.sh b/harness/down.sh new file mode 100755 index 0000000..6fcc7d0 --- /dev/null +++ b/harness/down.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +[ -f "$STATE/pids" ] || exit 0 +tac "$STATE/pids" | while read -r name pid; do kill "$pid" 2>/dev/null && echo "stopped $name $pid"; done +rm -f "$STATE/pids" "$STATE/env" diff --git a/harness/fps.py b/harness/fps.py new file mode 100644 index 0000000..62d766d --- /dev/null +++ b/harness/fps.py @@ -0,0 +1,32 @@ +import subprocess, sys, time, os +from PIL import Image +state = os.environ.get("HARNESS_STATE", "/tmp/claude-1000/yumush-harness") +env = dict(os.environ) +for line in open(f"{state}/env"): + k, v = line.split()[1].split("=", 1) + env[k] = v +x0, y0, x1, y1, src_w = [int(a) for a in sys.argv[1:6]] +seconds = float(sys.argv[6]) if len(sys.argv) > 6 else 3 +def find_video(im): + for y in range(y0, y1): + if im.getpixel((x0 + (x1 - x0) // 2, y))[0] > 20: + return y +def read(path): + im = Image.open(path).convert("RGB") + top = find_video(im) + s = (x1 - x0) / src_w + n = 0 + for i in range(32): + px = im.getpixel((int(x0 + (i * 16 + 8) * s), int(top + 4 * s))) + if px[0] > 128: + n |= 1 << i + return n +samples = [] +end = time.time() + seconds +while time.time() < end: + p = f"{state}/shots/fps.png" + t = time.time() + subprocess.run(["grim", p], env=env, check=True) + samples.append((t, read(p))) +(t0, n0), (t1, n1) = samples[0], samples[-1] +print(f"frames {n0}->{n1} in {t1-t0:.2f}s = {(n1-n0)/(t1-t0):.1f} fps, {len(samples)} shots") diff --git a/harness/niri.kdl b/harness/niri.kdl new file mode 100644 index 0000000..8bf3362 --- /dev/null +++ b/harness/niri.kdl @@ -0,0 +1,20 @@ +debug { + dbus-interfaces-in-non-session-instances +} +hotkey-overlay { + skip-at-startup +} +animations { + off +} +prefer-no-csd +screenshot-path null +layout { + gaps 0 + default-column-width { proportion 0.5; } +} +gestures { + hot-corners { + off + } +} diff --git a/harness/portals.conf b/harness/portals.conf new file mode 100644 index 0000000..4791a4f --- /dev/null +++ b/harness/portals.conf @@ -0,0 +1,3 @@ +[preferred] +default=gtk +org.freedesktop.impl.portal.ScreenCast=gnome diff --git a/harness/session.sh b/harness/session.sh new file mode 100755 index 0000000..c82e1f4 --- /dev/null +++ b/harness/session.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +STATE="$1" +before="$(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' || true)" +niri --headless -c "$HERE/niri.kdl" >"$STATE/niri.log" 2>&1 & +echo "niri $!" >> "$STATE/pids" +socket="" +for _ in $(seq 100); do + socket="$(comm -13 <(echo "$before" | sort) <(ls "$XDG_RUNTIME_DIR" | grep -E '^wayland-[0-9]+$' | sort) | head -1)" + [ -n "$socket" ] && break + sleep 0.1 +done +export WAYLAND_DISPLAY="$socket" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland +export NIRI_SOCKET="$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)" +dbus-update-activation-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE NIRI_SOCKET XDG_CONFIG_HOME="$STATE/xdg" +{ + echo "export WAYLAND_DISPLAY=$WAYLAND_DISPLAY" + echo "export NIRI_SOCKET=$NIRI_SOCKET" + echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS" + echo "export XDG_CURRENT_DESKTOP=niri" +} > "$STATE/env" +wait diff --git a/harness/share.sh b/harness/share.sh new file mode 100755 index 0000000..f844e0e --- /dev/null +++ b/harness/share.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +cd "$HERE" +./ui.sh click 825 29; sleep 2 +./ui.sh click 1785 29; sleep 2 +./ui.sh click 144 980; sleep 3 +./ui.sh click 1740 28; sleep "${SETTLE:-6}" +./shot.sh watch +python3 fps.py 1193 54 1911 1015 "${SRC_W:-1280}" "${SECONDS_MEASURE:-5}" diff --git a/harness/shot.sh b/harness/shot.sh new file mode 100755 index 0000000..458bef8 --- /dev/null +++ b/harness/shot.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$STATE/env" +out="$STATE/shots/${1:-shot}.png" +grim "$out" && echo "$out" diff --git a/harness/ui.sh b/harness/ui.sh new file mode 100755 index 0000000..9f5ed37 --- /dev/null +++ b/harness/ui.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$STATE/env" +to() { wlrctl pointer move -4000 -4000; wlrctl pointer move "$1" "$2"; sleep 0.1; } +case "$1" in + click) to "$2" "$3"; wlrctl pointer click "${4:-left}";; + move) to "$2" "$3";; + type) wtype "$2";; + key) wtype -k "$2";; + clear) args=(); for _ in $(seq "${2:-30}"); do args+=(-k BackSpace); done; wtype "${args[@]}";; + field) to "$2" "$3"; wlrctl pointer click left; sleep 0.2; wlrctl pointer click left; sleep 0.2 + args=(); for _ in $(seq 30); do args+=(-k BackSpace); done; wtype "${args[@]}"; sleep 0.2; wtype "$4";; + scroll) wlrctl pointer scroll "$2" "${3:-0}";; +esac +sleep "${UI_DELAY:-0.3}" diff --git a/harness/up.sh b/harness/up.sh new file mode 100755 index 0000000..dcf71ec --- /dev/null +++ b/harness/up.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(dirname "$HERE")" +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +[ -e "$STATE/pids" ] && { echo "harness already up: $STATE"; exit 1; } +mkdir -p "$STATE/server" "$STATE/xdg/xdg-desktop-portal" "$STATE/shots" +cp "$ROOT/fullchain.pem" "$ROOT/privkey.pem" "$STATE/server/" +cp "$HERE/portals.conf" "$STATE/xdg/xdg-desktop-portal/niri-portals.conf" +(cd "$STATE/server" && exec "$ROOT/target/${PROFILE:-harness}/server" >"$STATE/server.log" 2>&1) & +echo "server $!" >> "$STATE/pids" +dbus-run-session -- "$HERE/session.sh" "$STATE" >"$STATE/session.log" 2>&1 & +echo "session $!" >> "$STATE/pids" +for _ in $(seq 100); do [ -s "$STATE/env" ] && break; sleep 0.2; done +cat "$STATE/env"