diff --git a/docs/dx7-calibration-plan.md b/docs/dx7-calibration-plan.md index 8ba1aee..892e963 100644 --- a/docs/dx7-calibration-plan.md +++ b/docs/dx7-calibration-plan.md @@ -65,9 +65,16 @@ math is still fake in the places that matter perceptually. EG levels improves some envelope metrics but fails the hard PRC log-mel target. Do not land it without isolated envelope parity. - Current trace evidence lives in - `artifacts/parity/dx7-envelope-trace/egstep.csv`: DX7 EG can spike above - unit gain and collapse to a tiny sustain within milliseconds, unlike the - current linear `env=rl` approximation. + `artifacts/parity/dx7-envelope-trace/egstep.csv`: DX7 raw EG state can + spike above unit gain and collapse to a tiny sustain within milliseconds, + unlike the current linear `env=rl` approximation. + - Dexed's rendered audio does not hear that raw state directly. The operator + path samples EG once per 64-sample block and linearly interpolates the + applied gain across the block, so a DX7-capable Aquarium envelope must + model both the rate/level state machine and its block-interpolated output. + - Aquarium staged operator envelopes now support per-segment curves, e.g. + `env=rl rates=.00145,.0508,.5268,.35 levels=2,.297,.0156,0 curves=lin,exp,exp,exp`. + This is a general staged-contour feature, not a DX7-specific syntax escape. 7. **Summed/cascaded modulation** - Render project-authored algorithm-8 stacks that isolate `6 -> 5 -> 3` diff --git a/src/AquariumSynth.Dsl/Dx7SysEx.cs b/src/AquariumSynth.Dsl/Dx7SysEx.cs index 2c26d90..0cb6f12 100644 --- a/src/AquariumSynth.Dsl/Dx7SysEx.cs +++ b/src/AquariumSynth.Dsl/Dx7SysEx.cs @@ -51,11 +51,21 @@ public sealed record Dx7RateLevelEnvelopeApproximation( 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)}"; + public string ToScriptSpec() + { + var curves = Envelope.Curve1 == RateLevelCurve.Linear && + Envelope.Curve2 == RateLevelCurve.Linear && + Envelope.Curve3 == RateLevelCurve.Linear && + Envelope.Curve4 == RateLevelCurve.Linear + ? "" + : $" curves={Curve(Envelope.Curve1)},{Curve(Envelope.Curve2)},{Curve(Envelope.Curve3)},{Curve(Envelope.Curve4)}"; + return $"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)}{curves} gate={F(GateSeconds)}"; + } private static string F(float value) => value.ToString("0.######", System.Globalization.CultureInfo.InvariantCulture); + + private static string Curve(RateLevelCurve curve) => curve == RateLevelCurve.Exponential ? "exp" : "lin"; } public sealed record Dx7EnvelopeTracePoint(float TimeSeconds, float Gain, int Stage); @@ -289,6 +299,41 @@ public static class Dx7SysEx return points; } + public static IReadOnlyList TraceInterpolatedEnvelope( + Dx7Envelope envelope, + float gateSeconds, + float durationSeconds, + int outputLevel = 99, + int sampleRate = 44100, + int blockSize = 64) + { + var state = Dx7EnvelopeState.Start(envelope, outputLevel, sampleRate); + var sampleCount = Math.Max(1, (int)MathF.Round(Math.Max(1f / sampleRate, durationSeconds) * sampleRate)); + var gateSample = Math.Clamp((int)MathF.Round(Math.Max(0, gateSeconds) * sampleRate), 0, sampleCount); + var points = new List(sampleCount); + var previousGain = 0f; + + for (var blockStart = 0; blockStart < sampleCount; blockStart += Math.Max(1, blockSize)) + { + if (blockStart >= gateSample) + { + state.KeyDown(envelope, down: false); + } + state.Advance(envelope); + var currentGain = state.Gain; + var count = Math.Min(blockSize, sampleCount - blockStart); + for (var i = 0; i < count; i++) + { + var t = (i + 1) / (float)blockSize; + var gain = previousGain + (currentGain - previousGain) * t; + points.Add(new Dx7EnvelopeTracePoint((blockStart + i) / (float)sampleRate, gain, state.Stage)); + } + previousGain = currentGain; + } + + return points; + } + public static Dx7VoiceBank ParseBank(ReadOnlySpan bytes) { var data = PackedBankData(bytes); diff --git a/src/AquariumSynth.Dsl/FaustExport.cs b/src/AquariumSynth.Dsl/FaustExport.cs index 03d64ad..06ce7e1 100644 --- a/src/AquariumSynth.Dsl/FaustExport.cs +++ b/src/AquariumSynth.Dsl/FaustExport.cs @@ -58,8 +58,10 @@ public static class FaustEmitter 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("seg_exp(t,t0,d,a,b) = exp(log(max(0.00001, a)) + (log(max(0.00001, b)) - log(max(0.00001, a))) * clip01((t - t0) / max(0.0001, d)));"); + source.AppendLine("seg_curve(c,t,t0,d,a,b) = select2(c < 0.5, seg_exp(t,t0,d,a,b), seg(t,t0,d,a,b));"); 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("rl4_env(r1,l1,c1,r2,l2,c2,r3,l3,c3,r4,l4,c4,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_curve(c4, age, rl_release_start(r1,r2,r3,g), r4, l3, l4)), l3), seg_curve(c3, age, r1 + r2, r3, l2, l3)), seg_curve(c2, age, r1, r2, l1, l2)), seg_curve(c1, 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);"); @@ -283,7 +285,10 @@ public static class FaustEmitter } 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})"; + $"rl4_env({F(envelope.Rate1Seconds)}, {F(envelope.Level1)}, {Curve(envelope.Curve1)}, {F(envelope.Rate2Seconds)}, {F(envelope.Level2)}, {Curve(envelope.Curve2)}, {F(envelope.Rate3Seconds)}, {F(envelope.Level3)}, {Curve(envelope.Curve3)}, {F(envelope.Rate4Seconds)}, {F(envelope.Level4)}, {Curve(envelope.Curve4)}, {gate})"; + + private static string Curve(RateLevelCurve curve) => + curve == RateLevelCurve.Exponential ? "1" : "0"; private static string OscillatorExpression(SynthPatch patch, Voice voice, int voiceIndex, string frequency, string duty, string fmIndex, ParameterMap parameters) { diff --git a/src/AquariumSynth.Dsl/Model.cs b/src/AquariumSynth.Dsl/Model.cs index e872035..f7ec65d 100644 --- a/src/AquariumSynth.Dsl/Model.cs +++ b/src/AquariumSynth.Dsl/Model.cs @@ -40,6 +40,12 @@ public sealed record Envelope( public float DurationSeconds => AttackSeconds + DecaySeconds + ReleaseSeconds; } +public enum RateLevelCurve +{ + Linear, + Exponential +} + public sealed record RateLevelEnvelope( float Rate1Seconds, float Level1, @@ -48,7 +54,11 @@ public sealed record RateLevelEnvelope( float Rate3Seconds, float Level3, float Rate4Seconds, - float Level4); + float Level4, + RateLevelCurve Curve1 = RateLevelCurve.Linear, + RateLevelCurve Curve2 = RateLevelCurve.Linear, + RateLevelCurve Curve3 = RateLevelCurve.Linear, + RateLevelCurve Curve4 = RateLevelCurve.Linear); public enum NoteSource { diff --git a/src/AquariumSynth.Dsl/PatchScript.cs b/src/AquariumSynth.Dsl/PatchScript.cs index 7a6f336..0745595 100644 --- a/src/AquariumSynth.Dsl/PatchScript.cs +++ b/src/AquariumSynth.Dsl/PatchScript.cs @@ -635,11 +635,20 @@ public static class PatchScript private ParsedEnvelope RateLevelParsedEnvelope(IReadOnlyList rates, IReadOnlyList levels, IReadOnlyDictionary fields, int line, string fieldPath) { + var curves = TryGetAny(fields, ["curves", "curve"], out var curveText) + ? ParseCurveList(curveText, line) + : [RateLevelCurve.Linear, RateLevelCurve.Linear, RateLevelCurve.Linear, RateLevelCurve.Linear]; + if (curves.Count != 4) + { + throw new PatchScriptException(line, "rate/level envelope needs four curves"); + } + 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)); + Math.Max(0, rates[0]), Math.Clamp(levels[0], 0, 4f), + Math.Max(0, rates[1]), Math.Clamp(levels[1], 0, 4f), + Math.Max(0, rates[2]), Math.Clamp(levels[2], 0, 4f), + Math.Max(0, rates[3]), Math.Clamp(levels[3], 0, 4f), + curves[0], curves[1], curves[2], curves[3]); 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), @@ -647,6 +656,22 @@ public static class PatchScript envelope); } + private static IReadOnlyList ParseCurveList(string value, int line) + { + var parts = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length == 0) + { + throw new PatchScriptException(line, "curves list cannot be empty"); + } + + return parts.Select(part => part.ToLowerInvariant() switch + { + "lin" or "linear" => RateLevelCurve.Linear, + "exp" or "exponential" => RateLevelCurve.Exponential, + _ => throw new PatchScriptException(line, $"unknown rate/level curve `{part}`") + }).ToArray(); + } + private float GateSeconds(IReadOnlyDictionary fields, int line, float defaultValue, string fieldPath) => GetBoundFloat(fields, line, defaultValue, $"{fieldPath}/note/gate", "gate", "hold", "duration"); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 666496c..02feabc 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -37,3 +37,5 @@ {"kind":"dx7_project_authored_patch_rendering","lesson":"Project-authored Dexed patches can be generated directly inside tests from explicit operator specs. Use this for lawful calibration rungs instead of squeezing every DX7 fact out of public-domain hard patches.","source":"DX7 project-authored summed-stack parity on 2026-05-14"} {"kind":"dx7_envelope_curve_cut","lesson":"Reusing the operator output amplitude curve for DX7 EG levels is not ready: it can improve isolated envelope shape metrics with shorter timing, but it failed the hard PRC log-mel target. Keep EG levels linear until isolated envelope parity passes without regressing PRC.","source":"DX7 envelope level experiment on 2026-05-14"} {"kind":"dx7_envelope_trace","lesson":"Direct DX7 EG tracing shows the current `env=rl` abstraction is the wrong shape for some DX7 envelopes: the traced EG can spike above unit gain and drop below .02 within about 9 ms while `env=rl` is still near 1. A runtime `env=dx7` surface was attempted and cut because matching the local trace did not yet match Dexed plugin audio.","source":"DX7 envelope trace artifact on 2026-05-14"} +{"kind":"dx7_envelope_applied_gain","lesson":"Dexed-style operator audio does not use the raw DX7 EG state directly. It samples the EG once per 64-sample block and linearly interpolates applied gain across the block. A DX7-capable Aquarium envelope must model that applied-gain timebase; matching raw EG trace alone can make a candidate far too quiet or otherwise wrong.","source":"DX7 interpolated envelope trace artifact on 2026-05-14"} +{"kind":"curved_rate_level_envelope","lesson":"Aquarium staged operator envelopes now support per-segment curves and deliberate levels above unity. Keep this authority in `RateLevelEnvelope`: it protects the invariant that multi-target operator contours can model exponential synth envelopes without inventing one-off DX7 syntax.","source":"Curved rate/level envelope implementation on 2026-05-14"} diff --git a/state/memory.json b/state/memory.json index 6c9bc0b..f7a333b 100644 --- a/state/memory.json +++ b/state/memory.json @@ -30,7 +30,9 @@ "DX7 ROM COM output compensation", "DX7 topology-aware route lowering", "DX7 envelope trace helper", + "DX7 block-interpolated envelope applied-gain trace helper", "staged operator envelope DSL", + "curved staged operator envelope segments", "DX7 envelope-to-ADSR approximation", "standard ADSR envelope model", "note frequency/gate model", @@ -69,9 +71,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, measured carrier output amplitude, isolated two-op modulation route scale, calibrated feedback amount table, ratio detune lowering, ROM COM output compensation, topology-aware route lowering, staged operator envelopes, DX7 envelope tracing, two Aquarium DSL rebuild attempts, first-class OperatorGraph support, public-domain SysEx fixture coverage, dexed-py reference rendering, project-authored Dexed patch rendering, Aquarium candidate rendering through Faust-generated C#, one thresholded rendered parity test for analog1.syx voice 13, a hard PRC SYNTH1 parity probe with listening WAV artifacts and log-mel <= 0.255, project-authored algorithm-8 summed-stack parity, and renderable delayed operator feedback.", - "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. The first rendered parity rung is behavioral and sine-like, not exact DX7 operator execution. A harder algorithm-8 target exposed that feedback must be delayed recursion in Faust, not a direct cyclic self-reference. Static DX7 output-level approximation helped import/rebuild math but was mathematically wrong for carrier amplitude. A single-carrier Dexed sweep shows carrier amplitude follows 2^((outputLevel - 99) / 8). Isolated two-op DX7 FM maps full-level modulation to Aquarium route index 6.275, while summed/cascaded algorithm-8 branches need a lower topology-aware route scale. Feedback now lowers through a fitted table instead of PRC-local constants. Ratio-mode detune belongs in operator frequency lowering. ROM COM values carry output-count compensation; because the amplitude curve was fitted against algorithm 32, DX7 carriers scale by 6/(COM+1). Project-authored Dexed patch rendering now gives lawful calibration targets. Reusing the operator output curve for EG levels was tested and cut because it failed hard-target log-mel. Direct envelope tracing shows current `env=rl` cannot express DX7 EG spike/drop behavior. Staged operator envelopes remain useful, but DX7 needs a separately proven model.", - "next": "Use `Dx7SysEx.TraceEnvelope` and `artifacts/parity/dx7-envelope-trace/egstep.csv` to design a DX7 envelope model that matches Dexed plugin audio before adding public syntax." + "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, measured carrier output amplitude, isolated two-op modulation route scale, calibrated feedback amount table, ratio detune lowering, ROM COM output compensation, topology-aware route lowering, staged operator envelopes with per-segment curves, raw and block-interpolated DX7 envelope tracing, two Aquarium DSL rebuild attempts, first-class OperatorGraph support, public-domain SysEx fixture coverage, dexed-py reference rendering, project-authored Dexed patch rendering, Aquarium candidate rendering through Faust-generated C#, one thresholded rendered parity test for analog1.syx voice 13, a hard PRC SYNTH1 parity probe with listening WAV artifacts and log-mel <= 0.255, project-authored algorithm-8 summed-stack parity, and renderable delayed operator feedback.", + "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. The first rendered parity rung is behavioral and sine-like, not exact DX7 operator execution. A harder algorithm-8 target exposed that feedback must be delayed recursion in Faust, not a direct cyclic self-reference. Static DX7 output-level approximation helped import/rebuild math but was mathematically wrong for carrier amplitude. A single-carrier Dexed sweep shows carrier amplitude follows 2^((outputLevel - 99) / 8). Isolated two-op DX7 FM maps full-level modulation to Aquarium route index 6.275, while summed/cascaded algorithm-8 branches need a lower topology-aware route scale. Feedback now lowers through a fitted table instead of PRC-local constants. Ratio-mode detune belongs in operator frequency lowering. ROM COM values carry output-count compensation; because the amplitude curve was fitted against algorithm 32, DX7 carriers scale by 6/(COM+1). Project-authored Dexed patch rendering now gives lawful calibration targets. Reusing the operator output curve for EG levels was tested and cut because it failed hard-target log-mel. Direct envelope tracing shows current linear `env=rl` cannot express DX7 EG spike/drop behavior. Dexed-style audio samples EG once per 64-sample block and interpolates applied gain, so raw EG parity alone is not audio parity. Staged operator envelopes now support linear/exponential segments and supranormal levels, which lets the DSL approximate that contour without a DX7-only syntax escape.", + "next": "Use the curved staged-envelope surface plus `Dx7SysEx.TraceEnvelope`, `Dx7SysEx.TraceInterpolatedEnvelope`, and `artifacts/parity/dx7-envelope-trace/egstep.csv` to calibrate a DX7 lowering that improves rendered PRC log-mel before adding any more public envelope syntax." }, "note_and_envelope_model": { "rule": "Notes own frequency, gate duration, and host/MIDI source. Envelopes own ADSR level shape.", @@ -86,7 +88,7 @@ }, "last_verified": { "command": "AQUARIUM_DX7_PYTHON= dotnet test AquariumSynthCSharp.slnx --no-restore", - "result": "63 passed; DX7 envelope trace artifact generated", - "commit": "pending DX7 envelope trace" + "result": "65 passed; staged envelope curves parse/render and DX7 trace artifact includes raw/applied/curved gain", + "commit": "pending DX7 interpolated envelope trace" } } diff --git a/state/scratch.md b/state/scratch.md index 6dbe650..4ed2dd3 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -15,16 +15,26 @@ Doctrine update: Completed this slice: +- Extended staged operator envelopes with per-segment curves: + `curves=lin,exp,exp,lin`. Linear remains the default, and levels can now + express deliberate transient overshoot above `1` instead of clipping away + the DX7 evidence. - Added `Dx7SysEx.TraceEnvelope`, a DX7 EG microscope that follows the internal rate/level state machine closely enough to expose gain and stage over time. +- Added `Dx7SysEx.TraceInterpolatedEnvelope`, which traces the gain actually + applied by Dexed-style operator rendering: one EG sample per 64-sample block, + linearly interpolated across the block. - Added an envelope comparison artifact test that writes - `artifacts/parity/dx7-envelope-trace/egstep.csv`. The first rows show the - current mismatch plainly: DX7 jumps to gain `2`, falls below `.02` in about - 9 ms, while Aquarium `env=rl` is still near `1` and linearly drifting. + `artifacts/parity/dx7-envelope-trace/egstep.csv`. The first rows show both + DX7 raw state and applied gain: raw jumps to `2` immediately, while applied + gain ramps from `.03125` to `2` over the first 64-sample block and remains + near `1` around 20 ms. Aquarium `env=rl` is a different contour entirely. + The artifact now also includes a curved Aquarium staged-envelope candidate + that tracks the applied-gain contour far more closely. - Tried adding a first `env=dx7` runtime lowering, then cut it. The trace matched the Python `graph.py` envelope but not Dexed plugin audio, so the - syntax was not allowed to survive. The durable result is the microscope, not - a half-proven model. + syntax was not allowed to survive. The durable result is the microscope and + the applied-gain trace, not a half-proven model. Previous slice: diff --git a/state/spine.yaml b/state/spine.yaml index 5e6274d..47f344e 100644 --- a/state/spine.yaml +++ b/state/spine.yaml @@ -1,6 +1,6 @@ project: AquariumSynthCSharp spine_version: 1 -updated: 2026-05-14T05:18:00+01:00 +updated: 2026-05-14T05:42:00+01:00 prime_directive: > Build coherent synth machinery. References exist to reveal missing structure, @@ -53,8 +53,10 @@ live_invariants: - `SummedOperatorModulationRouteIndex` is calibrated from the hard PRC target. It is no longer PRC-local, but project-authored algorithm-8 stack sweeps should tighten it before broad DX7 import. - DX7 calibration must proceed through isolated rungs in `docs/dx7-calibration-plan.md`; do not keep tuning hard PRC-specific constants as a substitute for a level/index model. - Staged operator envelopes own multi-target operator level contours through `env=rl rates=... levels=...`; do not force DX7-style contours back into the general ADSR voice envelope model. + - Staged operator envelopes may use per-segment curves through `curves=lin,exp,...`; this belongs to the rate/level contour authority, not to the standard ADSR envelope. - DX7 rate/level envelopes may lower to staged operator envelopes or labeled ADSR approximations, but exact DX7 EG timing/gain calibration remains missing pressure. - - DX7 envelope trace evidence now lives in `Dx7SysEx.TraceEnvelope` and `artifacts/parity/dx7-envelope-trace/egstep.csv`; do not add an `env=dx7` runtime surface until it matches Dexed plugin audio, not only the local trace helper. + - DX7 envelope trace evidence now lives in `Dx7SysEx.TraceEnvelope`, `Dx7SysEx.TraceInterpolatedEnvelope`, and `artifacts/parity/dx7-envelope-trace/egstep.csv`; Dexed-style audio uses block-interpolated applied gain, not the raw EG state alone. + - Do not add an `env=dx7` runtime surface until it matches Dexed plugin audio with the block-interpolated gain model, not only the raw trace helper. - Recompile only for graph shape changes; vary declared parameters through the hosted DSP control API. - Reference fixtures must preserve provenance, license status, source hash, and feature pressure. - Public-domain reference fixtures and dexed-py helpers are test/development material only; the NuGet package must ship only AquariumSynth.Dsl. @@ -114,8 +116,9 @@ next_agent_start_here: compensation, and topology-aware route lowering are now fitted or mapped; a project-authored algorithm-8 stack test now backs the summed route scale outside PRC. The attempted exponential EG level curve was cut because it - still failed PRC log-mel. Use `Dx7SysEx.TraceEnvelope` and the - `dx7-envelope-trace` artifact to design the next envelope model. + still failed PRC log-mel. Use `Dx7SysEx.TraceEnvelope`, + `Dx7SysEx.TraceInterpolatedEnvelope`, and the `dx7-envelope-trace` artifact + to design the next envelope model. must_read: - AGENTS.md - docs/audio-doctrine.md @@ -128,6 +131,22 @@ next_agent_start_here: - "dotnet test AquariumSynthCSharp.slnx --no-restore" completed_slices: + - date: 2026-05-14 + summary: > + Added per-segment curves to staged operator envelopes. `env=rl` remains + the same rate/level contour surface, but can now express linear or + exponential segments with deliberate levels above unity. The DX7 envelope + trace artifact includes a curved Aquarium candidate that is much closer + to Dexed's block-interpolated applied gain than the old linear contour. + verification: "dotnet test AquariumSynthCSharp.slnx --no-restore --filter \"OperatorGraphSyntaxParsesReadableRateLevelEnvelope|OperatorGraphSyntaxParsesCurvedRateLevelEnvelope|ProjectAuthoredDx7EnvelopeTraceWritesComparisonArtifact\": passed" + - date: 2026-05-14 + summary: > + Added `Dx7SysEx.TraceInterpolatedEnvelope` and extended the DX7 envelope + trace artifact with raw and applied gain columns. Dexed-style operator + rendering samples the EG once per 64-sample block and interpolates the + applied gain across the block, so matching the raw EG state alone is not + enough for audio parity. + verification: "dotnet test AquariumSynthCSharp.slnx --no-restore --filter \"TracesDx7EnvelopeAppliedBlockInterpolatedGain|TracesDx7EnvelopeInternalGainShape|ProjectAuthoredDx7EnvelopeTraceWritesComparisonArtifact\": passed" - date: 2026-05-14 summary: > Added `Dx7SysEx.TraceEnvelope` and an envelope trace comparison artifact. diff --git a/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs b/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs index 380d42a..41e5baf 100644 --- a/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs @@ -194,28 +194,51 @@ public sealed class Dx7ReferenceParityTests Level3: 43, Level4: 0); var dx7 = Dx7SysEx.TraceEnvelope(envelope, gateSeconds: 0.75f, durationSeconds: 1.1f); + var dx7Applied = Dx7SysEx.TraceInterpolatedEnvelope(envelope, gateSeconds: 0.75f, durationSeconds: 1.1f); var approximation = ScaledEnvelope(Dx7SysEx.ApproximateRateLevelEnvelope(envelope), 0.62f, 0.75f); var aquarium = TraceRateLevelEnvelope(approximation.Envelope, approximation.GateSeconds, durationSeconds: 1.1f); + var aquariumCurved = TraceRateLevelEnvelope( + new RateLevelEnvelope( + 64f / 44100, + 2f, + 0.0522449f - 64f / 44100, + 0.297302f, + 0.5790476f - 0.0522449f, + 0.015625f, + 0.35f, + 0f, + RateLevelCurve.Linear, + RateLevelCurve.Exponential, + RateLevelCurve.Exponential, + RateLevelCurve.Exponential), + gateSeconds: 0.75f, + durationSeconds: 1.1f); var artifactDir = ArtifactPath("parity", "dx7-envelope-trace"); Directory.CreateDirectory(artifactDir); var path = Path.Combine(artifactDir, "egstep.csv"); using var writer = new StreamWriter(path); - writer.WriteLine("time_seconds,dx7_gain,aquarium_gain,dx7_stage"); + writer.WriteLine("time_seconds,dx7_raw_gain,dx7_applied_gain,aquarium_rl_gain,aquarium_curved_gain,dx7_stage"); for (var i = 0; i < Math.Min(dx7.Count, aquarium.Length); i += 64) { writer.WriteLine(string.Join( ",", F(dx7[i].TimeSeconds), F(dx7[i].Gain), + F(dx7Applied[i].Gain), F(aquarium[i]), + F(aquariumCurved[i]), dx7[i].Stage.ToString(System.Globalization.CultureInfo.InvariantCulture))); } - var shape = NormalizedDistance( - dx7.Select(point => point.Gain).ToArray(), + var linearShape = NormalizedDistance( + dx7Applied.Select(point => point.Gain).ToArray(), aquarium); - Assert.True(shape > 0.75f, $"expected current Aquarium envelope to visibly differ; shape distance {shape}, artifact: {path}"); + var curvedShape = NormalizedDistance( + dx7Applied.Select(point => point.Gain).ToArray(), + aquariumCurved); + Assert.True(linearShape > 0.55f, $"expected current Aquarium envelope to visibly differ; shape distance {linearShape}, artifact: {path}"); + Assert.True(curvedShape < linearShape * 0.6f, $"expected curved Aquarium envelope to improve shape; linear {linearShape}, curved {curvedShape}, artifact: {path}"); } private static string FixturePath(params string[] parts) => @@ -336,7 +359,11 @@ public sealed class Dx7ReferenceParityTests envelope.Rate3Seconds * scale, envelope.Level3, envelope.Rate4Seconds * scale, - envelope.Level4); + envelope.Level4, + envelope.Curve1, + envelope.Curve2, + envelope.Curve3, + envelope.Curve4); return approximation with { Envelope = scaled, @@ -353,24 +380,31 @@ public sealed class Dx7ReferenceParityTests var age = sample / (float)sampleRate; var releaseStart = Math.Max(gateSeconds, envelope.Rate1Seconds + envelope.Rate2Seconds + envelope.Rate3Seconds); values[sample] = age < envelope.Rate1Seconds - ? Segment(age, 0, envelope.Rate1Seconds, 0, envelope.Level1) + ? Segment(age, 0, envelope.Rate1Seconds, 0, envelope.Level1, envelope.Curve1) : age < envelope.Rate1Seconds + envelope.Rate2Seconds - ? Segment(age, envelope.Rate1Seconds, envelope.Rate2Seconds, envelope.Level1, envelope.Level2) + ? Segment(age, envelope.Rate1Seconds, envelope.Rate2Seconds, envelope.Level1, envelope.Level2, envelope.Curve2) : age < envelope.Rate1Seconds + envelope.Rate2Seconds + envelope.Rate3Seconds - ? Segment(age, envelope.Rate1Seconds + envelope.Rate2Seconds, envelope.Rate3Seconds, envelope.Level2, envelope.Level3) + ? Segment(age, envelope.Rate1Seconds + envelope.Rate2Seconds, envelope.Rate3Seconds, envelope.Level2, envelope.Level3, envelope.Curve3) : age < releaseStart ? envelope.Level3 : age < releaseStart + envelope.Rate4Seconds - ? Segment(age, releaseStart, envelope.Rate4Seconds, envelope.Level3, envelope.Level4) + ? Segment(age, releaseStart, envelope.Rate4Seconds, envelope.Level3, envelope.Level4, envelope.Curve4) : envelope.Level4; } return values; } - private static float Segment(float time, float start, float duration, float from, float to) + private static float Segment(float time, float start, float duration, float from, float to, RateLevelCurve curve = RateLevelCurve.Linear) { var t = Math.Clamp((time - start) / Math.Max(0.0001f, duration), 0, 1); + if (curve == RateLevelCurve.Exponential) + { + var a = Math.Max(0.00001f, from); + var b = Math.Max(0.00001f, to); + return MathF.Exp(MathF.Log(a) + (MathF.Log(b) - MathF.Log(a)) * t); + } + return from + (to - from) * t; } diff --git a/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs b/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs index 76a16c8..fc47184 100644 --- a/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs @@ -316,6 +316,29 @@ public sealed class Dx7SysExTests Assert.True(trace[(int)(0.9f * 44100)].Gain < 0.001f); } + [Fact] + public void TracesDx7EnvelopeAppliedBlockInterpolatedGain() + { + var trace = Dx7SysEx.TraceInterpolatedEnvelope( + new Dx7Envelope( + Rate1: 98, + Rate2: 64, + Rate3: 48, + Rate4: 55, + Level1: 99, + Level2: 76, + Level3: 43, + Level4: 0), + gateSeconds: 0.75f, + durationSeconds: 1.1f); + + Assert.InRange(trace[0].Gain, 0.02f, 0.04f); + Assert.True(trace[63].Gain > 1.9f); + Assert.InRange(trace[127].Gain, 1.88f, 1.91f); + Assert.InRange(trace[(int)(0.02f * 44100)].Gain, 0.99f, 1.02f); + Assert.InRange(trace[(int)(0.2f * 44100)].Gain, 0.12f, 0.14f); + } + private static byte[] InitVoice(string name, int algorithm, int feedback) { var data = new byte[Dx7SysEx.VoiceEditBufferLength]; diff --git a/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs b/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs index bff12f2..f5b7b67 100644 --- a/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs @@ -333,7 +333,29 @@ public sealed class PatchScriptTests Assert.Equal(.4f, envelope.Rate4Seconds, 5); Assert.Equal(0, envelope.Level4); Assert.Equal(.75f, op2.Note.GateSeconds, 5); - Assert.Contains("rl4_env(0.004, 1, 0.12, 0.7, 0.2, 0.25, 0.4, 0, 0.75)", export.Source); + Assert.Equal(RateLevelCurve.Linear, envelope.Curve1); + Assert.Contains("rl4_env(0.004, 1, 0, 0.12, 0.7, 0, 0.2, 0.25, 0, 0.4, 0, 0, 0.75)", export.Source); + } + + [Fact] + public void OperatorGraphSyntaxParsesCurvedRateLevelEnvelope() + { + var patch = PatchScript.Parse(""" + opgraph name=pair freq=220 gain=.2 + operator name=op2 ratio=2 level=.8 env=rl rates=.004,.12,.2,.4 levels=1.2,.7,.25,0 curves=lin,exp,exp,lin gate=.75 + operator name=op1 ratio=1 level=1 env=ad:.01:.08 + route from=op2 to=op1 index=.8 + carrier name=op1 + """); + var export = FaustEmitter.Emit(patch); + + var envelope = Assert.Single(patch.OperatorGraphs[0].Operators, op => op.Id == 2).RateLevelEnvelope; + Assert.NotNull(envelope); + Assert.Equal(RateLevelCurve.Linear, envelope.Curve1); + Assert.Equal(RateLevelCurve.Exponential, envelope.Curve2); + Assert.Equal(RateLevelCurve.Exponential, envelope.Curve3); + Assert.Equal(RateLevelCurve.Linear, envelope.Curve4); + Assert.Contains("rl4_env(0.004, 1.2, 0, 0.12, 0.7, 1, 0.2, 0.25, 1, 0.4, 0, 0, 0.75)", export.Source); } [Fact]