diff --git a/docs/audio-doctrine.md b/docs/audio-doctrine.md index 5da7148..575383a 100644 --- a/docs/audio-doctrine.md +++ b/docs/audio-doctrine.md @@ -122,6 +122,11 @@ authorities. ## Metrics Analysis exists to catch regressions and support search, not to crown winners. +Aquarium Faust output can be rendered through Faust-generated C# in authoring +tests, which gives us candidate audio buffers without depending on the old Rust +renderer. That is only half of parity: reference targets still need a real +external render or a captured, lawful fixture before the comparison means +anything. Useful metrics: diff --git a/docs/reference-synth-roadmap.md b/docs/reference-synth-roadmap.md index 4ca87af..c1fe1ea 100644 --- a/docs/reference-synth-roadmap.md +++ b/docs/reference-synth-roadmap.md @@ -35,6 +35,9 @@ source format hash. known structural expectations that prove Aquarium can express the same behavior. Weak "it parsed" tests do not prove expressivity, and references without a credible parity test path should not be consumed. +- Aquarium Faust output can be rendered through Faust-generated C# for candidate + audio comparison. Reference audio still needs a real source fixture or renderer; + do not compare a rebuild only against itself and call that parity. - Do not add a generic graph escape hatch until a specific family of references forces it. - When a reference target exceeds the current voice-centric DSL, document the @@ -68,8 +71,9 @@ First deliverable: - Convert one or two public-domain or project-authored DX7-style voices into `ReferencePatch` records. - Build an Aquarium DSL approximation using explicit FM templates. -- Add mel/envelope/spectral comparison against rendered Dexed or internal - reference output once the render path is chosen. +- Add mel/envelope/spectral comparison against rendered Dexed output or a + captured, licensed reference fixture. Aquarium candidate rendering exists; + the missing DX7 parity surface is the reference side. Source: [Dexed](https://github.com/asb2m10/dexed) diff --git a/src/AquariumSynth.Dsl/FaustExport.cs b/src/AquariumSynth.Dsl/FaustExport.cs index cdbed47..f52b4f2 100644 --- a/src/AquariumSynth.Dsl/FaustExport.cs +++ b/src/AquariumSynth.Dsl/FaustExport.cs @@ -20,6 +20,10 @@ public sealed record FaustCompileOptions(FaustTargetLanguage Language, string Ou public sealed record FaustValidation(string Command, bool Success, int? StatusCode, string Stdout, string Stderr); +public sealed record FaustRenderOptions(int SampleRate = 44100, float DurationSeconds = 1); + +public sealed record FaustRender(float[] Samples, int SampleRate, string Command, string Stdout, string Stderr); + public static class FaustEmitter { public static FaustExport EmitScript(string script, FaustExportOptions? options = null) => @@ -591,6 +595,66 @@ public static class FaustCompiler return await CompileAsync(source, new FaustCompileOptions(FaustTargetLanguage.Cpp, output), faustPath, cancellationToken); } + public static async Task RenderAsync( + string source, + FaustRenderOptions? options = null, + string? faustPath = null, + CancellationToken cancellationToken = default) + { + options ??= new FaustRenderOptions(); + faustPath ??= FindFaust(); + if (faustPath is null) return null; + + var frames = Math.Max(1, (int)MathF.Round(options.SampleRate * Math.Max(options.DurationSeconds, 1f / options.SampleRate))); + var tempDir = Path.Combine(Path.GetTempPath(), $"aquarium-synth-render-{Guid.NewGuid():N}"); + Directory.CreateDirectory(tempDir); + try + { + var sourcePath = Path.Combine(tempDir, "render.dsp"); + var generatedPath = Path.Combine(tempDir, "RenderDsp.cs"); + var outputPath = Path.Combine(tempDir, "render.f32"); + await File.WriteAllTextAsync(sourcePath, source, cancellationToken); + + var faust = await RunAsync( + faustPath, + ["-lang", "csharp", "-double", "-cn", "RenderDsp", "-o", generatedPath, sourcePath], + cancellationToken); + if (faust.ExitCode != 0) + { + return new FaustRender([], options.SampleRate, faustPath, faust.Stdout, faust.Stderr); + } + + var archDir = await FaustArchDirAsync(faustPath, cancellationToken); + var basePath = archDir is null ? null : Path.Combine(archDir, "CSharpFaustBase.cs"); + if (basePath is null || !File.Exists(basePath)) + { + return new FaustRender([], options.SampleRate, faustPath, faust.Stdout, $"could not find CSharpFaustBase.cs under Faust archdir `{archDir}`"); + } + + File.Copy(basePath, Path.Combine(tempDir, "CSharpFaustBase.cs")); + await File.WriteAllTextAsync(Path.Combine(tempDir, "Render.csproj"), RenderProjectSource(), cancellationToken); + await File.WriteAllTextAsync(Path.Combine(tempDir, "Program.cs"), RenderProgramSource(), cancellationToken); + + var dotnet = await RunAsync( + "dotnet", + ["run", "--project", Path.Combine(tempDir, "Render.csproj"), "--", outputPath, options.SampleRate.ToString(CultureInfo.InvariantCulture), frames.ToString(CultureInfo.InvariantCulture)], + cancellationToken); + if (dotnet.ExitCode != 0 || !File.Exists(outputPath)) + { + return new FaustRender([], options.SampleRate, "dotnet", dotnet.Stdout, dotnet.Stderr); + } + + var bytes = await File.ReadAllBytesAsync(outputPath, cancellationToken); + var samples = new float[bytes.Length / sizeof(float)]; + Buffer.BlockCopy(bytes, 0, samples, 0, samples.Length * sizeof(float)); + return new FaustRender(samples, options.SampleRate, "dotnet", dotnet.Stdout, dotnet.Stderr); + } + finally + { + Directory.Delete(tempDir, recursive: true); + } + } + private static string Language(FaustTargetLanguage language) => language switch { FaustTargetLanguage.C => "c", @@ -600,6 +664,48 @@ public static class FaustCompiler _ => throw new ArgumentOutOfRangeException(nameof(language), language, null) }; + private static async Task FaustArchDirAsync(string faustPath, CancellationToken cancellationToken) + { + var result = await RunAsync(faustPath, ["-archdir"], cancellationToken); + return result.ExitCode == 0 ? result.Stdout.Trim() : null; + } + + private static string RenderProjectSource() => + """ + + + Exe + net10.0 + enable + enable + + + """; + + private static string RenderProgramSource() => + """ + using System.Globalization; + + var outputPath = args[0]; + var sampleRate = int.Parse(args[1], CultureInfo.InvariantCulture); + var frames = int.Parse(args[2], CultureInfo.InvariantCulture); + var dsp = new RenderDsp(); + dsp.Init(sampleRate); + + var inputs = new double[dsp.GetNumInputs()][]; + for (var i = 0; i < inputs.Length; i++) inputs[i] = new double[frames]; + + var outputs = new double[dsp.GetNumOutputs()][]; + for (var i = 0; i < outputs.Length; i++) outputs[i] = new double[frames]; + + dsp.Compute(frames, inputs, outputs); + + await using var stream = File.Create(outputPath); + await using var writer = new BinaryWriter(stream); + var output = outputs.Length == 0 ? Array.Empty() : outputs[0]; + for (var i = 0; i < frames; i++) writer.Write((float)output[i]); + """; + private static async Task<(int ExitCode, string Stdout, string Stderr)> RunAsync( string fileName, IReadOnlyList arguments, diff --git a/state/evidence.jsonl b/state/evidence.jsonl index d6646d3..b8b237e 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -19,4 +19,5 @@ {"kind":"faust_polyphony","lesson":"Prefer Faust-managed MIDI polyphony over Aquarium graph inflation. Aquarium should emit a single voice graph with standard `freq`, `gain`, and `gate` controls plus `[midi:on][nvoices:n]`; Faust architectures own MIDI decoding and voice allocation unless a concrete target proves the boundary insufficient.","source":"Faust official MIDI/polyphony docs and user preference for Faust support on 2026-05-13"} {"kind":"operator_graph_parameters","lesson":"Readable operator graph fields bind runtime parameters at exact `/opgraphs/...` field paths: graph gain/note fields, operator ratio/level/feedback/envelope fields, and route index fields. Keep compact `ops=`/`edges=` as importer scaffolding and avoid graph-wide macro routing.","source":"operator graph field-site binding slice on 2026-05-13"} {"kind":"dx7_envelopes","lesson":"DX7 four-rate/four-level operator envelopes can be lowered to labeled Aquarium ADSR approximations plus gate duration, but this is not exact DX7 EG execution. Reference rebuilds should record approximation as matched pressure and exactness as still missing.","source":"DX7 envelope approximation slice on 2026-05-13; Yamaha DX7 manual describes EGs as four rates and four levels"} +{"kind":"render_parity_harness","lesson":"Aquarium Faust output can now be compiled to Faust-generated C# and rendered into mono float samples for AudioAnalyzer comparisons. This proves the candidate side of parity; DX7 parity still requires a real Dexed/reference render or captured licensed fixture, not self-comparison.","source":"Faust render parity harness slice on 2026-05-13"} {"kind":"reference_parity_doctrine","lesson":"External synth references exist to exercise Aquarium DSL expressiveness, not to clone foreign internals. Consume only references that can be backed by parity tests proving Aquarium can reproduce the behavior in terse, readable syntax; parsing a format is inventory, not evidence.","source":"user clarified reference-synth purpose and parity-test requirement on 2026-05-13"} diff --git a/state/map.yaml b/state/map.yaml index 11d2d89..34b1844 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -19,6 +19,7 @@ modules: model: src/AquariumSynth.Dsl/Model.cs parser: src/AquariumSynth.Dsl/PatchScript.cs faust: src/AquariumSynth.Dsl/FaustExport.cs + faust_rendering: src/AquariumSynth.Dsl/FaustExport.cs sfxr: src/AquariumSynth.Dsl/SfxrParams.cs analysis: src/AquariumSynth.Dsl/AudioAnalysis.cs scoring: src/AquariumSynth.Dsl/ScriptMetrics.cs @@ -36,7 +37,7 @@ boundaries: - SFXR parameter mapping and atoms - analysis and comparison tools - script scoring - - Faust source and target-code generation + - Faust source generation, target-code generation, and candidate rendering checks: default: dotnet test package: dotnet pack src/AquariumSynth.Dsl/AquariumSynth.Dsl.csproj -c Release diff --git a/state/memory.json b/state/memory.json index 493188b..c4e96b5 100644 --- a/state/memory.json +++ b/state/memory.json @@ -23,6 +23,7 @@ "patch script parser", "SFXR atoms and parameter mapping", "analysis/comparison metrics", + "Faust-generated C# candidate rendering", "script scoring", "preset catalogs", "Faust emission and compiler wrapper" @@ -52,9 +53,9 @@ "rule": "Add DSL abstractions only when reference rebuilds prove the missing invariant. Do not consume references that cannot be backed by parity tests; parsing alone is inventory, not evidence of expressivity." }, "dx7_reference_path": { - "status": "DX7 SysEx parser extracts voice edit buffers, packed voices, packed 32-voice banks, six operators, envelopes, algorithm, feedback, oscillator sync, LFO, transpose, voice name, checksum validation, ReferencePatch features, algorithm topology from the reverse-engineered OPS algorithm ROM table, envelope-to-ADSR approximations, two Aquarium DSL rebuild attempts, and first-class OperatorGraph support.", + "status": "DX7 SysEx parser extracts voice edit buffers, packed voices, packed 32-voice banks, six operators, envelopes, algorithm, feedback, oscillator sync, LFO, transpose, voice name, checksum validation, ReferencePatch features, algorithm topology from the reverse-engineered OPS algorithm ROM table, envelope-to-ADSR approximations, two Aquarium DSL rebuild attempts, first-class OperatorGraph support, and Aquarium candidate rendering through Faust-generated C#.", "lesson": "Algorithm 32's additive six-carrier shape maps cleanly to six Aquarium voices. Algorithm 8 justified OperatorGraph: operators, modulation edges, carriers, and feedback belong to a graph authority, not Voice fields. Readable authoring uses operator/route/carrier declarations; compact ops/edges tuples are scaffolding only.", - "next": "Add rendered/audio comparison once a render path is explicit; exact DX7 feedback-register timing and exact DX7 EG execution remain separate pressure." + "next": "Choose Dexed/reference audio fixtures and add rendered DX7 parity comparisons; exact DX7 feedback-register timing and exact DX7 EG execution remain separate pressure." }, "note_and_envelope_model": { "rule": "Notes own frequency, gate duration, and host/MIDI source. Envelopes own ADSR level shape.", @@ -69,7 +70,7 @@ }, "last_verified": { "command": "dotnet test AquariumSynthCSharp.slnx --no-restore", - "result": "43 passed", - "commit": "pending reference parity doctrine update" + "result": "44 passed", + "commit": "pending Faust render parity harness" } } diff --git a/state/scratch.md b/state/scratch.md index 936744d..fe43b48 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -15,6 +15,17 @@ Doctrine update: Completed this slice: +- Added `FaustCompiler.RenderAsync`, which compiles Aquarium Faust output to + Faust-generated C#, runs it in a temp .NET project, and returns a mono float + sample buffer for analysis. +- Added a render test that proves a generated Aquarium patch produces non-silent + audio and can be compared through `AudioAnalyzer`. +- DX7 audio parity is still not claimed: the candidate renderer exists, but the + reference side needs Dexed output or a captured licensed fixture. +- Verified with `dotnet test AquariumSynthCSharp.slnx --no-restore`: 44 passed. + +Previous slice: + - Added `Dx7EnvelopeApproximation`, which lowers a DX7 four-rate/four-level EG to a labeled Aquarium ADSR approximation plus gate duration. - Reference rebuilds now record `operator_envelope_approximation` as matched diff --git a/state/spine.yaml b/state/spine.yaml index 9dd547f..d3849c0 100644 --- a/state/spine.yaml +++ b/state/spine.yaml @@ -1,6 +1,6 @@ project: AquariumSynthCSharp spine_version: 1 -updated: 2026-05-13T13:18:00+01:00 +updated: 2026-05-13T13:40:00+01:00 prime_directive: > Build coherent synth machinery. References exist to reveal missing structure, @@ -15,6 +15,7 @@ current_mechanism: parser: src/AquariumSynth.Dsl/PatchScript.cs model: src/AquariumSynth.Dsl/Model.cs faust_emitter: src/AquariumSynth.Dsl/FaustExport.cs + faust_renderer: src/AquariumSynth.Dsl/FaustExport.cs operator_graph_model: src/AquariumSynth.Dsl/Model.cs analysis: src/AquariumSynth.Dsl/AudioAnalysis.cs built_ins: src/AquariumSynth.Dsl/BuiltInScripts.cs @@ -33,6 +34,7 @@ live_invariants: - Notes own frequency, gate duration, and host/MIDI source; envelopes own ADSR level shape. Do not put note duration or SFXR punch back into the general envelope model. - Faust-managed MIDI polyphony is preferred: emit one voice graph with standard `freq`, `gain`, and `gate` controls plus `[midi:on][nvoices:n]` instead of inflating Aquarium graphs for local allocation. - Generated Faust should remain inspectable and deterministic. + - Aquarium Faust output may be rendered through Faust-generated C# for candidate audio comparison; reference parity still needs a real external render or captured licensed fixture. - Reference-patch correctness and synth parity tests live in AquariumSynthCSharp, not Aquarium. - Exposed patch parameters are runtime controls, not compile-time constants. - Parameter binding uses field-site references like `lpf=@/macro/brightness`; do not add target-routing semantics unless a later map proves a new authority is needed. @@ -50,9 +52,9 @@ reference_targets: priority: 1 purpose: "Structured FM/operator graph pressure test." source: "https://github.com/asb2m10/dexed" - status: "DX7 SysEx parser, algorithm topology extraction, envelope-to-ADSR approximation, two Aquarium DSL rebuild attempts, and first-class operator graph support exist." + status: "DX7 SysEx parser, algorithm topology extraction, envelope-to-ADSR approximation, two Aquarium DSL rebuild attempts, first-class operator graph support, and Aquarium candidate rendering through Faust-generated C# exist." first_slice: - - "Add rendered/audio comparison once a render path is explicit." + - "Choose Dexed/reference audio fixtures and add rendered DX7 parity comparisons." zynaddsubfx: priority: 2 purpose: "Additive, subtractive, PAD, formant, kit, and layered-instrument pressure test." @@ -86,9 +88,8 @@ reference_targets: next_agent_start_here: recommended_first_task: > - Add rendered/audio comparison once a render path is explicit, keeping - readable operator graph authoring syntax as operator/route/carrier - declarations. + Choose a lawful DX7 reference render source, then compare captured/reference + audio against Aquarium candidate renders produced through Faust-generated C#. must_read: - AGENTS.md - docs/audio-doctrine.md @@ -100,6 +101,14 @@ next_agent_start_here: - "dotnet test AquariumSynthCSharp.slnx --no-restore" completed_slices: + - date: 2026-05-13 + summary: > + Added `FaustCompiler.RenderAsync`, which compiles Aquarium Faust source to + Faust-generated C#, runs it in a temp .NET project, and returns mono float + samples. The first render test checks non-silent generated audio and feeds + the buffer through `AudioAnalyzer`; DX7 audio parity remains blocked on a + chosen reference renderer or captured fixture. + verification: "dotnet test AquariumSynthCSharp.slnx --no-restore: 44 passed" - date: 2026-05-13 summary: > Added `Dx7EnvelopeApproximation`, a labeled helper that lowers DX7 diff --git a/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs b/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs index 7248175..74f882c 100644 --- a/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs @@ -490,4 +490,23 @@ public sealed class PatchScriptTests if (File.Exists(output)) File.Delete(output); } } + + [Fact] + public async Task FaustCompilerRendersGeneratedSourceWhenInstalled() + { + var export = FaustEmitter.EmitScript("v w=sin f=440 gain=.2 sustain=.08 decay=.04"); + var render = await FaustCompiler.RenderAsync(export.Source, new FaustRenderOptions(DurationSeconds: .12f)); + + if (render is null) + { + return; + } + + Assert.True(render.Samples.Length > 1000, render.Stderr); + Assert.True(render.Samples.Max(MathF.Abs) > 0.001f, render.Stderr); + + var comparison = new AudioAnalyzer(new AudioAnalysisConfig(SampleRate: render.SampleRate)) + .Compare(render.Samples, render.Samples); + Assert.True(comparison.Score > 0.99f); + } }