From 73c5c1676f79d0790f3198b44abb14be2129af14 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 12 May 2026 06:48:31 +0100 Subject: [PATCH] Compile synth patches with bundled Faust --- scripts/publish-win-x64.ps1 | 4 + scripts/sync-faust-toolchain.ps1 | 57 ++ .../Audio/AquariumSynth.cs | 24 +- .../Ui/AquariumUi.cs | 9 + .../Audio/AquariumSynthHost.cs | 637 ++++++++++++++---- src/Aquarium.Engine/Render/Ui/DebugUi.cs | 36 + src/Aquarium.Epiphany/AquariumRuntime.cs | 7 +- state/evidence.jsonl | 1 + state/map.yaml | 5 +- state/memory.json | 4 +- 10 files changed, 656 insertions(+), 128 deletions(-) create mode 100644 scripts/sync-faust-toolchain.ps1 diff --git a/scripts/publish-win-x64.ps1 b/scripts/publish-win-x64.ps1 index fa33fee..ed03bcf 100644 --- a/scripts/publish-win-x64.ps1 +++ b/scripts/publish-win-x64.ps1 @@ -54,11 +54,15 @@ if ($LASTEXITCODE -ne 0) { throw "client runtime publish failed with exit code $LASTEXITCODE." } +& (Join-Path $PSScriptRoot "sync-faust-toolchain.ps1") -DestinationRoot (Join-Path $publishPath "Tools\Faust") + $requiredFiles = @( "Aquarium.Engine.exe", "Aquarium.Epiphany.dll", "Aquarium.Engine.Contracts.dll", "AquariumSynth.Dsl.dll", + "Tools\Faust\lib\faust.dll", + "Tools\Faust\share\faust\stdfaust.lib", "Assets\Aquarium-Engine-Icon.ico", "Assets\Fonts\Montserrat[wght].ttf", "Assets\Fonts\UbuntuSans[wdth,wght].ttf", diff --git a/scripts/sync-faust-toolchain.ps1 b/scripts/sync-faust-toolchain.ps1 new file mode 100644 index 0000000..151e687 --- /dev/null +++ b/scripts/sync-faust-toolchain.ps1 @@ -0,0 +1,57 @@ +param( + [string]$SourceRoot, + [string]$DestinationRoot +) + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version Latest + +if ([string]::IsNullOrWhiteSpace($SourceRoot)) { + $SourceRoot = if ($env:AQUARIUM_FAUST_HOME) { $env:AQUARIUM_FAUST_HOME } else { "C:\Program Files\Faust" } +} + +if ([string]::IsNullOrWhiteSpace($DestinationRoot)) { + $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") + $DestinationRoot = Join-Path $repoRoot "artifacts\faust\win-x64" +} + +$source = Resolve-Path $SourceRoot +$destination = $DestinationRoot +$sourceLib = Join-Path $source "lib\faust.dll" +$sourceShare = Join-Path $source "share\faust" +$sourceBin = Join-Path $source "bin" + +if (-not (Test-Path -LiteralPath $sourceLib)) { + throw "Faust DLL not found at $sourceLib" +} + +if (-not (Test-Path -LiteralPath $sourceShare)) { + throw "Faust libraries not found at $sourceShare" +} + +if (Test-Path -LiteralPath $destination) { + Remove-Item -LiteralPath $destination -Recurse -Force +} + +New-Item -ItemType Directory -Force -Path (Join-Path $destination "lib") | Out-Null +New-Item -ItemType Directory -Force -Path (Join-Path $destination "bin") | Out-Null +New-Item -ItemType Directory -Force -Path (Join-Path $destination "share\faust") | Out-Null + +Copy-Item -LiteralPath $sourceLib -Destination (Join-Path $destination "lib\faust.dll") -Force + +if (Test-Path -LiteralPath $sourceBin) { + Get-ChildItem -LiteralPath $sourceBin -File -Filter *.dll | + Copy-Item -Destination (Join-Path $destination "bin") -Force +} + +Get-ChildItem -LiteralPath $sourceShare -File -Filter *.lib | + Copy-Item -Destination (Join-Path $destination "share\faust") -Force + +$version = & (Join-Path $sourceBin "faust.exe") --version 2>$null | Select-Object -First 1 +if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($version)) { + Set-Content -Path (Join-Path $destination "VERSION.txt") -Value $version -Encoding UTF8 +} + +Write-Host "Faust toolchain synchronized:" +Write-Host " Source: $source" +Write-Host " Destination: $destination" diff --git a/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs b/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs index 5722939..6b34bb6 100644 --- a/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs +++ b/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs @@ -18,9 +18,10 @@ public sealed class AquariumSynthDocument AquariumSynthTrigger trigger, float gain = 1.0f, int faustCompileRevision = 0, - string? faustName = null) + string? faustName = null, + Action? statusSink = null) { - patches.Add(new AquariumSynthPatch(id, script, trigger, gain, faustCompileRevision, faustName ?? id)); + patches.Add(new AquariumSynthPatch(id, script, trigger, gain, faustCompileRevision, faustName ?? id, statusSink)); return this; } } @@ -31,7 +32,24 @@ public sealed record AquariumSynthPatch( AquariumSynthTrigger Trigger, float Gain = 1.0f, int FaustCompileRevision = 0, - string FaustName = "aquarium_patch"); + string FaustName = "aquarium_patch", + Action? StatusSink = null); + +public sealed record AquariumSynthPatchStatus( + string Id, + AquariumSynthPatchCompileState State, + string Message, + int Revision, + double ChangedAtSeconds); + +public enum AquariumSynthPatchCompileState +{ + Idle, + Queued, + Compiling, + Ready, + Failed +} public readonly record struct AquariumSynthTrigger(float IntervalSeconds, float PhaseSeconds = 0.0f) { diff --git a/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs b/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs index cb3ab93..562c4fc 100644 --- a/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs +++ b/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs @@ -72,6 +72,12 @@ public sealed class AquariumUiPanelBuilder(List controls) controls.Add(new AquariumUiText(label, read, write, tooltip, isVisible)); return this; } + + public AquariumUiPanelBuilder Readout(string label, Func read, string? tooltip = null, Func? isVisible = null) + { + controls.Add(new AquariumUiReadout(label, read, tooltip, isVisible)); + return this; + } } public readonly record struct AquariumUiOption(int Value, string Label); @@ -101,3 +107,6 @@ public sealed record AquariumUiOptions(string Label, Func Read, Action public sealed record AquariumUiText(string Label, Func Read, Action Write, string? Tooltip = null, Func? IsVisible = null) : AquariumUiControl(Label, Tooltip, IsVisible); + +public sealed record AquariumUiReadout(string Label, Func Read, string? Tooltip = null, Func? IsVisible = null) + : AquariumUiControl(Label, Tooltip, IsVisible); diff --git a/src/Aquarium.Engine/Audio/AquariumSynthHost.cs b/src/Aquarium.Engine/Audio/AquariumSynthHost.cs index e0355ad..4d63e08 100644 --- a/src/Aquarium.Engine/Audio/AquariumSynthHost.cs +++ b/src/Aquarium.Engine/Audio/AquariumSynthHost.cs @@ -1,4 +1,7 @@ +using System.Diagnostics; using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; using Aquarium.Engine.Audio; using AquariumSynth.Dsl; @@ -10,10 +13,12 @@ internal sealed class AquariumSynthHost : IDisposable private const int ChannelCount = 1; private const int BitsPerSample = 16; private const int MaxPlayingSounds = 16; + private const float CompileDebounceSeconds = 0.75f; - private readonly Dictionary cache = new(StringComparer.Ordinal); - private readonly Dictionary faustCompileRevisions = new(StringComparer.Ordinal); + private readonly Dictionary patches = new(StringComparer.Ordinal); private readonly List playing = []; + private FaustNative? faust; + private string? faustLoadError; private float timeSeconds; public void Update(AquariumSynthDocument synth, float deltaSeconds) @@ -24,76 +29,129 @@ internal sealed class AquariumSynthHost : IDisposable return; } + EnsureFaustLoaded(); foreach (var patch in synth.Patches) { - RequestFaustCompileIfNeeded(patch); + var runtime = GetRuntime(patch); + runtime.StatusSink = patch.StatusSink; + UpdatePatch(runtime, patch); + PublishStatus(runtime, patch); + if (ShouldTrigger(patch.Trigger, timeSeconds - deltaSeconds, timeSeconds)) { - Play(patch, synth.MasterGain); + Play(runtime, patch, synth.MasterGain); } } } - private void RequestFaustCompileIfNeeded(AquariumSynthPatch patch) + private PatchRuntime GetRuntime(AquariumSynthPatch patch) { - if (patch.FaustCompileRevision <= 0) + if (patches.TryGetValue(patch.Id, out var runtime)) + { + return runtime; + } + + runtime = new PatchRuntime(patch.Id); + patches.Add(patch.Id, runtime); + return runtime; + } + + private void UpdatePatch(PatchRuntime runtime, AquariumSynthPatch patch) + { + var desiredKey = CompileKey(patch); + if (runtime.DesiredKey != desiredKey) + { + runtime.DesiredKey = desiredKey; + runtime.ScriptChangedAt = timeSeconds; + runtime.SoundCache.Clear(); + if (runtime.State != AquariumSynthPatchCompileState.Compiling) + { + SetStatus(runtime, AquariumSynthPatchCompileState.Queued, "waiting for edit pause", patch.FaustCompileRevision); + } + } + + if (runtime.State == AquariumSynthPatchCompileState.Compiling || + runtime.ReadyKey == desiredKey || + runtime.DesiredKey != desiredKey || + timeSeconds - runtime.ScriptChangedAt < CompileDebounceSeconds) { return; } - if (faustCompileRevisions.TryGetValue(patch.Id, out var revision) && revision >= patch.FaustCompileRevision) + if (faust is null) { + SetStatus(runtime, AquariumSynthPatchCompileState.Failed, faustLoadError ?? "bundled Faust toolchain not found", patch.FaustCompileRevision); return; } - faustCompileRevisions[patch.Id] = patch.FaustCompileRevision; + StartCompile(runtime, patch, desiredKey, faust); + } + + private void StartCompile(PatchRuntime runtime, AquariumSynthPatch patch, string compileKey, FaustNative compiler) + { + SetStatus(runtime, AquariumSynthPatchCompileState.Compiling, "compiling Faust DSP", patch.FaustCompileRevision); var script = patch.Script; var patchId = patch.Id; - var faustName = patch.FaustName; - _ = Task.Run(async () => + var patchName = SafeFaustName(patch.FaustName); + var revision = patch.FaustCompileRevision; + + runtime.CompileTask = Task.Run(() => { try { - var export = FaustEmitter.EmitScript(script, new FaustExportOptions(SafeFaustName(faustName))); - var outputRoot = Path.Combine(AppContext.BaseDirectory, "Synth"); - Directory.CreateDirectory(outputRoot); - var dspPath = Path.Combine(outputRoot, $"{SafeFileName(patchId)}.dsp"); - var csharpPath = Path.Combine(outputRoot, $"{SafeFileName(patchId)}.cs"); - await File.WriteAllTextAsync(dspPath, export.Source); - var validation = await FaustCompiler.CompileAsync( - export.Source, - new FaustCompileOptions(FaustTargetLanguage.CSharp, csharpPath)); - if (validation is null) + var export = FaustEmitter.EmitScript(script, new FaustExportOptions(patchName)); + WriteDspSource(patchId, export.Source); + var synthPatch = PatchScript.Parse(script); + var duration = EstimateDuration(synthPatch); + var compiled = compiler.Compile(patchName, export.Source, duration); + lock (runtime.Sync) { - Console.WriteLine($"Aquarium synth patch `{patchId}` exported Faust DSP; Faust compiler not found."); - } - else if (validation.Success) - { - Console.WriteLine($"Aquarium synth patch `{patchId}` compiled Faust C# output."); - } - else - { - Console.WriteLine($"Aquarium synth patch `{patchId}` Faust compile failed: {validation.Stderr}"); + runtime.Compiled?.Dispose(); + runtime.Compiled = compiled; + runtime.ReadyKey = compileKey; + runtime.SoundCache.Clear(); + runtime.CompileTask = null; + runtime.SetStatus(AquariumSynthPatchCompileState.Ready, $"ready in {compiled.CompileMilliseconds:0} ms", revision, timeSeconds); } + + Console.WriteLine($"Aquarium synth patch `{patchId}` compiled with Faust in {compiled.CompileMilliseconds:0} ms."); } catch (Exception ex) { - Console.WriteLine($"Aquarium synth patch `{patchId}` Faust export failed: {ex.Message}"); + lock (runtime.Sync) + { + runtime.Compiled?.Dispose(); + runtime.Compiled = null; + runtime.ReadyKey = ""; + runtime.SoundCache.Clear(); + runtime.CompileTask = null; + runtime.SetStatus(AquariumSynthPatchCompileState.Failed, ex.Message, revision, timeSeconds); + } + + Console.WriteLine($"Aquarium synth patch `{patchId}` Faust compile failed: {ex.Message}"); } }); } - private bool ShouldTrigger(AquariumSynthTrigger trigger, float previousTime, float currentTime) + private void Play(PatchRuntime runtime, AquariumSynthPatch patch, float masterGain) { - var interval = MathF.Max(trigger.IntervalSeconds, 0.001f); - var previousBeat = MathF.Floor((previousTime - trigger.PhaseSeconds) / interval); - var currentBeat = MathF.Floor((currentTime - trigger.PhaseSeconds) / interval); - return currentBeat > previousBeat; - } + CachedSound? sound; + lock (runtime.Sync) + { + if (runtime.Compiled is null || runtime.ReadyKey != runtime.DesiredKey) + { + return; + } + + var gain = patch.Gain * masterGain; + var soundKey = gain.ToString("R", System.Globalization.CultureInfo.InvariantCulture); + if (!runtime.SoundCache.TryGetValue(soundKey, out sound)) + { + sound = new CachedSound(WriteWav(runtime.Compiled.Render(gain))); + runtime.SoundCache[soundKey] = sound; + } + } - private void Play(AquariumSynthPatch patch, float masterGain) - { - var sound = GetSound(patch, masterGain); if (sound.Bytes.Length == 0) { return; @@ -110,28 +168,71 @@ internal sealed class AquariumSynthHost : IDisposable instance.Play(); } - private CachedSound GetSound(AquariumSynthPatch patch, float masterGain) + private void EnsureFaustLoaded() { - var cacheKey = $"{patch.Id}:{patch.Gain}:{masterGain}:{patch.Script}"; - if (cache.TryGetValue(cacheKey, out var cached)) + if (faust is not null || faustLoadError is not null) { - return cached; + return; } - try + if (FaustNative.TryLoad(out var loaded, out var error)) { - var synthPatch = PatchScript.Parse(patch.Script); - var samples = SynthPatchRenderer.Render(synthPatch, patch.Gain * masterGain, SampleRate); - cached = new CachedSound(WriteWav(samples)); + faust = loaded; + Console.WriteLine($"Aquarium Faust toolchain loaded: {loaded!.Version}"); } - catch (Exception ex) + else { - Console.WriteLine($"Aquarium synth patch `{patch.Id}` failed: {ex.Message}"); - cached = new CachedSound([]); + faustLoadError = error; + Console.WriteLine($"Aquarium Faust toolchain unavailable: {error}"); + } + } + + private void PublishStatus(PatchRuntime runtime, AquariumSynthPatch patch) + { + AquariumSynthPatchStatus status; + lock (runtime.Sync) + { + status = runtime.Status; } - cache[cacheKey] = cached; - return cached; + patch.StatusSink?.Invoke(status); + } + + private void SetStatus(PatchRuntime runtime, AquariumSynthPatchCompileState state, string message, int revision) + { + lock (runtime.Sync) + { + runtime.SetStatus(state, message, revision, timeSeconds); + } + } + + private static bool ShouldTrigger(AquariumSynthTrigger trigger, float previousTime, float currentTime) + { + var interval = MathF.Max(trigger.IntervalSeconds, 0.001f); + var previousBeat = MathF.Floor((previousTime - trigger.PhaseSeconds) / interval); + var currentBeat = MathF.Floor((currentTime - trigger.PhaseSeconds) / interval); + return currentBeat > previousBeat; + } + + private static float EstimateDuration(SynthPatch patch) + { + var duration = patch.Voices.Count == 0 + ? 0.05f + : patch.Voices.Max(voice => voice.Envelope.DurationSeconds + 0.08f); + return Math.Clamp(duration, 0.05f, 3.0f); + } + + private static void WriteDspSource(string patchId, string source) + { + var outputRoot = Path.Combine(AppContext.BaseDirectory, "Synth"); + Directory.CreateDirectory(outputRoot); + File.WriteAllText(Path.Combine(outputRoot, $"{SafeFileName(patchId)}.dsp"), source); + } + + private static string CompileKey(AquariumSynthPatch patch) + { + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes($"{patch.FaustCompileRevision}\n{patch.FaustName}\n{patch.Script}")); + return Convert.ToHexString(bytes); } private static byte[] WriteWav(ReadOnlySpan samples) @@ -177,12 +278,47 @@ internal sealed class AquariumSynthHost : IDisposable public void Dispose() { + var compileTasks = patches.Values + .Select(runtime => runtime.CompileTask) + .Where(task => task is not null) + .Cast() + .ToArray(); + if (compileTasks.Length > 0) + { + _ = Task.WaitAll(compileTasks, TimeSpan.FromSeconds(10.0)); + } + foreach (var sound in playing) { sound.Dispose(); } + foreach (var runtime in patches.Values) + { + runtime.Compiled?.Dispose(); + } + playing.Clear(); + faust?.Dispose(); + } + + private sealed class PatchRuntime(string id) + { + public readonly object Sync = new(); + public readonly Dictionary SoundCache = new(StringComparer.Ordinal); + public string DesiredKey { get; set; } = ""; + public string ReadyKey { get; set; } = ""; + public float ScriptChangedAt { get; set; } + public CompiledFaustPatch? Compiled { get; set; } + public Task? CompileTask { get; set; } + public Action? StatusSink { get; set; } + public AquariumSynthPatchCompileState State => Status.State; + public AquariumSynthPatchStatus Status { get; private set; } = new(id, AquariumSynthPatchCompileState.Idle, "idle", 0, 0.0); + + public void SetStatus(AquariumSynthPatchCompileState state, string message, int revision, double changedAtSeconds) + { + Status = new AquariumSynthPatchStatus(id, state, message, revision, changedAtSeconds); + } } private sealed record CachedSound(byte[] Bytes); @@ -220,108 +356,369 @@ internal sealed class AquariumSynthHost : IDisposable [DllImport("winmm.dll", SetLastError = true)] private static extern bool PlaySound(IntPtr pszSound, IntPtr hmod, PlaySoundFlags fdwSound); -} -internal static class SynthPatchRenderer -{ - public static float[] Render(SynthPatch patch, float gain, int sampleRate) + private sealed class CompiledFaustPatch : IDisposable { - var duration = patch.Voices.Count == 0 - ? 0.0f - : patch.Voices.Max(voice => voice.Envelope.DurationSeconds + 0.08f); - duration = Math.Clamp(duration, 0.05f, 3.0f); - var samples = new float[(int)MathF.Ceiling(duration * sampleRate)]; - var random = new Random(1337); - for (var index = 0; index < samples.Length; index++) + private readonly FaustNative native; + private readonly IntPtr factory; + private readonly int outputCount; + private readonly int frameCount; + private bool disposed; + + public CompiledFaustPatch(FaustNative native, IntPtr factory, int outputCount, int frameCount, double compileMilliseconds) { - var t = index / (float)sampleRate; - var value = 0.0f; - foreach (var voice in patch.Voices) + this.native = native; + this.factory = factory; + this.outputCount = Math.Max(outputCount, 1); + this.frameCount = Math.Max(frameCount, 1); + CompileMilliseconds = compileMilliseconds; + } + + public double CompileMilliseconds { get; } + + public float[] Render(float gain) + { + ObjectDisposedException.ThrowIf(disposed, this); + var dsp = native.CreateInstance(factory); + try { - value += RenderVoice(voice, t, random); + native.InitInstance(dsp, SampleRate); + var outputs = new float[outputCount][]; + var outputPointers = new IntPtr[outputCount]; + var handles = new GCHandle[outputCount]; + try + { + for (var channel = 0; channel < outputCount; channel++) + { + outputs[channel] = new float[frameCount]; + handles[channel] = GCHandle.Alloc(outputs[channel], GCHandleType.Pinned); + outputPointers[channel] = handles[channel].AddrOfPinnedObject(); + } + + var pointersHandle = GCHandle.Alloc(outputPointers, GCHandleType.Pinned); + try + { + native.Compute(dsp, frameCount, IntPtr.Zero, pointersHandle.AddrOfPinnedObject()); + } + finally + { + pointersHandle.Free(); + } + } + finally + { + foreach (var handle in handles) + { + if (handle.IsAllocated) + { + handle.Free(); + } + } + } + + var mono = new float[frameCount]; + for (var index = 0; index < frameCount; index++) + { + var sample = 0.0f; + for (var channel = 0; channel < outputCount; channel++) + { + sample += outputs[channel][index]; + } + + mono[index] = Math.Clamp(sample / outputCount * gain, -1.0f, 1.0f); + } + + return mono; + } + finally + { + native.DeleteInstance(dsp); + } + } + + public void Dispose() + { + if (disposed) + { + return; } - value *= patch.Gain * gain; - samples[index] = patch.SoftClip ? MathF.Tanh(value * 1.35f) : Math.Clamp(value, -1.0f, 1.0f); + native.DeleteFactory(factory); + disposed = true; } - - return samples; } - private static float RenderVoice(Voice voice, float timeSeconds, Random random) + private sealed class FaustNative : IDisposable { - var envelope = EnvelopeAt(voice.Envelope, timeSeconds); - if (envelope <= 0.0f) + private const int ErrorBufferBytes = 4096; + + private readonly IntPtr library; + private readonly CreateFactoryFromStringFn createFactoryFromString; + private readonly DeleteFactoryFn deleteFactory; + private readonly CreateInstanceFn createInstance; + private readonly DeleteInstanceFn deleteInstance; + private readonly InitInstanceFn initInstance; + private readonly ComputeInstanceFn computeInstance; + private readonly GetNumOutputsFn getNumOutputs; + private readonly StartFactoriesFn startFactories; + private readonly StopFactoriesFn stopFactories; + private readonly string sharePath; + private bool disposed; + + private FaustNative(IntPtr library, string version, string sharePath) { - return 0.0f; + this.library = library; + Version = version; + this.sharePath = sharePath; + createFactoryFromString = Export("createCDSPFactoryFromString"); + deleteFactory = Export("deleteCDSPFactory"); + createInstance = Export("createCDSPInstance"); + deleteInstance = Export("deleteCDSPInstance"); + initInstance = Export("initCDSPInstance"); + computeInstance = Export("computeCDSPInstance"); + getNumOutputs = Export("getNumOutputsCDSPInstance"); + startFactories = Export("startMTDSPFactories"); + stopFactories = Export("stopMTDSPFactories"); + _ = startFactories(); } - var frequency = MathF.Max( - voice.Pitch.MinFrequencyHz, - voice.Oscillator.FrequencyHz * MathF.Pow(2.0f, voice.Pitch.RampPerSecond * timeSeconds + 0.5f * voice.Pitch.DeltaRampPerSecond * timeSeconds * timeSeconds)); - if (voice.Pitch.VibratoDepth > 0.0f && timeSeconds >= voice.Pitch.VibratoDelaySeconds) + public string Version { get; } + + public static bool TryLoad(out FaustNative? native, out string? error) { - frequency *= 1.0f + MathF.Sin(MathF.Tau * (timeSeconds - voice.Pitch.VibratoDelaySeconds) * voice.Pitch.VibratoHz) * voice.Pitch.VibratoDepth; + native = null; + error = null; + var home = FaustToolchain.Find(); + if (home is null) + { + error = "Faust toolchain not found. Expected Tools\\Faust beside Aquarium.Engine.exe or AQUARIUM_FAUST_HOME."; + return false; + } + + var dllPath = Path.Combine(home, "lib", "faust.dll"); + if (!File.Exists(dllPath)) + { + error = $"Faust DLL not found at {dllPath}."; + return false; + } + + var binPath = Path.Combine(home, "bin"); + var libPath = Path.Combine(home, "lib"); + var path = Environment.GetEnvironmentVariable("PATH") ?? ""; + Environment.SetEnvironmentVariable("PATH", $"{libPath};{binPath};{path}"); + + try + { + var library = NativeLibrary.Load(dllPath); + var getVersion = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, "getCLibFaustVersion")); + var version = Marshal.PtrToStringUTF8(getVersion()) ?? "unknown"; + native = new FaustNative(library, version, Path.Combine(home, "share", "faust")); + return true; + } + catch (Exception ex) + { + error = ex.Message; + return false; + } } - if (voice.Arpeggio is { } arpeggio && timeSeconds >= arpeggio.DelaySeconds) + public CompiledFaustPatch Compile(string name, string source, float durationSeconds) { - frequency *= arpeggio.Multiplier; + ObjectDisposedException.ThrowIf(disposed, this); + var stopwatch = Stopwatch.StartNew(); + using var args = new NativeStringArray(["-I", sharePath, "-single", "-ftz", "2", "-vec", "-lv", "1"]); + using var nativeName = new NativeUtf8String(name); + using var nativeSource = new NativeUtf8String(source); + using var target = new NativeUtf8String(""); + var errorBuffer = Marshal.AllocHGlobal(ErrorBufferBytes); + try + { + Span empty = stackalloc byte[ErrorBufferBytes]; + Marshal.Copy(empty.ToArray(), 0, errorBuffer, ErrorBufferBytes); + var factory = createFactoryFromString( + nativeName.Pointer, + nativeSource.Pointer, + args.Count, + args.Pointer, + target.Pointer, + errorBuffer, + -1); + if (factory == IntPtr.Zero) + { + var message = Marshal.PtrToStringUTF8(errorBuffer) ?? "unknown Faust compile failure"; + throw new InvalidOperationException(message.Trim()); + } + + var probe = createInstance(factory); + if (probe == IntPtr.Zero) + { + deleteFactory(factory); + throw new InvalidOperationException("Faust compiled but failed to create a DSP instance."); + } + + try + { + var outputs = Math.Max(getNumOutputs(probe), 1); + var frames = Math.Max(1, (int)MathF.Ceiling(durationSeconds * SampleRate)); + stopwatch.Stop(); + return new CompiledFaustPatch(this, factory, outputs, frames, stopwatch.Elapsed.TotalMilliseconds); + } + finally + { + deleteInstance(probe); + } + } + finally + { + Marshal.FreeHGlobal(errorBuffer); + } } - var phase = Frac(timeSeconds * frequency + voice.Oscillator.Phase); - var value = voice.Oscillator.Waveform switch + public IntPtr CreateInstance(IntPtr factory) { - Waveform.Sine => MathF.Sin(MathF.Tau * phase), - Waveform.Square => phase < voice.Oscillator.Duty ? -0.5f : 0.5f, - Waveform.Sawtooth => phase * 2.0f - 1.0f, - Waveform.Triangle => 1.0f - 4.0f * MathF.Abs(phase - 0.5f), - Waveform.Noise => random.NextSingle() * 2.0f - 1.0f, - _ => 0.0f, - }; + var dsp = createInstance(factory); + if (dsp == IntPtr.Zero) + { + throw new InvalidOperationException("failed to create Faust DSP instance"); + } - if (voice.Color.TremoloDepth > 0.0f && voice.Color.TremoloHz > 0.0f) - { - value *= 1.0f - Math.Clamp(voice.Color.TremoloDepth, 0.0f, 1.0f) * (0.5f + 0.5f * MathF.Sin(MathF.Tau * voice.Color.TremoloHz * timeSeconds)); + return dsp; } - var drive = Math.Clamp(voice.Color.Drive, 0.0f, 1.0f); - if (drive > 0.0f) + public void DeleteFactory(IntPtr factory) => _ = deleteFactory(factory); + + public void DeleteInstance(IntPtr dsp) => deleteInstance(dsp); + + public void InitInstance(IntPtr dsp, int sampleRate) => initInstance(dsp, sampleRate); + + public void Compute(IntPtr dsp, int count, IntPtr inputs, IntPtr outputs) => computeInstance(dsp, count, inputs, outputs); + + public void Dispose() { - var amount = 1.0f + drive * 12.0f; - value = MathF.Tanh(value * amount) / MathF.Tanh(amount); + if (disposed) + { + return; + } + + stopFactories(); + NativeLibrary.Free(library); + disposed = true; } - return value * envelope * voice.Gain; + private T Export(string name) + where T : Delegate + { + return Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, name)); + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr GetVersion(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr CreateFactoryFromStringFn(IntPtr name, IntPtr content, int argc, IntPtr argv, IntPtr target, IntPtr error, int optLevel); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool DeleteFactoryFn(IntPtr factory); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr CreateInstanceFn(IntPtr factory); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void DeleteInstanceFn(IntPtr dsp); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void InitInstanceFn(IntPtr dsp, int sampleRate); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void ComputeInstanceFn(IntPtr dsp, int count, IntPtr inputs, IntPtr outputs); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int GetNumOutputsFn(IntPtr dsp); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate bool StartFactoriesFn(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void StopFactoriesFn(); } - private static float EnvelopeAt(Envelope envelope, float timeSeconds) + private static class FaustToolchain { - if (timeSeconds < 0.0f) + public static string? Find() { - return 0.0f; - } + var candidates = new[] + { + Environment.GetEnvironmentVariable("AQUARIUM_FAUST_HOME"), + Path.Combine(AppContext.BaseDirectory, "Tools", "Faust"), + @"C:\Program Files\Faust" + }; - if (envelope.AttackSeconds > 0.0f && timeSeconds < envelope.AttackSeconds) - { - return timeSeconds / envelope.AttackSeconds; - } + foreach (var candidate in candidates) + { + if (string.IsNullOrWhiteSpace(candidate)) + { + continue; + } - var sustainStart = envelope.AttackSeconds; - if (timeSeconds < sustainStart + envelope.SustainSeconds) - { - var sustainT = envelope.SustainSeconds <= 0.0f ? 1.0f : (timeSeconds - sustainStart) / envelope.SustainSeconds; - return 1.0f + (1.0f - sustainT) * 2.0f * envelope.Punch; - } + var root = Path.GetFullPath(candidate); + if (File.Exists(Path.Combine(root, "lib", "faust.dll")) && + Directory.Exists(Path.Combine(root, "share", "faust"))) + { + return root; + } + } - var decayStart = sustainStart + envelope.SustainSeconds; - if (timeSeconds < decayStart + envelope.DecaySeconds) - { - return 1.0f - (timeSeconds - decayStart) / MathF.Max(envelope.DecaySeconds, 0.0001f); + return null; } - - return 0.0f; } - private static float Frac(float value) => value - MathF.Floor(value); + private sealed class NativeUtf8String : IDisposable + { + public NativeUtf8String(string value) + { + Pointer = Marshal.StringToCoTaskMemUTF8(value); + } + + public IntPtr Pointer { get; } + + public void Dispose() + { + if (Pointer != IntPtr.Zero) + { + Marshal.FreeCoTaskMem(Pointer); + } + } + } + + private sealed class NativeStringArray : IDisposable + { + private readonly NativeUtf8String[] strings; + private readonly GCHandle handle; + + public NativeStringArray(IReadOnlyList values) + { + strings = values.Select(value => new NativeUtf8String(value)).ToArray(); + var pointers = strings.Select(value => value.Pointer).ToArray(); + Count = pointers.Length; + handle = GCHandle.Alloc(pointers, GCHandleType.Pinned); + Pointer = handle.AddrOfPinnedObject(); + } + + public int Count { get; } + + public IntPtr Pointer { get; } + + public void Dispose() + { + if (handle.IsAllocated) + { + handle.Free(); + } + + foreach (var value in strings) + { + value.Dispose(); + } + } + } } diff --git a/src/Aquarium.Engine/Render/Ui/DebugUi.cs b/src/Aquarium.Engine/Render/Ui/DebugUi.cs index fb8a7ea..8ea8dc2 100644 --- a/src/Aquarium.Engine/Render/Ui/DebugUi.cs +++ b/src/Aquarium.Engine/Render/Ui/DebugUi.cs @@ -105,6 +105,9 @@ internal sealed class DebugUi case AquariumUiText text: controls.Add(new TextControl(text.Label, text.Read, text.Write, text.Tooltip, () => text.Visible)); break; + case AquariumUiReadout readout: + controls.Add(new ReadoutControl(readout.Label, readout.Read, readout.Tooltip, () => readout.Visible)); + break; } } @@ -433,6 +436,12 @@ internal sealed class DebugUi controls.Add(new TextControl(label, read, write, tooltip, isVisible)); return this; } + + public DebugUiPanel Readout(string label, Func read, string? tooltip = null, Func? isVisible = null) + { + controls.Add(new ReadoutControl(label, read, tooltip, isVisible)); + return this; + } } public readonly record struct DebugUiOption(int Value, string Label); @@ -804,6 +813,33 @@ internal sealed class DebugUi } } + private sealed class ReadoutControl(string label, Func read, string? tooltip, Func? isVisible) + : DebugUiControl(label, tooltip, isVisible) + { + public override bool IsInteractive => !string.IsNullOrWhiteSpace(Tooltip); + + public override void Draw( + ID2D1RenderTarget target, + IDWriteTextFormat format, + ID2D1SolidColorBrush rowBrush, + ID2D1SolidColorBrush hoverRowBrush, + ID2D1SolidColorBrush activeRowBrush, + ID2D1SolidColorBrush outlineBrush, + ID2D1SolidColorBrush primaryBrush, + ID2D1SolidColorBrush quietBrush, + ID2D1SolidColorBrush accentBrush, + ID2D1SolidColorBrush accentHoverBrush, + ID2D1SolidColorBrush accentActiveBrush, + ID2D1SolidColorBrush dimAccentBrush, + ID2D1SolidColorBrush trackHoverBrush, + ID2D1SolidColorBrush trackActiveBrush) + { + DrawRow(target, rowBrush, hoverRowBrush, activeRowBrush, outlineBrush); + target.DrawText(Label.ToUpperInvariant(), format, LabelBounds(), accentBrush, DrawTextOptions.Clip); + target.DrawText(read(), format, RectFromEdges(Bounds.Left + LabelWidth + 10.0f, Bounds.Top, Bounds.Right - 8.0f, Bounds.Bottom), primaryBrush, DrawTextOptions.Clip); + } + } + private abstract class SliderControl(string label, string? tooltip, Func? isVisible) : DebugUiControl(label, tooltip, isVisible) { private const float ThumbRadius = 4.0f; diff --git a/src/Aquarium.Epiphany/AquariumRuntime.cs b/src/Aquarium.Epiphany/AquariumRuntime.cs index 7fcfb70..522f7ca 100644 --- a/src/Aquarium.Epiphany/AquariumRuntime.cs +++ b/src/Aquarium.Epiphany/AquariumRuntime.cs @@ -26,6 +26,7 @@ public sealed class AquariumRuntime : IAquariumRuntime private string patchScript = "v w=sin f=440 g=.18 a=.002 s=.05 d=.35 pu=.28;v w=tri f=880 g=.04 s=.03 d=.28"; private int patchRate = 4; private int faustCompileRevision; + private AquariumSynthPatchStatus synthPatchStatus = new("epiphany-editor", AquariumSynthPatchCompileState.Idle, "idle", 0, 0.0); public AquariumRuntime(AquariumRuntimeOptions options) { @@ -54,9 +55,10 @@ public sealed class AquariumRuntime : IAquariumRuntime .Slider("Time", () => timeSeconds, value => timeSeconds = MathF.Max(0.0f, value), 0.0f, 720.0f, "0.0", "Scrubs Epiphany simulation time.") .Button("Flush State", FlushState, "Writes current Epiphany runtime state to CultCache.") .Section("Synth") + .Readout("Faust", () => $"{synthPatchStatus.State}: {synthPatchStatus.Message}", "Patch compilation status from Aquarium's bundled Faust toolchain.") .Text("Patch", () => patchScript, value => patchScript = value, "Aquarium patch DSL. Enter inserts ';'.") .Slider("Rate", () => patchRate, value => patchRate = Math.Clamp(value, 1, 12), 1, 12, "Triggers per 16 seconds.") - .Button("Compile Faust", () => faustCompileRevision++, "Exports Faust DSP and compiles C# output when Faust is installed.")); + .Button("Compile Faust", () => faustCompileRevision++, "Forces an async Faust compile through Aquarium's bundled toolchain.")); } public AquariumRuntimeOptions Options { get; } @@ -75,7 +77,8 @@ public sealed class AquariumRuntime : IAquariumRuntime AquariumSynthTrigger.Repeat(16.0f / Math.Max(patchRate, 1)), 1.0f, faustCompileRevision, - "epiphany_editor"); + "epiphany_editor", + status => synthPatchStatus = status); public AquariumFrame Frame => new(ViewFrame, cameraRig.Position, timeSeconds); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 58fa48c..a664ed3 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -55,3 +55,4 @@ {"timestamp":"2026-05-12T04:30:00+01:00","topic":"engine-client-boundary-vocabulary","lesson":"Aquarium.Engine and Aquarium.Engine.Contracts must speak renderer vocabulary, not Epiphany policy vocabulary. Engine contracts expose ViewFrame, height-field brushes, SDF objects, SDF lights, generic shader manifests, and generic proxy passes. Epiphany may call its own things grid, agents, bodies, or roles, but the engine only consumes declared rendering data. Enforce this with scripts/verify-boundaries.ps1 before every architectural pass.","files":["scripts/verify-boundaries.ps1","src/Aquarium.Engine.Contracts","src/Aquarium.Engine","src/Aquarium.Epiphany","state/memory.json","state/map.yaml"],"source":"engine-client extraction correction"} {"timestamp":"2026-05-12T05:30:00+01:00","topic":"client-ui-composition-contract","lesson":"Keep the engine debug panel as engine-owned UI, but expose a separate AquariumUiDocument contract for client overlay panels. Clients compose controls through Vortice-free panel builders; Aquarium.Engine translates those declarations into its DirectWrite/Direct2D overlay and owns input dispatch. Do not let Epiphany depend on DebugUi internals.","files":["src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/DirectWriteOverlay.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/memory.json"],"source":"client UI abstraction pass"} {"timestamp":"2026-05-12T06:15:00+01:00","topic":"synth-composition-contract","lesson":"Aquarium synth integration should mirror the UI boundary: clients declare patch scripts and trigger policy through AquariumSynthDocument, while Aquarium.Engine hosts preview playback and Faust export/compile requests. The current editor sound path is intentionally a pre-rendered preview; optimized realtime Faust DSP loading remains a separate engine-hosting pass, not something to smuggle into the DSL or client.","files":["src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs","src/Aquarium.Engine/Audio/AquariumSynthHost.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/memory.json"],"source":"synth API integration pass"} +{"timestamp":"2026-05-12T06:45:00+01:00","topic":"bundled-libfaust-dsp-host","lesson":"Aquarium users should not need a local Faust install. Published builds now bundle a slim Tools/Faust runtime, and AquariumSynthHost uses libfaust's LLVM C ABI to compile patch DSL output into native DSP factories asynchronously. Generated C# is not the optimized path. The current SFX path renders one-shot buffers from compiled Faust instances; the next cut is a proper streaming mixer/device backend over the same compiled-DSP spine.","files":["src/Aquarium.Engine/Audio/AquariumSynthHost.cs","scripts/sync-faust-toolchain.ps1","scripts/publish-win-x64.ps1","src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/memory.json","state/map.yaml"],"source":"user direction on bundled Faust and maximum-performance compiled DSP"} diff --git a/state/map.yaml b/state/map.yaml index 345e001..f27d0bf 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -23,6 +23,7 @@ current_model: overlay_text: src/Aquarium.Engine/Render/DirectWriteOverlay.cs debug_ui: src/Aquarium.Engine/Render/Ui/DebugUi.cs synth_host: src/Aquarium.Engine/Audio/AquariumSynthHost.cs + faust_toolchain_sync: scripts/sync-faust-toolchain.ps1 runtime_loader: src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs dev_reload: scripts/dev-reload.ps1 dev_watch: scripts/dev-watch.ps1 @@ -78,7 +79,7 @@ renderer_state: - SDF light buffer feeds Self emission and direct object lighting; future other Selves should join this light lane, not a generic field-instance table. - Studio2 PMREM and irradiance DDS cubemaps are loaded as D3D12 TextureCubes; PMREM serves roughness-mip specular, irradiance serves Lambertian diffuse IBL for non-metal bodies. - DirectWrite/Direct2D debug UI panel with code-first controls bound to renderer state. - - AquariumSynthDocument exposes client-declared patch scripts, trigger cadence, gain, and Faust compile revision; Aquarium.Engine hosts editor preview playback and writes Faust DSP/generated output when requested. + - AquariumSynthDocument exposes client-declared patch scripts, trigger cadence, gain, Faust compile revision, and compile status callbacks; Aquarium.Engine compiles patches asynchronously through bundled libfaust/LLVM and renders SFX buffers from compiled DSP instances. - Global GraphicsSettings document feeding render debug, exposure, bloom intensity, and bloom veil. - Temporal resolve uses scene color, metadata, and control history only; dormant event history lanes are cut until a real producer and consumer contract exists. - Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them. @@ -97,7 +98,7 @@ next_actions: - Keep scripts/verify-boundaries.ps1 green: Aquarium.Engine and Aquarium.Engine.Contracts must not contain Epiphany/client policy nouns such as grid, agent, body, or epiphany. - Verify publish output after every packaging-affecting change. - Grow renderer debug controls through the Direct2D/DirectWrite overlay path. - - Replace synth preview playback with generated Faust DSP loading when the optimized realtime host is ready. + - Replace temporary WinMM SFX playback with a real streaming audio mixer/device backend that consumes ready compiled Faust DSP instances. - Follow research/rendering/hdr-pbr-presentation.md before changing HDR exposure, bloom, tonemapping, or display transforms. - Follow docs/tsr-inspired-taa-spec.md when changing current temporal diagnostics. - Promote future runtime knobs into typed CultCache documents before they become process folklore. diff --git a/state/memory.json b/state/memory.json index ba6e0c6..06a877a 100644 --- a/state/memory.json +++ b/state/memory.json @@ -76,7 +76,9 @@ "audio": [ "Aquarium.Engine.Contracts exposes AquariumSynthDocument as the client-facing synth composition surface. Clients declare patch scripts, trigger cadence, gain, and Faust compile revision; Aquarium.Engine owns patch preview playback, Faust DSP export, and eventual optimized DSP hosting.", "AquariumSynth.Dsl is the patch language dependency. Keep the DSL parser and Faust emitter in the synth library; Aquarium should host and schedule patches through contracts rather than baking client sound policy into the engine.", - "Current Aquarium synth playback is a pre-rendered preview path for editor experimentation. Faust export and compile requests write DSP and generated output when Faust is installed, but generated realtime DSP loading is still the next optimization pass. Do not overclaim it as complete." + "Aquarium bundles Faust as a runtime toolchain under Tools/Faust for published builds and falls back to AQUARIUM_FAUST_HOME or C:/Program Files/Faust in dev. Do not require users to install Faust separately.", + "Aquarium synth patches compile asynchronously through libfaust's LLVM C ABI, not generated C#. The editor should surface Queued, Compiling, Ready, and Failed states; the render/audio frame must never block on DSP compilation.", + "Current SFX playback renders one-shot buffers from compiled Faust DSP instances and plays them through the temporary WinMM path. The next audio cut is a real streaming mixer/device backend that calls ready compiled DSP instances from the audio engine, never from UI or compile code." ], "state_and_reload": [ "CultCache is the client memory organ. Runtime state, camera, renderer knobs, body state, UI state, and future Epiphany connection state should be typed Cult documents.",