Replace Voicemeeter loopback with direct WASAPI probe

This commit is contained in:
Meta Vens 2026-05-18 19:49:19 +01:00
commit 35034e94e3
8 changed files with 294 additions and 163 deletions

View file

@ -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'

View file

@ -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()
}

View file

@ -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

View file

@ -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<WAVEFORMATEX>(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<WAVEFORMATEX>(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<WAVEFORMATEXTENSIBLE>(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)