From 3f4651a4884f5ec64f34e9abf425081de6716972 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 20:12:39 +0100 Subject: [PATCH] Run neighbor loopback through console WASAPI --- docs/implementation-plan.md | 6 +-- docs/neighbor-sender-setup.md | 16 +++---- notes/current-system-map.md | 2 +- notes/fresh-workspace-handoff.md | 2 +- scripts/capture_co_streamer_surfaces.py | 63 ++++++++++++++++++++++--- scripts/wasapi-loopback-capture.ps1 | 38 +++++++++++++-- state/map.yaml | 2 +- 7 files changed, 103 insertions(+), 26 deletions(-) diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 117bfd7..fa60b2a 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -11,7 +11,7 @@ - Neighbor sender deployment under `C:\Meta\LocalCastBridge`. - Madman's desktop start/stop launchers for the sender. - Receiver OBS scene has `Neighbor PC - Video` and `Neighbor PC - Focusrite` Media Sources. -- Voicemeeter loopback installed on the sender. +- Direct co-streamer loopback capture is now attempted with the repo WASAPI shim instead of Voicemeeter. - Receiver OBS scene has `Neighbor PC - System Audio` on SRT port `5102`. - Sender script uses `-nostdin` and repo-root logs so desktop launchers stay alive and diagnostics land in `C:\Meta\LocalCastBridge\logs`. - Sender video config is `1920x1080` for the interactive desktop. The `1024x768` SSH session size is not the streaming target. @@ -32,7 +32,7 @@ - OBS synchronized program surface: - `scripts/setup_obs_synced_program.py` derives OBS-controllable stems from an aligned program audio timeline: host voice, co-streamer voice, ambient, transients, co-streamer loopback, and local loopback. - `scripts/capture_co_streamer_surfaces.py` captures neighbor Focusrite and neighbor loopback with local loopback ground truth, estimates the late remote-family offset, and writes aligned co-streamer surfaces for the stem packer. - - `scripts/wasapi-loopback-capture.ps1` is the direct primary-playback loopback path. The current neighbor Focusrite render endpoint rejects WASAPI loopback initialization, so loopback remains unavailable until the render endpoint/driver path is changed or the sender FFmpeg build gains a working WASAPI input. + - `scripts/wasapi-loopback-capture.ps1` is the direct primary-playback loopback path. It must run in the neighbor's interactive console session; SSH-only capture sees the device but receives no render packets. - The tool creates/updates local OBS Media Sources for those stems and mutes/disables raw unsynchronized inputs. - Strict mode disables every scene item except the synchronized LocalCastBridge program video and stem controls. @@ -57,5 +57,5 @@ 10. Replace placeholder mic/speaker geometry with measured world coordinates, then build the delay/SRO alignment stage that feeds the bounded field cache and emits aligned six-channel blocks before FOA encoding. 11. Move the render-frame consumer into Aquarium Engine so dense brush/splat rendering replaces the deadline OpenGL point sink behind the same OBS Spout boundary. 12. Replace synthetic live-fusion observations with PS3 Eye detector observations. -13. Fix the neighbor direct loopback route: the sender FFmpeg build has no WASAPI input and the current Focusrite render endpoint rejects direct WASAPI loopback from `scripts/wasapi-loopback-capture.ps1`. +13. Keep the neighbor loopback leg running through the scheduled interactive WASAPI capture path and use it as the timing witness once actual neighbor app audio is present. 14. Let the co-streamer surface delay drive the shared presentation buffer horizon for audio stems, AmbiX, and remote video. diff --git a/docs/neighbor-sender-setup.md b/docs/neighbor-sender-setup.md index fb53d4a..30ddf38 100644 --- a/docs/neighbor-sender-setup.md +++ b/docs/neighbor-sender-setup.md @@ -98,11 +98,11 @@ Analogue 1 + 2 (Focusrite USB Audio) The sender FFmpeg build does not expose a native `wasapi` input device, so it cannot directly capture primary playback by itself. `scripts\wasapi-loopback-capture.ps1` -is the direct Core Audio loopback attempt. As of 2026-05-18, the Focusrite -render endpoint reports a 48 kHz stereo mix format but rejects loopback -initialization with `0x88890008`, so co-streamer loopback is not yet a usable -timing witness. Co-streamer Focusrite program bleed remains the temporary -alignment witness. +is the direct Core Audio loopback path. It works when launched in the logged-in +console session and audio is actually rendering; SSH-only launches can open the +endpoint but receive no render packets. `scripts\capture_co_streamer_surfaces.py` +therefore schedules the WASAPI loopback leg into the interactive session and +pulls the resulting raw float PCM back for alignment. Do not rename the loopback in config unless the replacement appears in: @@ -110,10 +110,8 @@ Do not rename the loopback in config unless the replacement appears in: ffmpeg -hide_banner -f dshow -list_devices true -i dummy ``` -If loopback is required, change the neighbor primary playback device to a -render endpoint that accepts WASAPI loopback or install/use a sender FFmpeg -build with a working WASAPI input. Do not widen OBS to unsynchronized raw audio -as a workaround. +If the loopback file is zero bytes, no app audio rendered during the capture +window. Do not widen OBS to unsynchronized raw audio as a workaround. ## SSH Testing Trap diff --git a/notes/current-system-map.md b/notes/current-system-map.md index b6603fb..2d7ab78 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -122,7 +122,7 @@ Ownership: - `scripts/setup_obs_synced_program.py` owns packaging aligned program audio into OBS-controllable stems and muting/disabling raw unsynchronized OBS inputs. - `scripts/capture_co_streamer_surfaces.py` owns the late-arriving neighbor surface import: it captures neighbor Focusrite and neighbor loopback over SSH while recording local loopback, estimates the remote-family offset, and writes aligned co-streamer surfaces for the OBS stem packer. -- `scripts/wasapi-loopback-capture.ps1` owns the attempted direct primary-playback loopback path. It bypasses virtual mixers and asks Windows Core Audio for the default render endpoint loopback stream. +- `scripts/wasapi-loopback-capture.ps1` owns the direct primary-playback loopback path. It bypasses virtual mixers and asks Windows Core Audio for the default render endpoint loopback stream. It must run in the neighbor's interactive console session to receive render packets. - OBS owns final source volume, track assignment, filters, and stream/record output. - Aquarium/Spout owns synchronized program video, not raw remote desktop capture. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index cf99d6e..b54b4e5 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -29,7 +29,7 @@ Get-Content .\state\evidence.jsonl -Tail 8 - Neighbor sender is deployed at `C:\Meta\LocalCastBridge` on `192.168.1.84`. - Madman's desktop has `Start LocalCast Sender.cmd` and `Stop LocalCast Sender.cmd`. - Receiver OBS scene collection has `Neighbor PC - Video`, `Neighbor PC - Focusrite`, and `Neighbor PC - System Audio` Media Sources added. -- Sender has Voicemeeter plus SoundVolumeView installed for system-output loopback. +- Sender uses SoundVolumeView for default device selection. Voicemeeter is no longer the loopback authority; co-streamer playback loopback uses the direct WASAPI shim scheduled into the neighbor console session. - Sender script was patched after failed transmission: live FFmpeg commands now include `-nostdin`, logs go under `C:\Meta\LocalCastBridge\logs`, and interactive video capture size is `1920x1080`. - Madman's desktop launchers call PowerShell wrappers: `scripts\start-localcast-desktop.ps1` and `scripts\stop-localcast-desktop.ps1`. - SSH-launched video capture fails with `gdigrab` error 5; test video from Madman's interactive desktop launcher. diff --git a/scripts/capture_co_streamer_surfaces.py b/scripts/capture_co_streamer_surfaces.py index 3399785..ecc999a 100644 --- a/scripts/capture_co_streamer_surfaces.py +++ b/scripts/capture_co_streamer_surfaces.py @@ -31,9 +31,10 @@ def main() -> int: parser.add_argument("--ffmpeg", default=r"C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\ffmpeg.exe") parser.add_argument("--remote-dir", default=r"C:\Meta\LocalCastBridge\calibration\remote-captures") parser.add_argument("--focusrite-device", default="Analogue 1 + 2 (Focusrite USB Audio)") - parser.add_argument("--loopback-device", default="Voicemeeter Out B3 (VB-Audio Voicemeeter VAIO)") + parser.add_argument("--loopback-device", default="") parser.add_argument("--loopback-capture", choices=("wasapi", "dshow"), default="wasapi") parser.add_argument("--remote-wasapi-script", default=r"C:\Meta\LocalCastBridge\scripts\wasapi-loopback-capture.ps1") + parser.add_argument("--remote-wasapi-role", choices=("Console", "Multimedia", "Communications"), default="Console") parser.add_argument("--local-loopback-query", default="Scarlett") parser.add_argument("--max-lag-ms", type=float, default=3000.0) parser.add_argument("--min-loopback-rms", type=float, default=1e-4) @@ -47,9 +48,10 @@ def main() -> int: stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") remote_focusrite = f"{args.remote_dir.rstrip('\\\\/')}\\co_streamer_focusrite-{stamp}.wav" - remote_loopback = f"{args.remote_dir.rstrip('\\\\/')}\\co_streamer_loopback-{stamp}.wav" + remote_loopback_ext = "f32" if args.loopback_capture == "wasapi" else "wav" + remote_loopback = f"{args.remote_dir.rstrip('\\\\/')}\\co_streamer_loopback-{stamp}.{remote_loopback_ext}" local_focusrite = surface_dir / "raw_focusrite.wav" - local_remote_loopback = surface_dir / "raw_loopback.wav" + local_remote_loopback = surface_dir / f"raw_loopback.{remote_loopback_ext}" local_reference = surface_dir / "local_loopback_reference.wav" commands = [ @@ -86,7 +88,7 @@ def main() -> int: sample_rate = int(args.sample_rate) _, reference = read_wav_float(local_reference, sample_rate) _, focusrite = read_wav_float(local_focusrite, sample_rate) - _, remote_loop = read_wav_float(local_remote_loopback, sample_rate) + remote_loop = read_loopback_capture(local_remote_loopback, sample_rate, args.loopback_capture) reference_mono = mono(reference) remote_loop_mono = mono(remote_loop) max_lag = int(float(args.max_lag_ms) * sample_rate / 1000.0) @@ -159,14 +161,47 @@ def remote_ffmpeg_command(args: argparse.Namespace, device: str, output: str, *, def remote_loopback_command(args: argparse.Namespace, output: str) -> str: if args.loopback_capture == "dshow": + if not args.loopback_device: + raise SystemExit("--loopback-device is required when --loopback-capture dshow") return remote_ffmpeg_command(args, args.loopback_device, output, channels=2) + log = output.rsplit(".", 1)[0] + ".log" + task = "LocalCastWasapiLoopbackCapture" return ( - f'powershell -NoProfile -ExecutionPolicy Bypass -File "{args.remote_wasapi_script}" ' - f'-Output "{output}" -Seconds {float(args.seconds):.3f} ' - f'-SampleRate {int(args.sample_rate)} -Channels 2' + "powershell -NoProfile -ExecutionPolicy Bypass -Command " + + quote_for_cmd( + "$ErrorActionPreference='Stop'; " + f"$out='{escape_ps(output)}'; $log='{escape_ps(log)}'; " + "Remove-Item -LiteralPath $out,$log -ErrorAction SilentlyContinue; " + f"$cmd='powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"{escape_ps(args.remote_wasapi_script)}\" " + f"-Output \"{escape_ps(output)}\" -Seconds {float(args.seconds):.3f} " + f"-SampleRate {int(args.sample_rate)} -Channels 2 -Role {args.remote_wasapi_role} *> \"{escape_ps(log)}\"'; " + "$bat=[IO.Path]::ChangeExtension($out,'.cmd'); " + "Set-Content -LiteralPath $bat -Encoding ASCII -Value ('@echo off' + [Environment]::NewLine + $cmd + [Environment]::NewLine); " + "$action=New-ScheduledTaskAction -Execute $bat; " + "$trigger=New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(10); " + "$principal=New-ScheduledTaskPrincipal -UserId ($env:COMPUTERNAME + '\\' + $env:USERNAME) -LogonType Interactive -RunLevel Limited; " + f"Register-ScheduledTask -TaskName '{task}' -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null; " + f"Start-ScheduledTask -TaskName '{task}'; " + f"$deadline=(Get-Date).AddSeconds({float(args.seconds) + 12.0:.3f}); " + "while((Get-Date) -lt $deadline){ " + " $info=Get-ScheduledTaskInfo -TaskName '" + task + "'; " + " if((Test-Path -LiteralPath $out) -and ((Get-Item -LiteralPath $out).Length -gt 0) -and $info.LastTaskResult -eq 0){ break } " + " Start-Sleep -Milliseconds 250 " + "}; " + "if(-not (Test-Path -LiteralPath $out)){ if(Test-Path -LiteralPath $log){Get-Content $log -Tail 40}; throw 'WASAPI loopback capture did not create output' }; " + "Write-Host ('wasapiLoopbackBytes=' + (Get-Item -LiteralPath $out).Length)" + ) ) +def quote_for_cmd(command: str) -> str: + return '"' + command.replace('"', '\\"') + '"' + + +def escape_ps(value: str) -> str: + return value.replace("'", "''") + + def sftp_get(ssh_target: str, remote_file: str, local_file: Path) -> None: remote_sftp_path = "/C:/" + remote_file.replace("\\", "/").split("C:/", 1)[-1] batch = f'get "{remote_sftp_path}" "{local_file}"\n' @@ -207,6 +242,16 @@ def read_wav_float(path: Path, target_rate: int) -> tuple[int, np.ndarray]: return int(rate), ensure_2d(samples) +def read_loopback_capture(path: Path, target_rate: int, capture_kind: str) -> np.ndarray: + if capture_kind == "wasapi": + samples = np.fromfile(path, dtype=np.float32) + if samples.size % 2: + samples = samples[:-1] + return samples.reshape(-1, 2).astype(np.float32) + _, samples = read_wav_float(path, target_rate) + return samples + + def pcm_to_float(samples: np.ndarray) -> np.ndarray: array = np.asarray(samples) if array.ndim == 1: @@ -230,8 +275,12 @@ def mono(samples: np.ndarray) -> np.ndarray: def normalized_delay(signal_a: np.ndarray, signal_b: np.ndarray, max_lag: int) -> tuple[int, float]: count = min(len(signal_a), len(signal_b)) + if count <= 0: + return 0, 0.0 a = signal_a[:count].astype(np.float32) b = signal_b[:count].astype(np.float32) + if float(np.std(a)) <= 1e-12 or float(np.std(b)) <= 1e-12: + return 0, 0.0 a = (a - float(np.mean(a))) / (float(np.std(a)) + 1e-9) b = (b - float(np.mean(b))) / (float(np.std(b)) + 1e-9) corr = signal.correlate(a, b, mode="full", method="fft") diff --git a/scripts/wasapi-loopback-capture.ps1 b/scripts/wasapi-loopback-capture.ps1 index 02a7187..290abb9 100644 --- a/scripts/wasapi-loopback-capture.ps1 +++ b/scripts/wasapi-loopback-capture.ps1 @@ -2,7 +2,9 @@ param( [string]$Output = "-", [double]$Seconds = 0, [int]$SampleRate = 48000, - [int]$Channels = 2 + [int]$Channels = 2, + [ValidateSet("Console", "Multimedia", "Communications")] + [string]$Role = "Console" ) $ErrorActionPreference = "Stop" @@ -17,6 +19,8 @@ namespace LocalCastBridge { public static class WasapiLoopbackCapture { const int eRender = 0; const int eConsole = 0; + const int eMultimedia = 1; + const int eCommunications = 2; const int CLSCTX_ALL = 23; const uint AUDCLNT_SHAREMODE_SHARED = 0; const uint AUDCLNT_STREAMFLAGS_LOOPBACK = 0x00020000; @@ -107,12 +111,13 @@ namespace LocalCastBridge { int GetNextPacketSize(out uint frames); } - public static void Capture(string outputPath, double seconds, int targetRate, int targetChannels) { + public static void Capture(string outputPath, double seconds, int targetRate, int targetChannels, string roleName) { Stream output = outputPath == "-" ? Console.OpenStandardOutput() : new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read); try { IMMDeviceEnumerator enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); IMMDevice device; - Check(enumerator.GetDefaultAudioEndpoint(eRender, eConsole, out device), "GetDefaultAudioEndpoint"); + int role = RoleFromName(roleName); + Check(enumerator.GetDefaultAudioEndpoint(eRender, role, out device), "GetDefaultAudioEndpoint"); IAudioClient audioClient; Guid audioClientId = IID_IAudioClient; Check(device.Activate(ref audioClientId, CLSCTX_ALL, IntPtr.Zero, out audioClient), "Activate IAudioClient"); @@ -122,12 +127,30 @@ namespace LocalCastBridge { Console.Error.WriteLine("MixFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); IntPtr activeFormatPtr = mixFormatPtr; IntPtr fallbackFormatPtr = IntPtr.Zero; + IntPtr closest = IntPtr.Zero; + int support = audioClient.IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, activeFormatPtr, out closest); + Console.Error.WriteLine("MixFormatSupport hr=0x{0:X8} closest={1}", support, closest != IntPtr.Zero); + if (support != 0 && closest != IntPtr.Zero) { + activeFormatPtr = closest; + fmt = Marshal.PtrToStructure(activeFormatPtr); + Console.Error.WriteLine("ClosestFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); + } int init = audioClient.Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, activeFormatPtr, IntPtr.Zero); if (init < 0) { fallbackFormatPtr = MakeWaveFormatPcm((ushort)targetChannels, (uint)targetRate, 16); activeFormatPtr = fallbackFormatPtr; fmt = Marshal.PtrToStructure(activeFormatPtr); Console.Error.WriteLine("RetryFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); + IntPtr retryClosest = IntPtr.Zero; + int retrySupport = audioClient.IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, activeFormatPtr, out retryClosest); + Console.Error.WriteLine("RetryFormatSupport hr=0x{0:X8} closest={1}", retrySupport, retryClosest != IntPtr.Zero); + if (retrySupport != 0 && retryClosest != IntPtr.Zero) { + Marshal.FreeHGlobal(fallbackFormatPtr); + fallbackFormatPtr = IntPtr.Zero; + activeFormatPtr = retryClosest; + fmt = Marshal.PtrToStructure(activeFormatPtr); + Console.Error.WriteLine("RetryClosestFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); + } init = audioClient.Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, activeFormatPtr, IntPtr.Zero); } Check(init, "Initialize loopback"); @@ -185,6 +208,7 @@ namespace LocalCastBridge { audioClient.Stop(); Marshal.FreeCoTaskMem(mixFormatPtr); if (fallbackFormatPtr != IntPtr.Zero) Marshal.FreeHGlobal(fallbackFormatPtr); + if (closest != IntPtr.Zero) Marshal.FreeCoTaskMem(closest); Marshal.ReleaseComObject(captureClient); Marshal.ReleaseComObject(audioClient); Marshal.ReleaseComObject(device); @@ -203,6 +227,12 @@ namespace LocalCastBridge { } } + static int RoleFromName(string roleName) { + if (String.Equals(roleName, "Multimedia", StringComparison.OrdinalIgnoreCase)) return eMultimedia; + if (String.Equals(roleName, "Communications", StringComparison.OrdinalIgnoreCase)) return eCommunications; + return eConsole; + } + static IntPtr MakeWaveFormatPcm(ushort channels, uint sampleRate, ushort bits) { WAVEFORMATEX fmt = new WAVEFORMATEX(); fmt.wFormatTag = 1; @@ -247,4 +277,4 @@ namespace LocalCastBridge { "@ Add-Type -TypeDefinition $source -[LocalCastBridge.WasapiLoopbackCapture]::Capture($Output, $Seconds, $SampleRate, $Channels) +[LocalCastBridge.WasapiLoopbackCapture]::Capture($Output, $Seconds, $SampleRate, $Channels, $Role) diff --git a/state/map.yaml b/state/map.yaml index 2dfc80b..7f6e1a2 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -147,7 +147,7 @@ current_status: summary: > First repo scaffold is in place and deployed to the neighbor sender at C:\Meta\LocalCastBridge. FFmpeg 8.1.1 with SRT and h264_nvenc is installed - there, Voicemeeter supplies system-output loopback, Madman's desktop has + there, direct WASAPI console-session capture now owns system-output loopback, Madman's desktop has start/stop launchers, the sender script has launcher-safe FFmpeg arguments and repo-root logs, desktop launchers use absolute tool paths, and the receiver OBS scene has matching Media Sources. Local calibration harness now