diff --git a/docs/audio-doctrine.md b/docs/audio-doctrine.md index 46020a4..4eddf64 100644 --- a/docs/audio-doctrine.md +++ b/docs/audio-doctrine.md @@ -93,6 +93,22 @@ Rules: - Recompilation is for graph shape changes. Parameter changes must flow through the hosted DSP control API. +## Notes And Envelopes + +Notes own pitch and gate. Envelopes own level shape. Do not mix those +authorities. + +- `Note` carries note frequency, gate duration for one-shot patches, and source + selection for host/MIDI-driven patches. +- `Envelope` is ADSR-shaped: attack time, decay time, sustain level, and release + time. +- Legacy SFXR sustain maps to note gate duration, because it is how long the + generated sound is held before release. +- Legacy SFXR punch maps to a non-unit sustain level when importing old SFXR + material. Keep that as compatibility mapping, not 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. + ## Metrics Analysis exists to catch regressions and support search, not to crown winners. diff --git a/src/AquariumSynth.Dsl/BuiltInScripts.cs b/src/AquariumSynth.Dsl/BuiltInScripts.cs index d76eaa0..c123d49 100644 --- a/src/AquariumSynth.Dsl/BuiltInScripts.cs +++ b/src/AquariumSynth.Dsl/BuiltInScripts.cs @@ -68,7 +68,7 @@ public static class BuiltInScripts gain=0.22 sustain=0.01451247166 decay=0.1306122449 - punch=0.45 + sustain_level=1.45 drive=0.201 arp_delay=0.081844 arp_mult=1.116121255 @@ -96,7 +96,7 @@ public static class BuiltInScripts gain=0.22 sustain=0.1907029478 decay=0.293877551 - punch=0.52 + sustain_level=1.52 pitch_ramp=0.0320625 phaser=-0.0008712 phaser_ramp=-0.00035 @@ -170,7 +170,7 @@ public static class BuiltInScripts freq=148.7934 sustain=0.01451247166 decay=0.1306122449 - punch=0.45 + sustain_level=1.45 drive=0.201 arp_delay=0.081844 arp_mult=1.116121255 @@ -193,7 +193,7 @@ public static class BuiltInScripts freq=20 sustain=0.1907029478 decay=0.293877551 - punch=0.52 + sustain_level=1.52 pitch_ramp=0.0320625 phaser=-0.0008712 phaser_ramp=-0.00035 @@ -274,7 +274,7 @@ public static class BuiltInScripts gain=0.2 sustain=0.04 decay=0.36 - punch=0.32 + sustain_level=1.32 lpf=0.68 hpf=0.03 drive=0.12 @@ -301,7 +301,7 @@ public static class BuiltInScripts gain=0.12 sustain=0.05 decay=0.5 - punch=0.22 + sustain_level=1.22 lpf=0.78 drive=0.06 @@ -354,7 +354,7 @@ public static class BuiltInScripts freq=58 sustain=0.045 decay=0.42 - punch=0.65 + sustain_level=1.65 pitch_ramp=-3.8 min_freq=32 lpf=0.85 @@ -419,7 +419,7 @@ public static class BuiltInScripts freq=115 sustain=0.055 decay=0.34 - punch=0.28 + sustain_level=1.28 pitch_ramp=-1.45 min_freq=62 lpf=0.78 @@ -878,7 +878,7 @@ public static class BuiltInScripts gain=0.18 fm_index=0.8 - voice use=Ping freq=523.25 gain=0.12 punch=0.12 + voice use=Ping freq=523.25 gain=0.12 sustain_level=1.12 voice use=Ping freq=659.25 gain=0.08 sustain=0.11 decay=0.84 fm=4.2 voice use=Ping freq=783.99 gain=0.07 sustain=0.08 decay=0.72 fm_index=1.9 voice wave=sine freq=261.63 gain=0.045 sustain=0.7 decay=1.3 fm=1.5 fm_index=0.65 fm_decay=1.2 @@ -896,7 +896,7 @@ public static class BuiltInScripts attack=0.001 sustain=0.045 decay=0.5 - punch=0.18 + sustain_level=1.18 lpf=0.82 hpf=0.035 drive=0.1 diff --git a/src/AquariumSynth.Dsl/FaustExport.cs b/src/AquariumSynth.Dsl/FaustExport.cs index 4ee1ad4..eddef70 100644 --- a/src/AquariumSynth.Dsl/FaustExport.cs +++ b/src/AquariumSynth.Dsl/FaustExport.cs @@ -51,7 +51,8 @@ public static class FaustEmitter source.AppendLine("wrap01(x) = x - floor(x);"); source.AppendLine("softclip(x) = ma.tanh(x * 1.35);"); source.AppendLine("fold(x) = 2.0 * abs(2.0 * (x / 4.0 - floor(x / 4.0)) - 1.0) - 1.0;"); - source.AppendLine("env(a,s,d,p) = select2(age < a, select2(age < a + s, select2(age < a + s + d, 0.0, 1.0 - (age - a - s) / max(0.0001, d)), 1.0 + (1.0 - (age - a) / max(0.0001, s)) * 2.0 * p), age / max(0.0001, a));"); + source.AppendLine("release_start(a,d,g) = max(g, a + d);"); + source.AppendLine("oneshot_adsr(a,d,s,r,g) = select2(age < a, select2(age < a + d, select2(age < release_start(a,d,g), select2(age < release_start(a,d,g) + r, 0.0, s * (1.0 - (age - release_start(a,d,g)) / max(0.0001, r))), s), 1.0 - (1.0 - s) * ((age - a) / max(0.0001, d))), age / max(0.0001, a));"); source.AppendLine("lfo_sin(hz, phase) = sin(2.0 * ma.PI * (age * hz + phase));"); source.AppendLine("lfo_tri(hz, phase) = 1.0 - 4.0 * abs((age * hz + phase - floor(age * hz + phase)) - 0.5);"); source.AppendLine("lfo_sq(hz, phase) = select2((age * hz + phase - floor(age * hz + phase)) < 0.5, -1.0, 1.0);"); @@ -131,13 +132,14 @@ public static class FaustEmitter var hpfMod = ModExpressionForTarget(voice.Modulators, ModTarget.HighPass); var minFreq = parameters.Expression(VoiceField(voiceIndex, "pitch/min_freq"), voice.Pitch.MinFrequencyHz); - var oscFreq = parameters.Expression(VoiceField(voiceIndex, "osc/freq"), voice.Oscillator.FrequencyHz); + 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 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); var vibratoHz = parameters.Expression(VoiceField(voiceIndex, "pitch/vibrato_hz"), voice.Pitch.VibratoHz); var vibratoDelay = parameters.Expression(VoiceField(voiceIndex, "pitch/vibrato_delay"), voice.Pitch.VibratoDelaySeconds); - var baseFreq = $"max({minFreq}, {oscFreq} * pow(2.0, {pitchRamp} * age + 0.5 * {pitchDelta} * age * age))"; + var baseFreq = $"max({minFreq}, {noteFreq} * pow(2.0, {pitchRamp} * age + 0.5 * {pitchDelta} * age * age))"; var hasVibrato = voice.Pitch.VibratoDepth != 0 && voice.Pitch.VibratoHz > 0 || parameters.IsBound(VoiceField(voiceIndex, "pitch/vibrato")) || parameters.IsBound(VoiceField(voiceIndex, "pitch/vibrato_hz")); @@ -151,7 +153,18 @@ public static class FaustEmitter var dutyExpression = $"clip01({parameters.Expression(VoiceField(voiceIndex, "osc/duty"), voice.Oscillator.Duty)} + {parameters.Expression(VoiceField(voiceIndex, "duty/ramp"), voice.Duty.RampPerSecond)} * age + patch_mod_duty + {duty})"; var fmIndex = $"max(0.0, {parameters.Expression(VoiceField(voiceIndex, "fm/index"), voice.Fm.Index)} + patch_mod_fm_index + {fmIndexMod}) * {FmDecay(parameters.Expression(VoiceField(voiceIndex, "fm/decay"), voice.Fm.IndexDecaySeconds), voice.Fm.IndexDecaySeconds, parameters.IsBound(VoiceField(voiceIndex, "fm/decay")))}"; var oscillator = OscillatorExpression(patch, voice, voiceIndex, frequency, dutyExpression, fmIndex, parameters); - var envelope = $"env({parameters.Expression(VoiceField(voiceIndex, "env/attack"), voice.Envelope.AttackSeconds)}, {parameters.Expression(VoiceField(voiceIndex, "env/sustain"), voice.Envelope.SustainSeconds)}, {parameters.Expression(VoiceField(voiceIndex, "env/decay"), voice.Envelope.DecaySeconds)}, {parameters.Expression(VoiceField(voiceIndex, "env/punch"), voice.Envelope.Punch)})"; + var envelope = EnvelopeExpression( + voice.Envelope, + noteGate, + voice.Note.Source == NoteSource.Host, + field => parameters.Expression(VoiceField(voiceIndex, field), field switch + { + "env/attack" => voice.Envelope.AttackSeconds, + "env/decay" => voice.Envelope.DecaySeconds, + "env/sustain_level" => voice.Envelope.SustainLevel, + "env/release" => voice.Envelope.ReleaseSeconds, + _ => throw new ArgumentOutOfRangeException(nameof(field), field, null) + })); var tremoloDepth = parameters.Expression(VoiceField(voiceIndex, "color/tremolo"), Math.Clamp(voice.Color.TremoloDepth, 0, 1)); var tremoloHz = parameters.Expression(VoiceField(voiceIndex, "color/tremolo_hz"), voice.Color.TremoloHz); var hasTremolo = voice.Color.TremoloDepth > 0 && voice.Color.TremoloHz > 0 || @@ -194,6 +207,41 @@ public static class FaustEmitter source.AppendLine(); } + private static string NoteFrequencyExpression(StringBuilder source, Note note, string name, string fieldPath, ParameterMap parameters) + { + if (note.Source != NoteSource.Host) + { + return parameters.Expression(fieldPath, note.FrequencyHz); + } + + var control = $"{name}_note_freq"; + source.AppendLine($"{control} = hslider(\"{Escape(fieldPath)}\", {F(note.FrequencyHz)}, 20, 20000, 0.01) : si.smoo;"); + return control; + } + + private static string NoteGateExpression(StringBuilder source, Note note, string name, string fieldPath, ParameterMap parameters) + { + if (note.Source != NoteSource.Host) + { + return parameters.Expression(fieldPath, note.GateSeconds); + } + + var control = $"{name}_note_gate"; + source.AppendLine($"{control} = button(\"{Escape(fieldPath)}\");"); + return control; + } + + private static string EnvelopeExpression(Envelope envelope, string gate, bool hostGate, Func value) + { + var attack = value("env/attack"); + var decay = value("env/decay"); + var sustain = value("env/sustain_level"); + var release = value("env/release"); + return hostGate + ? $"en.adsr({attack}, {decay}, {sustain}, {release}, {gate})" + : $"oneshot_adsr({attack}, {decay}, {sustain}, {release}, {gate})"; + } + private static string OscillatorExpression(SynthPatch patch, Voice voice, int voiceIndex, string frequency, string duty, string fmIndex, ParameterMap parameters) { var hasFmMod = patch.Controls.Any(control => control.Modulator.Target == ModTarget.FmIndex) || @@ -234,7 +282,18 @@ public static class FaustEmitter return; } - source.AppendLine($"{name}_freq = {F(graph.FrequencyHz)};"); + var graphNoteFreq = graph.Note.Source == NoteSource.Host + ? $"{name}_note_freq" + : F(graph.Note.FrequencyHz); + var graphNoteGate = graph.Note.Source == NoteSource.Host + ? $"{name}_note_gate" + : F(graph.Note.GateSeconds); + if (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\");"); + } + source.AppendLine($"{name}_freq = {graphNoteFreq};"); foreach (var op in ordered) { var opName = $"{name}_op_{op.Id}"; @@ -249,7 +308,18 @@ public static class FaustEmitter } var phaseMod = incoming.Count == 0 ? "0.0" : string.Join(" + ", incoming); - var envelope = $"env({F(op.Envelope.AttackSeconds)}, {F(op.Envelope.SustainSeconds)}, {F(op.Envelope.DecaySeconds)}, {F(op.Envelope.Punch)})"; + var envelope = EnvelopeExpression( + op.Envelope, + op.Note.Source == NoteSource.Host ? graphNoteGate : F(op.Note.GateSeconds), + op.Note.Source == NoteSource.Host, + field => field switch + { + "env/attack" => F(op.Envelope.AttackSeconds), + "env/decay" => F(op.Envelope.DecaySeconds), + "env/sustain_level" => F(op.Envelope.SustainLevel), + "env/release" => F(op.Envelope.ReleaseSeconds), + _ => throw new ArgumentOutOfRangeException(nameof(field), field, null) + }); source.AppendLine($"{opName} = sin(2.0 * ma.PI * (os.phasor(1.0, {name}_freq * {F(Math.Max(op.Ratio, 0))}) + ({phaseMod}) / ma.PI)) * {envelope} * {F(op.Level)};"); } diff --git a/src/AquariumSynth.Dsl/Model.cs b/src/AquariumSynth.Dsl/Model.cs index c309ff3..ddad265 100644 --- a/src/AquariumSynth.Dsl/Model.cs +++ b/src/AquariumSynth.Dsl/Model.cs @@ -33,13 +33,24 @@ public enum ModTarget public sealed record Envelope( float AttackSeconds = 0, - float SustainSeconds = 0.1f, - float DecaySeconds = 0.1f, - float Punch = 0) + float DecaySeconds = 0.01f, + float SustainLevel = 1, + float ReleaseSeconds = 0.1f) { - public float DurationSeconds => AttackSeconds + SustainSeconds + DecaySeconds; + public float DurationSeconds => AttackSeconds + DecaySeconds + ReleaseSeconds; } +public enum NoteSource +{ + OneShot, + Host +} + +public sealed record Note( + float FrequencyHz = 440, + float GateSeconds = 0.1f, + NoteSource Source = NoteSource.OneShot); + public sealed record Oscillator( Waveform Waveform = Waveform.Sine, float FrequencyHz = 440, @@ -94,10 +105,10 @@ public sealed record OperatorNode( float Ratio = 1, float Level = 1, float Feedback = 0, - float AttackSeconds = 0, - float ReleaseSeconds = 0, + Note Note = null!, Envelope Envelope = null!) { + public Note Note { get; init; } = Note ?? new(); public Envelope Envelope { get; init; } = Envelope ?? new(); } @@ -109,7 +120,11 @@ public sealed record OperatorGraph( IReadOnlyList Operators, IReadOnlyList Edges, IReadOnlyList Carriers, - float Gain = 0.2f); + Note Note = null!, + float Gain = 0.2f) +{ + public Note Note { get; init; } = Note ?? new(); +} public sealed record PatchParameter( string Path, @@ -147,6 +162,7 @@ public sealed record Repeat(float IntervalSeconds); public sealed record Voice { public Oscillator Oscillator { get; init; } = new(); + public Note Note { get; init; } = new(); public Envelope Envelope { get; init; } = new(); public PitchMotion Pitch { get; init; } = new(); public DutyMotion Duty { get; init; } = new(); diff --git a/src/AquariumSynth.Dsl/PatchScript.cs b/src/AquariumSynth.Dsl/PatchScript.cs index 663d862..71969da 100644 --- a/src/AquariumSynth.Dsl/PatchScript.cs +++ b/src/AquariumSynth.Dsl/PatchScript.cs @@ -157,6 +157,18 @@ public static class PatchScript private Voice ParseVoice(IReadOnlyDictionary fields, int voiceIndex, int line) { var waveform = TryGetAny(fields, ["wave", "w"], out var wave) ? ParseWaveform(wave, line) : Waveform.Sine; + var frequency = GetBoundFloat(fields, line, 440, VoiceField(voiceIndex, "note/frequency"), "freq", "frequency", "f"); + var gateSeconds = GetBoundFloat(fields, line, 0.1f, VoiceField(voiceIndex, "note/gate"), "gate", "hold", "duration", "sustain", "s"); + var sustainLevel = GetBoundFloat(fields, line, 1, VoiceField(voiceIndex, "env/sustain_level"), "sustain_level", "sl"); + if (TryGetAny(fields, ["punch", "pu"], out var punch)) + { + sustainLevel = 1 + ParseBoundFloat(punch, line, 0, VoiceField(voiceIndex, "env/sustain_level")); + } + var noteSource = ParseNoteSource(GetAny(fields, ["note_source", "source"], "oneshot"), line); + if (TryGetAny(fields, ["midi"], out var midi) && ParseBool(midi, line)) + { + noteSource = NoteSource.Host; + } var formants = TryGetAny(fields, ["formants", "fs"], out var formantSpec) ? ParseFormants(formantSpec, line) : []; @@ -179,14 +191,15 @@ public static class PatchScript { Oscillator = new Oscillator( waveform, - GetBoundFloat(fields, line, 440, VoiceField(voiceIndex, "osc/freq"), "freq", "frequency", "f"), + frequency, GetBoundFloat(fields, line, 0.5f, VoiceField(voiceIndex, "osc/duty"), "duty", "du"), GetBoundFloat(fields, line, 0, VoiceField(voiceIndex, "osc/phase"), "phase", "pa")), + Note = new Note(frequency, gateSeconds, noteSource), Envelope = new Envelope( GetBoundFloat(fields, line, 0, VoiceField(voiceIndex, "env/attack"), "attack", "a"), - GetBoundFloat(fields, line, 0.1f, VoiceField(voiceIndex, "env/sustain"), "sustain", "s"), - GetBoundFloat(fields, line, 0.1f, VoiceField(voiceIndex, "env/decay"), "decay", "d"), - GetBoundFloat(fields, line, 0, VoiceField(voiceIndex, "env/punch"), "punch", "pu")), + GetBoundFloat(fields, line, 0, VoiceField(voiceIndex, "env/decay"), "env_decay", "ed"), + sustainLevel, + GetBoundFloat(fields, line, 0.1f, VoiceField(voiceIndex, "env/release"), "release", "rel", "decay", "d")), Pitch = new PitchMotion( GetBoundFloat(fields, line, 20, VoiceField(voiceIndex, "pitch/min_freq"), "min_freq", "min"), GetBoundFloat(fields, line, 0, VoiceField(voiceIndex, "pitch/ramp"), "pitch_ramp", "pr"), @@ -290,6 +303,10 @@ public static class PatchScript operators, edges, carriers, + new Note( + GetBoundFloat(fields, line, 440, $"{graphPath}/note/frequency", "freq", "frequency", "f"), + GetBoundFloat(fields, line, 0.1f, $"{graphPath}/note/gate", "gate", "hold", "duration"), + ParseNoteSource(GetAny(fields, ["note_source", "source"], "oneshot"), line)), GetBoundFloat(fields, line, 0.2f, $"{graphPath}/gain", "gain", "g"))); } @@ -308,6 +325,10 @@ public static class PatchScript line, GetAny(fields, ["name", "n"], $"opgraph{graphIndex}"), GetBoundFloat(fields, line, 440, $"{graphPath}/freq", "freq", "frequency", "f"), + new Note( + GetBoundFloat(fields, line, 440, $"{graphPath}/note/frequency", "freq", "frequency", "f"), + GetBoundFloat(fields, line, 0.1f, $"{graphPath}/note/gate", "gate", "hold", "duration"), + ParseNoteSource(GetAny(fields, ["note_source", "source"], "oneshot"), line)), GetBoundFloat(fields, line, 0.2f, $"{graphPath}/gain", "gain", "g")); } @@ -315,22 +336,23 @@ public static class PatchScript { var graph = RequiredPendingOperatorGraph(line); var id = ParseOperatorId(Required(fields, "name", line), line); - var envelope = TryGetAny(fields, ["env", "envelope"], out var envSpec) + var envelopeSpec = TryGetAny(fields, ["env", "envelope"], out var envSpec) ? ParseEnvelopeSpec(envSpec, line) - : new Envelope( - GetFloat(fields, line, 0, "attack", "a"), - GetFloat(fields, line, 0.1f, "sustain", "s"), - GetFloat(fields, line, 0.1f, "decay", "d"), - GetFloat(fields, line, 0, "punch", "pu")); + : new ParsedEnvelope( + new Envelope( + GetFloat(fields, line, 0, "attack", "a"), + GetFloat(fields, line, 0, "env_decay", "ed"), + GetFloat(fields, line, 1, "sustain_level", "sl"), + GetFloat(fields, line, 0.1f, "release", "rel", "decay", "d")), + GetFloat(fields, line, graph.Note.GateSeconds, "gate", "hold", "duration")); graph.Operators.Add(new OperatorNode( id, GetFloat(fields, line, 1, "ratio", "r"), GetFloat(fields, line, 1, "level", "l"), GetFloat(fields, line, 0, "feedback", "fb"), - 0, - GetFloat(fields, line, 0, "release"), - envelope)); + graph.Note with { GateSeconds = envelopeSpec.GateSeconds }, + envelopeSpec.Envelope)); } private void AddOperatorRoute(IReadOnlyDictionary fields, int line) @@ -361,6 +383,7 @@ public static class PatchScript graph.Operators, graph.Edges, graph.Carriers.Count > 0 ? graph.Carriers : graph.Operators.Select(op => op.Id).ToList(), + graph.Note, graph.Gain)); } @@ -486,9 +509,8 @@ public static class PatchScript ParseFloat(pieces[1], line), ParseFloat(pieces[2], line), pieces.Length >= 4 ? ParseFloat(pieces[3], line) : 0, - 0, - 0, - pieces.Length >= 6 ? new Envelope(0, ParseFloat(pieces[4], line), ParseFloat(pieces[5], line)) : new Envelope()); + pieces.Length >= 6 ? new Note(GateSeconds: ParseFloat(pieces[4], line)) : new Note(), + pieces.Length >= 6 ? new Envelope(ReleaseSeconds: ParseFloat(pieces[5], line)) : new Envelope()); }) .ToList(); @@ -520,24 +542,28 @@ public static class PatchScript .Select(part => ParseInt(part, line)) .ToList(); - private static Envelope ParseEnvelopeSpec(string value, int line) + private static ParsedEnvelope ParseEnvelopeSpec(string value, int line) { var pieces = value.Split(':'); return pieces[0].ToLowerInvariant() switch { - "ad" when pieces.Length == 3 => new Envelope( + "ad" when pieces.Length == 3 => AdEnvelope( ParseFloat(pieces[1], line), - 0, ParseFloat(pieces[2], line)), - "adsr" when pieces.Length == 5 => new Envelope( - ParseFloat(pieces[1], line), - ParseFloat(pieces[2], line), - ParseFloat(pieces[4], line), - ParseFloat(pieces[3], line)), + "adsr" when pieces.Length == 5 => new ParsedEnvelope( + new Envelope( + ParseFloat(pieces[1], line), + ParseFloat(pieces[2], line), + ParseFloat(pieces[3], line), + ParseFloat(pieces[4], line)), + 0.1f), _ => throw new PatchScriptException(line, $"bad envelope `{value}`") }; } + private static ParsedEnvelope AdEnvelope(float attackSeconds, float decaySeconds) => + new(new Envelope(attackSeconds, decaySeconds, 0, 0), attackSeconds + decaySeconds); + private static int ParseOperatorId(string value, int line) { var normalized = value.StartsWith("op", StringComparison.OrdinalIgnoreCase) @@ -606,12 +632,15 @@ public static class PatchScript int Line, string Name, float FrequencyHz, + Note Note, float Gain) { public List Operators { get; } = []; public List Edges { get; } = []; public List Carriers { get; } = []; } + + private sealed record ParsedEnvelope(Envelope Envelope, float GateSeconds); } private static readonly (string[] Keys, ModTarget Target)[] ModTargets = @@ -727,6 +756,13 @@ public static class PatchScript _ => throw new PatchScriptException(line, $"unknown mod waveform `{value}`") }; + private static NoteSource ParseNoteSource(string value, int line) => value.ToLowerInvariant() switch + { + "oneshot" or "one_shot" or "trigger" or "fixed" => NoteSource.OneShot, + "host" or "midi" or "gate" => NoteSource.Host, + _ => throw new PatchScriptException(line, $"unknown note source `{value}`") + }; + private static ModTarget ParseModTarget(string value, int line) { foreach (var (keys, target) in ModTargets) diff --git a/src/AquariumSynth.Dsl/Presets.cs b/src/AquariumSynth.Dsl/Presets.cs index ea4675b..50385c7 100644 --- a/src/AquariumSynth.Dsl/Presets.cs +++ b/src/AquariumSynth.Dsl/Presets.cs @@ -4,14 +4,14 @@ public static class Presets { public static SynthPatch AquariumPluck() { - var envelope = new Envelope(0.002f, 0.09f, 0.43f, 0.38f); + var envelope = new Envelope(0.002f, 0, 1.38f, 0.43f); return new SynthPatch { Voices = [ - Simple(new Oscillator(Waveform.Sine, 440), envelope, 0.18f), - Simple(new Oscillator(Waveform.Triangle, 880), envelope, 0.05f), - Simple(new Oscillator(Waveform.Sine, 1760), envelope, 0.018f) + Simple(new Oscillator(Waveform.Sine, 440), envelope, 0.09f, 0.18f), + Simple(new Oscillator(Waveform.Triangle, 880), envelope, 0.09f, 0.05f), + Simple(new Oscillator(Waveform.Sine, 1760), envelope, 0.09f, 0.018f) ], Gain = 0.95f, SoftClip = true @@ -20,13 +20,13 @@ public static class Presets public static SynthPatch AquariumHeartbeat() { - var envelope = new Envelope(0.004f, 0.08f, 0.2f, 0.62f); + var envelope = new Envelope(0.004f, 0, 1.62f, 0.2f); return new SynthPatch { Voices = [ - Simple(new Oscillator(Waveform.Sine, 72), envelope, 0.22f), - Simple(new Oscillator(Waveform.Sine, 116), envelope, 0.09f) + Simple(new Oscillator(Waveform.Sine, 72), envelope, 0.08f, 0.22f), + Simple(new Oscillator(Waveform.Sine, 116), envelope, 0.08f, 0.09f) ], Gain = 0.9f, SoftClip = true @@ -35,7 +35,7 @@ public static class Presets public static SynthPatch AquariumVoice() { - var voice = Simple(new Oscillator(Waveform.Triangle, 220), new Envelope(0.018f, 0.34f, 0.28f, 0.08f), 0.18f) with + var voice = Simple(new Oscillator(Waveform.Triangle, 220), new Envelope(0.018f, 0, 1.08f, 0.28f), 0.34f, 0.18f) with { Pitch = new PitchMotion(VibratoDepth: 0.018f, VibratoHz: 5.6f), Color = new VoiceColor(0.035f, 0.18f, 0.04f, 0.12f, 4.2f, 0.68f), @@ -58,9 +58,10 @@ public static class Presets public static SynthPatch Sfxr(string name) => SfxrParams.Named(name)?.ToPatch() ?? throw new ArgumentException($"Unknown SFXR preset `{name}`.", nameof(name)); - private static Voice Simple(Oscillator oscillator, Envelope envelope, float gain) => new() + private static Voice Simple(Oscillator oscillator, Envelope envelope, float gateSeconds, float gain) => new() { Oscillator = oscillator, + Note = new Note(oscillator.FrequencyHz, gateSeconds), Envelope = envelope, Gain = gain }; diff --git a/src/AquariumSynth.Dsl/ReferenceRebuilds.cs b/src/AquariumSynth.Dsl/ReferenceRebuilds.cs index 4950104..2c9eb32 100644 --- a/src/AquariumSynth.Dsl/ReferenceRebuilds.cs +++ b/src/AquariumSynth.Dsl/ReferenceRebuilds.cs @@ -26,7 +26,7 @@ public static class ReferenceRebuildCatalog new("self_feedback_operators", "6", "Approximated with fold/drive on the highest partial.") ], [ - new("operator_envelopes", "per-operator four-stage DX7 EG", "Aquarium currently has attack/sustain/decay/punch, not DX7 rate/level envelopes."), + new("operator_envelopes", "per-operator four-stage DX7 EG", "Aquarium now has ADSR envelopes, but not DX7 rate/level envelopes."), new("output_compensation", "algorithm ROM COM", "Aquarium voice gains are explicit and not derived from DX7 COM scaling.") ], "This is the honest easy case: DX7 algorithm 32 is mostly additive synthesis, so the current voice DSL can represent the carrier layout without pretending to own a full operator graph."), diff --git a/src/AquariumSynth.Dsl/SfxrParams.cs b/src/AquariumSynth.Dsl/SfxrParams.cs index 7b74691..3cf24ee 100644 --- a/src/AquariumSynth.Dsl/SfxrParams.cs +++ b/src/AquariumSynth.Dsl/SfxrParams.cs @@ -168,11 +168,12 @@ public sealed record SfxrParams var voice = new Voice { Oscillator = new Oscillator(WaveType, baseFrequency, 0.5f - Math.Clamp(Duty, 0, 1) * 0.5f), + Note = new Note(baseFrequency, NormalizedEnvSeconds(EnvSustain)), Envelope = new Envelope( NormalizedEnvSeconds(EnvAttack), - NormalizedEnvSeconds(EnvSustain), - NormalizedEnvSeconds(EnvDecay), - Math.Clamp(EnvPunch, -1, 1)), + 0, + 1 + Math.Clamp(EnvPunch, -1, 1), + NormalizedEnvSeconds(EnvDecay)), Pitch = new PitchMotion( Math.Min(SfxrFrequencyHz(FreqLimit), baseFrequency), -Cube(FreqRamp) * 9.5f, diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 859aa41..1f89f24 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -15,3 +15,4 @@ {"kind":"dx7_reference_rebuilds","lesson":"Two DX7-style Aquarium rebuilds now make the pressure explicit: algorithm 32 maps cleanly to layered additive voices, but algorithm 8 exposes missing graph structure (operator modulation edges, summed modulators, and operator-local self-feedback). Do not patch this with more Voice fields; decide whether an operator graph model owns this invariant.","source":"DX7 rebuild catalog slice on 2026-05-13"} {"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 non-unit sustain level only as compatibility import behavior.","source":"user identified SFXR sustain as note duration and Punch as non-unit sustain; note/envelope standardization slice on 2026-05-13"} diff --git a/state/memory.json b/state/memory.json index 891012f..17f5516 100644 --- a/state/memory.json +++ b/state/memory.json @@ -16,6 +16,8 @@ "reference rebuild catalog", "DX7 SysEx structural parsing", "DX7 algorithm topology metadata", + "standard ADSR envelope model", + "note frequency/gate model", "patch script parser", "SFXR atoms and parameter mapping", "analysis/comparison metrics", @@ -50,7 +52,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 envelope internals; exact DX7 feedback-register timing remains separate pressure." + "next": "Refine operator graph parameter binding and host MIDI note retrigger semantics; 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 non-unit sustain level as compatibility import behavior, not as a general envelope field.", + "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." }, "runtime_parameters": { "rule": "Patch parameters are runtime controls, not compile-time constants.", @@ -60,7 +67,7 @@ }, "last_verified": { "command": "dotnet test AquariumSynthCSharp.slnx --no-restore", - "result": "36 passed", - "commit": "pending readable operator graph syntax commit" + "result": "39 passed", + "commit": "pending note/envelope standardization commit" } } diff --git a/state/scratch.md b/state/scratch.md index 316df5a..2c49003 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -7,9 +7,21 @@ the synth library while Aquarium work continues elsewhere. Completed this 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. +- SFXR sustain duration now maps to `Note.GateSeconds`; SFXR punch maps to a + non-unit ADSR sustain level during import/legacy parsing. +- Added host note mode for MIDI-oriented patches through stable note frequency + and note gate controls in generated Faust. +- Moved built-in authoring examples off `punch=` and onto `sustain_level=`. +- Verified with `dotnet test AquariumSynthCSharp.slnx --no-restore`: 39 passed. + +Previous slice: + - Replaced the DX7 algorithm-8 authoring surface with readable operator graph syntax: `operator`, `route`, and `carrier` declarations. -- Added `env=ad:attack:decay` and `env=adsr:attack:sustain:level:release` +- Added `env=ad:attack:decay` and `env=adsr:attack:decay:sustain:release` envelope forms for operator declarations. - Kept compact `ops=`/`edges=` syntax as parser/interchange scaffolding, but it is no longer the built-in authoring example. @@ -85,6 +97,7 @@ Parameter slice: Next likely slice: - Refine operator graphs with parameter bindings inside graph fields and decide - whether ADSR level semantics should stop borrowing `Envelope.Punch`. + how host MIDI note age/retrigger semantics should be represented beyond the + current frequency/gate controls. - Keep tests focused on structure first, then add rendered audio comparison once the render path is explicit. diff --git a/state/spine.yaml b/state/spine.yaml index c31134e..2bb8c8d 100644 --- a/state/spine.yaml +++ b/state/spine.yaml @@ -1,6 +1,6 @@ project: AquariumSynthCSharp spine_version: 1 -updated: 2026-05-13T11:46:38+01:00 +updated: 2026-05-13T12:20:00+01:00 prime_directive: > Build coherent synth machinery. References exist to reveal missing structure, @@ -30,6 +30,7 @@ live_invariants: - Patch scripts lower into explicit graph records before Faust emission. - 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. - 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. @@ -47,7 +48,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 envelope internals." + - "Refine operator graph parameter binding and host MIDI note retrigger semantics." - "Add rendered/audio comparison once a render path is explicit." zynaddsubfx: priority: 2 @@ -82,8 +83,9 @@ reference_targets: next_agent_start_here: recommended_first_task: > - Refine operator graph parameter binding and envelope internals. Keep - readable authoring syntax as operator/route/carrier declarations. + Refine operator graph parameter binding and host MIDI note retrigger + semantics. Keep readable authoring syntax as operator/route/carrier + declarations. must_read: - AGENTS.md - docs/audio-doctrine.md @@ -95,11 +97,19 @@ next_agent_start_here: - "dotnet test AquariumSynthCSharp.slnx --no-restore" completed_slices: + - date: 2026-05-13 + summary: > + Standardized the live envelope model as ADSR and added explicit Note + records for frequency, one-shot gate duration, and host/MIDI source. + SFXR sustain now maps to note gate duration; SFXR punch maps to non-unit + sustain level only as compatibility import behavior. Generated Faust can + emit one-shot ADSR envelopes or host gate/frequency controls. + verification: "dotnet test AquariumSynthCSharp.slnx --no-restore: 39 passed" - date: 2026-05-13 summary: > Added readable operator graph authoring syntax with `operator`, `route`, and `carrier` declarations, plus `env=ad:attack:decay` and - `env=adsr:attack:sustain:level:release` forms. Converted the DX7 + `env=adsr:attack:decay:sustain:release` forms. Converted the DX7 algorithm-8 rebuild away from compact number soup. verification: "dotnet test AquariumSynthCSharp.slnx --no-restore: 36 passed" - date: 2026-05-13 diff --git a/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs b/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs index e38aebd..2d86acb 100644 --- a/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs @@ -259,8 +259,8 @@ public sealed class PatchScriptTests Assert.Equal(2, patch.Parameters.Count); Assert.Equal(3, patch.ParameterBindings.Count); Assert.Contains(patch.ParameterBindings, binding => binding.FieldPath == "/voices/0/fm/index"); - Assert.Contains(patch.ParameterBindings, binding => binding.FieldPath == "/voices/0/env/decay"); - Assert.Contains(patch.ParameterBindings, binding => binding.FieldPath == "/voices/1/env/decay"); + Assert.Contains(patch.ParameterBindings, binding => binding.FieldPath == "/voices/0/env/release"); + Assert.Contains(patch.ParameterBindings, binding => binding.FieldPath == "/voices/1/env/release"); } [Fact] @@ -300,9 +300,10 @@ public sealed class PatchScriptTests Assert.Equal(.01f, op2.Envelope.AttackSeconds, 5); Assert.Equal(.2f, op2.Envelope.DecaySeconds, 5); Assert.Equal(.02f, op1.Envelope.AttackSeconds, 5); - Assert.Equal(.1f, op1.Envelope.SustainSeconds, 5); - Assert.Equal(.65f, op1.Envelope.Punch, 5); - Assert.Equal(.3f, op1.Envelope.DecaySeconds, 5); + Assert.Equal(.1f, op1.Envelope.DecaySeconds, 5); + Assert.Equal(.65f, op1.Envelope.SustainLevel, 5); + Assert.Equal(.3f, op1.Envelope.ReleaseSeconds, 5); + Assert.Equal(.21f, op2.Note.GateSeconds, 5); } [Fact] @@ -337,6 +338,34 @@ public sealed class PatchScriptTests Assert.Empty(export.Warnings); } + [Fact] + public void VoiceEnvelopeUsesStandardAdsrAndNoteGate() + { + var patch = PatchScript.Parse("v w=saw f=220 gate=.4 attack=.01 env_decay=.08 sustain_level=.6 release=.3"); + var voice = Assert.Single(patch.Voices); + var export = FaustEmitter.Emit(patch); + + Assert.Equal(220, voice.Note.FrequencyHz); + Assert.Equal(.4f, voice.Note.GateSeconds, 5); + Assert.Equal(.01f, voice.Envelope.AttackSeconds, 5); + Assert.Equal(.08f, voice.Envelope.DecaySeconds, 5); + Assert.Equal(.6f, voice.Envelope.SustainLevel, 5); + Assert.Equal(.3f, voice.Envelope.ReleaseSeconds, 5); + Assert.Contains("oneshot_adsr", export.Source); + } + + [Fact] + public void MidiVoiceEmitsHostNoteControls() + { + var patch = PatchScript.Parse("v w=saw f=220 midi=true attack=.01 env_decay=.08 sustain_level=.6 release=.3"); + 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.Contains("en.adsr", export.Source); + } + [Fact] public async Task FaustCompilerValidatesGeneratedSourceWhenInstalled() { @@ -365,6 +394,20 @@ public sealed class PatchScriptTests Assert.True(validation.Success, validation.Stderr); } + [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 validation = await FaustCompiler.ValidateAsync(export.Source); + + if (validation is null) + { + return; + } + + Assert.True(validation.Success, validation.Stderr); + } + [Fact] public async Task FaustCompilerCanEmitCSharpWhenInstalled() { diff --git a/tests/AquariumSynth.Dsl.Tests/SfxrPatchReferenceTests.cs b/tests/AquariumSynth.Dsl.Tests/SfxrPatchReferenceTests.cs index 837488b..cac867a 100644 --- a/tests/AquariumSynth.Dsl.Tests/SfxrPatchReferenceTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/SfxrPatchReferenceTests.cs @@ -34,6 +34,7 @@ public sealed class SfxrPatchReferenceTests private static void AssertVoiceClose(Voice expected, Voice actual, string context) { AssertOscillatorClose(expected.Oscillator, actual.Oscillator, context); + AssertNoteClose(expected.Note, actual.Note, context); AssertEnvelopeClose(expected.Envelope, actual.Envelope, context); AssertPitchClose(expected.Pitch, actual.Pitch, context); AssertClose(expected.Duty.RampPerSecond, actual.Duty.RampPerSecond, context, "duty.ramp"); @@ -59,9 +60,16 @@ public sealed class SfxrPatchReferenceTests private static void AssertEnvelopeClose(Envelope expected, Envelope actual, string context) { AssertClose(expected.AttackSeconds, actual.AttackSeconds, context, "env.attack"); - AssertClose(expected.SustainSeconds, actual.SustainSeconds, context, "env.sustain"); AssertClose(expected.DecaySeconds, actual.DecaySeconds, context, "env.decay"); - AssertClose(expected.Punch, actual.Punch, context, "env.punch"); + AssertClose(expected.SustainLevel, actual.SustainLevel, context, "env.sustain_level"); + AssertClose(expected.ReleaseSeconds, actual.ReleaseSeconds, context, "env.release"); + } + + private static void AssertNoteClose(Note expected, Note actual, string context) + { + AssertClose(expected.FrequencyHz, actual.FrequencyHz, context, "note.frequency"); + AssertClose(expected.GateSeconds, actual.GateSeconds, context, "note.gate"); + Assert.Equal(expected.Source, actual.Source); } private static void AssertPitchClose(PitchMotion expected, PitchMotion actual, string context)