Use Faust standard MIDI polyphony

This commit is contained in:
Meta Vens 2026-05-13 16:10:08 +01:00
commit 3e0f424d98
9 changed files with 169 additions and 25 deletions

View file

@ -110,6 +110,11 @@ authorities.
as a general envelope field.
- Host/MIDI note mode should expose stable note frequency and note gate controls
that the engine can wire to MIDI note-on/note-off behavior.
- Faust-managed polyphony is the preferred MIDI path. Aquarium should describe a
single voice graph and emit Faust's standard `freq`, `gain`, and `gate`
controls with `[midi:on][nvoices:n]` options, leaving MIDI decoding and voice
allocation to Faust architectures unless a concrete target proves that
boundary insufficient.
## Metrics

View file

@ -35,7 +35,7 @@ public static class FaustEmitter
var source = new StringBuilder();
source.AppendLine("import(\"stdfaust.lib\");");
source.AppendLine($"declare name \"{Escape(options.Name)}\";");
source.AppendLine("declare options \"[nvoices:1]\";");
source.AppendLine($"declare options \"{FaustOptions(patch.Playback)}\";");
source.AppendLine();
source.AppendLine("time = ba.time / ma.SR;");
if (patch.Repeat is { } repeat)
@ -59,6 +59,13 @@ public static class FaustEmitter
source.AppendLine("lfo_hold(hz, phase) = no.noise : ba.latch(os.oscrs(hz));");
source.AppendLine();
var hostPlayback = UsesHostPlayback(patch.Playback);
if (hostPlayback)
{
EmitPlaybackControls(source, patch.Playback);
source.AppendLine();
}
EmitParameterControls(source, patch, parameters);
if (patch.Parameters.Count > 0)
{
@ -81,12 +88,13 @@ public static class FaustEmitter
for (var i = 0; i < patch.OperatorGraphs.Count; i++)
{
var name = $"opgraph_{i}";
EmitOperatorGraph(source, patch.OperatorGraphs[i], name, warnings);
EmitOperatorGraph(source, patch.Playback, patch.OperatorGraphs[i], name, warnings);
voices.Add(name);
}
var mix = voices.Count == 0 ? "0.0" : string.Join(" + ", voices);
var final = $"({mix}) * {parameters.Expression("/patch/gain", patch.Gain)}";
if (hostPlayback) final = $"({final}) * gain";
if (patch.SoftClip) final = $"softclip({final})";
var unbound = parameters.UnboundParameterIds().ToList();
if (unbound.Count > 0)
@ -106,6 +114,23 @@ public static class FaustEmitter
}
}
private static string FaustOptions(Playback playback)
{
var voices = playback.Mode == PlaybackMode.Poly ? Math.Max(1, playback.Voices) : 1;
var midi = playback.Midi || playback.Mode == PlaybackMode.Poly ? "[midi:on]" : "";
return $"{midi}[nvoices:{voices}]";
}
private static bool UsesHostPlayback(Playback playback) =>
playback.Midi || playback.Mode is PlaybackMode.Mono or PlaybackMode.Poly;
private static void EmitPlaybackControls(StringBuilder source, Playback playback)
{
source.AppendLine($"freq = nentry(\"freq\", {F(playback.FrequencyHz)}, 20, 20000, 0.01) : si.smoo;");
source.AppendLine($"gain = nentry(\"gain\", {F(playback.Gain)}, 0, 1, 0.001) : si.smoo;");
source.AppendLine("gate = button(\"gate\");");
}
private static void EmitVoice(
StringBuilder source,
SynthPatch patch,
@ -132,8 +157,8 @@ public static class FaustEmitter
var hpfMod = ModExpressionForTarget(voice.Modulators, ModTarget.HighPass);
var minFreq = parameters.Expression(VoiceField(voiceIndex, "pitch/min_freq"), voice.Pitch.MinFrequencyHz);
var noteFreq = NoteFrequencyExpression(source, voice.Note, name, VoiceField(voiceIndex, "note/frequency"), parameters);
var noteGate = NoteGateExpression(source, voice.Note, name, VoiceField(voiceIndex, "note/gate"), parameters);
var noteFreq = NoteFrequencyExpression(source, patch.Playback, voice.Note, name, VoiceField(voiceIndex, "note/frequency"), parameters);
var noteGate = NoteGateExpression(source, patch.Playback, voice.Note, name, VoiceField(voiceIndex, "note/gate"), parameters);
var pitchRamp = parameters.Expression(VoiceField(voiceIndex, "pitch/ramp"), voice.Pitch.RampPerSecond);
var pitchDelta = parameters.Expression(VoiceField(voiceIndex, "pitch/delta"), voice.Pitch.DeltaRampPerSecond);
var vibratoDepth = parameters.Expression(VoiceField(voiceIndex, "pitch/vibrato"), voice.Pitch.VibratoDepth);
@ -156,7 +181,7 @@ public static class FaustEmitter
var envelope = EnvelopeExpression(
voice.Envelope,
noteGate,
voice.Note.Source == NoteSource.Host,
UsesHostPlayback(patch.Playback) || voice.Note.Source == NoteSource.Host,
field => parameters.Expression(VoiceField(voiceIndex, field), field switch
{
"env/attack" => voice.Envelope.AttackSeconds,
@ -207,8 +232,12 @@ public static class FaustEmitter
source.AppendLine();
}
private static string NoteFrequencyExpression(StringBuilder source, Note note, string name, string fieldPath, ParameterMap parameters)
private static string NoteFrequencyExpression(StringBuilder source, Playback playback, Note note, string name, string fieldPath, ParameterMap parameters)
{
if (UsesHostPlayback(playback))
{
return "freq";
}
if (note.Source != NoteSource.Host)
{
return parameters.Expression(fieldPath, note.FrequencyHz);
@ -219,8 +248,12 @@ public static class FaustEmitter
return control;
}
private static string NoteGateExpression(StringBuilder source, Note note, string name, string fieldPath, ParameterMap parameters)
private static string NoteGateExpression(StringBuilder source, Playback playback, Note note, string name, string fieldPath, ParameterMap parameters)
{
if (UsesHostPlayback(playback))
{
return "gate";
}
if (note.Source != NoteSource.Host)
{
return parameters.Expression(fieldPath, note.GateSeconds);
@ -263,7 +296,7 @@ public static class FaustEmitter
};
}
private static void EmitOperatorGraph(StringBuilder source, OperatorGraph graph, string name, List<string> warnings)
private static void EmitOperatorGraph(StringBuilder source, Playback playback, OperatorGraph graph, string name, List<string> warnings)
{
if (graph.Operators.Count == 0)
{
@ -282,13 +315,17 @@ public static class FaustEmitter
return;
}
var graphNoteFreq = graph.Note.Source == NoteSource.Host
var graphNoteFreq = UsesHostPlayback(playback)
? "freq"
: graph.Note.Source == NoteSource.Host
? $"{name}_note_freq"
: F(graph.Note.FrequencyHz);
var graphNoteGate = graph.Note.Source == NoteSource.Host
var graphNoteGate = UsesHostPlayback(playback)
? "gate"
: graph.Note.Source == NoteSource.Host
? $"{name}_note_gate"
: F(graph.Note.GateSeconds);
if (graph.Note.Source == NoteSource.Host)
if (!UsesHostPlayback(playback) && graph.Note.Source == NoteSource.Host)
{
source.AppendLine($"{name}_note_freq = hslider(\"/{name}/note/frequency\", {F(graph.Note.FrequencyHz)}, 20, 20000, 0.01) : si.smoo;");
source.AppendLine($"{name}_note_gate = button(\"/{name}/note/gate\");");
@ -310,8 +347,8 @@ public static class FaustEmitter
var phaseMod = incoming.Count == 0 ? "0.0" : string.Join(" + ", incoming);
var envelope = EnvelopeExpression(
op.Envelope,
op.Note.Source == NoteSource.Host ? graphNoteGate : F(op.Note.GateSeconds),
op.Note.Source == NoteSource.Host,
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host ? graphNoteGate : F(op.Note.GateSeconds),
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host,
field => field switch
{
"env/attack" => F(op.Envelope.AttackSeconds),

View file

@ -46,11 +46,25 @@ public enum NoteSource
Host
}
public enum PlaybackMode
{
OneShot,
Mono,
Poly
}
public sealed record Note(
float FrequencyHz = 440,
float GateSeconds = 0.1f,
NoteSource Source = NoteSource.OneShot);
public sealed record Playback(
PlaybackMode Mode = PlaybackMode.OneShot,
int Voices = 1,
bool Midi = false,
float FrequencyHz = 440,
float Gain = 1);
public sealed record Oscillator(
Waveform Waveform = Waveform.Sine,
float FrequencyHz = 440,
@ -183,6 +197,7 @@ public sealed record SynthPatch
public IReadOnlyList<ControlLane> Controls { get; init; } = Array.Empty<ControlLane>();
public IReadOnlyList<PatchParameter> Parameters { get; init; } = Array.Empty<PatchParameter>();
public IReadOnlyList<ParameterBinding> ParameterBindings { get; init; } = Array.Empty<ParameterBinding>();
public Playback Playback { get; init; } = new();
public Repeat? Repeat { get; init; }
public float Gain { get; init; } = 1;
public bool SoftClip { get; init; } = true;

View file

@ -41,6 +41,7 @@ public static class PatchScript
public List<OperatorGraph> OperatorGraphs => _operatorGraphs;
public bool HasOutput => Voices.Count > 0 || _operatorGraphs.Count > 0 || _pendingOperatorGraph is not null;
private Repeat? Repeat { get; set; }
private Playback Playback { get; set; } = new();
private float Gain { get; set; } = 1;
private bool SoftClip { get; set; } = true;
@ -54,6 +55,7 @@ public static class PatchScript
Controls = _controls,
Parameters = _parameters,
ParameterBindings = _parameterBindings,
Playback = Playback,
Repeat = Repeat,
Gain = Gain,
SoftClip = SoftClip
@ -147,6 +149,37 @@ public static class PatchScript
{
if (TryGetAny(fields, ["gain", "g"], out var gain)) Gain = ParseBoundFloat(gain, line, Gain, "/patch/gain");
if (TryGetAny(fields, ["soft_clip", "clip"], out var softClip)) SoftClip = ParseBool(softClip, line);
if (TryGetAny(fields, ["mode", "playback"], out var mode))
{
var playbackMode = ParsePlaybackMode(mode, line);
Playback = Playback with
{
Mode = playbackMode,
Midi = playbackMode == PlaybackMode.Poly || Playback.Midi
};
}
if (TryGetAny(fields, ["polyphony", "voices", "nvoices"], out var voices))
{
var count = ParseInt(voices, line);
if (count < 1) throw new PatchScriptException(line, "polyphony must be at least 1");
Playback = Playback with
{
Voices = count,
Mode = count > 1 ? PlaybackMode.Poly : Playback.Mode,
Midi = count > 1 || Playback.Midi
};
}
if (TryGetAny(fields, ["midi"], out var midi))
{
var enabled = ParseBool(midi, line);
Playback = Playback with
{
Midi = enabled,
Mode = enabled && Playback.Mode == PlaybackMode.OneShot ? PlaybackMode.Mono : Playback.Mode
};
}
if (TryGetAny(fields, ["note_freq", "note_frequency"], out var noteFreq)) Playback = Playback with { FrequencyHz = ParseFloat(noteFreq, line) };
if (TryGetAny(fields, ["note_gain", "velocity"], out var noteGain)) Playback = Playback with { Gain = ParseFloat(noteGain, line) };
if (TryGetAny(fields, ["repeat", "r", "rp"], out var repeat))
{
var interval = ParseBoundFloat(repeat, line, 0.1f, "/patch/repeat");
@ -170,6 +203,12 @@ public static class PatchScript
if (TryGetAny(fields, ["midi"], out var midi) && ParseBool(midi, line))
{
noteSource = NoteSource.Host;
Playback = Playback with
{
Midi = true,
Mode = Playback.Mode == PlaybackMode.OneShot ? PlaybackMode.Mono : Playback.Mode,
FrequencyHz = frequency
};
}
var formants = TryGetAny(fields, ["formants", "fs"], out var formantSpec)
? ParseFormants(formantSpec, line)
@ -709,7 +748,7 @@ public static class PatchScript
private static string CanonicalCommand(string command) => command.ToLowerInvariant() switch
{
"p" or "patch" => "patch",
"p" or "patch" or "instrument" => "patch",
"d" or "default" or "defaults" => "defaults",
"def" or "t" or "template" => "template",
"v" or "voice" => "voice",
@ -765,6 +804,14 @@ public static class PatchScript
_ => throw new PatchScriptException(line, $"unknown note source `{value}`")
};
private static PlaybackMode ParsePlaybackMode(string value, int line) => value.ToLowerInvariant() switch
{
"oneshot" or "one_shot" or "trigger" or "fixed" => PlaybackMode.OneShot,
"mono" or "monophonic" or "host" => PlaybackMode.Mono,
"poly" or "polyphonic" or "midi" => PlaybackMode.Poly,
_ => throw new PatchScriptException(line, $"unknown playback mode `{value}`")
};
private static ModTarget ParseModTarget(string value, int line)
{
foreach (var (keys, target) in ModTargets)

View file

@ -16,3 +16,4 @@
{"kind":"operator_graph_model","lesson":"DX7 algorithm-8 pressure justified a first-class OperatorGraph abstraction. OperatorGraph owns FM topology: operators, modulation edges, carriers, and feedback. Do not hide this authority inside Voice fields. Remaining DX7 pressure is exact feedback-register timing and rate/level envelopes.","source":"operator graph implementation slice on 2026-05-13"}
{"kind":"operator_graph_authoring","lesson":"Operator graph authoring should use readable `operator`, `route`, and `carrier` declarations with `env=ad:...` or `env=adsr:...`. Compact `ops=`/`edges=` tuples are acceptable as importer/interchange scaffolding only, not the face of the DSL.","source":"user rejected number-soup operator syntax; readable operator graph syntax slice on 2026-05-13"}
{"kind":"note_envelope_model","lesson":"Aquarium's general envelope model is ADSR: attack, decay, sustain level, release. Note timing belongs to `Note` records: frequency, gate duration, and host/MIDI source. SFXR sustain maps to note gate duration; SFXR punch maps to lower sustain level plus voice gain compensation so ADSR peak remains implicit 1 and the held level sits below the transient.","source":"user identified SFXR sustain as note duration and Punch as transient above sustain; punch mapping correction on 2026-05-13"}
{"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"}

View file

@ -18,6 +18,7 @@
"DX7 algorithm topology metadata",
"standard ADSR envelope model",
"note frequency/gate model",
"Faust-managed playback/polyphony contract",
"patch script parser",
"SFXR atoms and parameter mapping",
"analysis/comparison metrics",
@ -52,12 +53,12 @@
"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, two Aquarium DSL rebuild attempts, and first-class OperatorGraph support.",
"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": "Refine operator graph parameter binding and host MIDI note retrigger semantics; exact DX7 feedback-register timing remains separate pressure."
"next": "Refine operator graph parameter binding and Faust MIDI integration details; exact DX7 feedback-register timing remains separate pressure."
},
"note_and_envelope_model": {
"rule": "Notes own frequency, gate duration, and host/MIDI source. Envelopes own ADSR level shape.",
"sfxr_mapping": "SFXR sustain is note gate duration. SFXR punch maps to lower ADSR sustain level plus voice gain compensation so the implicit attack peak stays at 1 and the held level sits below it.",
"faust_surface": "One-shot patches use generated ADSR over patch age and note gate duration. Host/MIDI patches expose note frequency and note gate controls for the engine to wire."
"faust_surface": "One-shot patches use generated ADSR over patch age and note gate duration. MIDI mono/poly patches emit Faust's standard freq/gain/gate controls and [midi:on][nvoices:n] metadata so Faust architectures own note allocation."
},
"runtime_parameters": {
"rule": "Patch parameters are runtime controls, not compile-time constants.",
@ -67,7 +68,7 @@
},
"last_verified": {
"command": "dotnet test AquariumSynthCSharp.slnx --no-restore",
"result": "40 passed",
"commit": "pending punch mapping correction commit"
"result": "41 passed",
"commit": "pending Faust polyphony playback commit"
}
}

View file

@ -7,6 +7,16 @@ the synth library while Aquarium work continues elsewhere.
Completed this slice:
- Added a patch-level `Playback` contract for `OneShot`, `Mono`, and `Poly`
playback with Faust MIDI polyphony settings.
- `instrument midi=true polyphony=8` now lowers to Faust's standard
`[midi:on][nvoices:8]` option and `freq`, `gain`, `gate` controls.
- Host/MIDI playback no longer emits per-voice `/voices/0/note/frequency` and
`/voices/0/note/gate` controls; Faust architecture owns allocation.
- Verified with `dotnet test AquariumSynthCSharp.slnx --no-restore`: 41 passed.
Previous slice:
- Split note timing from envelope shape. `Note` now owns frequency, one-shot
gate duration, and host/MIDI source; `Envelope` now owns ADSR shape:
attack, decay, sustain level, and release.

View file

@ -1,6 +1,6 @@
project: AquariumSynthCSharp
spine_version: 1
updated: 2026-05-13T12:20:00+01:00
updated: 2026-05-13T12:36:00+01:00
prime_directive: >
Build coherent synth machinery. References exist to reveal missing structure,
@ -31,6 +31,7 @@ live_invariants:
- Operator graphs own FM topology: operators, modulation edges, carriers, and feedback. Do not hide this authority inside Voice fields.
- Readable operator graph authoring uses `operator`, `route`, and `carrier` declarations; compact `ops=`/`edges=` is only scaffolding/interchange.
- 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.
- Reference-patch correctness and synth parity tests live in AquariumSynthCSharp, not Aquarium.
- Exposed patch parameters are runtime controls, not compile-time constants.
@ -48,7 +49,7 @@ reference_targets:
source: "https://github.com/asb2m10/dexed"
status: "DX7 SysEx parser, algorithm topology extraction, two Aquarium DSL rebuild attempts, and first-class operator graph support exist."
first_slice:
- "Refine operator graph parameter binding and host MIDI note retrigger semantics."
- "Refine operator graph parameter binding and Faust MIDI integration details."
- "Add rendered/audio comparison once a render path is explicit."
zynaddsubfx:
priority: 2
@ -83,8 +84,8 @@ reference_targets:
next_agent_start_here:
recommended_first_task: >
Refine operator graph parameter binding and host MIDI note retrigger
semantics. Keep readable authoring syntax as operator/route/carrier
Refine operator graph parameter binding and Faust MIDI integration details.
Keep readable authoring syntax as operator/route/carrier
declarations.
must_read:
- AGENTS.md
@ -97,6 +98,13 @@ next_agent_start_here:
- "dotnet test AquariumSynthCSharp.slnx --no-restore"
completed_slices:
- date: 2026-05-13
summary: >
Added a patch-level Playback contract and `instrument` authoring surface
for Faust-managed MIDI mono/polyphony. `instrument midi=true polyphony=8`
emits `[midi:on][nvoices:8]` and standard `freq`, `gain`, and `gate`
controls instead of Aquarium-owned voice allocation.
verification: "dotnet test AquariumSynthCSharp.slnx --no-restore: 41 passed"
- date: 2026-05-13
summary: >
Standardized the live envelope model as ADSR and added explicit Note

View file

@ -371,11 +371,31 @@ public sealed class PatchScriptTests
var export = FaustEmitter.Emit(patch);
Assert.Equal(NoteSource.Host, patch.Voices[0].Note.Source);
Assert.Contains("hslider(\"/voices/0/note/frequency\", 220", export.Source);
Assert.Contains("button(\"/voices/0/note/gate\")", export.Source);
Assert.Equal(PlaybackMode.Mono, patch.Playback.Mode);
Assert.True(patch.Playback.Midi);
Assert.Contains("declare options \"[midi:on][nvoices:1]\";", export.Source);
Assert.Contains("freq = nentry(\"freq\", 220", export.Source);
Assert.Contains("gain = nentry(\"gain\", 1", export.Source);
Assert.Contains("gate = button(\"gate\")", export.Source);
Assert.Contains("en.adsr", export.Source);
}
[Fact]
public void PolyphonicPatchUsesFaustStandardMidiSurface()
{
var patch = PatchScript.Parse("instrument midi=true polyphony=8; v w=saw f=330 attack=.01 env_decay=.08 sustain_level=.6 release=.3");
var export = FaustEmitter.Emit(patch);
Assert.Equal(PlaybackMode.Poly, patch.Playback.Mode);
Assert.Equal(8, patch.Playback.Voices);
Assert.Contains("declare options \"[midi:on][nvoices:8]\";", export.Source);
Assert.Contains("freq = nentry(\"freq\", 440", export.Source);
Assert.Contains("gain = nentry(\"gain\", 1", export.Source);
Assert.Contains("gate = button(\"gate\")", export.Source);
Assert.DoesNotContain("/voices/0/note/frequency", export.Source);
Assert.DoesNotContain("/voices/0/note/gate", export.Source);
}
[Fact]
public async Task FaustCompilerValidatesGeneratedSourceWhenInstalled()
{
@ -407,7 +427,7 @@ public sealed class PatchScriptTests
[Fact]
public async Task FaustCompilerValidatesMidiGatePatchWhenInstalled()
{
var export = FaustEmitter.EmitScript("v w=saw f=220 midi=true attack=.01 env_decay=.08 sustain_level=.6 release=.3");
var export = FaustEmitter.EmitScript("instrument midi=true polyphony=8; v w=saw f=220 attack=.01 env_decay=.08 sustain_level=.6 release=.3");
var validation = await FaustCompiler.ValidateAsync(export.Source);
if (validation is null)