Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
feat(omnidisc): screen share, application audio and calls on Windows
tonhowtf1c7d74fa0148
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 46962e3c..fa652d94 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -5949,6 +5949,8 @@ dependencies = ["tokio-tungstenite 0.30.0","tracing","wgpu",+ "windows 0.61.3",+ "windows-core 0.61.2",][[package]]diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex b94e2b07..872a91d9 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -81,7 +81,7 @@ fs4 = "1"[target.'cfg(windows)'.dependencies]keyring = { version = "3", features = ["windows-native"] }webview2-com = "0.38"-windows = { version = "0.61", features = ["Win32_System_Com", "Win32_UI_WindowsAndMessaging"] }+windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Media_Audio", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Variant", "Win32_UI_WindowsAndMessaging"] }# Reading WKWebView's cookie store directly — document.cookie cannot see# HttpOnly cookies, which is the whole point of the auth webview (#287).diff --git a/src-tauri/omnidisc-media/Cargo.toml b/src-tauri/omnidisc-media/Cargo.tomlindex 45ede983..989b182c 100644--- a/src-tauri/omnidisc-media/Cargo.toml+++ b/src-tauri/omnidisc-media/Cargo.toml@@ -39,6 +39,38 @@ objc2-core-video = { version = "0.3.2", features = ["CVPixelBuffer", "CVImageBufobjc2-core-media = { version = "0.3.2", features = ["CMSampleBuffer", "CMFormatDescription", "CMTime", "CMBase", "CMBlockBuffer", "CMAttachment", "CMSync"] }objc2-video-toolbox = { version = "0.3.2", features = ["VTCompressionSession", "VTCompressionProperties", "VTSession", "VTErrors", "VTBase", "VTVideoEncoderList", "VTUtilities"] }+[target.'cfg(windows)'.dependencies]+windows-core = "0.61"+windows = { version = "0.61", features = [+ "Foundation",+ "Graphics",+ "Graphics_Capture",+ "Graphics_DirectX",+ "Graphics_DirectX_Direct3D11",+ "Wdk_System_SystemServices",+ "Win32_Foundation",+ "Win32_Graphics_Direct3D",+ "Win32_Graphics_Direct3D11",+ "Win32_Graphics_Dwm",+ "Win32_Graphics_Dxgi",+ "Win32_Graphics_Dxgi_Common",+ "Win32_Graphics_Gdi",+ "Win32_Media_Audio",+ "Win32_Media_MediaFoundation",+ "Win32_Security",+ "Win32_Storage_Xps",+ "Win32_System_Com",+ "Win32_System_Com_StructuredStorage",+ "Win32_System_Ole",+ "Win32_System_SystemInformation",+ "Win32_System_Threading",+ "Win32_System_Variant",+ "Win32_System_WinRT",+ "Win32_System_WinRT_Direct3D11",+ "Win32_System_WinRT_Graphics_Capture",+ "Win32_UI_WindowsAndMessaging",+] }+[dev-dependencies]reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }tokio-tungstenite = { version = "0.30", features = ["native-tls"] }diff --git a/src-tauri/omnidisc-media/src/audio/io.rs b/src-tauri/omnidisc-media/src/audio/io.rsindex 4d2e7bd0..1c800d96 100644--- a/src-tauri/omnidisc-media/src/audio/io.rs+++ b/src-tauri/omnidisc-media/src/audio/io.rs@@ -15,6 +15,12 @@ pub enum AudioIoError {PermissionDenied,DeviceBusy,Unsupported(String),+ /// The stream handle died but the device is still there — WASAPI answers+ /// this when the default endpoint changes under a running stream.+ Invalidated(String),+ /// A glitch that did not stop anything: an over/underrun, or a route the+ /// backend already followed on its own.+ Transient(String),Other(String),}@@ -25,9 +31,18 @@ impl AudioIoError {Self::PermissionDenied => "permission_denied",Self::DeviceBusy => "device_busy",Self::Unsupported(_) => "unsupported",+ Self::Invalidated(_) => "invalidated",+ Self::Transient(_) => "transient",Self::Other(_) => "other",}}++ /// Did the stream actually stop? Tearing a call down and re-opening the+ /// device because one buffer arrived late is worse than the late buffer,+ /// and on WASAPI late buffers are routine under load.+ pub fn fatal(&self) -> bool {+ !matches!(self, Self::Transient(_))+ }}impl std::fmt::Display for AudioIoError {@@ -37,17 +52,47 @@ impl std::fmt::Display for AudioIoError {Self::PermissionDenied => write!(f, "audio permission denied"),Self::DeviceBusy => write!(f, "audio device busy"),Self::Unsupported(s) => write!(f, "unsupported audio config: {s}"),+ Self::Invalidated(s) => write!(f, "audio stream invalidated: {s}"),+ Self::Transient(s) => write!(f, "audio glitch: {s}"),Self::Other(s) => write!(f, "{s}"),}}}+/// Access-denied as it reaches us through `std::io::Error`'s message: the+/// Windows HRESULT `E_ACCESSDENIED` and the plain Win32 `ERROR_ACCESS_DENIED`.+/// Matching the number and not the sentence is what keeps this working on a+/// non-English Windows.+#[cfg_attr(not(windows), allow(dead_code))]+fn is_access_denied(message: &str) -> bool {+ message.contains("(os error -2147024891)") || message.contains("(os error 5)")+}++/// WASAPI answers a microphone blocked in the Windows privacy settings with a+/// bare `E_ACCESSDENIED`, which cpal cannot map and reports as a backend error.+/// Left unclassified it becomes "the mic failed" instead of "grant the+/// permission", which is the one message that would let the user fix it.+#[cfg(windows)]+fn platform_permission_denied(e: &cpal::Error) -> bool {+ e.message().map(is_access_denied).unwrap_or(false)+}++#[cfg(not(windows))]+fn platform_permission_denied(_: &cpal::Error) -> bool {+ false+}+fn classify(e: cpal::Error) -> AudioIoError {match e.kind() {cpal::ErrorKind::PermissionDenied => AudioIoError::PermissionDenied,cpal::ErrorKind::DeviceNotAvailable => AudioIoError::NoDevice,cpal::ErrorKind::DeviceBusy => AudioIoError::DeviceBusy,cpal::ErrorKind::UnsupportedConfig => AudioIoError::Unsupported(e.to_string()),+ cpal::ErrorKind::StreamInvalidated => AudioIoError::Invalidated(e.to_string()),+ cpal::ErrorKind::Xrun+ | cpal::ErrorKind::DeviceChanged+ | cpal::ErrorKind::RealtimeDenied => AudioIoError::Transient(e.to_string()),+ _ if platform_permission_denied(&e) => AudioIoError::PermissionDenied,_ => AudioIoError::Other(e.to_string()),}}@@ -80,7 +125,7 @@ pub fn classify_loss(still_listed: bool, probe: &AudioIoError) -> DeviceLoss {}}-pub type FaultSink = Arc<dyn Fn(StreamFault, String) + Send + Sync>;+pub type FaultSink = Arc<dyn Fn(StreamFault, AudioIoError) + Send + Sync>;enum IoCmd {StartInput {@@ -204,7 +249,7 @@ fn build_input(let (producer, consumer) =rtrb::RingBuffer::<f32>::new(sample_rate as usize * INPUT_RING_SECONDS);let err_cb = move |e: cpal::Error| {- faults(StreamFault::Input, e.to_string());+ faults(StreamFault::Input, classify(e));};let stream = match supported.sample_format() {SampleFormat::F32 => device.build_input_stream(@@ -247,20 +292,27 @@ fn input_callback<T: Copy + Send + 'static>(channels: usize,convert: impl Fn(T) -> f32 + Send + 'static,) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static {- let mut mono: Vec<f32> = Vec::with_capacity(8192);+ // WASAPI does not hand over the same number of frames every callback, so a+ // fixed scratch buffer has to loop instead of dropping whatever did not+ // fit — a dropped tail is a click in the middle of a sentence.+ const CHUNK_FRAMES: usize = 2048;+ let mut mono: Vec<f32> = vec![0.0; CHUNK_FRAMES];move |data: &[T], _| {- mono.clear();let inv = 1.0 / channels as f32;- for frame in data.chunks(channels) {- let mut acc = 0.0f32;- for s in frame {- acc += convert(*s);- }- if mono.len() < mono.capacity() {- mono.push(acc * inv);+ for block in data.chunks(CHUNK_FRAMES * channels) {+ let frames = block.len() / channels;+ for (o, frame) in mono[..frames]+ .iter_mut()+ .zip(block.chunks_exact(channels.max(1)))+ {+ let mut acc = 0.0f32;+ for s in frame {+ acc += convert(*s);+ }+ *o = acc * inv;}+ let _ = producer.push_partial_slice(&mono[..frames]);}- let _ = producer.push_partial_slice(&mono);}}@@ -275,7 +327,7 @@ fn build_output(let channels = config.channels.max(1);let sample_rate = config.sample_rate;let err_cb = move |e: cpal::Error| {- faults(StreamFault::Output, e.to_string());+ faults(StreamFault::Output, classify(e));};let stream = match supported.sample_format() {SampleFormat::F32 => device.build_output_stream(@@ -322,14 +374,16 @@ fn output_callback<T: Copy + Send + 'static>(let mut renderer = OutputRenderer::new(sample_rate, channels);let mut scratch: Vec<f32> = vec![0.0; 16_384];move |data: &mut [T], _| {- let n = data.len().min(scratch.len());+ // Growing once beats filling the tail with silence forever on a device+ // whose period is larger than the guess made here.+ if scratch.len() < data.len() {+ scratch.resize(data.len(), 0.0);+ }+ let n = data.len();renderer.render(&mixer, &mut scratch[..n]);for (d, s) in data.iter_mut().zip(scratch[..n].iter()) {*d = convert(*s);}- for d in data.iter_mut().skip(n) {- *d = convert(0.0);- }}}@@ -361,6 +415,46 @@ mod tests {);}+ #[test]+ fn a_glitch_does_not_end_the_stream_but_everything_else_does() {+ assert!(!AudioIoError::Transient("xrun".into()).fatal());+ assert!(AudioIoError::Invalidated("default changed".into()).fatal());+ assert!(AudioIoError::NoDevice.fatal());+ assert!(AudioIoError::PermissionDenied.fatal());+ assert!(AudioIoError::Other("boom".into()).fatal());+ }++ #[test]+ fn windows_access_denied_is_recognised_by_its_number() {+ assert!(is_access_denied("Access is denied. (os error -2147024891)"));+ assert!(is_access_denied("Acesso negado. (os error 5)"));+ assert!(!is_access_denied(+ "The device is not available. (os error -2147023728)"+ ));+ assert!(!is_access_denied("no error code here"));+ }++ #[test]+ fn cpal_kinds_map_to_the_right_severity() {+ use cpal::{Error, ErrorKind};+ assert_eq!(+ classify(Error::new(ErrorKind::Xrun)),+ AudioIoError::Transient(Error::new(ErrorKind::Xrun).to_string())+ );+ assert_eq!(+ classify(Error::new(ErrorKind::DeviceChanged)),+ AudioIoError::Transient(Error::new(ErrorKind::DeviceChanged).to_string())+ );+ assert_eq!(+ classify(Error::new(ErrorKind::StreamInvalidated)),+ AudioIoError::Invalidated(Error::new(ErrorKind::StreamInvalidated).to_string())+ );+ assert_eq!(+ classify(Error::new(ErrorKind::DeviceNotAvailable)),+ AudioIoError::NoDevice+ );+ }+#[test]fn a_listed_device_that_will_not_open_is_a_plain_failure() {assert_eq!(diff --git a/src-tauri/omnidisc-media/src/audio/playback.rs b/src-tauri/omnidisc-media/src/audio/playback.rsindex 8a071b3d..b0a36f7b 100644--- a/src-tauri/omnidisc-media/src/audio/playback.rs+++ b/src-tauri/omnidisc-media/src/audio/playback.rs@@ -174,6 +174,27 @@ impl Mixer {}}+/// Put one mono sample on a device frame.+///+/// Copying it into every channel is fine on the stereo endpoints macOS almost+/// always has, and wrong on the 5.1/7.1 endpoints Windows hands out for HDMI+/// and receivers: it would put speech in the centre, the surrounds and the+/// subwoofer at once, and make the call louder than everything else. Front+/// left/right is where a mono source belongs; the rest stays quiet.+fn place(frame: &mut [f32], sample: f32) {+ match frame.len() {+ 0 => {}+ 1 => frame[0] = sample,+ _ => {+ frame[0] = sample;+ frame[1] = sample;+ for c in frame[2..].iter_mut() {+ *c = 0.0;+ }+ }+ }+}+pub struct OutputRenderer {step: f64,pos: f64,@@ -206,7 +227,7 @@ impl OutputRenderer {mixer.mix_into(mix, scratch);for (i, frame) in data.chunks_mut(self.channels).enumerate() {let s = if i < n { mix[i] } else { 0.0 };- frame.fill(s);+ place(frame, s);}return;}@@ -227,7 +248,7 @@ impl OutputRenderer {let frac = (p - idx as f64) as f32;let a = self.buf48.get(idx).copied().unwrap_or(0.0);let b = self.buf48.get(idx + 1).copied().unwrap_or(a);- frame.fill(a + (b - a) * frac);+ place(frame, a + (b - a) * frac);p += self.step;}let consumed = (p.floor() as usize).min(self.buf48.len());@@ -331,6 +352,35 @@ mod tests {assert!((out[479] - 0.5).abs() < 1e-6);}+ #[test]+ fn surround_endpoints_get_the_voice_on_the_front_pair_only() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(48_000);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ let _ = p1.push_partial_slice(&vec![0.5; 4800]);+ let mut r = OutputRenderer::new(MIX_RATE, 6);+ let mut data = vec![9.0; 480 * 6];+ r.render(&mixer, &mut data);+ assert!((data[0] - 0.5).abs() < 1e-6, "front left");+ assert!((data[1] - 0.5).abs() < 1e-6, "front right");+ for (i, s) in data[2..6].iter().enumerate() {+ assert_eq!(*s, 0.0, "channel {} must stay quiet", i + 2);+ }+ }++ #[test]+ fn a_mono_endpoint_still_hears_the_call() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(48_000);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ let _ = p1.push_partial_slice(&vec![0.5; 4800]);+ let mut r = OutputRenderer::new(MIX_RATE, 1);+ let mut data = vec![0.0; 480];+ r.render(&mixer, &mut data);+ assert!((data[0] - 0.5).abs() < 1e-6);+ assert!((data[479] - 0.5).abs() < 1e-6);+ }+#[test]fn renderer_resamples_to_device_rate_and_channels() {let mixer = Mixer::default();diff --git a/src-tauri/omnidisc-media/src/capture/mod.rs b/src-tauri/omnidisc-media/src/capture/mod.rsindex f6a5c344..10d1c52e 100644--- a/src-tauri/omnidisc-media/src/capture/mod.rs+++ b/src-tauri/omnidisc-media/src/capture/mod.rs@@ -4,12 +4,17 @@ use std::sync::Arc;#[cfg(target_os = "macos")]mod macos;#[cfg(target_os = "macos")]-pub use macos::*;+pub use self::macos::*;-#[cfg(not(target_os = "macos"))]+#[cfg(windows)]+mod windows;+#[cfg(windows)]+pub use self::windows::*;++#[cfg(not(any(target_os = "macos", windows)))]mod stub;-#[cfg(not(target_os = "macos"))]-pub use stub::*;+#[cfg(not(any(target_os = "macos", windows)))]+pub use self::stub::*;#[derive(Debug, Clone)]pub struct CaptureOptions {diff --git a/src-tauri/omnidisc-media/src/capture/windows/audio.rs b/src-tauri/omnidisc-media/src/capture/windows/audio.rsnew file mode 100644index 00000000..1a674a09--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/windows/audio.rs@@ -0,0 +1,459 @@+use crate::capture::{AudioSink, AUDIO_CHANNELS, AUDIO_SAMPLE_RATE};+use crate::stream::{AudioApp, StreamError};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{mpsc, Arc};+use std::time::{Duration, Instant};+use windows::core::{implement, Interface, Ref};+use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};+use windows::Win32::Media::Audio::{+ eRender, ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation,+ IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl,+ IAudioCaptureClient, IAudioClient, IAudioSessionControl2, IAudioSessionManager2,+ IMMDeviceEnumerator, MMDeviceEnumerator, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED,+ AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK, AUDIOCLIENT_ACTIVATION_PARAMS,+ AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,+ AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, DEVICE_STATE_ACTIVE,+ PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,+ PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,+ WAVEFORMATEX,+};+use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PROPVARIANT_0_0};+use windows::Win32::System::Com::{+ CoCreateInstance, CoInitializeEx, CoUninitialize, BLOB, CLSCTX_ALL, COINIT_MULTITHREADED,+};+use windows::Win32::System::Threading::{CreateEventW, SetEvent, WaitForSingleObject};+use windows::Win32::System::Variant::VT_BLOB;++const WAVE_FORMAT_PCM: u16 = 1;+const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;+/// `ActivateAudioInterfaceAsync` can sit on a slow audio engine; the TODO+/// budget for "screen share started" is 12 s.+const ACTIVATE_TIMEOUT_MS: u32 = 12_000;+const BUFFER_DURATION_100NS: i64 = 20 * 10_000;+const HEARTBEAT_QUIET: Duration = Duration::from_millis(250);+const HEARTBEAT_FRAMES: usize = (AUDIO_SAMPLE_RATE as usize / 100) * AUDIO_CHANNELS as usize;++/// WASAPI process loopback landed in Windows 10 build 20348 (Server 2022 /+/// Windows 11). Below that there is no per-application audio at all.+pub const MIN_LOOPBACK_BUILD: u32 = 20348;++pub fn windows_build() -> u32 {+ use windows::Wdk::System::SystemServices::RtlGetVersion;+ use windows::Win32::System::SystemInformation::OSVERSIONINFOW;+ let mut info = OSVERSIONINFOW {+ dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32,+ ..Default::default()+ };+ let status = unsafe { RtlGetVersion(&mut info) };+ if status.is_ok() {+ info.dwBuildNumber+ } else {+ 0+ }+}++pub fn process_loopback_supported() -> bool {+ windows_build() >= MIN_LOOPBACK_BUILD+}++pub fn unsupported_build_error() -> StreamError {+ StreamError::Capture(format!(+ "sharing application audio needs Windows 10 build {MIN_LOOPBACK_BUILD} or newer (this machine reports build {}); update Windows or share without audio",+ windows_build()+ ))+}++#[implement(IActivateAudioInterfaceCompletionHandler)]+struct Completion {+ event: isize,+}++impl IActivateAudioInterfaceCompletionHandler_Impl for Completion_Impl {+ fn ActivateCompleted(+ &self,+ _operation: Ref<'_, IActivateAudioInterfaceAsyncOperation>,+ ) -> windows::core::Result<()> {+ unsafe {+ let _ = SetEvent(HANDLE(self.event as *mut std::ffi::c_void));+ }+ Ok(())+ }+}++struct Event(HANDLE);++impl Event {+ fn new() -> Result<Self, StreamError> {+ let handle = unsafe { CreateEventW(None, false, false, None) }+ .map_err(|e| StreamError::Capture(format!("CreateEventW: {e}")))?;+ Ok(Self(handle))+ }++ fn raw(&self) -> HANDLE {+ self.0+ }++ fn wait(&self, ms: u32) -> bool {+ unsafe { WaitForSingleObject(self.0, ms) == WAIT_OBJECT_0 }+ }+}++impl Drop for Event {+ fn drop(&mut self) {+ unsafe {+ let _ = CloseHandle(self.0);+ }+ }+}++fn wave_format(float: bool) -> WAVEFORMATEX {+ let bits: u16 = if float { 32 } else { 16 };+ let channels = AUDIO_CHANNELS as u16;+ let block_align = channels * bits / 8;+ WAVEFORMATEX {+ wFormatTag: if float {+ WAVE_FORMAT_IEEE_FLOAT+ } else {+ WAVE_FORMAT_PCM+ },+ nChannels: channels,+ nSamplesPerSec: AUDIO_SAMPLE_RATE,+ nAvgBytesPerSec: AUDIO_SAMPLE_RATE * block_align as u32,+ nBlockAlign: block_align,+ wBitsPerSample: bits,+ cbSize: 0,+ }+}++struct Activated {+ client: IAudioClient,+ float: bool,+}++fn activate(pid: u32, include_tree: bool) -> Result<IAudioClient, StreamError> {+ let mut params = AUDIOCLIENT_ACTIVATION_PARAMS {+ ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,+ Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {+ ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {+ TargetProcessId: pid,+ ProcessLoopbackMode: if include_tree {+ PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE+ } else {+ PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE+ },+ },+ },+ };+ let mut prop = PROPVARIANT::default();+ // SAFETY: VT_BLOB borrows `params` for the duration of the call only;+ // `ActivateAudioInterfaceAsync` copies the blob before returning.+ unsafe {+ let inner: &mut PROPVARIANT_0_0 = &mut prop.Anonymous.Anonymous;+ inner.vt = VT_BLOB;+ inner.Anonymous.blob = BLOB {+ cbSize: std::mem::size_of::<AUDIOCLIENT_ACTIVATION_PARAMS>() as u32,+ pBlobData: &mut params as *mut AUDIOCLIENT_ACTIVATION_PARAMS as *mut u8,+ };+ }++ let event = Event::new()?;+ let handler: IActivateAudioInterfaceCompletionHandler = Completion {+ event: event.raw().0 as isize,+ }+ .into();+ let operation = unsafe {+ ActivateAudioInterfaceAsync(+ VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,+ &IAudioClient::IID,+ Some(&prop),+ &handler,+ )+ }+ .map_err(|e| StreamError::Capture(format!("ActivateAudioInterfaceAsync: {e}")))?;+ if !event.wait(ACTIVATE_TIMEOUT_MS) {+ return Err(StreamError::Capture(+ "the Windows audio engine did not answer within 12 s; try sharing without audio".into(),+ ));+ }+ let mut hr = windows::core::HRESULT(0);+ let mut raw: Option<windows::core::IUnknown> = None;+ unsafe {+ operation+ .GetActivateResult(&mut hr, &mut raw)+ .map_err(|e| StreamError::Capture(format!("GetActivateResult: {e}")))?;+ }+ hr.ok()+ .map_err(|e| StreamError::Capture(format!("process loopback activation refused: {e}")))?;+ raw.ok_or_else(|| StreamError::Capture("process loopback returned no audio client".into()))?+ .cast::<IAudioClient>()+ .map_err(|e| StreamError::Capture(format!("IAudioClient: {e}")))+}++fn try_initialize(pid: u32, include_tree: bool, float: bool) -> Result<Activated, StreamError> {+ let client = activate(pid, include_tree)?;+ let format = wave_format(float);+ unsafe {+ client+ .Initialize(+ AUDCLNT_SHAREMODE_SHARED,+ AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK,+ BUFFER_DURATION_100NS,+ 0,+ &format,+ None,+ )+ .map_err(|e| {+ StreamError::Capture(format!(+ "the audio engine refused 48 kHz stereo {} capture: {e}",+ if float { "float" } else { "16-bit" }+ ))+ })?;+ }+ Ok(Activated { client, float })+}++fn initialize(pid: u32, include_tree: bool) -> Result<Activated, StreamError> {+ match try_initialize(pid, include_tree, true) {+ Ok(activated) => Ok(activated),+ Err(e) => {+ tracing::debug!("[omnidisc-media] {e}; retrying as 16-bit PCM");+ try_initialize(pid, include_tree, false)+ }+ }+}++pub struct AudioCaptureHandle {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl AudioCaptureHandle {+ pub fn stop(mut self) {+ self.shutdown();+ }++ fn shutdown(&mut self) {+ self.stop.store(true, Ordering::Release);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++impl Drop for AudioCaptureHandle {+ fn drop(&mut self) {+ self.shutdown();+ }+}++fn pump(+ activated: Activated,+ sink: AudioSink,+ stop: Arc<AtomicBool>,+ ready: &Event,+) -> Result<(), StreamError> {+ let client = activated.client;+ unsafe {+ client+ .SetEventHandle(ready.raw())+ .map_err(|e| StreamError::Capture(format!("SetEventHandle: {e}")))?;+ }+ let capture: IAudioCaptureClient = unsafe { client.GetService() }+ .map_err(|e| StreamError::Capture(format!("IAudioCaptureClient: {e}")))?;+ unsafe {+ client+ .Start()+ .map_err(|e| StreamError::Capture(format!("IAudioClient::Start: {e}")))?;+ }+ let silence = vec![0f32; HEARTBEAT_FRAMES];+ // The publish side expects whole 10 ms frames; WASAPI packet sizes are not+ // guaranteed to line up, so partial frames are carried over instead of+ // being dropped.+ let mut pending: Vec<f32> = Vec::with_capacity(HEARTBEAT_FRAMES * 4);+ let mut last_pcm = Instant::now();+ while !stop.load(Ordering::Acquire) {+ ready.wait(100);+ loop {+ let mut data: *mut u8 = std::ptr::null_mut();+ let mut frames: u32 = 0;+ let mut flags: u32 = 0;+ let got = unsafe { capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None) };+ // A successful call with zero frames means the buffer is empty+ // (AUDCLNT_S_BUFFER_EMPTY); nothing was acquired, so nothing is+ // released.+ if got.is_err() || frames == 0 {+ break;+ }+ let channels = AUDIO_CHANNELS as usize;+ let samples = frames as usize * channels;+ if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null() {+ pending.resize(pending.len() + samples, 0.0);+ } else if activated.float {+ let src = unsafe { std::slice::from_raw_parts(data as *const f32, samples) };+ pending.extend_from_slice(src);+ } else {+ let src = unsafe { std::slice::from_raw_parts(data as *const i16, samples) };+ pending.extend(src.iter().map(|s| *s as f32 / i16::MAX as f32));+ }+ unsafe {+ let _ = capture.ReleaseBuffer(frames);+ }+ let whole = pending.len() / HEARTBEAT_FRAMES * HEARTBEAT_FRAMES;+ if whole > 0 {+ sink(&pending[..whole]);+ pending.drain(..whole);+ last_pcm = Instant::now();+ }+ }+ if last_pcm.elapsed() >= HEARTBEAT_QUIET {+ // WHY: process loopback delivers nothing at all while the target is+ // silent, and the publish gate upstream waits for a first packet.+ sink(&silence);+ last_pcm = Instant::now();+ }+ }+ unsafe {+ let _ = client.Stop();+ }+ Ok(())+}++pub fn start_process_loopback(+ pid: u32,+ include_tree: bool,+ sink: AudioSink,+) -> Result<AudioCaptureHandle, StreamError> {+ if !process_loopback_supported() {+ return Err(unsupported_build_error());+ }+ let stop = Arc::new(AtomicBool::new(false));+ let stop_thread = stop.clone();+ let (tx, rx) = mpsc::channel::<Result<(), StreamError>>();+ let thread = std::thread::Builder::new()+ .name("omnidisc-wasapi".into())+ .spawn(move || {+ let com = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };+ let ready = match Event::new() {+ Ok(e) => e,+ Err(e) => {+ let _ = tx.send(Err(e));+ if com.is_ok() {+ unsafe { CoUninitialize() };+ }+ return;+ }+ };+ match initialize(pid, include_tree) {+ Ok(activated) => {+ let _ = tx.send(Ok(()));+ if let Err(e) = pump(activated, sink, stop_thread, &ready) {+ tracing::warn!("[omnidisc-media] process loopback stopped: {e}");+ }+ }+ Err(e) => {+ let _ = tx.send(Err(e));+ }+ }+ if com.is_ok() {+ unsafe { CoUninitialize() };+ }+ })+ .map_err(|e| StreamError::Capture(format!("wasapi thread: {e}")))?;+ match rx.recv() {+ Ok(Ok(())) => Ok(AudioCaptureHandle {+ stop,+ thread: Some(thread),+ }),+ Ok(Err(e)) => {+ let _ = thread.join();+ Err(e)+ }+ Err(_) => {+ let _ = thread.join();+ Err(StreamError::Capture(+ "the audio capture thread stopped before it started".into(),+ ))+ }+ }+}++/// Enumerates render sessions across **every** active endpoint, not just the+/// default one: engines like FMOD and OpenAL open their own device, and a+/// session that only exists on a secondary endpoint would otherwise be missing.+/// Silent sessions stay in the list so a paused tab is still pickable.+pub fn audio_apps() -> Vec<AudioApp> {+ let own_pid = std::process::id();+ let mut out: Vec<AudioApp> = Vec::new();+ let mut seen: Vec<u32> = Vec::new();+ let enumerator: IMMDeviceEnumerator =+ match unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) } {+ Ok(e) => e,+ Err(e) => {+ tracing::debug!("[omnidisc-media] MMDeviceEnumerator: {e}");+ return out;+ }+ };+ let devices = match unsafe { enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) } {+ Ok(d) => d,+ Err(e) => {+ tracing::debug!("[omnidisc-media] EnumAudioEndpoints: {e}");+ return out;+ }+ };+ let count = unsafe { devices.GetCount() }.unwrap_or(0);+ for i in 0..count {+ let Ok(device) = (unsafe { devices.Item(i) }) else {+ continue;+ };+ let manager: IAudioSessionManager2 = match unsafe { device.Activate(CLSCTX_ALL, None) } {+ Ok(m) => m,+ Err(_) => continue,+ };+ let Ok(sessions) = (unsafe { manager.GetSessionEnumerator() }) else {+ continue;+ };+ let n = unsafe { sessions.GetCount() }.unwrap_or(0);+ for s in 0..n {+ let Ok(control) = (unsafe { sessions.GetSession(s) }) else {+ continue;+ };+ let Ok(control2) = control.cast::<IAudioSessionControl2>() else {+ continue;+ };+ if unsafe { control2.IsSystemSoundsSession() }.is_ok() {+ continue;+ }+ let Ok(pid) = (unsafe { control2.GetProcessId() }) else {+ continue;+ };+ if pid == 0 || pid == own_pid || seen.contains(&pid) {+ continue;+ }+ seen.push(pid);+ if let Some(app) = super::sources::audio_app(pid) {+ out.push(app);+ }+ }+ }+ out.sort_by_key(|a| a.name.to_lowercase());+ out+}++/// COM apartment guard for the enumeration helpers, which may run on a tokio+/// blocking thread whose apartment we do not control.+pub struct ComGuard(bool);++impl ComGuard {+ pub fn mta() -> Self {+ let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };+ Self(hr.is_ok())+ }+}++impl Drop for ComGuard {+ fn drop(&mut self) {+ if self.0 {+ unsafe { CoUninitialize() };+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/capture/windows/d3d.rs b/src-tauri/omnidisc-media/src/capture/windows/d3d.rsnew file mode 100644index 00000000..fc5c0568--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/windows/d3d.rs@@ -0,0 +1,489 @@+use crate::stream::StreamError;+use std::sync::{Arc, Mutex, OnceLock, Weak};+use windows::core::Interface;+use windows::Win32::Foundation::HMODULE;+use windows::Win32::Graphics::Direct3D::{+ D3D_DRIVER_TYPE, D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_FEATURE_LEVEL,+ D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1,+};+use windows::Win32::Graphics::Direct3D11::{+ D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Multithread, ID3D11Texture2D,+ ID3D11VideoContext, ID3D11VideoDevice, ID3D11VideoProcessor, ID3D11VideoProcessorEnumerator,+ ID3D11VideoProcessorInputView, ID3D11VideoProcessorOutputView, D3D11_BIND_RENDER_TARGET,+ D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT,+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT, D3D11_MAPPED_SUBRESOURCE, D3D11_MAP_READ, D3D11_SDK_VERSION,+ D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING,+ D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE, D3D11_VIDEO_PROCESSOR_CONTENT_DESC,+ D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0,+ D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0,+ D3D11_VIDEO_PROCESSOR_STREAM, D3D11_VPIV_DIMENSION, D3D11_VPIV_DIMENSION_TEXTURE2D,+ D3D11_VPOV_DIMENSION_TEXTURE2D,+};+use windows::Win32::Graphics::Dxgi::Common::{+ DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12, DXGI_RATIONAL, DXGI_SAMPLE_DESC,+};++const NV12_RING: usize = 3;++/// D3D11 device shared by the capture session and the encoder.+///+/// COM interfaces from `windows-rs` are `!Send`, but this device is created+/// with multithread protection on (`ID3D11Multithread::SetMultithreadProtected`),+/// so the immediate context may legally be driven from the WGC callback thread+/// and the encode thread at the same time. That is the invariant behind the+/// `Send`/`Sync` impls below; do not hand these objects to a context that has+/// multithread protection disabled.+pub struct Gpu {+ device: ID3D11Device,+ context: ID3D11DeviceContext,+}++unsafe impl Send for Gpu {}+unsafe impl Sync for Gpu {}++fn hr(what: &str, e: windows::core::Error) -> StreamError {+ StreamError::Capture(format!("{what}: {e}"))+}++fn create_device(+ driver: D3D_DRIVER_TYPE,+) -> windows::core::Result<(ID3D11Device, ID3D11DeviceContext)> {+ let levels = [D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0];+ let mut device: Option<ID3D11Device> = None;+ let mut context: Option<ID3D11DeviceContext> = None;+ let mut level = D3D_FEATURE_LEVEL::default();+ unsafe {+ D3D11CreateDevice(+ None,+ driver,+ HMODULE::default(),+ D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,+ Some(&levels),+ D3D11_SDK_VERSION,+ Some(&mut device),+ Some(&mut level),+ Some(&mut context),+ )?;+ }+ match (device, context) {+ (Some(d), Some(c)) => Ok((d, c)),+ _ => Err(windows::core::Error::from_win32()),+ }+}++impl Gpu {+ fn create() -> Result<Self, StreamError> {+ let (device, context) = match create_device(D3D_DRIVER_TYPE_HARDWARE) {+ Ok(pair) => pair,+ Err(e) => {+ tracing::warn!(+ "[omnidisc-media] no hardware D3D11 device ({e}); falling back to the WARP software rasteriser, screen share will be slow"+ );+ create_device(D3D_DRIVER_TYPE_WARP)+ .map_err(|e| hr("D3D11CreateDevice (WARP)", e))?+ }+ };+ let multithread: ID3D11Multithread =+ context.cast().map_err(|e| hr("ID3D11Multithread", e))?;+ unsafe {+ let _ = multithread.SetMultithreadProtected(true);+ }+ Ok(Self { device, context })+ }++ pub fn device(&self) -> &ID3D11Device {+ &self.device+ }++ pub fn context(&self) -> &ID3D11DeviceContext {+ &self.context+ }++ fn texture(+ &self,+ width: u32,+ height: u32,+ format: DXGI_FORMAT,+ staging: bool,+ seed: Option<&[u8]>,+ seed_pitch: u32,+ ) -> Result<ID3D11Texture2D, StreamError> {+ let desc = D3D11_TEXTURE2D_DESC {+ Width: width,+ Height: height,+ MipLevels: 1,+ ArraySize: 1,+ Format: format,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: if staging {+ D3D11_USAGE_STAGING+ } else {+ D3D11_USAGE_DEFAULT+ },+ BindFlags: if staging {+ 0+ } else {+ (D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE).0 as u32+ },+ CPUAccessFlags: if staging {+ D3D11_CPU_ACCESS_READ.0 as u32+ } else {+ 0+ },+ MiscFlags: 0,+ };+ let initial = seed.map(|data| D3D11_SUBRESOURCE_DATA {+ pSysMem: data.as_ptr().cast(),+ SysMemPitch: seed_pitch,+ SysMemSlicePitch: 0,+ });+ let mut out: Option<ID3D11Texture2D> = None;+ unsafe {+ self.device+ .CreateTexture2D(+ &desc,+ initial.as_ref().map(|d| d as *const _),+ Some(&mut out),+ )+ .map_err(|e| hr("CreateTexture2D", e))?;+ }+ out.ok_or_else(|| StreamError::Capture("CreateTexture2D returned nothing".into()))+ }++ pub fn bgra_texture(&self, width: u32, height: u32) -> Result<ID3D11Texture2D, StreamError> {+ self.texture(width, height, DXGI_FORMAT_B8G8R8A8_UNORM, false, None, 0)+ }+}++/// Process-wide device. Capture and encode must share one so a captured texture+/// can be converted without crossing devices.+pub fn gpu() -> Result<Arc<Gpu>, StreamError> {+ static GPU: OnceLock<Result<Arc<Gpu>, String>> = OnceLock::new();+ GPU.get_or_init(|| Gpu::create().map(Arc::new).map_err(|e| e.to_string()))+ .clone()+ .map_err(StreamError::Capture)+}++struct PoolInner {+ free: Vec<ID3D11Texture2D>,+}++unsafe impl Send for PoolInner {}++/// Fixed-size ring of BGRA textures so the capture callback never writes into a+/// texture the encoder still holds.+pub struct TexturePool {+ inner: Arc<Mutex<PoolInner>>,+ gpu: Arc<Gpu>,+ width: u32,+ height: u32,+ budget: usize,+ handed_out: Arc<Mutex<usize>>,+}++impl TexturePool {+ pub fn new(gpu: Arc<Gpu>, width: u32, height: u32, budget: usize) -> Self {+ Self {+ inner: Arc::new(Mutex::new(PoolInner { free: Vec::new() })),+ gpu,+ width,+ height,+ budget,+ handed_out: Arc::new(Mutex::new(0)),+ }+ }++ pub fn size(&self) -> (u32, u32) {+ (self.width, self.height)+ }++ pub fn acquire(&self) -> Result<PooledTexture, StreamError> {+ let reused = self.inner.lock().ok().and_then(|mut g| g.free.pop());+ let texture = match reused {+ Some(t) => t,+ None => {+ let live = self.handed_out.lock().map(|g| *g).unwrap_or(0);+ if live >= self.budget {+ return Err(StreamError::Capture(+ "capture texture pool exhausted; the encoder is not releasing frames"+ .into(),+ ));+ }+ self.gpu.bgra_texture(self.width, self.height)?+ }+ };+ if let Ok(mut g) = self.handed_out.lock() {+ *g += 1;+ }+ Ok(PooledTexture {+ texture: Some(texture),+ pool: Arc::downgrade(&self.inner),+ handed_out: Arc::downgrade(&self.handed_out),+ })+ }+}++pub struct PooledTexture {+ texture: Option<ID3D11Texture2D>,+ pool: Weak<Mutex<PoolInner>>,+ handed_out: Weak<Mutex<usize>>,+}++// SAFETY: the texture is only ever touched through the shared `Gpu`, whose+// immediate context is multithread-protected (see `Gpu`).+unsafe impl Send for PooledTexture {}+unsafe impl Sync for PooledTexture {}++impl PooledTexture {+ pub fn texture(&self) -> Option<&ID3D11Texture2D> {+ self.texture.as_ref()+ }+}++impl Drop for PooledTexture {+ fn drop(&mut self) {+ if let (Some(t), Some(pool)) = (self.texture.take(), self.pool.upgrade()) {+ if let Ok(mut g) = pool.lock() {+ g.free.push(t);+ }+ }+ if let Some(count) = self.handed_out.upgrade() {+ if let Ok(mut g) = count.lock() {+ *g = g.saturating_sub(1);+ }+ }+ }+}++/// BGRA -> NV12 with scaling, on the GPU, through the D3D11 video processor.+/// Both publish paths need NV12: Media Foundation encoders take it directly and+/// libwebrtc's `NV12Buffer` is the cheapest raw hand-off.+pub struct Nv12Converter {+ gpu: Arc<Gpu>,+ video_device: ID3D11VideoDevice,+ video_context: ID3D11VideoContext,+ enumerator: ID3D11VideoProcessorEnumerator,+ processor: ID3D11VideoProcessor,+ ring: Vec<(ID3D11Texture2D, ID3D11VideoProcessorOutputView)>,+ next: usize,+ staging: Option<ID3D11Texture2D>,+ dst_width: u32,+ dst_height: u32,+}++// SAFETY: same invariant as `Gpu` — the underlying immediate context is+// multithread-protected, and a converter is only driven from one thread at a+// time (the encode loop owns it).+unsafe impl Send for Nv12Converter {}++pub struct Nv12Cpu {+ pub data: Vec<u8>,+ pub stride_y: u32,+ pub stride_uv: u32,+ pub width: u32,+ pub height: u32,+}++impl Nv12Cpu {+ pub fn planes(&self) -> (&[u8], &[u8]) {+ let split = (self.stride_y * self.height) as usize;+ let split = split.min(self.data.len());+ self.data.split_at(split)+ }+}++impl Nv12Converter {+ pub fn new(+ gpu: Arc<Gpu>,+ src_width: u32,+ src_height: u32,+ dst_width: u32,+ dst_height: u32,+ ) -> Result<Self, StreamError> {+ let video_device: ID3D11VideoDevice = gpu+ .device()+ .cast()+ .map_err(|e| hr("ID3D11VideoDevice (no GPU video support)", e))?;+ let video_context: ID3D11VideoContext = gpu+ .context()+ .cast()+ .map_err(|e| hr("ID3D11VideoContext", e))?;+ let desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC {+ InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,+ InputFrameRate: DXGI_RATIONAL {+ Numerator: 60,+ Denominator: 1,+ },+ InputWidth: src_width,+ InputHeight: src_height,+ OutputFrameRate: DXGI_RATIONAL {+ Numerator: 60,+ Denominator: 1,+ },+ OutputWidth: dst_width,+ OutputHeight: dst_height,+ Usage: windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_USAGE_PLAYBACK_NORMAL,+ };+ let enumerator = unsafe {+ video_device+ .CreateVideoProcessorEnumerator(&desc)+ .map_err(|e| hr("CreateVideoProcessorEnumerator", e))?+ };+ let processor = unsafe {+ video_device+ .CreateVideoProcessor(&enumerator, 0)+ .map_err(|e| hr("CreateVideoProcessor", e))?+ };+ unsafe {+ video_context.VideoProcessorSetStreamFrameFormat(+ &processor,+ 0,+ D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,+ );+ }++ let mut ring = Vec::with_capacity(NV12_RING);+ for _ in 0..NV12_RING {+ let tex = gpu.texture(dst_width, dst_height, DXGI_FORMAT_NV12, false, None, 0)?;+ let view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC {+ ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D,+ Anonymous: D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 {+ Texture2D: windows::Win32::Graphics::Direct3D11::D3D11_TEX2D_VPOV {+ MipSlice: 0,+ },+ },+ };+ let mut view: Option<ID3D11VideoProcessorOutputView> = None;+ unsafe {+ video_device+ .CreateVideoProcessorOutputView(&tex, &enumerator, &view_desc, Some(&mut view))+ .map_err(|e| hr("CreateVideoProcessorOutputView", e))?;+ }+ let view = view.ok_or_else(|| {+ StreamError::Capture("CreateVideoProcessorOutputView returned nothing".into())+ })?;+ ring.push((tex, view));+ }++ Ok(Self {+ gpu,+ video_device,+ video_context,+ enumerator,+ processor,+ ring,+ next: 0,+ staging: None,+ dst_width,+ dst_height,+ })+ }++ pub fn size(&self) -> (u32, u32) {+ (self.dst_width, self.dst_height)+ }++ pub fn convert(&mut self, src: &ID3D11Texture2D) -> Result<ID3D11Texture2D, StreamError> {+ let idx = self.next % self.ring.len();+ self.next = self.next.wrapping_add(1);+ let input_desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC {+ FourCC: 0,+ ViewDimension: D3D11_VPIV_DIMENSION(D3D11_VPIV_DIMENSION_TEXTURE2D.0),+ Anonymous: D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 {+ Texture2D: windows::Win32::Graphics::Direct3D11::D3D11_TEX2D_VPIV {+ MipSlice: 0,+ ArraySlice: 0,+ },+ },+ };+ let mut input_view: Option<ID3D11VideoProcessorInputView> = None;+ unsafe {+ self.video_device+ .CreateVideoProcessorInputView(+ src,+ &self.enumerator,+ &input_desc,+ Some(&mut input_view),+ )+ .map_err(|e| hr("CreateVideoProcessorInputView", e))?;+ }+ let input_view = input_view.ok_or_else(|| {+ StreamError::Capture("CreateVideoProcessorInputView returned nothing".into())+ })?;+ let (out_tex, out_view) = &self.ring[idx];+ // WHY: `pInputSurface` is a `ManuallyDrop`, so the reference it holds is+ // never released on its own — the view is dropped by hand after the blt+ // or it leaks one COM reference per captured frame.+ let mut streams = [D3D11_VIDEO_PROCESSOR_STREAM {+ Enable: true.into(),+ OutputIndex: 0,+ InputFrameOrField: 0,+ PastFrames: 0,+ FutureFrames: 0,+ ppPastSurfaces: std::ptr::null_mut(),+ pInputSurface: std::mem::ManuallyDrop::new(Some(input_view)),+ ppFutureSurfaces: std::ptr::null_mut(),+ ppPastSurfacesRight: std::ptr::null_mut(),+ pInputSurfaceRight: std::mem::ManuallyDrop::new(None),+ ppFutureSurfacesRight: std::ptr::null_mut(),+ }];+ let result = unsafe {+ self.video_context+ .VideoProcessorBlt(&self.processor, out_view, 0, &streams)+ };+ unsafe {+ std::mem::ManuallyDrop::drop(&mut streams[0].pInputSurface);+ std::mem::ManuallyDrop::drop(&mut streams[0].pInputSurfaceRight);+ }+ result.map_err(|e| hr("VideoProcessorBlt", e))?;+ Ok(out_tex.clone())+ }++ /// CPU copy of the last converted frame. Only the raw publish path (and the+ /// system-memory Media Foundation fallback) needs this; the D3D-aware+ /// encoder consumes the texture directly.+ pub fn read_back(&mut self, nv12: &ID3D11Texture2D) -> Result<Nv12Cpu, StreamError> {+ if self.staging.is_none() {+ self.staging = Some(self.gpu.texture(+ self.dst_width,+ self.dst_height,+ DXGI_FORMAT_NV12,+ true,+ None,+ 0,+ )?);+ }+ let staging = self+ .staging+ .as_ref()+ .ok_or_else(|| StreamError::Capture("no staging texture".into()))?;+ let ctx = self.gpu.context();+ unsafe { ctx.CopyResource(staging, nv12) };+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();+ unsafe {+ ctx.Map(staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))+ .map_err(|e| hr("Map(NV12 staging)", e))?;+ }+ let stride = mapped.RowPitch;+ let rows = self.dst_height as usize + self.dst_height as usize / 2;+ let len = stride as usize * rows;+ let mut data = vec![0u8; len];+ // WHY: D3D11 maps NV12 as one allocation — the UV plane starts exactly+ // `RowPitch * Height` bytes in and shares the Y row pitch. There is no+ // per-plane pitch to query for a mapped NV12 staging resource.+ unsafe {+ std::ptr::copy_nonoverlapping(mapped.pData as *const u8, data.as_mut_ptr(), len);+ ctx.Unmap(staging, 0);+ }+ Ok(Nv12Cpu {+ data,+ stride_y: stride,+ stride_uv: stride,+ width: self.dst_width,+ height: self.dst_height,+ })+ }+}diff --git a/src-tauri/omnidisc-media/src/capture/windows/mod.rs b/src-tauri/omnidisc-media/src/capture/windows/mod.rsnew file mode 100644index 00000000..053c88a6--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/windows/mod.rs@@ -0,0 +1,272 @@+mod audio;+pub mod d3d;+mod sources;+mod wgc;++pub use audio::{process_loopback_supported, windows_build, MIN_LOOPBACK_BUILD};+pub use d3d::{gpu, Gpu, Nv12Converter, Nv12Cpu, PooledTexture};++use super::{+ unix_micros, AudioSink, CaptureApi, CaptureGeometry, CaptureOptions, VideoSink, VideoTick,+};+use crate::stream::{AudioMode, SourceId, StreamError, StreamSources};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};+use windows::Graphics::Capture::GraphicsCaptureSession;+use windows::Win32::Graphics::Direct3D11::ID3D11Texture2D;++/// One captured screen frame. The pixels stay on the GPU: `texture` is a BGRA+/// `ID3D11Texture2D` owned by the capture pool and recycled when the frame is+/// dropped, so nothing is read back to system memory unless the encoder asks.+pub struct CapturedFrame {+ texture: PooledTexture,+ pub width: u32,+ pub height: u32,+ pub capture_us: i64,+}++impl CapturedFrame {+ pub fn width(&self) -> u32 {+ self.width+ }++ pub fn height(&self) -> u32 {+ self.height+ }++ pub fn capture_us(&self) -> i64 {+ self.capture_us+ }++ pub fn texture(&self) -> Option<&ID3D11Texture2D> {+ self.texture.texture()+ }+}++struct SyntheticSource {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl Drop for SyntheticSource {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Release);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++pub struct VideoCapture {+ _wgc: Option<wgc::Capture>,+ _synthetic: Option<SyntheticSource>,+}++impl VideoCapture {+ pub fn stop(self) {}+}++pub struct AudioCapture {+ inner: Option<audio::AudioCaptureHandle>,+}++impl AudioCapture {+ pub fn stop(self) {+ if let Some(h) = self.inner {+ h.stop();+ }+ }+}++fn start_synthetic(+ width: u32,+ height: u32,+ fps: u16,+ sink: VideoSink,+) -> Result<(VideoCapture, CaptureGeometry), StreamError> {+ let (width, height) = ((width.max(2)) & !1, (height.max(2)) & !1);+ let gpu = gpu()?;+ let pool = d3d::TexturePool::new(gpu.clone(), width, height, 4);+ let stop = Arc::new(AtomicBool::new(false));+ let stop2 = stop.clone();+ let thread = std::thread::Builder::new()+ .name("omnidisc-synthetic".into())+ .spawn(move || {+ let interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);+ let row = width as usize * 4;+ let mut pixels = vec![0u8; row * height as usize];+ let mut next = Instant::now();+ let mut n: u64 = 0;+ while !stop2.load(Ordering::Acquire) {+ let shift = (n % 256) as usize;+ for y in 0..height as usize {+ let base = y * row;+ let v = ((y / 4 + shift) % 256) as u8;+ for x in 0..width as usize {+ let p = base + x * 4;+ pixels[p] = v;+ pixels[p + 1] = ((x + shift) % 256) as u8;+ pixels[p + 2] = v.wrapping_add(64);+ pixels[p + 3] = 255;+ }+ }+ match pool.acquire() {+ Ok(slot) => {+ if let Some(tex) = slot.texture() {+ unsafe {+ gpu.context().UpdateSubresource(+ tex,+ 0,+ None,+ pixels.as_ptr().cast(),+ row as u32,+ 0,+ );+ }+ sink(VideoTick::Frame(CapturedFrame {+ texture: slot,+ width,+ height,+ capture_us: unix_micros(),+ }));+ }+ }+ Err(e) => tracing::debug!("[omnidisc-media] synthetic frame: {e}"),+ }+ n += 1;+ next += interval;+ let now = Instant::now();+ if next > now {+ std::thread::sleep(next - now);+ } else if now - next > Duration::from_millis(200) {+ next = now;+ }+ }+ })+ .map_err(|e| StreamError::Capture(format!("synthetic thread: {e}")))?;+ Ok((+ VideoCapture {+ _wgc: None,+ _synthetic: Some(SyntheticSource {+ stop,+ thread: Some(thread),+ }),+ },+ CaptureGeometry { width, height, fps },+ ))+}++fn wgc_available() -> Result<(), StreamError> {+ match GraphicsCaptureSession::IsSupported() {+ Ok(true) => Ok(()),+ _ => Err(StreamError::Capture(+ "Windows.Graphics.Capture is unavailable; screen sharing needs Windows 10 version 1903 or newer".into(),+ )),+ }+}++pub struct Platform;++impl CaptureApi for Platform {+ fn list_sources(thumbnails: bool) -> Result<StreamSources, StreamError> {+ let _com = audio::ComGuard::mta();+ wgc_available()?;+ let displays = sources::display_sources(thumbnails);+ if displays.is_empty() {+ return Err(StreamError::Capture(+ "no displays were reported by Windows".into(),+ ));+ }+ let windows = sources::window_sources(thumbnails);+ let loopback = audio::process_loopback_supported();+ let apps = if loopback {+ audio::audio_apps()+ } else {+ Vec::new()+ };+ Ok(StreamSources {+ displays,+ windows,+ apps,+ app_audio_supported: loopback,+ system_audio_supported: loopback,+ })+ }++ fn start_video(+ opts: &CaptureOptions,+ sink: VideoSink,+ ) -> Result<(VideoCapture, CaptureGeometry), StreamError> {+ if let SourceId::Synthetic { width, height } = opts.source {+ return start_synthetic(width, height, opts.fps, sink);+ }+ // `GraphicsCaptureSession::IsSupported` is a WinRT static call, so the+ // caller's thread needs an apartment even though the session itself+ // runs on our own.+ let _com = audio::ComGuard::mta();+ wgc_available()?;+ let gpu = gpu()?;+ let target = match opts.source {+ SourceId::Display { id } => wgc::Target::Monitor(sources::monitor_from_id(id)?.handle),+ SourceId::Window { id } => {+ wgc::Target::Window(sources::window_from_id(id).ok_or(StreamError::SourceGone)?)+ }+ SourceId::Synthetic { .. } => return Err(StreamError::Unsupported),+ };+ let (capture, geometry) =+ wgc::start(gpu, target, sink, opts.cursor, opts.fps, opts.height)?;+ Ok((+ VideoCapture {+ _wgc: Some(capture),+ _synthetic: None,+ },+ geometry,+ ))+ }++ fn start_audio(+ mode: AudioMode,+ sink: AudioSink,+ ) -> Result<(AudioCapture, AudioMode), StreamError> {+ if mode == AudioMode::None {+ return Ok((AudioCapture { inner: None }, AudioMode::None));+ }+ if !audio::process_loopback_supported() {+ return Err(audio::unsupported_build_error());+ }+ let own_pid = std::process::id();+ let mut attempt = mode;+ loop {+ let started = match attempt {+ AudioMode::App { pid } if pid > 0 => {+ audio::start_process_loopback(pid as u32, true, sink.clone())+ }+ AudioMode::App { pid } => Err(StreamError::Capture(format!(+ "invalid audio source pid {pid}"+ ))),+ // "System except us": exclude our own process tree so the share+ // never echoes OmniGet's own output back into the room.+ AudioMode::System => audio::start_process_loopback(own_pid, false, sink.clone()),+ AudioMode::None => return Ok((AudioCapture { inner: None }, AudioMode::None)),+ };+ match started {+ Ok(handle) => {+ return Ok((+ AudioCapture {+ inner: Some(handle),+ },+ attempt,+ ))+ }+ Err(e) => {+ tracing::warn!("[omnidisc-media] audio capture {attempt:?} failed: {e}");+ attempt = match attempt {+ AudioMode::App { .. } => AudioMode::System,+ _ => return Ok((AudioCapture { inner: None }, AudioMode::None)),+ };+ }+ }+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/capture/windows/sources.rs b/src-tauri/omnidisc-media/src/capture/windows/sources.rsnew file mode 100644index 00000000..66891b37--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/windows/sources.rs@@ -0,0 +1,484 @@+use crate::stream::{AudioApp, SourceId, StreamError, StreamSource};+use base64::Engine;+use std::ffi::c_void;+use windows::core::BOOL;+use windows::core::PWSTR;+use windows::Win32::Foundation::{FALSE, HWND, LPARAM, RECT, TRUE};+use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_CLOAKED};+use windows::Win32::Graphics::Gdi::{+ CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, EnumDisplayMonitors, GetDC,+ GetMonitorInfoW, ReleaseDC, SelectObject, SetStretchBltMode, StretchBlt, BITMAPINFO,+ BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HALFTONE, HDC, HGDIOBJ, HMONITOR, MONITORINFO,+ MONITORINFOEXW, SRCCOPY,+};+use windows::Win32::Storage::Xps::{PrintWindow, PRINT_WINDOW_FLAGS};+use windows::Win32::System::Threading::{+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION,+};+use windows::Win32::UI::WindowsAndMessaging::{+ EnumWindows, GetAncestor, GetWindowLongW, GetWindowRect, GetWindowTextLengthW, GetWindowTextW,+ GetWindowThreadProcessId, IsIconic, IsWindow, IsWindowVisible, GA_ROOT, GWL_EXSTYLE, GWL_STYLE,+ MONITORINFOF_PRIMARY, WS_CHILD, WS_EX_TOOLWINDOW,+};++const THUMB_WIDTH: u32 = 320;+const PW_RENDERFULLCONTENT: PRINT_WINDOW_FLAGS = PRINT_WINDOW_FLAGS(2);+const MIN_WINDOW_EDGE: i32 = 64;++pub struct Monitor {+ pub handle: HMONITOR,+ pub rect: RECT,+ pub primary: bool,+}++// SAFETY: HMONITOR is a plain handle; it is only used to build a capture item.+unsafe impl Send for Monitor {}++unsafe extern "system" fn monitor_proc(+ monitor: HMONITOR,+ _hdc: HDC,+ _rect: *mut RECT,+ data: LPARAM,+) -> BOOL {+ let list = unsafe { &mut *(data.0 as *mut Vec<Monitor>) };+ let mut info = MONITORINFOEXW {+ monitorInfo: MONITORINFO {+ cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,+ ..Default::default()+ },+ ..Default::default()+ };+ let ok = unsafe {+ GetMonitorInfoW(+ monitor,+ &mut info as *mut MONITORINFOEXW as *mut MONITORINFO,+ )+ };+ if ok.as_bool() {+ list.push(Monitor {+ handle: monitor,+ rect: info.monitorInfo.rcMonitor,+ primary: info.monitorInfo.dwFlags & MONITORINFOF_PRIMARY != 0,+ });+ }+ TRUE+}++pub fn monitors() -> Vec<Monitor> {+ let mut list: Vec<Monitor> = Vec::new();+ unsafe {+ let _ = EnumDisplayMonitors(+ None,+ None,+ Some(monitor_proc),+ LPARAM(&mut list as *mut Vec<Monitor> as isize),+ );+ }+ list+}++pub struct Window {+ pub handle: HWND,+ pub title: String,+ pub app: Option<String>,+ pub width: u32,+ pub height: u32,+}++// SAFETY: HWND is a plain handle; used only to build a capture item.+unsafe impl Send for Window {}++fn window_text(hwnd: HWND) -> String {+ let len = unsafe { GetWindowTextLengthW(hwnd) };+ if len <= 0 {+ return String::new();+ }+ let mut buf = vec![0u16; len as usize + 1];+ let written = unsafe { GetWindowTextW(hwnd, &mut buf) };+ if written <= 0 {+ return String::new();+ }+ String::from_utf16_lossy(&buf[..written as usize])+}++fn is_cloaked(hwnd: HWND) -> bool {+ let mut cloaked: u32 = 0;+ let ok = unsafe {+ DwmGetWindowAttribute(+ hwnd,+ DWMWA_CLOAKED,+ &mut cloaked as *mut u32 as *mut c_void,+ std::mem::size_of::<u32>() as u32,+ )+ };+ ok.is_ok() && cloaked != 0+}++pub fn process_path(pid: u32) -> Option<String> {+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }.ok()?;+ let mut buf = vec![0u16; 512];+ let mut len = buf.len() as u32;+ let ok = unsafe {+ QueryFullProcessImageNameW(+ handle,+ PROCESS_NAME_FORMAT(0),+ PWSTR(buf.as_mut_ptr()),+ &mut len,+ )+ };+ let _ = unsafe { windows::Win32::Foundation::CloseHandle(handle) };+ if ok.is_err() || len == 0 {+ return None;+ }+ Some(String::from_utf16_lossy(&buf[..len as usize]))+}++pub fn process_name(pid: u32) -> Option<String> {+ let path = process_path(pid)?;+ let stem = path+ .rsplit(['\\', '/'])+ .next()+ .unwrap_or(&path)+ .trim_end_matches(".exe")+ .trim_end_matches(".EXE")+ .to_string();+ if stem.is_empty() {+ None+ } else {+ Some(stem)+ }+}++unsafe extern "system" fn window_proc(hwnd: HWND, data: LPARAM) -> BOOL {+ let ctx = unsafe { &mut *(data.0 as *mut (Vec<Window>, u32)) };+ let (list, own_pid) = (&mut ctx.0, ctx.1);+ if list.len() >= 128 {+ return FALSE;+ }+ if !unsafe { IsWindowVisible(hwnd) }.as_bool() || unsafe { IsIconic(hwnd) }.as_bool() {+ return TRUE;+ }+ if unsafe { GetAncestor(hwnd, GA_ROOT) } != hwnd {+ return TRUE;+ }+ let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) } as u32;+ if style & WS_CHILD.0 != 0 {+ return TRUE;+ }+ let ex_style = unsafe { GetWindowLongW(hwnd, GWL_EXSTYLE) } as u32;+ if ex_style & WS_EX_TOOLWINDOW.0 != 0 {+ return TRUE;+ }+ if is_cloaked(hwnd) {+ return TRUE;+ }+ let mut pid: u32 = 0;+ unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) };+ if pid == 0 || pid == own_pid {+ return TRUE;+ }+ let mut rect = RECT::default();+ if unsafe { GetWindowRect(hwnd, &mut rect) }.is_err() {+ return TRUE;+ }+ let w = rect.right - rect.left;+ let h = rect.bottom - rect.top;+ if w < MIN_WINDOW_EDGE || h < MIN_WINDOW_EDGE {+ return TRUE;+ }+ let title = window_text(hwnd);+ let app = process_name(pid);+ if title.trim().is_empty() && app.is_none() {+ return TRUE;+ }+ list.push(Window {+ handle: hwnd,+ title,+ app,+ width: w as u32,+ height: h as u32,+ });+ TRUE+}++pub fn windows_list() -> Vec<Window> {+ let mut ctx: (Vec<Window>, u32) = (Vec::new(), std::process::id());+ unsafe {+ let _ = EnumWindows(+ Some(window_proc),+ LPARAM(&mut ctx as *mut (Vec<Window>, u32) as isize),+ );+ }+ ctx.0+}++struct Dib {+ dc: HDC,+ bitmap: windows::Win32::Graphics::Gdi::HBITMAP,+ old: HGDIOBJ,+ bits: *mut c_void,+ width: i32,+ height: i32,+}++impl Dib {+ fn new(reference: HDC, width: i32, height: i32) -> Option<Self> {+ if width <= 0 || height <= 0 {+ return None;+ }+ let dc = unsafe { CreateCompatibleDC(Some(reference)) };+ if dc.is_invalid() {+ return None;+ }+ let info = BITMAPINFO {+ bmiHeader: BITMAPINFOHEADER {+ biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,+ biWidth: width,+ // Negative height gives a top-down DIB, which matches the row+ // order the JPEG encoder expects.+ biHeight: -height,+ biPlanes: 1,+ biBitCount: 32,+ biCompression: BI_RGB.0,+ ..Default::default()+ },+ ..Default::default()+ };+ let mut bits: *mut c_void = std::ptr::null_mut();+ let bitmap =+ unsafe { CreateDIBSection(Some(dc), &info, DIB_RGB_COLORS, &mut bits, None, 0) };+ let bitmap = match bitmap {+ Ok(b) if !bits.is_null() => b,+ _ => {+ unsafe {+ let _ = DeleteDC(dc);+ };+ return None;+ }+ };+ let old = unsafe { SelectObject(dc, bitmap.into()) };+ Some(Self {+ dc,+ bitmap,+ old,+ bits,+ width,+ height,+ })+ }++ fn to_jpeg_data_url(&self) -> Option<String> {+ let pixels = self.width as usize * self.height as usize * 4;+ let bgra = unsafe { std::slice::from_raw_parts(self.bits as *const u8, pixels) };+ let mut rgb = Vec::with_capacity(self.width as usize * self.height as usize * 3);+ for px in bgra.chunks_exact(4) {+ rgb.push(px[2]);+ rgb.push(px[1]);+ rgb.push(px[0]);+ }+ let mut jpeg = Vec::new();+ let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 60);+ enc.encode(+ &rgb,+ self.width as u32,+ self.height as u32,+ image::ExtendedColorType::Rgb8,+ )+ .ok()?;+ Some(format!(+ "data:image/jpeg;base64,{}",+ base64::engine::general_purpose::STANDARD.encode(jpeg)+ ))+ }+}++impl Drop for Dib {+ fn drop(&mut self) {+ unsafe {+ SelectObject(self.dc, self.old);+ let _ = DeleteObject(self.bitmap.into());+ let _ = DeleteDC(self.dc);+ }+ }+}++fn thumb_size(width: u32, height: u32) -> (i32, i32) {+ let w = THUMB_WIDTH.min(width.max(1));+ let h = ((height as u64 * w as u64) / width.max(1) as u64).clamp(1, THUMB_WIDTH as u64) as u32;+ (w as i32, h as i32)+}++pub fn monitor_thumbnail(m: &Monitor) -> Option<String> {+ let w = m.rect.right - m.rect.left;+ let h = m.rect.bottom - m.rect.top;+ if w <= 0 || h <= 0 {+ return None;+ }+ let screen = unsafe { GetDC(None) };+ if screen.is_invalid() {+ return None;+ }+ let (tw, th) = thumb_size(w as u32, h as u32);+ let out = (|| {+ let dib = Dib::new(screen, tw, th)?;+ unsafe {+ SetStretchBltMode(dib.dc, HALFTONE);+ StretchBlt(+ dib.dc,+ 0,+ 0,+ tw,+ th,+ Some(screen),+ m.rect.left,+ m.rect.top,+ w,+ h,+ SRCCOPY,+ )+ .ok()+ .ok()?;+ }+ dib.to_jpeg_data_url()+ })();+ unsafe { ReleaseDC(None, screen) };+ out+}++pub fn window_thumbnail(win: &Window) -> Option<String> {+ let screen = unsafe { GetDC(None) };+ if screen.is_invalid() {+ return None;+ }+ let (tw, th) = thumb_size(win.width, win.height);+ let out = (|| {+ let full = Dib::new(screen, win.width as i32, win.height as i32)?;+ let printed = unsafe { PrintWindow(win.handle, full.dc, PW_RENDERFULLCONTENT) }.as_bool();+ if !printed {+ return None;+ }+ let thumb = Dib::new(screen, tw, th)?;+ unsafe {+ SetStretchBltMode(thumb.dc, HALFTONE);+ StretchBlt(+ thumb.dc,+ 0,+ 0,+ tw,+ th,+ Some(full.dc),+ 0,+ 0,+ win.width as i32,+ win.height as i32,+ SRCCOPY,+ )+ .ok()+ .ok()?;+ }+ thumb.to_jpeg_data_url()+ })();+ unsafe { ReleaseDC(None, screen) };+ out+}++/// HWNDs are 32-bit significant by contract (USER handles are sign-extended on+/// 64-bit Windows), so the frontend's `u32` source id round-trips exactly.+pub fn window_id(hwnd: HWND) -> u32 {+ hwnd.0 as usize as u32+}++pub fn window_from_id(id: u32) -> Option<HWND> {+ // Rebuild the handle rather than re-enumerating: a window that was+ // minimised or lost its title between the picker and the start of the share+ // is still a valid capture target.+ let hwnd = HWND(id as usize as *mut c_void);+ if unsafe { IsWindow(Some(hwnd)) }.as_bool() {+ Some(hwnd)+ } else {+ None+ }+}++pub fn display_sources(thumbnails: bool) -> Vec<StreamSource> {+ monitors()+ .iter()+ .enumerate()+ .map(|(i, m)| {+ let w = (m.rect.right - m.rect.left).max(0) as u32;+ let h = (m.rect.bottom - m.rect.top).max(0) as u32;+ StreamSource {+ id: SourceId::Display { id: i as u32 + 1 },+ title: if m.primary {+ format!("Display {} ({w}×{h}, primary)", i + 1)+ } else {+ format!("Display {} ({w}×{h})", i + 1)+ },+ app_name: None,+ width: w,+ height: h,+ thumbnail: if thumbnails {+ monitor_thumbnail(m)+ } else {+ None+ },+ }+ })+ .collect()+}++pub fn window_sources(thumbnails: bool) -> Vec<StreamSource> {+ let mut out = Vec::new();+ for (i, w) in windows_list().into_iter().enumerate() {+ let title = if w.title.trim().is_empty() {+ w.app.clone().unwrap_or_default()+ } else {+ w.title.clone()+ };+ out.push(StreamSource {+ id: SourceId::Window {+ id: window_id(w.handle),+ },+ title,+ app_name: w.app.clone(),+ width: w.width,+ height: w.height,+ thumbnail: if thumbnails && i < 16 {+ window_thumbnail(&w)+ } else {+ None+ },+ });+ if out.len() >= 40 {+ break;+ }+ }+ out+}++pub fn monitor_from_id(id: u32) -> Result<Monitor, StreamError> {+ let mut list = monitors();+ if id == 0 || id as usize > list.len() {+ return Err(StreamError::SourceGone);+ }+ Ok(list.remove(id as usize - 1))+}++pub fn audio_app(pid: u32) -> Option<AudioApp> {+ let path = process_path(pid)?;+ let name = path+ .rsplit(['\\', '/'])+ .next()+ .unwrap_or(&path)+ .trim_end_matches(".exe")+ .trim_end_matches(".EXE")+ .to_string();+ if name.is_empty() {+ return None;+ }+ Some(AudioApp {+ pid: pid as i32,+ name,+ bundle_id: path,+ })+}diff --git a/src-tauri/omnidisc-media/src/capture/windows/wgc.rs b/src-tauri/omnidisc-media/src/capture/windows/wgc.rsnew file mode 100644index 00000000..e2184135--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/windows/wgc.rs@@ -0,0 +1,326 @@+use super::d3d::{Gpu, TexturePool};+use super::CapturedFrame;+use crate::capture::{unix_micros, CaptureGeometry, VideoSink, VideoTick};+use crate::stream::{resolve_geometry, StreamError};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{mpsc, Arc};+use std::time::{Duration, Instant};+use windows::core::{Interface, Ref};+use windows::Foundation::TypedEventHandler;+use windows::Graphics::Capture::{+ Direct3D11CaptureFramePool, GraphicsCaptureItem, GraphicsCaptureSession,+};+use windows::Graphics::DirectX::Direct3D11::IDirect3DDevice;+use windows::Graphics::DirectX::DirectXPixelFormat;+use windows::Graphics::SizeInt32;+use windows::Win32::Foundation::HWND;+use windows::Win32::Graphics::Direct3D11::{ID3D11Texture2D, D3D11_BOX};+use windows::Win32::Graphics::Dxgi::IDXGIDevice;+use windows::Win32::Graphics::Gdi::HMONITOR;+use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED};+use windows::Win32::System::WinRT::Direct3D11::{+ CreateDirect3D11DeviceFromDXGIDevice, IDirect3DDxgiInterfaceAccess,+};+use windows::Win32::System::WinRT::Graphics::Capture::IGraphicsCaptureItemInterop;++const POOL_BUFFERS: i32 = 2;+const POOL_BUDGET: usize = 4;++pub enum Target {+ Monitor(HMONITOR),+ Window(HWND),+}++// SAFETY: HMONITOR and HWND are opaque handle values, not thread-affine+// pointers; they are only passed to the capture-item interop factory.+unsafe impl Send for Target {}++/// `IDirect3DDevice` is agile (WinRT free-threaded marshalling), so it may be+/// used from the frame-pool callback thread that WGC picks.+struct SendDevice(IDirect3DDevice);+unsafe impl Send for SendDevice {}++impl SendDevice {+ // A method, not a field read: edition-2021 closures capture disjoint+ // fields, and capturing the bare `IDirect3DDevice` would make the handler+ // closure `!Send`.+ fn get(&self) -> &IDirect3DDevice {+ &self.0+ }+}++fn cap_err(what: &str, e: windows::core::Error) -> StreamError {+ StreamError::Capture(format!("{what}: {e}"))+}++pub fn direct3d_device(gpu: &Gpu) -> Result<IDirect3DDevice, StreamError> {+ let dxgi: IDXGIDevice = gpu.device().cast().map_err(|e| cap_err("IDXGIDevice", e))?;+ let inspectable = unsafe {+ CreateDirect3D11DeviceFromDXGIDevice(&dxgi)+ .map_err(|e| cap_err("CreateDirect3D11DeviceFromDXGIDevice", e))?+ };+ inspectable+ .cast()+ .map_err(|e| cap_err("IDirect3DDevice", e))+}++pub fn capture_item(target: &Target) -> Result<GraphicsCaptureItem, StreamError> {+ let interop = windows::core::factory::<GraphicsCaptureItem, IGraphicsCaptureItemInterop>()+ .map_err(|e| cap_err("IGraphicsCaptureItemInterop", e))?;+ let item = unsafe {+ match target {+ Target::Monitor(m) => interop.CreateForMonitor::<GraphicsCaptureItem>(*m),+ Target::Window(w) => interop.CreateForWindow::<GraphicsCaptureItem>(*w),+ }+ };+ item.map_err(|e| {+ // WGC refuses items the user is not allowed to capture, and refuses+ // everything when the machine is below Windows 10 1903.+ if e.code().0 == windows::Win32::Foundation::E_INVALIDARG.0 {+ StreamError::SourceGone+ } else {+ cap_err("GraphicsCaptureItem", e)+ }+ })+}++struct Session {+ session: GraphicsCaptureSession,+ pool: Direct3D11CaptureFramePool,+}++// SAFETY: WGC objects are agile (free-threaded marshalled); the session is+// created and closed on the capture thread and never touched concurrently.+unsafe impl Send for Session {}++pub struct Capture {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl Capture {+ fn shutdown(&mut self) {+ self.stop.store(true, Ordering::Release);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++impl Drop for Capture {+ fn drop(&mut self) {+ self.shutdown();+ }+}++#[allow(clippy::too_many_arguments)]+fn build(+ gpu: &Arc<Gpu>,+ item: &GraphicsCaptureItem,+ pool: TexturePool,+ sink: VideoSink,+ cursor: bool,+ fps: u16,+ last_frame_us: Arc<AtomicU64>,+) -> Result<Session, StreamError> {+ let device = direct3d_device(gpu)?;+ let size = item.Size().map_err(|e| cap_err("item size", e))?;+ let frame_pool = Direct3D11CaptureFramePool::CreateFreeThreaded(+ &device,+ DirectXPixelFormat::B8G8R8A8UIntNormalized,+ POOL_BUFFERS,+ size,+ )+ .map_err(|e| cap_err("Direct3D11CaptureFramePool", e))?;++ let gpu_cb = gpu.clone();+ let min_interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);+ let mut last_emit: Option<Instant> = None;+ let mut pool_size = size;+ let device_cb = SendDevice(device.clone());+ let handler = TypedEventHandler::<Direct3D11CaptureFramePool, windows::core::IInspectable>::new(+ move |sender: Ref<'_, Direct3D11CaptureFramePool>, _| {+ let Ok(sender) = sender.ok() else {+ return Ok(());+ };+ let Ok(frame) = sender.TryGetNextFrame() else {+ return Ok(());+ };+ if let Ok(content) = frame.ContentSize() {+ if content.Width != pool_size.Width || content.Height != pool_size.Height {+ // WHY: WGC stops delivering frames after the item resizes+ // unless the pool is recreated at the new size. Our own+ // textures stay at the size the encoder was configured for;+ // the copy below clamps to the smaller of the two.+ let _ = sender.Recreate(+ device_cb.get(),+ DirectXPixelFormat::B8G8R8A8UIntNormalized,+ POOL_BUFFERS,+ content,+ );+ pool_size = content;+ }+ }+ let now = Instant::now();+ if let Some(prev) = last_emit {+ if now.duration_since(prev) + Duration::from_micros(500) < min_interval {+ return Ok(());+ }+ }+ let Ok(surface) = frame.Surface() else {+ return Ok(());+ };+ let Ok(access) = surface.cast::<IDirect3DDxgiInterfaceAccess>() else {+ return Ok(());+ };+ let source: ID3D11Texture2D = match unsafe { access.GetInterface() } {+ Ok(t) => t,+ Err(_) => return Ok(()),+ };+ let slot = match pool.acquire() {+ Ok(s) => s,+ Err(e) => {+ tracing::debug!("[omnidisc-media] wgc: {e}");+ return Ok(());+ }+ };+ let Some(dst) = slot.texture() else {+ return Ok(());+ };+ let (pw, ph) = pool.size();+ let src_w = pool_size.Width.max(0) as u32;+ let src_h = pool_size.Height.max(0) as u32;+ let box_ = D3D11_BOX {+ left: 0,+ top: 0,+ front: 0,+ right: pw.min(src_w),+ bottom: ph.min(src_h),+ back: 1,+ };+ if box_.right == 0 || box_.bottom == 0 {+ return Ok(());+ }+ unsafe {+ gpu_cb+ .context()+ .CopySubresourceRegion(dst, 0, 0, 0, 0, &source, 0, Some(&box_));+ }+ last_emit = Some(now);+ let capture_us = unix_micros();+ last_frame_us.store(capture_us as u64, Ordering::Relaxed);+ sink(VideoTick::Frame(CapturedFrame {+ texture: slot,+ width: pw,+ height: ph,+ capture_us,+ }));+ Ok(())+ },+ );+ frame_pool+ .FrameArrived(&handler)+ .map_err(|e| cap_err("FrameArrived", e))?;++ let session = frame_pool+ .CreateCaptureSession(item)+ .map_err(|e| cap_err("CreateCaptureSession", e))?;+ if let Err(e) = session.SetIsCursorCaptureEnabled(cursor) {+ tracing::debug!("[omnidisc-media] SetIsCursorCaptureEnabled unavailable: {e}");+ }+ // Windows 11 only; on Windows 10 the yellow border cannot be removed.+ if let Err(e) = session.SetIsBorderRequired(false) {+ tracing::debug!("[omnidisc-media] SetIsBorderRequired unavailable: {e}");+ }+ session+ .StartCapture()+ .map_err(|e| cap_err("StartCapture", e))?;+ Ok(Session {+ session,+ pool: frame_pool,+ })+}++/// Starts a WGC capture on a dedicated MTA thread. The thread also emits+/// `VideoTick::Idle` whenever a frame interval passes without a new frame — WGC+/// is dirty-driven like ScreenCaptureKit, so a still screen delivers nothing.+pub fn start(+ gpu: Arc<Gpu>,+ target: Target,+ sink: VideoSink,+ cursor: bool,+ fps: u16,+ requested_height: Option<u16>,+) -> Result<(Capture, CaptureGeometry), StreamError> {+ let stop = Arc::new(AtomicBool::new(false));+ let stop_thread = stop.clone();+ let (tx, rx) = mpsc::channel::<Result<CaptureGeometry, StreamError>>();+ let thread = std::thread::Builder::new()+ .name("omnidisc-wgc".into())+ .spawn(move || {+ let com = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };+ let last_frame_us = Arc::new(AtomicU64::new(0));+ let started = capture_item(&target).and_then(|item| {+ let size: SizeInt32 = item.Size().map_err(|e| cap_err("item size", e))?;+ let (native_w, native_h) = (size.Width.max(2) as u32, size.Height.max(2) as u32);+ let (width, height) = resolve_geometry(native_w, native_h, requested_height);+ let pool = TexturePool::new(gpu.clone(), native_w, native_h, POOL_BUDGET);+ let session = build(+ &gpu,+ &item,+ pool,+ sink.clone(),+ cursor,+ fps,+ last_frame_us.clone(),+ )?;+ Ok((session, CaptureGeometry { width, height, fps }))+ });+ let session = match started {+ Ok((session, geometry)) => {+ let _ = tx.send(Ok(geometry));+ session+ }+ Err(e) => {+ let _ = tx.send(Err(e));+ if com.is_ok() {+ unsafe { CoUninitialize() };+ }+ return;+ }+ };+ let interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);+ while !stop_thread.load(Ordering::Acquire) {+ std::thread::sleep(interval);+ let last = last_frame_us.load(Ordering::Relaxed) as i64;+ if unix_micros() - last > interval.as_micros() as i64 {+ sink(VideoTick::Idle);+ }+ }+ let _ = session.session.Close();+ let _ = session.pool.Close();+ if com.is_ok() {+ unsafe { CoUninitialize() };+ }+ })+ .map_err(|e| StreamError::Capture(format!("wgc thread: {e}")))?;+ match rx.recv() {+ Ok(Ok(geometry)) => Ok((+ Capture {+ stop,+ thread: Some(thread),+ },+ geometry,+ )),+ Ok(Err(e)) => {+ let _ = thread.join();+ Err(e)+ }+ Err(_) => {+ let _ = thread.join();+ Err(StreamError::Capture(+ "the screen capture thread stopped before it started".into(),+ ))+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/encode/mod.rs b/src-tauri/omnidisc-media/src/encode/mod.rsindex 420ce2a9..3bd35b54 100644--- a/src-tauri/omnidisc-media/src/encode/mod.rs+++ b/src-tauri/omnidisc-media/src/encode/mod.rs@@ -4,12 +4,25 @@ use std::sync::atomic::{AtomicU64, Ordering};#[cfg(target_os = "macos")]mod videotoolbox;#[cfg(target_os = "macos")]-pub use videotoolbox::VideoEncoder;+pub use self::videotoolbox::{clamp_codec, publish_path, VideoEncoder};-#[cfg(not(target_os = "macos"))]+#[cfg(windows)]+mod windows;+#[cfg(windows)]+pub use self::windows::{clamp_codec, publish_path, VideoEncoder};++#[cfg(not(any(target_os = "macos", windows)))]mod stub;-#[cfg(not(target_os = "macos"))]-pub use stub::VideoEncoder;+#[cfg(not(any(target_os = "macos", windows)))]+pub use self::stub::{clamp_codec, publish_path, VideoEncoder};++/// How a platform hands frames to LiveKit: through our own encoder and the+/// `PreEncoded` pass-through, or as raw frames for libwebrtc to encode.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PublishPath {+ PreEncoded,+ Raw,+}#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct EncoderConfig {diff --git a/src-tauri/omnidisc-media/src/encode/stub.rs b/src-tauri/omnidisc-media/src/encode/stub.rsindex abe9675a..8e9663d5 100644--- a/src-tauri/omnidisc-media/src/encode/stub.rs+++ b/src-tauri/omnidisc-media/src/encode/stub.rs@@ -1,9 +1,17 @@-use super::{EncoderConfig, EncoderCounters};+use super::{EncoderConfig, EncoderCounters, PublishPath};use crate::capture::CapturedFrame;-use crate::stream::StreamError;+use crate::stream::{StreamCodec, StreamError};use livekit::webrtc::video_source::native::NativeVideoSource;use std::sync::Arc;+pub fn clamp_codec(codec: StreamCodec) -> StreamCodec {+ codec+}++pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {+ PublishPath::PreEncoded+}+pub struct VideoEncoder;impl VideoEncoder {@@ -27,7 +35,7 @@ impl VideoEncoder {None}- pub fn name(&self) -> &'static str {+ pub fn name(&self) -> &str {"none"}diff --git a/src-tauri/omnidisc-media/src/encode/videotoolbox.rs b/src-tauri/omnidisc-media/src/encode/videotoolbox.rsindex 9138a68d..87f62cfb 100644--- a/src-tauri/omnidisc-media/src/encode/videotoolbox.rs+++ b/src-tauri/omnidisc-media/src/encode/videotoolbox.rs@@ -1,4 +1,4 @@-use super::{EncoderConfig, EncoderCounters};+use super::{EncoderConfig, EncoderCounters, PublishPath};use crate::capture::CapturedFrame;use crate::stream::{StreamCodec, StreamError, StreamMode};use livekit::webrtc::video_frame::{EncodedFrameType, EncodedVideoCodec, EncodedVideoFrame};@@ -36,6 +36,14 @@ use std::time::Instant;const KEYFRAME_INTERVAL: i32 = 240;+pub fn clamp_codec(codec: StreamCodec) -> StreamCodec {+ codec+}++pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {+ PublishPath::PreEncoded+}+struct FrameCtx {submit: Instant,capture_us: i64,@@ -485,7 +493,7 @@ impl VideoEncoder {self.hw}- pub fn name(&self) -> &'static str {+ pub fn name(&self) -> &str {"VideoToolbox"}diff --git a/src-tauri/omnidisc-media/src/encode/windows/mf.rs b/src-tauri/omnidisc-media/src/encode/windows/mf.rsnew file mode 100644index 00000000..8588d36d--- /dev/null+++ b/src-tauri/omnidisc-media/src/encode/windows/mf.rs@@ -0,0 +1,815 @@+use crate::capture::{gpu, CapturedFrame, Gpu, Nv12Converter};+use crate::encode::{EncoderConfig, EncoderCounters};+use crate::stream::{StreamError, StreamMode};+use livekit::webrtc::video_frame::{EncodedFrameType, EncodedVideoCodec, EncodedVideoFrame};+use livekit::webrtc::video_source::{native::NativeVideoSource, VideoResolution};+use std::collections::VecDeque;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, OnceLock, Weak};+use std::time::Instant;+use windows::core::{implement, Interface, Ref};+use windows::Win32::Foundation::E_NOTIMPL;+use windows::Win32::Graphics::Direct3D11::ID3D11Texture2D;+use windows::Win32::Media::MediaFoundation::{+ eAVEncCommonRateControlMode_CBR, eAVEncH264VProfile_High, eAVEncH264VProfile_Main,+ CODECAPI_AVEncCommonMeanBitRate, CODECAPI_AVEncCommonRateControlMode, CODECAPI_AVEncMPVGOPSize,+ CODECAPI_AVEncVideoForceKeyFrame, CODECAPI_AVLowLatencyMode, ICodecAPI, IMF2DBuffer,+ IMFActivate, IMFAsyncCallback, IMFAsyncCallback_Impl, IMFAsyncResult, IMFDXGIDeviceManager,+ IMFMediaEventGenerator, IMFMediaType, IMFSample, IMFTransform, METransformHaveOutput,+ METransformNeedInput, MFCreateDXGIDeviceManager, MFCreateDXGISurfaceBuffer, MFCreateMediaType,+ MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFSampleExtension_CleanPoint,+ MFStartup, MFTEnumEx, MFT_FRIENDLY_NAME_Attribute, MFVideoFormat_H264, MFVideoFormat_NV12,+ MFVideoInterlace_Progressive, MFSTARTUP_LITE, MFT_CATEGORY_VIDEO_ENCODER,+ MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_SORTANDFILTER, MFT_MESSAGE_COMMAND_FLUSH,+ MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_END_OF_STREAM,+ MFT_MESSAGE_NOTIFY_END_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM,+ MFT_MESSAGE_SET_D3D_MANAGER, MFT_OUTPUT_DATA_BUFFER, MFT_REGISTER_TYPE_INFO, MF_LOW_LATENCY,+ MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE,+ MF_MT_MPEG2_PROFILE, MF_MT_MPEG_SEQUENCE_HEADER, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE,+ MF_SA_D3D11_AWARE, MF_TRANSFORM_ASYNC, MF_TRANSFORM_ASYNC_UNLOCK, MF_VERSION,+};+use windows::Win32::System::Com::CoTaskMemFree;+use windows::Win32::System::Variant::{VARIANT, VARIANT_0_0, VT_BOOL, VT_UI4};++const KEYFRAME_INTERVAL: u32 = 240;+const QUEUE_DEPTH: usize = 2;++fn enc_err(what: &str, e: windows::core::Error) -> StreamError {+ StreamError::Encoder(format!("{what}: {e}"))+}++fn mf_startup() -> Result<(), StreamError> {+ static STARTED: OnceLock<Result<(), String>> = OnceLock::new();+ STARTED+ .get_or_init(|| unsafe {+ MFStartup(MF_VERSION, MFSTARTUP_LITE).map_err(|e| format!("MFStartup: {e}"))+ })+ .clone()+ .map_err(StreamError::Encoder)+}++fn var_u32(value: u32) -> VARIANT {+ let mut v = VARIANT::default();+ unsafe {+ let inner: &mut VARIANT_0_0 = &mut v.Anonymous.Anonymous;+ inner.vt = VT_UI4;+ inner.Anonymous.ulVal = value;+ }+ v+}++fn var_bool(value: bool) -> VARIANT {+ let mut v = VARIANT::default();+ unsafe {+ let inner: &mut VARIANT_0_0 = &mut v.Anonymous.Anonymous;+ inner.vt = VT_BOOL;+ inner.Anonymous.boolVal =+ windows::Win32::Foundation::VARIANT_BOOL(if value { -1 } else { 0 });+ }+ v+}++fn pack2(a: u32, b: u32) -> u64 {+ ((a as u64) << 32) | b as u64+}++struct Pending {+ hungry: usize,+ queue: VecDeque<(IMFSample, Instant)>,+}++struct Shared {+ transform: IMFTransform,+ generator: IMFMediaEventGenerator,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ width: u32,+ height: u32,+ io: Mutex<()>,+ pending: Mutex<Pending>,+ callback: Mutex<Option<IMFAsyncCallback>>,+ seq_header: Mutex<Vec<u8>>,+ stopping: AtomicBool,+ in_flight: Mutex<VecDeque<Instant>>,+}++// SAFETY: every call into the MFT and its event generator goes through the+// `io` mutex or is itself thread-safe (`IMFMediaEventGenerator` is documented+// free-threaded), and the LiveKit source is `Send + Sync`.+unsafe impl Send for Shared {}+unsafe impl Sync for Shared {}++#[implement(IMFAsyncCallback)]+struct EventCallback {+ shared: Weak<Shared>,+}++impl IMFAsyncCallback_Impl for EventCallback_Impl {+ fn GetParameters(&self, _flags: *mut u32, _queue: *mut u32) -> windows::core::Result<()> {+ Err(E_NOTIMPL.into())+ }++ fn Invoke(&self, result: Ref<'_, IMFAsyncResult>) -> windows::core::Result<()> {+ let Some(shared) = self.shared.upgrade() else {+ return Ok(());+ };+ let Ok(result) = result.ok() else {+ return Ok(());+ };+ let event = match unsafe { shared.generator.EndGetEvent(result) } {+ Ok(e) => e,+ Err(_) => return Ok(()),+ };+ let kind = unsafe { event.GetType() }.unwrap_or(0);+ if kind == METransformNeedInput.0 as u32 {+ shared.on_need_input();+ } else if kind == METransformHaveOutput.0 as u32 {+ shared.on_have_output();+ }+ if !shared.stopping.load(Ordering::Acquire) {+ let cb = shared.callback.lock().ok().and_then(|g| g.clone());+ if let Some(cb) = cb {+ let _ = unsafe { shared.generator.BeginGetEvent(&cb, None) };+ }+ }+ Ok(())+ }+}++impl Shared {+ fn on_need_input(&self) {+ let next = {+ let Ok(mut pending) = self.pending.lock() else {+ return;+ };+ match pending.queue.pop_front() {+ Some(item) => Some(item),+ None => {+ pending.hungry += 1;+ None+ }+ }+ };+ if let Some((sample, submitted)) = next {+ self.submit(sample, submitted);+ }+ }++ fn submit(&self, sample: IMFSample, submitted: Instant) {+ let _guard = self.io.lock();+ if unsafe { self.transform.ProcessInput(0, &sample, 0) }.is_err() {+ self.counters.errors.fetch_add(1, Ordering::Relaxed);+ return;+ }+ self.counters.submitted.fetch_add(1, Ordering::Relaxed);+ if let Ok(mut q) = self.in_flight.lock() {+ while q.len() > 8 {+ q.pop_front();+ }+ q.push_back(submitted);+ }+ }++ fn on_have_output(&self) {+ let mut buffers = [MFT_OUTPUT_DATA_BUFFER {+ dwStreamID: 0,+ pSample: std::mem::ManuallyDrop::new(None),+ dwStatus: 0,+ pEvents: std::mem::ManuallyDrop::new(None),+ }];+ let mut status: u32 = 0;+ let ok = {+ let _guard = self.io.lock();+ unsafe { self.transform.ProcessOutput(0, &mut buffers, &mut status) }+ };+ let sample = std::mem::ManuallyDrop::into_inner(std::mem::replace(+ &mut buffers[0].pSample,+ std::mem::ManuallyDrop::new(None),+ ));+ let _events = std::mem::ManuallyDrop::into_inner(std::mem::replace(+ &mut buffers[0].pEvents,+ std::mem::ManuallyDrop::new(None),+ ));+ if ok.is_err() {+ self.counters.errors.fetch_add(1, Ordering::Relaxed);+ return;+ }+ let Some(sample) = sample else {+ return;+ };+ if let Err(e) = self.publish(&sample) {+ tracing::debug!("[omnidisc-media] mf output: {e}");+ self.counters.errors.fetch_add(1, Ordering::Relaxed);+ }+ }++ fn publish(&self, sample: &IMFSample) -> Result<(), StreamError> {+ let keyframe = unsafe { sample.GetUINT32(&MFSampleExtension_CleanPoint) }.unwrap_or(0) != 0;+ let timestamp_us = unsafe { sample.GetSampleTime() }.unwrap_or(0) / 10;+ let buffer = unsafe { sample.ConvertToContiguousBuffer() }+ .map_err(|e| enc_err("ConvertToContiguousBuffer", e))?;+ let mut data: *mut u8 = std::ptr::null_mut();+ let mut max_len: u32 = 0;+ let mut len: u32 = 0;+ unsafe {+ buffer+ .Lock(&mut data, Some(&mut max_len), Some(&mut len))+ .map_err(|e| enc_err("IMFMediaBuffer::Lock", e))?;+ }+ let mut payload: Vec<u8> = Vec::with_capacity(len as usize + 128);+ if keyframe {+ if let Ok(header) = self.seq_header.lock() {+ let slice = unsafe { std::slice::from_raw_parts(data, len as usize) };+ // Hardware MFTs usually inline SPS/PPS ahead of every IDR; the+ // ones that do not leave them only in MF_MT_MPEG_SEQUENCE_HEADER,+ // and libwebrtc's packetizer needs them in the access unit.+ if !header.is_empty() && !starts_with_parameter_set(slice) {+ payload.extend_from_slice(header.as_slice());+ }+ }+ }+ unsafe {+ payload.extend_from_slice(std::slice::from_raw_parts(data, len as usize));+ let _ = buffer.Unlock();+ }+ if payload.is_empty() {+ return Ok(());+ }+ self.counters.encoded.fetch_add(1, Ordering::Relaxed);+ self.counters+ .bytes+ .fetch_add(payload.len() as u64, Ordering::Relaxed);+ // Low-latency H.264 without B-frames leaves the MFT in submission+ // order, so the oldest outstanding submit time belongs to this frame.+ let latency = self+ .in_flight+ .lock()+ .ok()+ .and_then(|mut q| q.pop_front())+ .map(|t| t.elapsed().as_nanos() as u64)+ .unwrap_or(0);+ self.counters+ .latency_ns_sum+ .fetch_add(latency, Ordering::Relaxed);+ self.counters+ .latency_ns_max+ .fetch_max(latency, Ordering::Relaxed);+ if keyframe {+ self.counters.keyframes.fetch_add(1, Ordering::Relaxed);+ }+ let frame = EncodedVideoFrame {+ codec: EncodedVideoCodec::H264,+ payload: &payload,+ timestamp_us,+ frame_type: if keyframe {+ EncodedFrameType::Key+ } else {+ EncodedFrameType::Delta+ },+ resolution: VideoResolution {+ width: self.width,+ height: self.height,+ },+ frame_metadata: None,+ };+ if self.source.capture_encoded_frame(&frame) {+ self.counters.captured_ok.fetch_add(1, Ordering::Relaxed);+ } else {+ self.counters+ .captured_rejected+ .fetch_add(1, Ordering::Relaxed);+ }+ Ok(())+ }+}++fn starts_with_parameter_set(data: &[u8]) -> bool {+ let nal = if data.starts_with(&[0, 0, 0, 1]) {+ data.get(4)+ } else if data.starts_with(&[0, 0, 1]) {+ data.get(3)+ } else {+ return false;+ };+ matches!(nal.map(|b| b & 0x1f), Some(7) | Some(8))+}++struct HardwareMft {+ transform: IMFTransform,+ name: String,+}++fn enumerate_hardware_h264() -> Result<Vec<HardwareMft>, StreamError> {+ mf_startup()?;+ let output = MFT_REGISTER_TYPE_INFO {+ guidMajorType: MFMediaType_Video,+ guidSubtype: MFVideoFormat_H264,+ };+ let mut list: *mut Option<IMFActivate> = std::ptr::null_mut();+ let mut count: u32 = 0;+ unsafe {+ MFTEnumEx(+ MFT_CATEGORY_VIDEO_ENCODER,+ MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER,+ None,+ Some(&output),+ &mut list,+ &mut count,+ )+ .map_err(|e| enc_err("MFTEnumEx", e))?;+ }+ let mut found = Vec::new();+ for i in 0..count as isize {+ let activate = unsafe { (*list.offset(i)).clone() };+ let Some(activate) = activate else { continue };+ let name = read_friendly_name(&activate);+ if let Ok(transform) = unsafe { activate.ActivateObject::<IMFTransform>() } {+ found.push(HardwareMft { transform, name });+ }+ }+ if !list.is_null() {+ unsafe { CoTaskMemFree(Some(list as *const std::ffi::c_void)) };+ }+ Ok(found)+}++fn read_friendly_name(activate: &IMFActivate) -> String {+ let mut ptr = windows::core::PWSTR::null();+ let mut len: u32 = 0;+ let ok =+ unsafe { activate.GetAllocatedString(&MFT_FRIENDLY_NAME_Attribute, &mut ptr, &mut len) };+ if ok.is_err() || ptr.is_null() {+ return "Media Foundation".into();+ }+ let name = unsafe { ptr.to_string() }.unwrap_or_else(|_| "Media Foundation".into());+ unsafe { CoTaskMemFree(Some(ptr.0 as *const std::ffi::c_void)) };+ name+}++/// True when at least one vendor-neutral hardware H.264 MFT (Intel QSV, AMD+/// VCN or NVIDIA through Media Foundation) can be activated on this machine.+pub fn hardware_h264_available() -> bool {+ match enumerate_hardware_h264() {+ Ok(list) => !list.is_empty(),+ Err(_) => false,+ }+}++pub struct MfEncoder {+ shared: Arc<Shared>,+ codec_api: Option<CodecApi>,+ converter: Mutex<Option<Nv12Converter>>,+ gpu: Arc<Gpu>,+ dxgi_manager: Option<DxgiManager>,+ cfg: EncoderConfig,+ name: String,+ finished: AtomicBool,+}++struct CodecApi(ICodecAPI);+// SAFETY: ICodecAPI on an encoder MFT is free-threaded; every use here is a+// simple property set.+unsafe impl Send for CodecApi {}+unsafe impl Sync for CodecApi {}++struct DxgiManager(#[allow(dead_code)] IMFDXGIDeviceManager);+// SAFETY: the manager is only held to keep the D3D device alive for the MFT.+unsafe impl Send for DxgiManager {}+unsafe impl Sync for DxgiManager {}++impl MfEncoder {+ pub fn new(+ cfg: EncoderConfig,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ ) -> Result<Self, StreamError> {+ let gpu = gpu().map_err(|e| StreamError::Encoder(e.to_string()))?;+ let candidates = enumerate_hardware_h264()?;+ if candidates.is_empty() {+ return Err(StreamError::Encoder(+ "no hardware H.264 encoder is registered with Media Foundation".into(),+ ));+ }+ let mut last: Option<StreamError> = None;+ for candidate in candidates {+ match Self::configure(&candidate, &cfg, &gpu, source.clone(), counters.clone()) {+ Ok(enc) => return Ok(enc),+ Err(e) => {+ tracing::debug!(+ "[omnidisc-media] hardware encoder '{}' unusable: {e}",+ candidate.name+ );+ last = Some(e);+ }+ }+ }+ Err(last.unwrap_or_else(|| {+ StreamError::Encoder("no hardware H.264 encoder could be configured".into())+ }))+ }++ fn configure(+ mft: &HardwareMft,+ cfg: &EncoderConfig,+ gpu: &Arc<Gpu>,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ ) -> Result<Self, StreamError> {+ let transform = mft.transform.clone();+ let attributes = unsafe { transform.GetAttributes() }+ .map_err(|e| enc_err("IMFTransform::GetAttributes", e))?;+ let is_async = unsafe { attributes.GetUINT32(&MF_TRANSFORM_ASYNC) }.unwrap_or(0) == 1;+ if is_async {+ unsafe {+ attributes+ .SetUINT32(&MF_TRANSFORM_ASYNC_UNLOCK, 1)+ .map_err(|e| enc_err("MF_TRANSFORM_ASYNC_UNLOCK", e))?;+ }+ }+ let _ = unsafe { attributes.SetUINT32(&MF_LOW_LATENCY, 1) };++ let d3d_aware = unsafe { attributes.GetUINT32(&MF_SA_D3D11_AWARE) }.unwrap_or(0) == 1;+ let mut dxgi_manager = None;+ if d3d_aware {+ match Self::attach_d3d(&transform, gpu) {+ Ok(m) => dxgi_manager = Some(DxgiManager(m)),+ Err(e) => tracing::debug!("[omnidisc-media] D3D11 hand-off refused: {e}"),+ }+ }++ let bps = cfg.bitrate_kbps.max(1) * 1000;+ let out_type =+ unsafe { MFCreateMediaType() }.map_err(|e| enc_err("MFCreateMediaType", e))?;+ unsafe {+ out_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video).ok();+ out_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_H264).ok();+ out_type.SetUINT32(&MF_MT_AVG_BITRATE, bps).ok();+ out_type+ .SetUINT64(&MF_MT_FRAME_SIZE, pack2(cfg.width, cfg.height))+ .ok();+ out_type+ .SetUINT64(&MF_MT_FRAME_RATE, pack2(cfg.fps.max(1) as u32, 1))+ .ok();+ out_type+ .SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)+ .ok();+ out_type+ .SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, pack2(1, 1))+ .ok();+ out_type+ .SetUINT32(+ &MF_MT_MPEG2_PROFILE,+ if cfg.mode == StreamMode::Game {+ eAVEncH264VProfile_Main.0 as u32+ } else {+ eAVEncH264VProfile_High.0 as u32+ },+ )+ .ok();+ transform+ .SetOutputType(0, &out_type, 0)+ .map_err(|e| enc_err("SetOutputType(H264)", e))?;+ }++ let in_type =+ unsafe { MFCreateMediaType() }.map_err(|e| enc_err("MFCreateMediaType", e))?;+ unsafe {+ in_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video).ok();+ in_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_NV12).ok();+ in_type+ .SetUINT64(&MF_MT_FRAME_SIZE, pack2(cfg.width, cfg.height))+ .ok();+ in_type+ .SetUINT64(&MF_MT_FRAME_RATE, pack2(cfg.fps.max(1) as u32, 1))+ .ok();+ in_type+ .SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)+ .ok();+ in_type+ .SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, pack2(1, 1))+ .ok();+ transform+ .SetInputType(0, &in_type, 0)+ .map_err(|e| enc_err("SetInputType(NV12)", e))?;+ }++ let codec_api = transform.cast::<ICodecAPI>().ok().map(CodecApi);+ if let Some(api) = codec_api.as_ref() {+ unsafe {+ let _ = api.0.SetValue(&CODECAPI_AVLowLatencyMode, &var_bool(true));+ let _ = api.0.SetValue(+ &CODECAPI_AVEncCommonRateControlMode,+ &var_u32(eAVEncCommonRateControlMode_CBR.0 as u32),+ );+ let _ = api+ .0+ .SetValue(&CODECAPI_AVEncCommonMeanBitRate, &var_u32(bps));+ let _ = api+ .0+ .SetValue(&CODECAPI_AVEncMPVGOPSize, &var_u32(KEYFRAME_INTERVAL));+ }+ }++ let provides_samples = unsafe { transform.GetOutputStreamInfo(0) }+ .map(|info| {+ info.dwFlags+ & windows::Win32::Media::MediaFoundation::MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0+ as u32+ != 0+ })+ .unwrap_or(false);++ if !provides_samples {+ return Err(StreamError::Encoder(format!(+ "the '{}' encoder wants the caller to allocate output samples, which this build does not do",+ mft.name+ )));+ }+ let seq_header = read_sequence_header(&transform);++ let generator = transform+ .cast::<IMFMediaEventGenerator>()+ .map_err(|e| enc_err("IMFMediaEventGenerator (encoder is not asynchronous)", e))?;++ unsafe {+ transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)+ .map_err(|e| enc_err("NOTIFY_BEGIN_STREAMING", e))?;+ transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)+ .map_err(|e| enc_err("NOTIFY_START_OF_STREAM", e))?;+ }++ let shared = Arc::new(Shared {+ transform,+ generator,+ source,+ counters: counters.clone(),+ width: cfg.width,+ height: cfg.height,+ io: Mutex::new(()),+ pending: Mutex::new(Pending {+ hungry: 0,+ queue: VecDeque::with_capacity(QUEUE_DEPTH),+ }),+ callback: Mutex::new(None),+ seq_header: Mutex::new(seq_header),+ stopping: AtomicBool::new(false),+ in_flight: Mutex::new(VecDeque::with_capacity(8)),+ });+ let callback: IMFAsyncCallback = EventCallback {+ shared: Arc::downgrade(&shared),+ }+ .into();+ if let Ok(mut slot) = shared.callback.lock() {+ *slot = Some(callback.clone());+ }+ unsafe {+ shared+ .generator+ .BeginGetEvent(&callback, None)+ .map_err(|e| enc_err("BeginGetEvent", e))?;+ }+ counters.applied_bps.store(bps as u64, Ordering::Relaxed);+ Ok(Self {+ shared,+ codec_api,+ converter: Mutex::new(None),+ gpu: gpu.clone(),+ dxgi_manager,+ cfg: *cfg,+ name: format!("Media Foundation ({})", mft.name),+ finished: AtomicBool::new(false),+ })+ }++ fn attach_d3d(+ transform: &IMFTransform,+ gpu: &Arc<Gpu>,+ ) -> Result<IMFDXGIDeviceManager, StreamError> {+ let mut token: u32 = 0;+ let mut manager: Option<IMFDXGIDeviceManager> = None;+ unsafe {+ MFCreateDXGIDeviceManager(&mut token, &mut manager)+ .map_err(|e| enc_err("MFCreateDXGIDeviceManager", e))?;+ }+ let manager =+ manager.ok_or_else(|| StreamError::Encoder("no DXGI device manager".into()))?;+ unsafe {+ manager+ .ResetDevice(gpu.device(), token)+ .map_err(|e| enc_err("IMFDXGIDeviceManager::ResetDevice", e))?;+ transform+ .ProcessMessage(MFT_MESSAGE_SET_D3D_MANAGER, manager.as_raw() as usize)+ .map_err(|e| enc_err("MFT_MESSAGE_SET_D3D_MANAGER", e))?;+ }+ Ok(manager)+ }++ fn sample_from(+ &self,+ nv12: &ID3D11Texture2D,+ capture_us: i64,+ ) -> Result<IMFSample, StreamError> {+ let sample = unsafe { MFCreateSample() }.map_err(|e| enc_err("MFCreateSample", e))?;+ let buffer = if self.dxgi_manager.is_some() {+ let buffer = unsafe {+ MFCreateDXGISurfaceBuffer(&ID3D11Texture2D::IID, nv12, 0, false)+ .map_err(|e| enc_err("MFCreateDXGISurfaceBuffer", e))?+ };+ let len = buffer+ .cast::<IMF2DBuffer>()+ .ok()+ .and_then(|b| unsafe { b.GetContiguousLength() }.ok())+ .unwrap_or(self.cfg.width * self.cfg.height * 3 / 2);+ unsafe {+ let _ = buffer.SetCurrentLength(len);+ }+ buffer+ } else {+ let mut converter = self+ .converter+ .lock()+ .map_err(|_| StreamError::Encoder("converter poisoned".into()))?;+ let cpu = converter+ .as_mut()+ .ok_or_else(|| StreamError::Encoder("no converter".into()))?+ .read_back(nv12)?;+ let tight = (self.cfg.width * self.cfg.height * 3 / 2) as usize;+ let buffer = unsafe { MFCreateMemoryBuffer(tight as u32) }+ .map_err(|e| enc_err("MFCreateMemoryBuffer", e))?;+ let mut data: *mut u8 = std::ptr::null_mut();+ unsafe {+ buffer+ .Lock(&mut data, None, None)+ .map_err(|e| enc_err("IMFMediaBuffer::Lock", e))?;+ let (y, uv) = cpu.planes();+ for row in 0..self.cfg.height as usize {+ let src = row * cpu.stride_y as usize;+ let dst = row * self.cfg.width as usize;+ if src + self.cfg.width as usize <= y.len() {+ std::ptr::copy_nonoverlapping(+ y.as_ptr().add(src),+ data.add(dst),+ self.cfg.width as usize,+ );+ }+ }+ let uv_base = (self.cfg.width * self.cfg.height) as usize;+ for row in 0..(self.cfg.height / 2) as usize {+ let src = row * cpu.stride_uv as usize;+ let dst = uv_base + row * self.cfg.width as usize;+ if src + self.cfg.width as usize <= uv.len() {+ std::ptr::copy_nonoverlapping(+ uv.as_ptr().add(src),+ data.add(dst),+ self.cfg.width as usize,+ );+ }+ }+ let _ = buffer.Unlock();+ let _ = buffer.SetCurrentLength(tight as u32);+ }+ buffer+ };+ unsafe {+ sample+ .AddBuffer(&buffer)+ .map_err(|e| enc_err("IMFSample::AddBuffer", e))?;+ let _ = sample.SetSampleTime(capture_us * 10);+ let _ = sample.SetSampleDuration(10_000_000i64 / self.cfg.fps.max(1) as i64);+ }+ Ok(sample)+ }++ pub fn encode(&self, frame: &CapturedFrame, force_key: bool) -> Result<(), StreamError> {+ let Some(texture) = frame.texture() else {+ return Err(StreamError::Encoder("captured frame has no texture".into()));+ };+ let nv12 = {+ let mut slot = self+ .converter+ .lock()+ .map_err(|_| StreamError::Encoder("converter poisoned".into()))?;+ let needs_new = match slot.as_ref() {+ Some(c) => c.size() != (self.cfg.width, self.cfg.height),+ None => true,+ };+ if needs_new {+ *slot = Some(Nv12Converter::new(+ self.gpu.clone(),+ frame.width(),+ frame.height(),+ self.cfg.width,+ self.cfg.height,+ )?);+ }+ slot.as_mut()+ .ok_or_else(|| StreamError::Encoder("no converter".into()))?+ .convert(texture)?+ };+ if force_key {+ if let Some(api) = self.codec_api.as_ref() {+ unsafe {+ let _ = api+ .0+ .SetValue(&CODECAPI_AVEncVideoForceKeyFrame, &var_u32(1));+ }+ }+ }+ let sample = self.sample_from(&nv12, frame.capture_us())?;+ let submitted = Instant::now();+ let hungry = {+ let Ok(mut pending) = self.shared.pending.lock() else {+ return Err(StreamError::Encoder("encoder queue poisoned".into()));+ };+ if pending.hungry > 0 {+ pending.hungry -= 1;+ true+ } else {+ while pending.queue.len() >= QUEUE_DEPTH {+ pending.queue.pop_front();+ self.shared.counters.dropped.fetch_add(1, Ordering::Relaxed);+ }+ pending.queue.push_back((sample.clone(), submitted));+ false+ }+ };+ if hungry {+ self.shared.submit(sample, submitted);+ }+ Ok(())+ }++ pub fn set_bitrate(&self, bps: u64) {+ if let Some(api) = self.codec_api.as_ref() {+ unsafe {+ let _ = api+ .0+ .SetValue(&CODECAPI_AVEncCommonMeanBitRate, &var_u32(bps as u32));+ }+ }+ self.shared+ .counters+ .applied_bps+ .store(bps, Ordering::Relaxed);+ }++ pub fn set_framerate(&self, _fps: u16) {}++ pub fn hardware(&self) -> Option<bool> {+ Some(true)+ }++ pub fn name(&self) -> &str {+ &self.name+ }++ pub fn finish(&self) {+ if self.finished.swap(true, Ordering::AcqRel) {+ return;+ }+ self.shared.stopping.store(true, Ordering::Release);+ let _guard = self.shared.io.lock();+ unsafe {+ let _ = self+ .shared+ .transform+ .ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);+ let _ = self+ .shared+ .transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);+ let _ = self+ .shared+ .transform+ .ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0);+ }+ if let Ok(mut slot) = self.shared.callback.lock() {+ *slot = None;+ }+ }+}++impl Drop for MfEncoder {+ fn drop(&mut self) {+ self.finish();+ }+}++fn read_sequence_header(transform: &IMFTransform) -> Vec<u8> {+ let Ok(media_type): Result<IMFMediaType, _> = (unsafe { transform.GetOutputCurrentType(0) })+ else {+ return Vec::new();+ };+ let mut ptr: *mut u8 = std::ptr::null_mut();+ let mut len: u32 = 0;+ let ok =+ unsafe { media_type.GetAllocatedBlob(&MF_MT_MPEG_SEQUENCE_HEADER, &mut ptr, &mut len) };+ if ok.is_err() || ptr.is_null() || len == 0 {+ return Vec::new();+ }+ let out = unsafe { std::slice::from_raw_parts(ptr, len as usize) }.to_vec();+ unsafe { CoTaskMemFree(Some(ptr as *const std::ffi::c_void)) };+ out+}diff --git a/src-tauri/omnidisc-media/src/encode/windows/mod.rs b/src-tauri/omnidisc-media/src/encode/windows/mod.rsnew file mode 100644index 00000000..2f77b238--- /dev/null+++ b/src-tauri/omnidisc-media/src/encode/windows/mod.rs@@ -0,0 +1,111 @@+mod mf;+mod raw;++use super::{EncoderConfig, EncoderCounters, PublishPath};+use crate::capture::CapturedFrame;+use crate::stream::{StreamCodec, StreamError};+use livekit::webrtc::video_source::native::NativeVideoSource;+use std::sync::{Arc, OnceLock};++/// Windows publishes H.264 only: the Media Foundation encoder wired here is+/// H.264, and libwebrtc's Windows build has no HEVC encoder for the raw path.+pub fn clamp_codec(codec: StreamCodec) -> StreamCodec {+ if codec != StreamCodec::H264 {+ tracing::info!("[omnidisc-media] {codec:?} is not encodable on Windows; using H.264");+ }+ StreamCodec::H264+}++fn forced_path() -> Option<PublishPath> {+ match std::env::var("OMNIDISC_WIN_ENCODER")+ .unwrap_or_default()+ .to_ascii_lowercase()+ .as_str()+ {+ "raw" | "libwebrtc" | "software" => Some(PublishPath::Raw),+ "mf" | "mediafoundation" | "hardware" => Some(PublishPath::PreEncoded),+ _ => None,+ }+}++fn hardware_present() -> bool {+ static AVAILABLE: OnceLock<bool> = OnceLock::new();+ *AVAILABLE.get_or_init(mf::hardware_h264_available)+}++pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {+ if let Some(forced) = forced_path() {+ return forced;+ }+ if hardware_present() {+ PublishPath::PreEncoded+ } else {+ PublishPath::Raw+ }+}++pub enum VideoEncoder {+ Mf(mf::MfEncoder),+ Raw(raw::RawEncoder),+}++impl VideoEncoder {+ pub fn new(+ cfg: EncoderConfig,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ ) -> Result<Self, StreamError> {+ match publish_path(&cfg) {+ PublishPath::PreEncoded => mf::MfEncoder::new(cfg, source, counters)+ .map(VideoEncoder::Mf)+ .map_err(|e| {+ StreamError::Encoder(format!(+ "{e}; set OMNIDISC_WIN_ENCODER=raw to publish through the software encoder instead"+ ))+ }),+ PublishPath::Raw => raw::RawEncoder::new(cfg, source, counters).map(VideoEncoder::Raw),+ }+ }++ pub fn encode(&self, frame: &CapturedFrame, force_key: bool) -> Result<(), StreamError> {+ match self {+ Self::Mf(e) => e.encode(frame, force_key),+ Self::Raw(e) => e.encode(frame, force_key),+ }+ }++ pub fn set_bitrate(&self, bps: u64) {+ match self {+ Self::Mf(e) => e.set_bitrate(bps),+ Self::Raw(e) => e.set_bitrate(bps),+ }+ }++ pub fn set_framerate(&self, fps: u16) {+ match self {+ Self::Mf(e) => e.set_framerate(fps),+ Self::Raw(e) => e.set_framerate(fps),+ }+ }++ pub fn hardware(&self) -> Option<bool> {+ match self {+ Self::Mf(e) => e.hardware(),+ Self::Raw(e) => e.hardware(),+ }+ }++ pub fn name(&self) -> &str {+ match self {+ Self::Mf(e) => e.name(),+ Self::Raw(e) => e.name(),+ }+ }++ pub fn finish(&self) {+ match self {+ Self::Mf(e) => e.finish(),+ Self::Raw(e) => e.finish(),+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/encode/windows/raw.rs b/src-tauri/omnidisc-media/src/encode/windows/raw.rsnew file mode 100644index 00000000..a1ec284f--- /dev/null+++ b/src-tauri/omnidisc-media/src/encode/windows/raw.rs@@ -0,0 +1,133 @@+use crate::capture::{gpu, CapturedFrame, Gpu, Nv12Converter};+use crate::encode::{EncoderConfig, EncoderCounters};+use crate::stream::StreamError;+use livekit::webrtc::video_frame::{NV12Buffer, VideoFrame, VideoRotation};+use livekit::webrtc::video_source::native::NativeVideoSource;+use std::sync::atomic::Ordering;+use std::sync::{Arc, Mutex};+use std::time::Instant;++/// Publishes raw NV12 frames and lets libwebrtc pick the encoder. This is the+/// path Windows uses when no hardware Media Foundation H.264 MFT is available:+/// slower and software-bound, but it always produces a working share.+pub struct RawEncoder {+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ converter: Mutex<Option<Nv12Converter>>,+ gpu: Arc<Gpu>,+ cfg: EncoderConfig,+}++impl RawEncoder {+ pub fn new(+ cfg: EncoderConfig,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ ) -> Result<Self, StreamError> {+ let gpu = gpu().map_err(|e| StreamError::Encoder(e.to_string()))?;+ counters+ .applied_bps+ .store(cfg.bitrate_kbps as u64 * 1000, Ordering::Relaxed);+ Ok(Self {+ source,+ counters,+ converter: Mutex::new(None),+ gpu,+ cfg,+ })+ }++ pub fn encode(&self, frame: &CapturedFrame, _force_key: bool) -> Result<(), StreamError> {+ let Some(texture) = frame.texture() else {+ return Err(StreamError::Encoder("captured frame has no texture".into()));+ };+ let started = Instant::now();+ let mut slot = self+ .converter+ .lock()+ .map_err(|_| StreamError::Encoder("converter poisoned".into()))?;+ let needs_new = match slot.as_ref() {+ Some(c) => c.size() != (self.cfg.width, self.cfg.height),+ None => true,+ };+ if needs_new {+ *slot = Some(Nv12Converter::new(+ self.gpu.clone(),+ frame.width(),+ frame.height(),+ self.cfg.width,+ self.cfg.height,+ )?);+ }+ let converter = slot+ .as_mut()+ .ok_or_else(|| StreamError::Encoder("no converter".into()))?;+ let nv12 = converter.convert(texture)?;+ let cpu = converter.read_back(&nv12)?;+ drop(slot);++ let mut buffer = NV12Buffer::with_strides(+ self.cfg.width,+ self.cfg.height,+ self.cfg.width,+ self.cfg.width,+ );+ {+ let (dst_y, dst_uv) = buffer.data_mut();+ let (src_y, src_uv) = cpu.planes();+ let w = self.cfg.width as usize;+ for row in 0..self.cfg.height as usize {+ let src = row * cpu.stride_y as usize;+ let dst = row * w;+ if src + w <= src_y.len() && dst + w <= dst_y.len() {+ dst_y[dst..dst + w].copy_from_slice(&src_y[src..src + w]);+ }+ }+ for row in 0..(self.cfg.height / 2) as usize {+ let src = row * cpu.stride_uv as usize;+ let dst = row * w;+ if src + w <= src_uv.len() && dst + w <= dst_uv.len() {+ dst_uv[dst..dst + w].copy_from_slice(&src_uv[src..src + w]);+ }+ }+ }+ let video = VideoFrame {+ rotation: VideoRotation::VideoRotation0,+ timestamp_us: frame.capture_us(),+ frame_metadata: None,+ buffer,+ };+ self.source.capture_frame(&video);+ self.counters.submitted.fetch_add(1, Ordering::Relaxed);+ self.counters.encoded.fetch_add(1, Ordering::Relaxed);+ self.counters.captured_ok.fetch_add(1, Ordering::Relaxed);+ let latency = started.elapsed().as_nanos() as u64;+ self.counters+ .latency_ns_sum+ .fetch_add(latency, Ordering::Relaxed);+ self.counters+ .latency_ns_max+ .fetch_max(latency, Ordering::Relaxed);+ Ok(())+ }++ pub fn set_bitrate(&self, bps: u64) {+ // libwebrtc owns rate control on this path; record what was asked so the+ // debug panel does not claim a number we never applied.+ self.counters.applied_bps.store(bps, Ordering::Relaxed);+ }++ pub fn set_framerate(&self, _fps: u16) {}++ /// Unknown until the SDK reports `encoder_implementation`; never claim+ /// hardware we did not select ourselves.+ pub fn hardware(&self) -> Option<bool> {+ None+ }++ pub fn name(&self) -> &str {+ "libwebrtc"+ }++ pub fn finish(&self) {}+}diff --git a/src-tauri/omnidisc-media/src/livekit_backend.rs b/src-tauri/omnidisc-media/src/livekit_backend.rsindex b3f4058e..cbcf9e54 100644--- a/src-tauri/omnidisc-media/src/livekit_backend.rs+++ b/src-tauri/omnidisc-media/src/livekit_backend.rs@@ -198,12 +198,50 @@ fn map_io_error(e: &AudioIoError, kind: DeviceKind) -> String {/// system default, and only then give up — a USB mic that was yanked and put/// back must not need a rejoin, and a permission the user revoked must not look/// like a broken app.-fn recover(shared: &Arc<Shared>, kind: DeviceKind) {+fn recover(shared: &Arc<Shared>, kind: DeviceKind, message: String) {const BACKOFF_MS: [u64; 3] = [250, 1_000, 3_000];let wanted = match kind {DeviceKind::Input => shared.input_device(),DeviceKind::Output => shared.output_device(),};+ // Long enough for the failing callback to unwind before its stream is+ // dropped, short enough that nobody sees it.+ std::thread::sleep(Duration::from_millis(50));+ if !shared.still_wanted(kind) {+ return;+ }+ // One silent attempt before saying anything. Windows invalidates the stream+ // handle whenever the default endpoint changes — switching headphones in+ // the tray is a routine action, and it must not flash "microphone lost" at+ // someone who is mid-sentence.+ let reopened = match kind {+ DeviceKind::Input => shared.io.start_input(wanted.clone()),+ DeviceKind::Output => shared.io.start_output(wanted.clone()),+ };+ if reopened.is_ok() {+ match kind {+ DeviceKind::Input => shared.input_running.store(true, Ordering::Release),+ DeviceKind::Output => shared.output_running.store(true, Ordering::Release),+ }+ tracing::debug!(+ "[omnidisc-media] the {:?} device came back immediately after: {}",+ kind,+ message+ );+ return;+ }+ shared.emit(EngineNotification::Error {+ code: match kind {+ DeviceKind::Input => "ERR_VOICE_MIC_LOST".into(),+ DeviceKind::Output => "ERR_VOICE_OUTPUT_LOST".into(),+ },+ message,+ });+ shared.emit(EngineNotification::Device {+ kind,+ status: DeviceStatus::Lost,+ cause: None,+ });for (attempt, wait) in BACKOFF_MS.iter().enumerate() {std::thread::sleep(Duration::from_millis(*wait));if !shared.still_wanted(kind) {@@ -337,7 +375,7 @@ impl LiveKitBackend {let feeder =Arc::new(Feeder::spawn(flags.clone(), capture_sink).map_err(MediaError::Device)?);let fault_slot = shared_slot.clone();- let fault_sink: crate::audio::io::FaultSink = Arc::new(move |fault, message| {+ let fault_sink: crate::audio::io::FaultSink = Arc::new(move |fault, error| {let Some(shared) = fault_slot.lock().ok()@@ -345,6 +383,11 @@ impl LiveKitBackend {else {return;};+ if !error.fatal() {+ tracing::debug!("[omnidisc-media] audio glitch on {:?}: {}", fault, error);+ return;+ }+ let message = error.to_string();tracing::warn!("[omnidisc-media] audio stream fault {:?}: {}",fault,@@ -353,26 +396,13 @@ impl LiveKitBackend {let kind = match fault {StreamFault::Input => {shared.input_running.store(false, Ordering::Release);- shared.emit(EngineNotification::Error {- code: "ERR_VOICE_MIC_LOST".into(),- message,- });DeviceKind::Input}StreamFault::Output => {shared.output_running.store(false, Ordering::Release);- shared.emit(EngineNotification::Error {- code: "ERR_VOICE_OUTPUT_LOST".into(),- message,- });DeviceKind::Output}};- shared.emit(EngineNotification::Device {- kind,- status: DeviceStatus::Lost,- cause: None,- });// The cpal error callback runs on the device thread: re-opening a// device from here would deadlock the very thread that has to answer.if shared.recovering(kind).swap(true, Ordering::AcqRel) {@@ -382,7 +412,7 @@ impl LiveKitBackend {if std::thread::Builder::new().name("omnidisc-audio-recovery".into()).spawn(move || {- recover(&worker, kind);+ recover(&worker, kind, message);worker.recovering(kind).store(false, Ordering::Release);}).is_err()diff --git a/src-tauri/omnidisc-media/src/streaming.rs b/src-tauri/omnidisc-media/src/streaming.rsindex 36af4524..c2d77355 100644--- a/src-tauri/omnidisc-media/src/streaming.rs+++ b/src-tauri/omnidisc-media/src/streaming.rs@@ -1,5 +1,5 @@use crate::capture::{self, AudioSink, CaptureOptions, CapturedFrame, VideoSink, VideoTick};-use crate::encode::{EncoderConfig, EncoderCounters, VideoEncoder};+use crate::encode::{self, EncoderConfig, EncoderCounters, PublishPath, VideoEncoder};use crate::livekit_backend::LiveKitBackend;use crate::stream::{resolve_bitrate, AudioMode, PublishStats, ResolvedStream, StreamCodec, StreamError, StreamMode,@@ -142,6 +142,7 @@ struct AudioPublish {capture: capture::AudioCapture,_track: LocalAudioTrack,publication: LocalTrackPublication,+ mode: AudioMode,}pub struct ActiveStream {@@ -205,7 +206,7 @@ pub async fn start_stream(let (video_capture, geometry) = capture::start_video(&opts, vsink)?;let (width, height) = (geometry.width, geometry.height);- let codec = codec_from_policy(&req.policy, height, req.fps);+ let codec = encode::clamp_codec(codec_from_policy(&req.policy, height, req.fps));let bitrate = resolve_bitrate(&req.policy,width,@@ -215,6 +216,15 @@ pub async fn start_stream(req.bitrate_kbps,);let configured_bps = bitrate as u64 * 1000;+ let cfg = EncoderConfig {+ width,+ height,+ fps: req.fps,+ codec,+ bitrate_kbps: bitrate,+ mode: req.mode,+ };+ let path = encode::publish_path(&cfg);let resolved = ResolvedStream {width,height,@@ -225,7 +235,11 @@ pub async fn start_stream(audio: req.audio,};- let source = NativeVideoSource::new_encoded(VideoResolution { width, height });+ let resolution = VideoResolution { width, height };+ let source = match path {+ PublishPath::PreEncoded => NativeVideoSource::new_encoded(resolution),+ PublishPath::Raw => NativeVideoSource::new(resolution, true),+ };let track = LocalVideoTrack::create_video_track("omnidisc-screen",RtcVideoSource::Native(source.clone()),@@ -242,7 +256,10 @@ pub async fn start_stream(source: TrackSource::Screenshare,video_codec: to_video_codec(codec),simulcast: false,- video_encoder: VideoEncoderBackend::PreEncoded,+ video_encoder: match path {+ PublishPath::PreEncoded => VideoEncoderBackend::PreEncoded,+ PublishPath::Raw => VideoEncoderBackend::Auto,+ },video_encoding: Some(VideoEncoding {max_bitrate: configured_bps,max_framerate: req.fps as f64,@@ -257,27 +274,21 @@ pub async fn start_stream(// S-07 §5.1: prime the sender with raw frames so the pass-through selector// switches before the first encoded frame (otherwise it segfaults on macOS).- for _ in 0..PRIMER_FRAMES {- let black = VideoFrame {- rotation: VideoRotation::VideoRotation0,- timestamp_us: 0,- frame_metadata: None,- buffer: I420Buffer::new_black(width, height),- };- source.capture_frame(&black);- tokio::time::sleep(Duration::from_millis(PRIMER_INTERVAL_MS)).await;+ if path == PublishPath::PreEncoded {+ for _ in 0..PRIMER_FRAMES {+ let black = VideoFrame {+ rotation: VideoRotation::VideoRotation0,+ timestamp_us: 0,+ frame_metadata: None,+ buffer: I420Buffer::new_black(width, height),+ };+ source.capture_frame(&black);+ tokio::time::sleep(Duration::from_millis(PRIMER_INTERVAL_MS)).await;+ }+ tokio::time::sleep(Duration::from_millis(PRIMER_INTERVAL_MS * 2)).await;}- tokio::time::sleep(Duration::from_millis(PRIMER_INTERVAL_MS * 2)).await;let counters = Arc::new(EncoderCounters::default());- let cfg = EncoderConfig {- width,- height,- fps: req.fps,- codec,- bitrate_kbps: bitrate,- mode: req.mode,- };let encoder = Arc::new(VideoEncoder::new(cfg, source.clone(), counters.clone())?);let encode_loop = EncodeLoop::spawn(encoder.clone(),@@ -291,6 +302,10 @@ pub async fn start_stream(}let audio = start_screenshare_audio(&room, req.audio).await;+ // Report the mode actually obtained, not the one asked for: the capture+ // side degrades per-app -> system-except-us -> none on its own.+ let mut resolved = resolved;+ resolved.audio = audio.as_ref().map(|a| a.mode).unwrap_or(AudioMode::None);Ok(ActiveStream {resolved,@@ -373,6 +388,7 @@ async fn start_screenshare_audio(room: &Arc<Room>, mode: AudioMode) -> Option<Aucapture: capture_handle,_track: track,publication: pub_,+ mode: obtained,}),Err(e) => {tracing::warn!("[omnidisc-media] publish screenshare audio: {e}");@@ -446,7 +462,12 @@ fn apply_outbound(stats: &mut PublishStats, rtc: &[RtcStats]) {RtcStats::OutboundRtp(o) if o.stream.kind == "video" => {stats.fps_sent = o.outbound.frames_per_second;stats.target_kbps = o.outbound.target_bitrate / 1000.0;- stats.encoder = o.outbound.encoder_implementation.clone();+ // On the pass-through the SDK only knows "passthrough"; the+ // encoder that actually ran is ours, so keep our name.+ let reported = &o.outbound.encoder_implementation;+ if !reported.is_empty() && !reported.to_lowercase().contains("passthrough") {+ stats.encoder = reported.clone();+ }stats.quality_limitation = format!("{:?}", o.outbound.quality_limitation_reason);if let Some(m) = mimes.get(&o.stream.codec_id) {if m.contains("265") || m.to_lowercase().contains("hevc") {diff --git a/src-tauri/omnidisc-media/src/viewer/mod.rs b/src-tauri/omnidisc-media/src/viewer/mod.rsindex 197c5739..f52295de 100644--- a/src-tauri/omnidisc-media/src/viewer/mod.rs+++ b/src-tauri/omnidisc-media/src/viewer/mod.rs@@ -2,7 +2,7 @@ mod wgpu_surface;pub use wgpu_surface::{FrameSlot, Planes, WgpuViewer};-#[cfg(target_os = "macos")]+#[cfg(any(target_os = "macos", target_os = "windows"))]use crate::stream::StreamError;use crate::stream::{Viewport, WatchStats};use futures::StreamExt;@@ -62,6 +62,47 @@ pub unsafe fn create_appkit_surface(WgpuViewer::from_surface(instance, surface, width, height)}+/// Build the viewer surface from a Win32 window.+///+/// There is no layer ordering to fix here: WebView2 lives in its own child+/// `HWND` that DWM composes above the parent's swap chain, so the overlay is on+/// top by construction — unlike AppKit, where both are sibling `CALayer`s.+///+/// # Safety+///+/// `hwnd` must be a live window handle that stays alive for as long as the+/// returned [`WgpuViewer`], and this must be called from the thread that owns+/// that window — `raw-window-handle` requires it, and the swap chain is bound+/// to the window's message loop.+#[cfg(target_os = "windows")]+pub unsafe fn create_win32_surface(+ hwnd: isize,+ hinstance: isize,+ width: u32,+ height: u32,+) -> Result<Arc<WgpuViewer>, StreamError> {+ use raw_window_handle::{+ RawDisplayHandle, RawWindowHandle, Win32WindowHandle, WindowsDisplayHandle,+ };+ use std::num::NonZeroIsize;++ let hwnd = NonZeroIsize::new(hwnd).ok_or_else(|| StreamError::Viewer("null hwnd".into()))?;+ let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();+ desc.backends = wgpu::Backends::PRIMARY;+ let instance = wgpu::Instance::new(desc);+ let mut handle = Win32WindowHandle::new(hwnd);+ // Vulkan's `VkWin32SurfaceCreateInfoKHR` wants the module handle; DX12 does+ // not. Passing it keeps both backends usable instead of betting on DX12.+ handle.hinstance = NonZeroIsize::new(hinstance);+ let surface = instance+ .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {+ raw_display_handle: Some(RawDisplayHandle::Windows(WindowsDisplayHandle::new())),+ raw_window_handle: RawWindowHandle::Win32(handle),+ })+ .map_err(|e| StreamError::Viewer(format!("create_surface: {e}")))?;+ WgpuViewer::from_surface(instance, surface, width, height)+}+fn pack_i420(buf: &I420Buffer, full_range: bool) -> Planes {let (w, h) = (buf.width(), buf.height());let (cw, ch) = (buf.chroma_width(), buf.chroma_height());diff --git a/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rs b/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rsindex 04625f23..a03967be 100644--- a/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rs+++ b/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rs@@ -136,21 +136,35 @@ impl WgpuViewer {})).map_err(|e| StreamError::Viewer(format!("no gpu device: {e}")))?;let caps = surface.get_capabilities(&adapter);+ // An adapter that cannot present to this window answers with empty+ // lists instead of an error; indexing them would abort the app.+ let first_format = *caps.formats.first().ok_or_else(|| {+ StreamError::Viewer("this GPU cannot draw into the stream window".into())+ })?;let format = caps.formats.iter().copied().find(|f| !f.is_srgb())- .unwrap_or(caps.formats[0]);+ .unwrap_or(first_format);let config = wgpu::SurfaceConfiguration {usage: wgpu::TextureUsages::RENDER_ATTACHMENT,format,color_space: wgpu::SurfaceColorSpace::Auto,width: width.max(1),height: height.max(1),- present_mode: wgpu::PresentMode::Fifo,+ present_mode: caps+ .present_modes+ .iter()+ .copied()+ .find(|m| *m == wgpu::PresentMode::Fifo)+ .unwrap_or(wgpu::PresentMode::AutoVsync),desired_maximum_frame_latency: 2,- alpha_mode: caps.alpha_modes[0],+ alpha_mode: caps+ .alpha_modes+ .first()+ .copied()+ .unwrap_or(wgpu::CompositeAlphaMode::Auto),view_formats: vec![],};surface.configure(&device, &config);diff --git a/src-tauri/src/commands/omnidisc/ducking.rs b/src-tauri/src/commands/omnidisc/ducking.rsnew file mode 100644index 00000000..730097fc--- /dev/null+++ b/src-tauri/src/commands/omnidisc/ducking.rs@@ -0,0 +1,79 @@+//! Keep Windows from muffling everything else the moment a call starts.+//!+//! Windows attenuates every other application by ~80 % while a process holds a+//! communications stream. Nobody asks for it and nothing in the app explains+//! it: the user joins a voice channel and the music, the game and the video+//! they deliberately left playing all drop. OmniDisc already has its own+//! ducking (`omnidisc.voice.ducking_percent`), it applies to the call mix, and+//! it is off unless the user turns it on — the system's version is a second,+//! invisible one on top.+//!+//! `IAudioSessionControl2::SetDuckingPreference(TRUE)` opts this process out.+//! It has to be set before the communications stream opens, which is why this+//! runs when the voice engine starts rather than when a call begins.+//!+//! No-op everywhere else: macOS and Linux do not duck other applications.++/// Ask Windows not to duck other applications for us. Best effort: failing+/// only means the platform default stays, so it never blocks a call.+pub fn opt_out_of_system_ducking() {+ #[cfg(windows)]+ {+ if std::thread::Builder::new()+ .name("omnidisc-ducking".into())+ .spawn(|| match windows_impl::apply() {+ Ok(()) => {+ tracing::info!("[omnidisc] opted out of the Windows ducking of other apps")+ }+ Err(e) => tracing::warn!(+ "[omnidisc] could not opt out of the Windows ducking of other apps: {}",+ e+ ),+ })+ .is_err()+ {+ tracing::warn!("[omnidisc] could not start the ducking opt-out thread");+ }+ }+}++#[cfg(windows)]+mod windows_impl {+ use windows::core::Interface;+ use windows::Win32::Foundation::RPC_E_CHANGED_MODE;+ use windows::Win32::Media::Audio::{+ eConsole, eRender, IAudioSessionControl2, IAudioSessionManager2, IMMDeviceEnumerator,+ MMDeviceEnumerator,+ };+ use windows::Win32::System::Com::{+ CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED,+ };++ pub fn apply() -> windows::core::Result<()> {+ unsafe {+ // Tauri's main thread is an STA; this runs on its own thread, so an+ // MTA is free here. `RPC_E_CHANGED_MODE` would only mean someone+ // else already initialised it — still usable, just not ours to undo.+ let hr = CoInitializeEx(None, COINIT_MULTITHREADED);+ let owns_com = hr.is_ok();+ if hr.is_err() && hr != RPC_E_CHANGED_MODE {+ return Err(hr.into());+ }+ let result = set_preference();+ if owns_com {+ CoUninitialize();+ }+ result+ }+ }++ unsafe fn set_preference() -> windows::core::Result<()> {+ let enumerator: IMMDeviceEnumerator =+ CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?;+ let device = enumerator.GetDefaultAudioEndpoint(eRender, eConsole)?;+ let manager: IAudioSessionManager2 = device.Activate(CLSCTX_ALL, None)?;+ let session = manager.GetAudioSessionControl(None, 0)?;+ let session: IAudioSessionControl2 = session.cast()?;+ session.SetDuckingPreference(true)+ }+}diff --git a/src-tauri/src/commands/omnidisc/mod.rs b/src-tauri/src/commands/omnidisc/mod.rsindex 4ca4af0d..3addd81b 100644--- a/src-tauri/src/commands/omnidisc/mod.rs+++ b/src-tauri/src/commands/omnidisc/mod.rs@@ -1,6 +1,7 @@pub mod api;pub mod auth;pub mod device;+pub mod ducking;pub mod gateway;pub mod mls;pub mod store;diff --git a/src-tauri/src/commands/omnidisc/stream.rs b/src-tauri/src/commands/omnidisc/stream.rsindex dc740eb2..f31576bd 100644--- a/src-tauri/src/commands/omnidisc/stream.rs+++ b/src-tauri/src/commands/omnidisc/stream.rs@@ -53,6 +53,35 @@ fn emit_voice(let _ = app.emit(EVENT_VOICE, payload);}+/// What this build can actually do with media, so the interface never has to+/// guess from the platform name.+#[derive(Debug, Clone, Copy, serde::Serialize)]+pub struct MediaCapabilities {+ /// A voice backend was created at startup. False means calls are dead+ /// weight in the UI and the entry points should say so.+ pub voice: bool,+ /// Screen capture exists for this platform. Whether the user has granted+ /// the permission is a separate answer, and it belongs to the share dialog.+ pub screen_share: bool,+ /// Someone else's stream can be rendered into a window.+ pub stream_viewer: bool,+}++#[tauri::command]+pub async fn omnidisc_media_capabilities(+ state: tauri::State<'_, crate::AppState>,+) -> Result<MediaCapabilities, String> {+ // Deliberately not probed by calling into the capture layer: on macOS the+ // first enumeration is what raises the screen-recording prompt, and asking+ // for that permission before the user has asked to share anything is the+ // kind of thing that gets an app denied for good.+ Ok(MediaCapabilities {+ voice: state.omnidisc_voice.livekit_backend().is_some(),+ screen_share: cfg!(any(target_os = "macos", target_os = "windows")),+ stream_viewer: cfg!(any(target_os = "macos", target_os = "windows")),+ })+}+#[tauri::command]pub async fn omnidisc_stream_sources(state: tauri::State<'_, crate::AppState>,@@ -300,7 +329,16 @@ pub async fn omnidisc_stream_watch(.build().map_err(|e| format!("OmniDisc: could not open the stream window: {e}"))?;- let renderer = create_surface_on_main(&app, &window).await?;+ let renderer = match create_surface_on_main(&app, &window).await {+ Ok(r) => r,+ Err(e) => {+ // A window that cannot draw anything is worse than no window: it+ // looks like the stream is loading forever.+ let _ = window.close();+ publication.set_subscribed(false);+ return Err(e);+ }+ };let rt = backend.runtime_handle().ok_or_else(|| "ERR_VOICE_UNAVAILABLE".to_string())?;@@ -345,13 +383,45 @@ async fn create_surface_on_main(rx.await.map_err(|_| "OmniDisc: surface creation dropped".to_string())?}- #[cfg(not(target_os = "macos"))]+ #[cfg(target_os = "windows")]+ {+ let hwnd = window.hwnd().map_err(|e| format!("OmniDisc: hwnd: {e}"))?.0 as isize;+ let hinstance = window_hinstance(hwnd);+ let (w, h) = (size.width, size.height);+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.run_on_main_thread(move || {+ let result =+ unsafe { omnidisc_media::viewer::create_win32_surface(hwnd, hinstance, w, h) };+ let _ = tx.send(result.map_err(err));+ })+ .map_err(|e| format!("OmniDisc: main thread dispatch: {e}"))?;+ rx.await+ .map_err(|_| "OmniDisc: surface creation dropped".to_string())?+ }+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]{let _ = (app, window, size);Err(StreamError::Unsupported.code().to_string())}}+/// The module handle Vulkan asks for. DX12 ignores it, so a zero here only+/// costs the Vulkan backend, never the whole viewer.+#[cfg(target_os = "windows")]+fn window_hinstance(hwnd: isize) -> isize {+ #[cfg(target_pointer_width = "64")]+ {+ use windows::Win32::Foundation::HWND;+ use windows::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, GWLP_HINSTANCE};+ unsafe { GetWindowLongPtrW(HWND(hwnd as *mut std::ffi::c_void), GWLP_HINSTANCE) }+ }+ #[cfg(not(target_pointer_width = "64"))]+ {+ let _ = hwnd;+ 0+ }+}+#[tauri::command]pub async fn omnidisc_stream_unwatch(app: tauri::AppHandle,diff --git a/src-tauri/src/commands/omnidisc/voice.rs b/src-tauri/src/commands/omnidisc/voice.rsindex b4642426..9777e2fb 100644--- a/src-tauri/src/commands/omnidisc/voice.rs+++ b/src-tauri/src/commands/omnidisc/voice.rs@@ -228,6 +228,7 @@ pub fn start(app: &tauri::AppHandle) {if manager.started.swap(true, Ordering::AcqRel) {return;}+ super::ducking::opt_out_of_system_ducking();let pump_engine = manager.engine.clone();tauri::async_runtime::spawn(async move { pump_engine.pump().await });let app = app.clone();@@ -626,6 +627,43 @@ pub async fn omnidisc_voice_ptt(.map_err(|e| e.code().to_string())}+/// Whether the OS actually handed us the push-to-talk key.+///+/// It can refuse: Windows gives a combination to the first process that asks+/// and answers everyone else with `ERROR_HOTKEY_ALREADY_REGISTERED`, and macOS+/// needs Accessibility permission. Both used to fail into a log line, so the+/// key simply did nothing and the app looked broken.+#[derive(Debug, Clone, Serialize)]+pub struct PttStatus {+ pub binding: String,+ pub registered: bool,+}++#[tauri::command]+pub async fn omnidisc_voice_ptt_status(app: tauri::AppHandle) -> Result<PttStatus, String> {+ use tauri_plugin_global_shortcut::GlobalShortcutExt;+ let binding = crate::storage::config::load_settings(&app)+ .omnidisc+ .voice+ .ptt_key+ .trim()+ .to_string();+ if binding.is_empty() {+ return Ok(PttStatus {+ binding,+ registered: false,+ });+ }+ let registered = binding+ .parse::<tauri_plugin_global_shortcut::Shortcut>()+ .map(|s| app.global_shortcut().is_registered(s))+ .unwrap_or(false);+ Ok(PttStatus {+ binding,+ registered,+ })+}+#[tauri::command]pub async fn omnidisc_voice_set_noise_suppression(state: tauri::State<'_, crate::AppState>,diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex 0a0b0d7a..08af69b0 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -8,6 +8,8 @@ pub fn reregister(app: &tauri::AppHandle) {if let Err(e) = app.global_shortcut().unregister_all() {tracing::warn!("Failed to unregister hotkeys: {}", e);}+ #[cfg(windows)]+ forget_held_ptt();register_from_settings(app);}@@ -35,10 +37,76 @@ pub fn handle_ptt(app: &tauri::AppHandle, shortcut: &Shortcut, pressed: bool) ->if ptt.is_empty() || !matches_binding(shortcut, ptt) {return false;}+ #[cfg(windows)]+ tame_key_repeat(app, *shortcut, pressed);crate::commands::omnidisc::voice::ptt_from_hotkey(app, pressed);true}+/// Windows repeats `WM_HOTKEY` for as long as the key is down, and the+/// global-shortcut backend answers every repeat by spawning a thread that+/// busy-polls that key until it comes back up. A few seconds of push-to-talk+/// would therefore pile up dozens of spinning threads — a call that heats the+/// machine while you talk. Dropping the registration for the duration of the+/// hold stops the repeat at the source, and the release still arrives, because+/// the thread the first press spawned is already watching the key.+#[cfg(windows)]+fn tame_key_repeat(app: &tauri::AppHandle, shortcut: Shortcut, pressed: bool) {+ use std::sync::atomic::Ordering;++ if !pressed {+ restore_ptt_binding(app, shortcut);+ return;+ }+ if PTT_HELD.swap(true, Ordering::AcqRel) {+ return;+ }+ let generation = PTT_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;+ if let Err(e) = app.global_shortcut().unregister(shortcut) {+ tracing::debug!("[hotkey] could not pause the push-to-talk binding: {}", e);+ }+ // A release that never lands would leave the microphone open and the key+ // unbound, so a hold gets an upper bound it can recover from.+ let app = app.clone();+ std::thread::spawn(move || {+ std::thread::sleep(PTT_MAX_HOLD);+ if PTT_GENERATION.load(Ordering::Acquire) != generation {+ return;+ }+ tracing::warn!("[hotkey] push-to-talk stayed down too long; releasing it");+ crate::commands::omnidisc::voice::ptt_from_hotkey(&app, false);+ restore_ptt_binding(&app, shortcut);+ });+}++#[cfg(windows)]+fn restore_ptt_binding(app: &tauri::AppHandle, shortcut: Shortcut) {+ use std::sync::atomic::Ordering;++ if !PTT_HELD.swap(false, Ordering::AcqRel) {+ return;+ }+ PTT_GENERATION.fetch_add(1, Ordering::AcqRel);+ if let Err(e) = app.global_shortcut().register(shortcut) {+ tracing::warn!("[hotkey] push-to-talk could not be re-armed: {}", e);+ }+}++#[cfg(windows)]+fn forget_held_ptt() {+ use std::sync::atomic::Ordering;++ PTT_HELD.store(false, Ordering::Release);+ PTT_GENERATION.fetch_add(1, Ordering::AcqRel);+}++#[cfg(windows)]+static PTT_HELD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+#[cfg(windows)]+static PTT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+#[cfg(windows)]+const PTT_MAX_HOLD: std::time::Duration = std::time::Duration::from_secs(30);+fn register_one(app: &tauri::AppHandle, binding: &str, label: &str) {match binding.parse::<Shortcut>() {Ok(shortcut) => {@@ -60,6 +128,14 @@ fn register_one(app: &tauri::AppHandle, binding: &str, label: &str) {}),);}+ #[cfg(not(target_os = "macos"))]+ {+ tracing::warn!(+ "[hotkey] '{}' is probably already claimed by another application; \+ the user has to pick a different combination",+ binding+ );+ }} else {tracing::info!("[hotkey] registered {}: {}", label, binding);}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 0952bc4a..c1b04276 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -904,6 +904,8 @@ pub fn run() {commands::omnidisc::voice::omnidisc_voice_set_noise_suppression,commands::omnidisc::voice::omnidisc_voice_mic_test,commands::omnidisc::voice::omnidisc_voice_set_ducking,+ commands::omnidisc::voice::omnidisc_voice_ptt_status,+ commands::omnidisc::stream::omnidisc_media_capabilities,commands::omnidisc::stream::omnidisc_stream_sources,commands::omnidisc::stream::omnidisc_stream_start,commands::omnidisc::stream::omnidisc_stream_stop,diff --git a/src/components/omnidisc/VoiceBar.svelte b/src/components/omnidisc/VoiceBar.svelteindex 702c8725..87dd47b6 100644--- a/src/components/omnidisc/VoiceBar.svelte+++ b/src/components/omnidisc/VoiceBar.svelte@@ -2,7 +2,7 @@import { goto } from "$app/navigation";import { t } from "$lib/i18n";import { translateBackendError } from "$lib/error-translate";- import { isMac, modKey } from "$lib/platform";+ import { formatBinding } from "$lib/platform";import { getSettings } from "$lib/stores/settings-store.svelte";import { getChannel, getGuild } from "$lib/stores/omnidisc-store.svelte";import {@@ -22,7 +22,12 @@leaveVoice,retryVoice,} from "$lib/stores/omnidisc-voice-store.svelte";- import { isPublishing, stopStream, isStreamBusy } from "$lib/stores/omnidisc-stream-store.svelte";+ import {+ isPublishing,+ stopStream,+ isStreamBusy,+ getMediaCapabilities,+ } from "$lib/stores/omnidisc-stream-store.svelte";import ShareScreenDialog from "$components/omnidisc/ShareScreenDialog.svelte";let shareOpen = $state(false);@@ -44,14 +49,8 @@let outputError = $derived(getOutputError());let ping = $derived(stats?.rtt_ms != null ? Math.round(stats.rtt_ms) : null);let pttKey = $derived(getSettings()?.omnidisc?.voice?.ptt_key ?? "");- let pttLabel = $derived(- pttKey- ? pttKey- .split("+")- .map((part) => (part === "CmdOrCtrl" ? modKey() : part))- .join(isMac() ? "" : "+")- : "",- );+ let pttLabel = $derived(formatBinding(pttKey));+ let canShare = $derived(getMediaCapabilities().screen_share);let stateLabel = $derived.by(() => {switch (connState) {@@ -167,12 +166,21 @@{$t("omnidisc.stream.stop_sharing")}</button>{:else}- <button type="button" class="share" onclick={() => (shareOpen = true)} disabled={connState !== "connected"}>+ <button+ type="button"+ class="share"+ onclick={() => (shareOpen = true)}+ disabled={connState !== "connected" || !canShare}+ title={canShare ? undefined : $t("omnidisc.error.stream_unsupported")}+ ><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="13" rx="2" /><path d="M12 8v5M9.5 10.5 12 8l2.5 2.5" /></svg>{$t("omnidisc.stream.share_screen")}</button>{/if}</div>+ {#if !publishing && !canShare}+ <p class="note quiet">{$t("omnidisc.error.stream_unsupported")}</p>+ {/if}<div class="actions"><button@@ -443,6 +451,11 @@border-radius: var(--radius-sm);}+ .note.quiet {+ color: var(--text-muted);+ padding: 0 var(--space-2);+ }+.note.warn {background: color-mix(in srgb, var(--warning) 14%, transparent);}diff --git a/src/components/omnidisc/VoiceChannelView.svelte b/src/components/omnidisc/VoiceChannelView.svelteindex eebade1d..298ba9d6 100644--- a/src/components/omnidisc/VoiceChannelView.svelte+++ b/src/components/omnidisc/VoiceChannelView.svelte@@ -21,6 +21,7 @@isStreamBusy,refreshStreamStats,getStreamStats,+ getMediaCapabilities,} from "$lib/stores/omnidisc-stream-store.svelte";import type { OmnidiscChannel } from "$lib/omnidisc/types";@@ -41,6 +42,7 @@let confirmSwitch = $state(false);let publishing = $derived(isPublishing());let streamBusy = $derived(isStreamBusy());+ let canWatch = $derived(getMediaCapabilities().stream_viewer);let inspectorOpen = $state(false);let volumes = $state<Record<string, number>>({});@@ -118,9 +120,18 @@<span class="name">{name}{#if m.userId === me} <span class="you">({$t("omnidisc.voice.you")})</span>{/if}</span>{#if live && m.userId !== me}<div class="watch">- <button type="button" class="btn small" onclick={() => void toggleWatch(m.userId)} disabled={streamBusy}>+ <button+ type="button"+ class="btn small"+ onclick={() => void toggleWatch(m.userId)}+ disabled={streamBusy || !canWatch}+ title={canWatch ? undefined : $t("omnidisc.stream.watch_unsupported")}+ >{watching ? $t("omnidisc.stream.stop_watching") : $t("omnidisc.stream.watch")}</button>+ {#if !canWatch}+ <span class="watch-note">{$t("omnidisc.stream.watch_unsupported")}</span>+ {/if}{#if watching}{#if ws && ws.width > 0}<span class="res-badge">{ws.width}×{ws.height} · {Math.round(ws.fps_received)}fps{#if ws.codec} · {ws.codec.replace("video/", "").toUpperCase()}{/if}</span>@@ -279,6 +290,13 @@border-radius: var(--radius-sm);}+ .watch-note {+ font-size: var(--text-xs);+ color: var(--text-muted);+ text-align: center;+ line-height: 1.4;+ }+.res-badge {font-size: var(--text-xs);color: var(--text-muted);diff --git a/src/components/omnidisc/VoiceSettings.svelte b/src/components/omnidisc/VoiceSettings.svelteindex 5f3bd0be..c4a96c5c 100644--- a/src/components/omnidisc/VoiceSettings.svelte+++ b/src/components/omnidisc/VoiceSettings.svelte@@ -2,7 +2,7 @@import { onDestroy, onMount } from "svelte";import { t } from "$lib/i18n";import { translateBackendError } from "$lib/error-translate";- import { isMac, modKey } from "$lib/platform";+ import { formatBinding, isMac } from "$lib/platform";import { getSettings } from "$lib/stores/settings-store.svelte";import {getDevices,@@ -18,6 +18,8 @@isMicTesting,getMicLevel,micLevelStale,+ isPttRegistered,+ refreshPttStatus,} from "$lib/stores/omnidisc-voice-store.svelte";let settings = $derived(getSettings());@@ -39,18 +41,11 @@let levelPercent = $derived(Math.round(Math.min(1, Math.max(0, (level.rmsDb + 60) / 60)) * 100));let pttLabel = $derived(formatBinding(voice.ptt_key ?? ""));+ let pttRefused = $derived(!!voice.ptt_key && isPttRegistered() === false);let vadValue = $derived(vadDraft ?? voice.vad_threshold_db ?? -45);let duckValue = $derived(duckDraft ?? voice.ducking_percent ?? 0);let relayOnly = $derived(voice.relay_only === true);- function formatBinding(binding: string): string {- if (!binding) return "";- return binding- .split("+")- .map((part) => (part === "CmdOrCtrl" ? modKey() : part === "Meta" || part === "Super" ? (isMac() ? "⌘" : "Win") : part))- .join(isMac() ? "" : "+");- }-function mapKeyName(key: string): string | null {if (key.length === 1 && /[a-zA-Z]/.test(key)) return key.toUpperCase();if (key.length === 1 && /[0-9]/.test(key)) return key;@@ -122,6 +117,7 @@onMount(() => {void refreshDevices();+ void refreshPttStatus();clock = setInterval(() => (now = Date.now()), 1000);});@@ -213,8 +209,11 @@<div class="setting-col"><span class="setting-label">{$t("omnidisc.voice.ptt_key")}</span><span class="setting-path">{$t("omnidisc.voice.ptt_key_desc")}</span>- {#if isMac() && voice.ptt_key}- <span class="setting-path">{$t("omnidisc.voice.ptt_permission_hint")}</span>+ {#if pttRefused}+ <span class="setting-path refused" role="status">+ {$t("omnidisc.voice.ptt_refused")}+ {isMac() ? $t("omnidisc.voice.ptt_permission_hint") : $t("omnidisc.voice.ptt_conflict_hint")}+ </span>{/if}</div><div class="row-actions">@@ -297,6 +296,16 @@gap: var(--space-2);}+ .setting-path.refused {+ color: var(--warning);+ white-space: normal;+ overflow: visible;+ text-overflow: clip;+ line-height: 1.45;+ max-width: 52ch;+ margin-top: var(--space-1);+ }+.button.active {background: var(--accent);color: var(--on-accent);diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.jsonindex 0d1d9788..292845a6 100644--- a/src/lib/i18n/el.json+++ b/src/lib/i18n/el.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex ae7cba75..65a44bec 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.jsonindex 17fe5e27..c1ec5724 100644--- a/src/lib/i18n/es.json+++ b/src/lib/i18n/es.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.jsonindex b8ce3513..5a663dff 100644--- a/src/lib/i18n/fr.json+++ b/src/lib/i18n/fr.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.jsonindex 9fc911dc..5bcdb921 100644--- a/src/lib/i18n/it.json+++ b/src/lib/i18n/it.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.jsonindex 63252c92..1c6b9e93 100644--- a/src/lib/i18n/ja.json+++ b/src/lib/i18n/ja.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.tsindex 7adfc667..68c8b396 100644--- a/src/lib/i18n/keys.ts+++ b/src/lib/i18n/keys.ts@@ -1574,6 +1574,7 @@ export type TranslationKeys =| 'omnidisc.stream.stop_watching'| 'omnidisc.stream.volume'| 'omnidisc.stream.watch'+ | 'omnidisc.stream.watch_unsupported'| 'omnidisc.stream.you_live'| 'omnidisc.title'| 'omnidisc.voice.connected_to'@@ -1620,12 +1621,14 @@ export type TranslationKeys =| 'omnidisc.voice.participants'| 'omnidisc.voice.ping'| 'omnidisc.voice.ptt_clear'+ | 'omnidisc.voice.ptt_conflict_hint'| 'omnidisc.voice.ptt_hold'| 'omnidisc.voice.ptt_key'| 'omnidisc.voice.ptt_key_desc'| 'omnidisc.voice.ptt_permission_hint'| 'omnidisc.voice.ptt_record'| 'omnidisc.voice.ptt_recording'+ | 'omnidisc.voice.ptt_refused'| 'omnidisc.voice.quality_excellent'| 'omnidisc.voice.quality_good'| 'omnidisc.voice.quality_lost'diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.jsonindex 2ed08f05..dd6c40ee 100644--- a/src/lib/i18n/pt.json+++ b/src/lib/i18n/pt.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.jsonindex 40af2615..049bb87b 100644--- a/src/lib/i18n/ru.json+++ b/src/lib/i18n/ru.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.jsonindex bb19ed16..6d2d67b9 100644--- a/src/lib/i18n/zh-TW.json+++ b/src/lib/i18n/zh-TW.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.jsonindex 8c017e90..f68a966a 100644--- a/src/lib/i18n/zh.json+++ b/src/lib/i18n/zh.json@@ -4452,6 +4452,8 @@"ptt_recording": "Press a key combination…","ptt_clear": "Use voice activity instead","ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",+ "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.","vad_threshold": "Voice sensitivity","vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.","e2ee_on": "End-to-end encrypted",@@ -4495,6 +4497,7 @@"share_cta": "Share {{res}}","watch": "Watch","stop_watching": "Stop watching",+ "watch_unsupported": "Watching a stream is not available on this platform yet.","volume": "Stream volume","fullscreen": "Fullscreen","connecting": "Connecting…",diff --git a/src/lib/platform.ts b/src/lib/platform.tsindex e67b9173..ed89e4f2 100644--- a/src/lib/platform.ts+++ b/src/lib/platform.ts@@ -34,3 +34,26 @@ export function modKey(): string {export function shortcut(...keys: string[]): string {return isMac() ? `${modKey()}${keys.join("")}` : [modKey(), ...keys].join("+");}++/**+ * Rótulo de um atalho gravado no formato do Tauri (`CmdOrCtrl+Shift+K`).+ *+ * Vive aqui e não em cada componente porque duas cópias divergiram: uma+ * traduzia `Meta` para `Win` fora do macOS e a outra deixava `Meta` cru, então+ * o mesmo atalho aparecia com nomes diferentes em duas telas do mesmo app.+ */+export function formatBinding(binding: string): string {+ if (!binding) return "";+ const mac = isMac();+ return binding+ .split("+")+ .map((part) => {+ if (part === "CmdOrCtrl") return modKey();+ if (part === "Meta" || part === "Super" || part === "Command") return mac ? "⌘" : "Win";+ if (part === "Alt") return mac ? "⌥" : "Alt";+ if (part === "Shift") return mac ? "⇧" : "Shift";+ if (part === "Control" || part === "Ctrl") return mac ? "⌃" : "Ctrl";+ return part;+ })+ .join(mac ? "" : "+");+}diff --git a/src/lib/stores/omnidisc-stream-store.svelte.ts b/src/lib/stores/omnidisc-stream-store.svelte.tsindex 09a93de6..995f59a7 100644--- a/src/lib/stores/omnidisc-stream-store.svelte.ts+++ b/src/lib/stores/omnidisc-stream-store.svelte.ts@@ -90,6 +90,24 @@ export interface StartArgs {policy?: StreamingPolicy;}+export interface MediaCapabilities {+ voice: boolean;+ screen_share: boolean;+ stream_viewer: boolean;+}++/**+ * What the interface assumes until the backend answers — which it does on+ * mount, before anyone can click. Assuming "yes" keeps the buttons from+ * blinking into existence on the platforms where they do work; when the answer+ * is "no" they end up disabled with the reason attached, never silently gone.+ */+const ASSUMED_CAPABILITIES: MediaCapabilities = {+ voice: true,+ screen_share: true,+ stream_viewer: true,+};+const RESOLUTIONS = [540, 720, 1080, 1440, 2160];const FRAMERATES = [15, 30, 60, 90, 120, 144];@@ -99,6 +117,7 @@ let stats = $state<StreamStats | null>(null);let busy = $state(false);let lastError = $state<string | null>(null);let streamers = $state<Record<string, boolean>>({});+let capabilities = $state<MediaCapabilities>(ASSUMED_CAPABILITIES);let unlisten: UnlistenFn | null = null;let initialized = false;@@ -135,6 +154,18 @@ export function clearStreamError() {lastError = null;}+export function getMediaCapabilities(): MediaCapabilities {+ return capabilities;+}++export async function refreshMediaCapabilities(): Promise<void> {+ try {+ capabilities = await invoke<MediaCapabilities>("omnidisc_media_capabilities");+ } catch (e) {+ console.warn("[omnidisc] media capabilities unavailable", errorText(e));+ }+}+export function isStreamer(userId: string): boolean {return streamers[userId] === true;}@@ -278,6 +309,7 @@ interface StreamEventPayload {export async function initStream(): Promise<void> {if (initialized) return;initialized = true;+ void refreshMediaCapabilities();try {unlisten = await listen<StreamEventPayload>("omnidisc://voice", (event) => {const p = event.payload;diff --git a/src/lib/stores/omnidisc-voice-store.svelte.ts b/src/lib/stores/omnidisc-voice-store.svelte.tsindex 22c09e47..a2843c62 100644--- a/src/lib/stores/omnidisc-voice-store.svelte.ts+++ b/src/lib/stores/omnidisc-voice-store.svelte.ts@@ -117,6 +117,7 @@ let muted = $state(false);let deafened = $state(false);let busy = $state(false);let backendAvailable = $state(true);+let pttRegistered = $state<boolean | null>(null);let speaking = $state<Record<string, boolean>>({});let quality = $state<VoiceQuality>("unknown");let stats = $state<VoiceStatsWire | null>(null);@@ -660,6 +661,7 @@ export async function setNoiseSuppression(enabled: boolean): Promise<void> {export async function setPttKey(key: string): Promise<void> {await updateSettings({ omnidisc: { voice: { ptt_key: key } } });+ await refreshPttStatus();try {await invoke("omnidisc_voice_ptt", { pressed: false });} catch {@@ -667,6 +669,28 @@ export async function setPttKey(key: string): Promise<void> {}}+/**+ * `null` while unknown or while no key is set; `false` when the OS refused to+ * hand the combination over — Windows gives it to whoever asked first, macOS+ * wants Accessibility permission. Both used to fail silently, so the key just+ * did nothing.+ */+export function isPttRegistered(): boolean | null {+ return pttRegistered;+}++export async function refreshPttStatus(): Promise<void> {+ try {+ const status = await invoke<{ binding: string; registered: boolean }>(+ "omnidisc_voice_ptt_status",+ );+ pttRegistered = status.binding ? status.registered : null;+ } catch (e) {+ pttRegistered = null;+ console.warn("[omnidisc] push-to-talk status unavailable", errorText(e));+ }+}+export async function setVadThreshold(db: number): Promise<void> {await updateSettings({ omnidisc: { voice: { vad_threshold_db: db } } });}