Add staged operator envelopes

This commit is contained in:
Meta Vens 2026-05-13 19:28:07 +01:00
commit 85e5413daa
11 changed files with 239 additions and 31 deletions

View file

@ -46,6 +46,18 @@ public sealed record Dx7OperatorLevelApproximation(
int VelocityOffset,
string Notes);
public sealed record Dx7RateLevelEnvelopeApproximation(
RateLevelEnvelope Envelope,
float GateSeconds,
string Notes)
{
public string ToScriptSpec() =>
$"env=rl rates={F(Envelope.Rate1Seconds)},{F(Envelope.Rate2Seconds)},{F(Envelope.Rate3Seconds)},{F(Envelope.Rate4Seconds)} " +
$"levels={F(Envelope.Level1)},{F(Envelope.Level2)},{F(Envelope.Level3)},{F(Envelope.Level4)} gate={F(GateSeconds)}";
private static string F(float value) => value.ToString("0.######", System.Globalization.CultureInfo.InvariantCulture);
}
public sealed record Dx7Operator(
int Number,
Dx7Envelope Envelope,
@ -199,6 +211,23 @@ public static class Dx7SysEx
"Approximation: DX7 output level uses nonlinear scaling plus key/velocity offsets before envelope gain.");
}
public static Dx7RateLevelEnvelopeApproximation ApproximateRateLevelEnvelope(Dx7Envelope envelope)
{
var l1 = Level(envelope.Level1);
var l2 = Level(envelope.Level2);
var l3 = Level(envelope.Level3);
var l4 = Level(envelope.Level4);
var r1 = SegmentSeconds(envelope.Rate1, Math.Abs(l1 - l4));
var r2 = SegmentSeconds(envelope.Rate2, Math.Abs(l1 - l2));
var r3 = SegmentSeconds(envelope.Rate3, Math.Abs(l2 - l3));
var r4 = SegmentSeconds(envelope.Rate4, Math.Abs(l3 - l4));
return new Dx7RateLevelEnvelopeApproximation(
new RateLevelEnvelope(r1, l1, r2, l2, r3, l3, r4, l4),
Math.Max(r1 + r2 + r3, 0.02f),
"Approximation: DX7 EG uses four rate/level segments; Aquarium staged envelopes preserve the intermediate target levels.");
}
public static Dx7VoiceBank ParseBank(ReadOnlySpan<byte> bytes)
{
var data = PackedBankData(bytes);

View file

@ -57,6 +57,9 @@ public static class FaustEmitter
source.AppendLine("fold(x) = 2.0 * abs(2.0 * (x / 4.0 - floor(x / 4.0)) - 1.0) - 1.0;");
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("seg(t,t0,d,a,b) = a + (b - a) * clip01((t - t0) / max(0.0001, d));");
source.AppendLine("rl_release_start(r1,r2,r3,g) = max(g, r1 + r2 + r3);");
source.AppendLine("rl4_env(r1,l1,r2,l2,r3,l3,r4,l4,g) = select2(age < r1, select2(age < r1 + r2, select2(age < r1 + r2 + r3, select2(age < rl_release_start(r1,r2,r3,g), select2(age < rl_release_start(r1,r2,r3,g) + r4, l4, seg(age, rl_release_start(r1,r2,r3,g), r4, l3, l4)), l3), seg(age, r1 + r2, r3, l2, l3)), seg(age, r1, r2, l1, l2)), seg(age, 0, r1, 0, l1));");
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);");
@ -279,6 +282,9 @@ public static class FaustEmitter
: $"oneshot_adsr({attack}, {decay}, {sustain}, {release}, {gate})";
}
private static string RateLevelEnvelopeExpression(RateLevelEnvelope envelope, string gate) =>
$"rl4_env({F(envelope.Rate1Seconds)}, {F(envelope.Level1)}, {F(envelope.Rate2Seconds)}, {F(envelope.Level2)}, {F(envelope.Rate3Seconds)}, {F(envelope.Level3)}, {F(envelope.Rate4Seconds)}, {F(envelope.Level4)}, {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) ||
@ -346,18 +352,22 @@ public static class FaustEmitter
.Select(edge => $"{name}_op_{edge.SourceId} * {parameters.Expression($"{graphPath}/routes/{edge.SourceId}>{edge.TargetId}/index", edge.Index)}")
.ToList();
var externalPhaseMod = incoming.Count == 0 ? "0.0" : string.Join(" + ", incoming);
var envelope = EnvelopeExpression(
op.Envelope,
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host ? graphNoteGate : F(op.Note.GateSeconds),
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host,
field => field switch
{
"env/attack" => parameters.Expression($"{operatorPath}/env/attack", op.Envelope.AttackSeconds),
"env/decay" => parameters.Expression($"{operatorPath}/env/decay", op.Envelope.DecaySeconds),
"env/sustain_level" => parameters.Expression($"{operatorPath}/env/sustain_level", op.Envelope.SustainLevel),
"env/release" => parameters.Expression($"{operatorPath}/env/release", op.Envelope.ReleaseSeconds),
_ => throw new ArgumentOutOfRangeException(nameof(field), field, null)
});
var envelope = op.RateLevelEnvelope is not null
? RateLevelEnvelopeExpression(
op.RateLevelEnvelope,
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host ? graphNoteGate : F(op.Note.GateSeconds))
: EnvelopeExpression(
op.Envelope,
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host ? graphNoteGate : F(op.Note.GateSeconds),
UsesHostPlayback(playback) || op.Note.Source == NoteSource.Host,
field => field switch
{
"env/attack" => parameters.Expression($"{operatorPath}/env/attack", op.Envelope.AttackSeconds),
"env/decay" => parameters.Expression($"{operatorPath}/env/decay", op.Envelope.DecaySeconds),
"env/sustain_level" => parameters.Expression($"{operatorPath}/env/sustain_level", op.Envelope.SustainLevel),
"env/release" => parameters.Expression($"{operatorPath}/env/release", op.Envelope.ReleaseSeconds),
_ => throw new ArgumentOutOfRangeException(nameof(field), field, null)
});
if (op.Feedback != 0)
{
var feedback = parameters.Expression($"{operatorPath}/feedback", op.Feedback);

View file

@ -40,6 +40,16 @@ public sealed record Envelope(
public float DurationSeconds => AttackSeconds + DecaySeconds + ReleaseSeconds;
}
public sealed record RateLevelEnvelope(
float Rate1Seconds,
float Level1,
float Rate2Seconds,
float Level2,
float Rate3Seconds,
float Level3,
float Rate4Seconds,
float Level4);
public enum NoteSource
{
OneShot,
@ -120,7 +130,8 @@ public sealed record OperatorNode(
float Level = 1,
float Feedback = 0,
Note Note = null!,
Envelope Envelope = null!)
Envelope Envelope = null!,
RateLevelEnvelope? RateLevelEnvelope = null)
{
public Note Note { get; init; } = Note ?? new();
public Envelope Envelope { get; init; } = Envelope ?? new();

View file

@ -380,7 +380,7 @@ public static class PatchScript
var id = ParseOperatorId(Required(fields, "name", line), line);
var operatorPath = $"{graph.Path}/operators/{id}";
var envelopeSpec = TryGetAny(fields, ["env", "envelope"], out var envSpec)
? ParseEnvelopeSpec(envSpec, line, operatorPath)
? ParseEnvelopeSpec(envSpec, fields, line, operatorPath)
: new ParsedEnvelope(
new Envelope(
GetBoundFloat(fields, line, 0, $"{operatorPath}/env/attack", "attack", "a"),
@ -395,7 +395,8 @@ public static class PatchScript
GetBoundFloat(fields, line, 1, $"{operatorPath}/level", "level", "l"),
GetBoundFloat(fields, line, 0, $"{operatorPath}/feedback", "feedback", "fb"),
graph.Note with { GateSeconds = envelopeSpec.GateSeconds },
envelopeSpec.Envelope));
envelopeSpec.Envelope,
envelopeSpec.RateLevelEnvelope));
}
private void AddOperatorRoute(IReadOnlyDictionary<string, string> fields, int line)
@ -585,7 +586,7 @@ public static class PatchScript
.Select(part => ParseInt(part, line))
.ToList();
private ParsedEnvelope ParseEnvelopeSpec(string value, int line, string fieldPath)
private ParsedEnvelope ParseEnvelopeSpec(string value, IReadOnlyDictionary<string, string> fields, int line, string fieldPath)
{
var pieces = value.Split(':');
return pieces[0].ToLowerInvariant() switch
@ -599,7 +600,9 @@ public static class PatchScript
ParseBoundFloat(pieces[2], line, 0, $"{fieldPath}/env/decay"),
ParseBoundFloat(pieces[3], line, 1, $"{fieldPath}/env/sustain_level"),
ParseBoundFloat(pieces[4], line, 0.1f, $"{fieldPath}/env/release")),
0.1f),
GateSeconds(fields, line, 0.1f, fieldPath)),
"rl" or "ratelevel" when pieces.Length == 1 => ParseRateLevelEnvelope(fields, line, fieldPath),
"rl" or "ratelevel" when pieces.Length == 9 => ParseRateLevelEnvelope(pieces, fields, line, fieldPath),
_ => throw new PatchScriptException(line, $"bad envelope `{value}`")
};
}
@ -607,6 +610,57 @@ public static class PatchScript
private static ParsedEnvelope AdEnvelope(float attackSeconds, float decaySeconds) =>
new(new Envelope(attackSeconds, decaySeconds, 0, 0), attackSeconds + decaySeconds);
private ParsedEnvelope ParseRateLevelEnvelope(IReadOnlyDictionary<string, string> fields, int line, string fieldPath)
{
var rates = ParseFloatList(Required(fields, "rates", line), line, "rates");
var levels = ParseFloatList(Required(fields, "levels", line), line, "levels");
if (rates.Count != 4 || levels.Count != 4)
{
throw new PatchScriptException(line, "rate/level envelope needs four rates and four levels");
}
return RateLevelParsedEnvelope(rates, levels, fields, line, fieldPath);
}
private ParsedEnvelope ParseRateLevelEnvelope(string[] pieces, IReadOnlyDictionary<string, string> fields, int line, string fieldPath)
{
var rates = new[] { pieces[1], pieces[3], pieces[5], pieces[7] }
.Select(part => ParseFloat(part, line))
.ToArray();
var levels = new[] { pieces[2], pieces[4], pieces[6], pieces[8] }
.Select(part => ParseFloat(part, line))
.ToArray();
return RateLevelParsedEnvelope(rates, levels, fields, line, fieldPath);
}
private ParsedEnvelope RateLevelParsedEnvelope(IReadOnlyList<float> rates, IReadOnlyList<float> levels, IReadOnlyDictionary<string, string> fields, int line, string fieldPath)
{
var envelope = new RateLevelEnvelope(
Math.Max(0, rates[0]), Math.Clamp(levels[0], 0, 1.5f),
Math.Max(0, rates[1]), Math.Clamp(levels[1], 0, 1.5f),
Math.Max(0, rates[2]), Math.Clamp(levels[2], 0, 1.5f),
Math.Max(0, rates[3]), Math.Clamp(levels[3], 0, 1.5f));
var defaultGate = Math.Max(envelope.Rate1Seconds + envelope.Rate2Seconds + envelope.Rate3Seconds, 0.02f);
return new ParsedEnvelope(
new Envelope(envelope.Rate1Seconds, envelope.Rate2Seconds + envelope.Rate3Seconds, envelope.Level3, envelope.Rate4Seconds),
GateSeconds(fields, line, defaultGate, fieldPath),
envelope);
}
private float GateSeconds(IReadOnlyDictionary<string, string> fields, int line, float defaultValue, string fieldPath) =>
GetBoundFloat(fields, line, defaultValue, $"{fieldPath}/note/gate", "gate", "hold", "duration");
private static IReadOnlyList<float> ParseFloatList(string value, int line, string fieldName)
{
var parts = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 0)
{
throw new PatchScriptException(line, $"{fieldName} list cannot be empty");
}
return parts.Select(part => ParseFloat(part, line)).ToArray();
}
private static int ParseOperatorId(string value, int line)
{
var normalized = value.StartsWith("op", StringComparison.OrdinalIgnoreCase)
@ -684,7 +738,7 @@ public static class PatchScript
public List<int> Carriers { get; } = [];
}
private sealed record ParsedEnvelope(Envelope Envelope, float GateSeconds);
private sealed record ParsedEnvelope(Envelope Envelope, float GateSeconds, RateLevelEnvelope? RateLevelEnvelope = null);
}
private static readonly (string[] Keys, ModTarget Target)[] ModTargets =