diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 8983913..117bfd7 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -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/configure-voicemeeter-routing.ps1` is called by the neighbor desktop launcher to route Voicemeeter virtual inputs to B3 before FFmpeg starts. + - `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. - 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 loopback route so `Voicemeeter Out B3` carries real program audio; current remote loopback captures are near-silent and cannot serve as the timing witness. +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`. 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 3801875..fb53d4a 100644 --- a/docs/neighbor-sender-setup.md +++ b/docs/neighbor-sender-setup.md @@ -18,7 +18,6 @@ - FFmpeg reports: - `srt` input/output protocol - `h264_nvenc` encoder -- Voicemeeter installed through winget as `VB-Audio.Voicemeeter`. - SoundVolumeView installed through winget as `NirSoft.SoundVolumeView`. ## Sender Config @@ -76,23 +75,18 @@ Start launcher: - runs `scripts\start-localcast-desktop.ps1` - uses `config\localcast.json` - passes the winget FFmpeg alias path explicitly -- starts Voicemeeter - calls `SoundVolumeView.exe` by absolute path inside PowerShell because the winget alias is not reliably available in interactive `cmd.exe` -- sets Windows default render to `Voicemeeter VAIO3 Input` -- sets Windows default capture to `Voicemeeter Out B3` -- runs `scripts\configure-voicemeeter-routing.ps1` to route Voicemeeter virtual - inputs to B3 and unmute output buses before FFmpeg starts +- sets Windows default render to `Focusrite USB Audio\Device\Speakers\Render` +- sets Windows default capture to `Focusrite USB Audio\Device\Analogue 1 + 2\Capture` - writes FFmpeg logs under `C:\Meta\LocalCastBridge\logs` - - Voicemeeter routing details are written to - `C:\Meta\LocalCastBridge\logs\voicemeeter-routing.log` Stop launcher: - runs `scripts\stop-localcast-desktop.ps1` - stops FFmpeg processes whose command line contains `srt://` - restores Windows default render to `Focusrite USB Audio\Device\Speakers\Render` -- closes `voicemeeter_x64.exe` +- restores Windows default render to `Focusrite USB Audio\Device\Speakers\Render` ## Audio Reality @@ -102,18 +96,13 @@ FFmpeg DirectShow discovery originally exposed one hardware audio input: Analogue 1 + 2 (Focusrite USB Audio) ``` -After Voicemeeter install, FFmpeg exposes virtual loopback inputs including: - -```text -Voicemeeter Out B3 (VB-Audio Voicemeeter VAIO) -``` - -LocalCastBridge uses that device as `system-loopback`. - -The routing script can prove that Voicemeeter accepted the B3 route, but B3 -will still be silent when no app audio is actually playing into the default -render device. In that case the co-streamer Focusrite bleed remains the -alignment witness until real loopback audio appears. +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. Do not rename the loopback in config unless the replacement appears in: @@ -121,9 +110,10 @@ Do not rename the loopback in config unless the replacement appears in: ffmpeg -hide_banner -f dshow -list_devices true -i dummy ``` -If Madman cannot hear local audio while LocalCast is running, open Voicemeeter -and set hardware output `A1` to the intended physical device, probably -Focusrite speakers/headphones. The stream capture itself is independent of OBS. +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. ## SSH Testing Trap diff --git a/notes/current-system-map.md b/notes/current-system-map.md index aad08d2..b6603fb 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -122,8 +122,8 @@ 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/configure-voicemeeter-routing.ps1` owns the neighbor launcher-side route from Voicemeeter virtual inputs to B3, with a sender-side routing log. +- `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. - OBS owns final source volume, track assignment, filters, and stream/record output. - Aquarium/Spout owns synchronized program video, not raw remote desktop capture. -Invariant: raw SRT ingest, Desktop Audio, Mic/Aux, and other non-program scene items may exist for diagnostics, but they must be disabled or muted when broadcasting the synchronized program. Missing synchronized feeds should appear as explicit silent placeholders, not as live unsynchronized substitutes. The co-streamer Focusrite, co-streamer loopback, and remote video are the latest-arriving surface family; their measured delay should set the presentation buffer horizon instead of being patched in after the local field. +Invariant: raw SRT ingest, Desktop Audio, Mic/Aux, and other non-program scene items may exist for diagnostics, but they must be disabled or muted when broadcasting the synchronized program. Missing synchronized feeds should appear as explicit silent placeholders, not as live unsynchronized substitutes. The co-streamer Focusrite, co-streamer loopback, and remote video are the latest-arriving surface family; their measured delay should set the presentation buffer horizon instead of being patched in after the local field. Do not reintroduce Voicemeeter as the loopback authority without a concrete invariant; prefer direct WASAPI loopback or a sender FFmpeg build with native WASAPI input. diff --git a/scripts/capture_co_streamer_surfaces.py b/scripts/capture_co_streamer_surfaces.py index 4e8e505..3399785 100644 --- a/scripts/capture_co_streamer_surfaces.py +++ b/scripts/capture_co_streamer_surfaces.py @@ -32,6 +32,8 @@ def main() -> int: 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-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("--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) @@ -52,7 +54,7 @@ def main() -> int: commands = [ remote_ffmpeg_command(args, args.focusrite_device, remote_focusrite, channels=1), - remote_ffmpeg_command(args, args.loopback_device, remote_loopback, channels=2), + remote_loopback_command(args, remote_loopback), ] if args.dry_run: for command in commands: @@ -155,6 +157,16 @@ 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": + return remote_ffmpeg_command(args, args.loopback_device, output, channels=2) + 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' + ) + + 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' diff --git a/scripts/configure-voicemeeter-routing.ps1 b/scripts/configure-voicemeeter-routing.ps1 deleted file mode 100644 index cee1a66..0000000 --- a/scripts/configure-voicemeeter-routing.ps1 +++ /dev/null @@ -1,110 +0,0 @@ -param( - [string]$VoicemeeterExe = "C:\Program Files (x86)\VB\Voicemeeter\voicemeeter_x64.exe", - [string]$VoicemeeterRemoteDll = "C:\Program Files (x86)\VB\Voicemeeter\VoicemeeterRemote64.dll", - [int[]]$CandidateStrips = @(7, 5, 6, 3, 4), - [int[]]$CandidateBuses = @(7, 6, 5, 4, 3, 2, 1, 0), - [string]$LogPath = "C:\Meta\LocalCastBridge\logs\voicemeeter-routing.log", - [switch]$AlsoMonitorA1 -) - -$ErrorActionPreference = "Stop" - -New-Item -ItemType Directory -Force (Split-Path -Parent $LogPath) | Out-Null -"$(Get-Date -Format o) configuring Voicemeeter routing" | Set-Content -LiteralPath $LogPath -Encoding UTF8 - -function Log-Line { - param([string]$Line) - $Line | Tee-Object -FilePath $LogPath -Append -} - -if (-not (Test-Path -LiteralPath $VoicemeeterRemoteDll)) { - throw "Voicemeeter Remote DLL not found: $VoicemeeterRemoteDll" -} - -if (-not (Get-Process -Name "voicemeeter_x64" -ErrorAction SilentlyContinue)) { - if (-not (Test-Path -LiteralPath $VoicemeeterExe)) { - throw "Voicemeeter executable not found: $VoicemeeterExe" - } - Start-Process -FilePath $VoicemeeterExe - Start-Sleep -Seconds 3 -} - -$escapedDll = $VoicemeeterRemoteDll.Replace("\", "\\") -$source = @" -using System; -using System.Runtime.InteropServices; - -public static class LocalCastVoicemeeterRemote { - [DllImport("$escapedDll", CallingConvention = CallingConvention.StdCall)] - public static extern int VBVMR_Login(); - - [DllImport("$escapedDll", CallingConvention = CallingConvention.StdCall)] - public static extern int VBVMR_Logout(); - - [DllImport("$escapedDll", CallingConvention = CallingConvention.StdCall)] - public static extern int VBVMR_SetParameterFloat( - [MarshalAs(UnmanagedType.LPStr)] string name, - float value - ); - - [DllImport("$escapedDll", CallingConvention = CallingConvention.StdCall)] - public static extern int VBVMR_GetVoicemeeterType(ref int voicemeeterType); -} -"@ - -Add-Type -TypeDefinition $source - -function Set-VMFloat { - param( - [string]$Name, - [float]$Value - ) - return [LocalCastVoicemeeterRemote]::VBVMR_SetParameterFloat($Name, $Value) -} - -$login = [LocalCastVoicemeeterRemote]::VBVMR_Login() -try { - if ($login -lt 0) { - throw "Voicemeeter Remote login failed with code $login" - } - Start-Sleep -Milliseconds 250 - - $voicemeeterType = 0 - [void][LocalCastVoicemeeterRemote]::VBVMR_GetVoicemeeterType([ref]$voicemeeterType) - Log-Line "Voicemeeter type: $voicemeeterType" - - $routed = @() - foreach ($strip in $CandidateStrips) { - $b3 = Set-VMFloat -Name "Strip[$strip].B3" -Value 1.0 - $mute = Set-VMFloat -Name "Strip[$strip].Mute" -Value 0.0 - Log-Line "Strip[$strip].B3 -> $b3" - Log-Line "Strip[$strip].Mute -> $mute" - if ($b3 -ge 0) { - $routed += "Strip[$strip].B3" - } - if ($AlsoMonitorA1) { - $a1 = Set-VMFloat -Name "Strip[$strip].A1" -Value 1.0 - Log-Line "Strip[$strip].A1 -> $a1" - } - if ($mute -ge 0) { - $gain = Set-VMFloat -Name "Strip[$strip].Gain" -Value 0.0 - Log-Line "Strip[$strip].Gain -> $gain" - } - } - - foreach ($bus in $CandidateBuses) { - $mute = Set-VMFloat -Name "Bus[$bus].Mute" -Value 0.0 - $gain = Set-VMFloat -Name "Bus[$bus].Gain" -Value 0.0 - Log-Line "Bus[$bus].Mute -> $mute" - Log-Line "Bus[$bus].Gain -> $gain" - } - - if ($routed.Count -eq 0) { - throw "No candidate Voicemeeter strips accepted B3 routing" - } - - Log-Line "Voicemeeter B3 routing enabled: $($routed -join ', ')" -} -finally { - [void][LocalCastVoicemeeterRemote]::VBVMR_Logout() -} diff --git a/scripts/start-localcast-desktop.ps1 b/scripts/start-localcast-desktop.ps1 index 50e9027..05a4b2e 100644 --- a/scripts/start-localcast-desktop.ps1 +++ b/scripts/start-localcast-desktop.ps1 @@ -1,35 +1,20 @@ $ErrorActionPreference = "Stop" $root = "C:\Meta\LocalCastBridge" -$voicemeeter = "C:\Program Files (x86)\VB\Voicemeeter\voicemeeter_x64.exe" $soundVolumeView = "C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\SoundVolumeView.exe" $ffmpeg = "C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\ffmpeg.exe" $config = Join-Path $root "config\localcast.json" $senderStart = Join-Path $root "scripts\sender-start.ps1" -$voicemeeterRouting = Join-Path $root "scripts\configure-voicemeeter-routing.ps1" Set-Location $root -if (Test-Path -LiteralPath $voicemeeter) { - Start-Process -FilePath $voicemeeter - Start-Sleep -Seconds 2 -} else { - Write-Warning "Voicemeeter was not found at $voicemeeter" -} - if (Test-Path -LiteralPath $soundVolumeView) { - & $soundVolumeView /SetDefault "VB-Audio Voicemeeter VAIO\Device\Voicemeeter VAIO3 Input\Render" 0 - & $soundVolumeView /SetDefault "VB-Audio Voicemeeter VAIO\Device\Voicemeeter VAIO3 Input\Render" 1 - & $soundVolumeView /SetDefault "VB-Audio Voicemeeter VAIO\Device\Voicemeeter Out B3\Capture" 0 - & $soundVolumeView /SetDefault "VB-Audio Voicemeeter VAIO\Device\Voicemeeter Out B3\Capture" 1 + & $soundVolumeView /SetDefault "Focusrite USB Audio\Device\Speakers\Render" 0 + & $soundVolumeView /SetDefault "Focusrite USB Audio\Device\Speakers\Render" 1 + & $soundVolumeView /SetDefault "Focusrite USB Audio\Device\Analogue 1 + 2\Capture" 0 + & $soundVolumeView /SetDefault "Focusrite USB Audio\Device\Analogue 1 + 2\Capture" 1 } else { Write-Warning "SoundVolumeView was not found at $soundVolumeView" } -if (Test-Path -LiteralPath $voicemeeterRouting) { - & $voicemeeterRouting -} else { - Write-Warning "Voicemeeter routing script was not found at $voicemeeterRouting" -} - & $senderStart -Config $config -FfmpegPath $ffmpeg diff --git a/scripts/wasapi-loopback-capture.ps1 b/scripts/wasapi-loopback-capture.ps1 new file mode 100644 index 0000000..02a7187 --- /dev/null +++ b/scripts/wasapi-loopback-capture.ps1 @@ -0,0 +1,250 @@ +param( + [string]$Output = "-", + [double]$Seconds = 0, + [int]$SampleRate = 48000, + [int]$Channels = 2 +) + +$ErrorActionPreference = "Stop" + +$source = @" +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; + +namespace LocalCastBridge { + public static class WasapiLoopbackCapture { + const int eRender = 0; + const int eConsole = 0; + const int CLSCTX_ALL = 23; + const uint AUDCLNT_SHAREMODE_SHARED = 0; + const uint AUDCLNT_STREAMFLAGS_LOOPBACK = 0x00020000; + const int AUDCLNT_BUFFERFLAGS_SILENT = 0x2; + static readonly Guid IID_IAudioClient = new Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"); + static readonly Guid IID_IAudioCaptureClient = new Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317"); + + [StructLayout(LayoutKind.Sequential)] + struct WAVEFORMATEX { + public ushort wFormatTag; + public ushort nChannels; + public uint nSamplesPerSec; + public uint nAvgBytesPerSec; + public ushort nBlockAlign; + public ushort wBitsPerSample; + public ushort cbSize; + } + + [StructLayout(LayoutKind.Sequential)] + struct WAVEFORMATEXTENSIBLE { + public WAVEFORMATEX Format; + public ushort wValidBitsPerSample; + public uint dwChannelMask; + public Guid SubFormat; + } + + [ComImport] + [Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] + class MMDeviceEnumerator { } + + [ComImport] + [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IMMDeviceEnumerator { + [PreserveSig] + int EnumAudioEndpoints(int dataFlow, uint stateMask, out IntPtr devices); + [PreserveSig] + int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint); + } + + [ComImport] + [Guid("D666063F-1587-4E43-81F1-B948E807363F")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IMMDevice { + [PreserveSig] + int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, out IAudioClient audioClient); + } + + [ComImport] + [Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IAudioClient { + [PreserveSig] + int Initialize(uint shareMode, uint streamFlags, long hnsBufferDuration, long hnsPeriodicity, IntPtr pFormat, IntPtr audioSessionGuid); + [PreserveSig] + int GetBufferSize(out uint bufferSize); + [PreserveSig] + int GetStreamLatency(out long latency); + [PreserveSig] + int GetCurrentPadding(out uint currentPadding); + [PreserveSig] + int IsFormatSupported(uint shareMode, IntPtr pFormat, out IntPtr closestMatch); + [PreserveSig] + int GetMixFormat(out IntPtr deviceFormat); + [PreserveSig] + int GetDevicePeriod(out long defaultDevicePeriod, out long minimumDevicePeriod); + [PreserveSig] + int Start(); + [PreserveSig] + int Stop(); + [PreserveSig] + int Reset(); + [PreserveSig] + int SetEventHandle(IntPtr eventHandle); + [PreserveSig] + int GetService(ref Guid iid, out IAudioCaptureClient captureClient); + } + + [ComImport] + [Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IAudioCaptureClient { + [PreserveSig] + int GetBuffer(out IntPtr data, out uint frames, out uint flags, out ulong devicePosition, out ulong qpcPosition); + [PreserveSig] + int ReleaseBuffer(uint frames); + [PreserveSig] + int GetNextPacketSize(out uint frames); + } + + public static void Capture(string outputPath, double seconds, int targetRate, int targetChannels) { + 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"); + IAudioClient audioClient; + Guid audioClientId = IID_IAudioClient; + Check(device.Activate(ref audioClientId, CLSCTX_ALL, IntPtr.Zero, out audioClient), "Activate IAudioClient"); + IntPtr mixFormatPtr; + Check(audioClient.GetMixFormat(out mixFormatPtr), "GetMixFormat"); + WAVEFORMATEX fmt = Marshal.PtrToStructure(mixFormatPtr); + 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; + 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); + init = audioClient.Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, activeFormatPtr, IntPtr.Zero); + } + Check(init, "Initialize loopback"); + IAudioCaptureClient captureClient; + Guid captureClientId = IID_IAudioCaptureClient; + Check(audioClient.GetService(ref captureClientId, out captureClient), "GetService IAudioCaptureClient"); + Check(audioClient.Start(), "Start"); + DateTime end = seconds > 0 ? DateTime.UtcNow.AddSeconds(seconds) : DateTime.MaxValue; + byte[] pcm = new byte[8192]; + try { + while (DateTime.UtcNow < end) { + uint packetFrames; + Check(captureClient.GetNextPacketSize(out packetFrames), "GetNextPacketSize"); + if (packetFrames == 0) { + Thread.Sleep(5); + continue; + } + IntPtr data; + uint frames; + uint flags; + ulong devicePosition; + ulong qpcPosition; + Check(captureClient.GetBuffer(out data, out frames, out flags, out devicePosition, out qpcPosition), "GetBuffer"); + try { + int sourceChannels = Math.Max(1, (int)fmt.nChannels); + int sourceBytesPerFrame = (int)fmt.nBlockAlign; + int sourceBits = (int)fmt.wBitsPerSample; + int sourceBytesPerSample = Math.Max(1, sourceBits / 8); + int frameBytes = targetChannels * 4; + int needed = checked((int)frames * frameBytes); + if (pcm.Length < needed) pcm = new byte[needed]; + int dst = 0; + for (int frame = 0; frame < frames; frame++) { + for (int ch = 0; ch < targetChannels; ch++) { + float sample = 0f; + if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) == 0) { + int srcCh = Math.Min(ch, sourceChannels - 1); + IntPtr src = IntPtr.Add(data, frame * sourceBytesPerFrame + srcCh * sourceBytesPerSample); + sample = ReadSample(src, sourceBits, fmt.wFormatTag, mixFormatPtr); + } + byte[] bytes = BitConverter.GetBytes(sample); + Buffer.BlockCopy(bytes, 0, pcm, dst, 4); + dst += 4; + } + } + output.Write(pcm, 0, needed); + output.Flush(); + } + finally { + Check(captureClient.ReleaseBuffer(frames), "ReleaseBuffer"); + } + } + } + finally { + audioClient.Stop(); + Marshal.FreeCoTaskMem(mixFormatPtr); + if (fallbackFormatPtr != IntPtr.Zero) Marshal.FreeHGlobal(fallbackFormatPtr); + Marshal.ReleaseComObject(captureClient); + Marshal.ReleaseComObject(audioClient); + Marshal.ReleaseComObject(device); + Marshal.ReleaseComObject(enumerator); + } + } + finally { + if (outputPath != "-") output.Dispose(); + } + } + + static void Check(int hr, string stage) { + if (hr < 0) { + Exception inner = Marshal.GetExceptionForHR(hr); + throw new InvalidOperationException(stage + " failed: 0x" + hr.ToString("X8") + " " + (inner == null ? "" : inner.Message), inner); + } + } + + static IntPtr MakeWaveFormatPcm(ushort channels, uint sampleRate, ushort bits) { + WAVEFORMATEX fmt = new WAVEFORMATEX(); + fmt.wFormatTag = 1; + fmt.nChannels = channels; + fmt.nSamplesPerSec = sampleRate; + fmt.wBitsPerSample = bits; + fmt.nBlockAlign = (ushort)(channels * bits / 8); + fmt.nAvgBytesPerSec = sampleRate * fmt.nBlockAlign; + fmt.cbSize = 0; + IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WAVEFORMATEX))); + Marshal.StructureToPtr(fmt, ptr, false); + return ptr; + } + + static float ReadSample(IntPtr source, int bits, ushort tag, IntPtr mixFormatPtr) { + bool isFloat = tag == 3; + if (tag == 65534) { + WAVEFORMATEXTENSIBLE ext = Marshal.PtrToStructure(mixFormatPtr); + isFloat = ext.SubFormat == new Guid("00000003-0000-0010-8000-00aa00389b71"); + } + if (isFloat && bits == 32) { + return Math.Max(-1f, Math.Min(1f, (float)Marshal.PtrToStructure(source, typeof(float)))); + } + if (bits == 16) { + return Marshal.ReadInt16(source) / 32768f; + } + if (bits == 24) { + int b0 = Marshal.ReadByte(source, 0); + int b1 = Marshal.ReadByte(source, 1); + int b2 = Marshal.ReadByte(source, 2); + int value = b0 | (b1 << 8) | (b2 << 16); + if ((value & 0x800000) != 0) value |= unchecked((int)0xff000000); + return Math.Max(-1f, Math.Min(1f, value / 8388608f)); + } + if (bits == 32) { + return Math.Max(-1f, Math.Min(1f, Marshal.ReadInt32(source) / 2147483648f)); + } + return 0f; + } + } +} +"@ + +Add-Type -TypeDefinition $source +[LocalCastBridge.WasapiLoopbackCapture]::Capture($Output, $Seconds, $SampleRate, $Channels) diff --git a/state/map.yaml b/state/map.yaml index e4e7fd1..d19f97e 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -212,8 +212,11 @@ current_status: except synchronized LocalCastBridge program surfaces. Co-streamer surface capture now records neighbor Focusrite and neighbor loopback while recording local loopback ground truth, then writes aligned co-streamer surface WAVs - for the stem packer. The neighbor desktop launcher now runs Voicemeeter - Remote routing so virtual inputs are sent to B3 before sender FFmpeg starts. + for the stem packer. The neighbor desktop launcher no longer uses + Voicemeeter; it restores the Focusrite speakers as the primary playback + device and the Focusrite analogue input as the default capture device. A + direct Core Audio WASAPI loopback shim exists, but the current Focusrite + render endpoint rejects loopback initialization with 0x88890008. Missing synchronized neighbor feeds are explicit silent placeholders, not raw unsynchronized substitutes. The live producer currently uses synthetic calibrated observations through the real `SensorRig.fuse` path until camera detector @@ -236,6 +239,7 @@ current_status: shotgun capture/transport path, 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 for - FOA encoding. Verify remote loopback again when actual neighbor app audio is - playing; if B3 remains silent with real app audio, replace the loopback - capture endpoint instead of widening OBS to unsynchronized raw sources. + FOA encoding. Fix neighbor loopback by using a render endpoint/driver that + accepts WASAPI loopback or a sender FFmpeg build with native WASAPI input; + do not reintroduce a virtual mixer unless direct loopback fails a concrete + invariant that the mixer actually satisfies.