From 61751bf4eed321386c95384d63a46cbcebb12d8b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 31 May 2026 02:35:46 +0100 Subject: [PATCH] Add system loopback audio stems --- .../Audio/AquariumAudio.cs | 46 +++ src/Aquarium.Engine/AquariumHost.cs | 1 + .../Audio/AquariumSynthHost.cs | 44 +++ .../Audio/WasapiLoopbackCaptureDevice.cs | 331 ++++++++++++++++++ state/evidence.jsonl | 1 + state/map.yaml | 5 + .../SynthPlaybackTests.cs | 20 ++ 7 files changed, 448 insertions(+) create mode 100644 src/Aquarium.Engine/Audio/WasapiLoopbackCaptureDevice.cs diff --git a/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs b/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs index 05e8fc8..c290253 100644 --- a/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs +++ b/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs @@ -8,6 +8,7 @@ public sealed class AquariumAudioDocument private readonly ConcurrentQueue controlFrames = new(); private readonly ConcurrentQueue streamingDspPrograms = new(); private readonly ConcurrentQueue streamingAudioBlocks = new(); + private readonly ConcurrentQueue captureRequests = new(); public static AquariumAudioDocument Empty { get; } = new(); @@ -131,6 +132,38 @@ public sealed class AquariumAudioDocument return drained; } + + public void EnqueueSystemLoopbackCapture( + string profileId, + string sourceId, + string displayName, + bool enabled, + long sequence) + { + if (string.IsNullOrWhiteSpace(profileId)) + { + return; + } + + captureRequests.Enqueue(new AquariumAudioCaptureRequest( + profileId, + string.IsNullOrWhiteSpace(sourceId) ? "system-loopback" : sourceId, + string.IsNullOrWhiteSpace(displayName) ? "System audio" : displayName, + AquariumAudioCaptureKind.SystemLoopback, + enabled, + sequence)); + } + + public IReadOnlyList DrainCaptureRequests(int maxRequests = 8) + { + var drained = new List(); + while (drained.Count < maxRequests && captureRequests.TryDequeue(out var request)) + { + drained.Add(request); + } + + return drained; + } } public sealed record AquariumPcmAudioChunk(float[] MonoSamples, int SampleRate, float LeftGain = 1.0f, float RightGain = 1.0f); @@ -178,6 +211,19 @@ public sealed record AquariumStreamingAudioChannel( string SourceId, float[] Samples); +public enum AquariumAudioCaptureKind +{ + SystemLoopback +} + +public sealed record AquariumAudioCaptureRequest( + string ProfileId, + string SourceId, + string DisplayName, + AquariumAudioCaptureKind Kind, + bool Enabled, + long Sequence); + public sealed record AquariumAudioStemFrame( string ProfileId, IReadOnlyList Channels, diff --git a/src/Aquarium.Engine/AquariumHost.cs b/src/Aquarium.Engine/AquariumHost.cs index 7ba0c72..aaa0961 100644 --- a/src/Aquarium.Engine/AquariumHost.cs +++ b/src/Aquarium.Engine/AquariumHost.cs @@ -134,6 +134,7 @@ public static class AquariumHost activeRuntime.OnSceneReady(); sceneReadyRuntime = activeRuntime; synthHost ??= new AquariumSynthHost(audioStemBus); + synthHost.Update(AquariumSynthDocument.Combine(activeRuntime.Synth, renderer.DebugSynth), activeRuntime.Audio, 0.0f); lastFrame = frameClock.Elapsed; } } diff --git a/src/Aquarium.Engine/Audio/AquariumSynthHost.cs b/src/Aquarium.Engine/Audio/AquariumSynthHost.cs index 798c7df..84e5b91 100644 --- a/src/Aquarium.Engine/Audio/AquariumSynthHost.cs +++ b/src/Aquarium.Engine/Audio/AquariumSynthHost.cs @@ -13,6 +13,8 @@ internal sealed class AquariumSynthHost : IDisposable private readonly IAquariumAudioStemBus audioStemBus; private readonly WasapiAudioDevice audioDevice = new(); private readonly AquaSynthPatchCompiler patchCompiler = new(new AquaSynthNativeOptions(DspSourceDirectory: Path.Combine(AppContext.BaseDirectory, "Synth"))); + private WasapiLoopbackCaptureDevice? loopbackCapture; + private AquariumAudioCaptureRequest? activeCaptureRequest; private float timeSeconds; public AquariumSynthHost(IAquariumAudioStemBus? audioStemBus = null) @@ -81,6 +83,11 @@ internal sealed class AquariumSynthHost : IDisposable PlayMonitorOutputs(block, stemFrame); } + foreach (var request in audio.DrainCaptureRequests()) + { + ApplyCaptureRequest(request); + } + if (!synth.Enabled) { return; @@ -113,6 +120,42 @@ internal sealed class AquariumSynthHost : IDisposable } } + private void ApplyCaptureRequest(AquariumAudioCaptureRequest request) + { + if (request.Kind != AquariumAudioCaptureKind.SystemLoopback) + { + return; + } + + if (!request.Enabled) + { + if (activeCaptureRequest?.ProfileId == request.ProfileId) + { + loopbackCapture?.Dispose(); + loopbackCapture = null; + activeCaptureRequest = null; + } + + return; + } + + if (activeCaptureRequest is not null && + activeCaptureRequest.ProfileId == request.ProfileId && + activeCaptureRequest.SourceId == request.SourceId && + activeCaptureRequest.DisplayName == request.DisplayName) + { + return; + } + + loopbackCapture?.Dispose(); + loopbackCapture = new WasapiLoopbackCaptureDevice( + audioStemBus, + request.ProfileId, + request.SourceId, + request.DisplayName); + activeCaptureRequest = request; + } + private void PlayMonitorOutputs(AquariumStreamingAudioBlock block, AquariumAudioStemFrame stemFrame) { if (block.MonitorLeftChannel < 0 && block.MonitorRightChannel < 0) @@ -341,6 +384,7 @@ internal sealed class AquariumSynthHost : IDisposable } streamingDsp.Dispose(); + loopbackCapture?.Dispose(); audioDevice.Dispose(); patchCompiler.Dispose(); } diff --git a/src/Aquarium.Engine/Audio/WasapiLoopbackCaptureDevice.cs b/src/Aquarium.Engine/Audio/WasapiLoopbackCaptureDevice.cs new file mode 100644 index 0000000..93bee09 --- /dev/null +++ b/src/Aquarium.Engine/Audio/WasapiLoopbackCaptureDevice.cs @@ -0,0 +1,331 @@ +using System.Runtime.InteropServices; + +namespace Aquarium.Engine.Audio; + +internal sealed class WasapiLoopbackCaptureDevice : IDisposable +{ + private static readonly bool TraceAudio = !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("AQUARIUM_AUDIO_TRACE")); + + private readonly IAquariumAudioStemBus stemBus; + private readonly string profileId; + private readonly string sourceId; + private readonly string displayName; + private readonly Thread thread; + private volatile bool running = true; + private volatile bool started; + private long sequence; + + public WasapiLoopbackCaptureDevice( + IAquariumAudioStemBus stemBus, + string profileId, + string sourceId, + string displayName) + { + this.stemBus = stemBus; + this.profileId = profileId; + this.sourceId = sourceId; + this.displayName = displayName; + thread = new Thread(CaptureThread) + { + IsBackground = true, + Name = "Aquarium WASAPI Loopback" + }; + thread.Start(); + } + + public void Dispose() + { + running = false; + if (started) + { + thread.Join(TimeSpan.FromSeconds(2.0)); + } + } + + private void CaptureThread() + { + started = true; + var comInitialized = false; + IAudioClient? audioClient = null; + try + { + var hr = CoInitializeEx(IntPtr.Zero, CoInit.Multithreaded); + if (hr < 0) + { + Marshal.ThrowExceptionForHR(hr); + } + + comInitialized = true; +#pragma warning disable CA1416 + var enumeratorType = Type.GetTypeFromCLSID(MMDeviceEnumeratorClsid, throwOnError: true) + ?? throw new InvalidOperationException("MMDeviceEnumerator COM type is not available."); +#pragma warning restore CA1416 + var deviceEnumerator = (IMMDeviceEnumerator)(Activator.CreateInstance(enumeratorType) + ?? throw new InvalidOperationException("failed to create MMDeviceEnumerator")); + Marshal.ThrowExceptionForHR(deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.Render, ERole.Console, out var device)); + var audioClientId = typeof(IAudioClient).GUID; + Marshal.ThrowExceptionForHR(device.Activate(ref audioClientId, ClsCtx.All, IntPtr.Zero, out var audioClientObject)); + audioClient = (IAudioClient)audioClientObject; + Marshal.ThrowExceptionForHR(audioClient.GetMixFormat(out var mixFormatPointer)); + try + { + var format = WasapiFormat.FromPointer(mixFormatPointer); + Marshal.ThrowExceptionForHR(audioClient.Initialize( + AudioClientShareMode.Shared, + AudioClientStreamFlags.Loopback | AudioClientStreamFlags.NoPersist, + 0, + 0, + mixFormatPointer, + IntPtr.Zero)); + var captureClientId = typeof(IAudioCaptureClient).GUID; + Marshal.ThrowExceptionForHR(audioClient.GetService(ref captureClientId, out var captureClientObject)); + var captureClient = (IAudioCaptureClient)captureClientObject; + Marshal.ThrowExceptionForHR(audioClient.Start()); + Console.WriteLine($"Aquarium WASAPI loopback started: profile={profileId} {format.SampleRate} Hz, {format.Channels} channels, {format.BitsPerSample}-bit {format.SampleKind}."); + + while (running) + { + Marshal.ThrowExceptionForHR(captureClient.GetNextPacketSize(out var packetFrames)); + while (packetFrames > 0) + { + Marshal.ThrowExceptionForHR(captureClient.GetBuffer( + out var buffer, + out var frames, + out var flags, + out _, + out _)); + try + { + PublishPacket(buffer, frames, flags, format); + } + finally + { + Marshal.ThrowExceptionForHR(captureClient.ReleaseBuffer(frames)); + } + + Marshal.ThrowExceptionForHR(captureClient.GetNextPacketSize(out packetFrames)); + } + + Thread.Sleep(4); + } + + audioClient.Stop(); + } + finally + { + Marshal.FreeCoTaskMem(mixFormatPointer); + } + } + catch (Exception ex) + { + Console.WriteLine($"Aquarium WASAPI loopback unavailable: {ex.Message}"); + } + finally + { + audioClient?.Stop(); + if (comInitialized) + { + CoUninitialize(); + } + } + } + + private void PublishPacket(IntPtr buffer, int frameCount, uint flags, WasapiFormat format) + { + if (frameCount <= 0) + { + return; + } + + var mono = (flags & AudioCaptureBufferFlagsSilent) != 0 + ? new float[frameCount] + : format.SampleKind == WasapiSampleKind.Float32 + ? ReadFloat32(buffer, frameCount, format.Channels) + : ReadPcm16(buffer, frameCount, format.Channels); + stemBus.Publish(new AquariumAudioStemFrame( + profileId, + [new AquariumAudioStemChannel(0, "system_mix", displayName, sourceId, mono)], + frameCount, + format.SampleRate, + Interlocked.Increment(ref sequence))); + + if (TraceAudio) + { + Console.WriteLine($"Aquarium loopback packet: profile={profileId} frames={frameCount} seq={sequence}"); + } + } + + private static unsafe float[] ReadFloat32(IntPtr buffer, int frameCount, int channels) + { + var output = new float[frameCount]; + var input = (float*)buffer; + for (var frame = 0; frame < frameCount; frame++) + { + var sum = 0.0f; + for (var channel = 0; channel < channels; channel++) + { + sum += *input++; + } + + output[frame] = Math.Clamp(sum / Math.Max(1, channels), -1.0f, 1.0f); + } + + return output; + } + + private static unsafe float[] ReadPcm16(IntPtr buffer, int frameCount, int channels) + { + var output = new float[frameCount]; + var input = (short*)buffer; + for (var frame = 0; frame < frameCount; frame++) + { + var sum = 0.0f; + for (var channel = 0; channel < channels; channel++) + { + sum += *input++ / 32768.0f; + } + + output[frame] = Math.Clamp(sum / Math.Max(1, channels), -1.0f, 1.0f); + } + + return output; + } + + private readonly record struct WasapiFormat(int Channels, int SampleRate, int BitsPerSample, int BlockAlign, WasapiSampleKind SampleKind) + { + public static WasapiFormat FromPointer(IntPtr pointer) + { + var tag = Marshal.ReadInt16(pointer, 0); + var channels = Marshal.ReadInt16(pointer, 2); + var sampleRate = Marshal.ReadInt32(pointer, 4); + var blockAlign = Marshal.ReadInt16(pointer, 12); + var bitsPerSample = Marshal.ReadInt16(pointer, 14); + var kind = tag switch + { + WaveFormatIeeeFloat => WasapiSampleKind.Float32, + WaveFormatPcm => WasapiSampleKind.Pcm16, + WaveFormatExtensible when bitsPerSample == 32 => WasapiSampleKind.Float32, + _ => WasapiSampleKind.Pcm16 + }; + return new WasapiFormat(channels, sampleRate, bitsPerSample, blockAlign, kind); + } + } + + private enum WasapiSampleKind + { + Float32, + Pcm16 + } + + private const uint AudioCaptureBufferFlagsSilent = 0x2; + private const short WaveFormatPcm = 1; + private const short WaveFormatIeeeFloat = 3; + private const short WaveFormatExtensible = -2; + + [DllImport("ole32.dll")] + private static extern int CoInitializeEx(IntPtr pvReserved, CoInit dwCoInit); + + [DllImport("ole32.dll")] + private static extern void CoUninitialize(); + + [Flags] + private enum CoInit : uint + { + Multithreaded = 0x0 + } + + [Flags] + private enum ClsCtx : uint + { + All = 23 + } + + private enum EDataFlow + { + Render, + Capture, + All + } + + private enum ERole + { + Console, + Multimedia, + Communications + } + + private enum AudioClientShareMode + { + Shared, + Exclusive + } + + [Flags] + private enum AudioClientStreamFlags : uint + { + Loopback = 0x00020000, + NoPersist = 0x00080000 + } + + private static readonly Guid MMDeviceEnumeratorClsid = new("BCDE0395-E52F-467C-8E3D-C4579291692E"); + + [ComImport] + [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDeviceEnumerator + { + int EnumAudioEndpoints(EDataFlow dataFlow, uint stateMask, out IntPtr devices); + + int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice endpoint); + } + + [ComImport] + [Guid("D666063F-1587-4E43-81F1-B948E807363F")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDevice + { + int Activate(ref Guid iid, ClsCtx clsCtx, IntPtr activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object interfaceObject); + } + + [ComImport] + [Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IAudioClient + { + int Initialize(AudioClientShareMode shareMode, AudioClientStreamFlags streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr audioSessionGuid); + + int GetBufferSize(out int bufferFrameCount); + + int GetStreamLatency(out long latency); + + int GetCurrentPadding(out int paddingFrameCount); + + int IsFormatSupported(AudioClientShareMode shareMode, IntPtr format, out IntPtr closestMatch); + + int GetMixFormat(out IntPtr deviceFormat); + + int GetDevicePeriod(out long defaultDevicePeriod, out long minimumDevicePeriod); + + int Start(); + + int Stop(); + + int Reset(); + + int SetEventHandle(IntPtr eventHandle); + + int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object serviceInterface); + } + + [ComImport] + [Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IAudioCaptureClient + { + int GetBuffer(out IntPtr dataBuffer, out int numFramesToRead, out uint bufferFlags, out long devicePosition, out long qpcPosition); + + int ReleaseBuffer(int numFramesRead); + + int GetNextPacketSize(out int numFramesInNextPacket); + } +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 3c0e3ab..c12c1bb 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -315,3 +315,4 @@ {"timestamp":"2026-05-30T22:33:00+01:00","topic":"headless-pipeline-hang-root-cause","lesson":"The apparent Fensalir headless hang was an initial shader pipeline failure hidden behind the loading-frame loop. dotnet-stack showed the main thread sleeping in D3D12Renderer.RenderPipelineLoadingFrame; a dump of the background pipeline task revealed FileNotFoundException for Render/Shaders/D3D12SdfCommon.hlsli beside the Aquarium.Fensalir client shader output. D3D12FensalirSpine.hlsl includes engine SDF shared files by relative path, but Aquarium.Fensalir.csproj only copied client shaders. The fix copies D3D12SdfCommon.hlsli, D3D12SdfMath.hlsli, and D3D12SdfProxy.hlsli into the client shader output and makes initial pipeline failure throw instead of spinning silently. Verification: Fensalir and Engine builds passed, then headless Engine run compiled pipelines, captured artifacts/runtime/fensalir-stereo-depth-pipeline-smoke.png, and exited.","files":["src/Aquarium.Fensalir/Aquarium.Fensalir.csproj","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/evidence.jsonl","state/map.yaml"],"source":"dotnet-stack report plus dotnet-dump analyze on stuck headless process; dotnet run --project src/Aquarium.Engine/Aquarium.Engine.csproj --no-build -- --headless --capture-frame artifacts/runtime/fensalir-stereo-depth-pipeline-smoke.png"} {"ts":"2026-05-30T23:10:27+01:00","type":"decision","status":"ok","note":"Added the first Fensalir Leap point-cloud render lane: Mesh resources whose SourceUri is derived-from a SurfacePage allocate UAV-capable point-list buffers, D3D12PointCloudFromDisparityCS fills PositionNormalUvColor vertices/indices from disparity, and D3D12PointCloudPS renders them into scene candidate MRTs. Verified engine/client build, stereo/resize tests, and headless shader pipeline capture artifacts/runtime/fensalir-point-cloud-pipeline-smoke.png."} {"timestamp":"2026-05-30T23:41:55+01:00","topic":"reservoir-presentation-reconstruction","lesson":"The first final-pass reservoir reconstruction denoiser is worth keeping only after maturity gating. The shader samples a bounded resolved-reservoir neighborhood in D3D12ReservoirPresentationResolvePS and weights neighbors by field id, travel, normal, coverage, detail, color, guide confidence, domain validity, and neighbor agreement. Ungated and age-eager versions improved some frames but regressed the curve; the kept gate requires reservoir maturity before filter strength is allowed. Latest 320x180 sweep reservoir-sequence-20260530-232852-* versus higher-work-grid reference improved f2/f4/f8 and reduced average RMSE from 21.944 to 21.221 against the pre-reconstruction 20260530-221043 curve, while f1 still regressed and remains the next target.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","state/scratch.md","state/map.yaml"],"source":"artifacts/fensalir-captures/reservoir-loss-curve-20260530-232852.csv"} +{"timestamp":"2026-05-31T23:58:00+01:00","topic":"system-loopback-audio-stems","lesson":"System speaker capture now enters Fensalir through an explicit AquariumAudioDocument capture request. AquariumSynthHost owns the WASAPI loopback device, publishes mono system_mix AquariumAudioStemFrame packets through IAquariumAudioStemBus, and clients consume those stems without owning capture APIs. The host drains pending audio requests once when the scene-ready audio host is created, so short clients do not strand Start-time requests. This closes the live-audio input seam for visualizers such as Perlines while preserving the engine audio host as the authority for OS audio I/O.","files":["src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs","src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Audio/AquariumSynthHost.cs","src/Aquarium.Engine/Audio/WasapiLoopbackCaptureDevice.cs","tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs","state/map.yaml"],"source":"dotnet build Fensalir.sln; dotnet test tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj --no-build; scripts/dev-reload.ps1 -Headless -RetainSlots 1 -ClientProject E:\\Projects\\Perlines\\src\\Perlines\\Perlines.csproj showed WASAPI loopback started for profile perlines:system-loopback"} diff --git a/state/map.yaml b/state/map.yaml index 0824ca2..aa7efac 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -117,6 +117,11 @@ invariants: owns an `IAquariumAudioStemBus` service for published processed stems, optional monitor playback is explicit, and OBS-facing publication remains a later host cut. + - System audio capture is an engine-owned audio-host request, not a client + sidecar. Clients enqueue a profile-keyed system-loopback capture request on + `AquariumAudioDocument`; Fensalir owns WASAPI loopback capture, publishes a + mono `system_mix` stem through `IAquariumAudioStemBus`, and clients consume + it through the same stem service as streaming DSP outputs. - The named D3D12 program-output texture is an external publication surface. After copying the completed backbuffer into it, the renderer must leave the resource in `Common` so OBS/EVE/native consumers can transition it for diff --git a/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs b/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs index 6d5bef6..a99cf3a 100644 --- a/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs +++ b/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs @@ -59,6 +59,26 @@ public sealed class SynthPlaybackTests Assert.Empty(document.DrainStreamingAudioBlocks()); } + [Fact] + public void AquariumAudioDocumentDrainsLoopbackCaptureRequests() + { + var document = new AquariumAudioDocument(); + document.EnqueueSystemLoopbackCapture( + "perlines:system-loopback", + "windows-default-render", + "System mix", + enabled: true, + sequence: 7); + + var drained = document.DrainCaptureRequests(); + + Assert.Single(drained); + Assert.Equal(AquariumAudioCaptureKind.SystemLoopback, drained[0].Kind); + Assert.Equal("perlines:system-loopback", drained[0].ProfileId); + Assert.True(drained[0].Enabled); + Assert.Empty(document.DrainCaptureRequests()); + } + [Fact] public void StreamingDspHostProcessesControlDrivenInputBlocksWhenToolchainIsAvailable() {