diff --git a/docs/dx7-calibration-plan.md b/docs/dx7-calibration-plan.md index cbed5e6..8ba1aee 100644 --- a/docs/dx7-calibration-plan.md +++ b/docs/dx7-calibration-plan.md @@ -64,6 +64,10 @@ math is still fake in the places that matter perceptually. - Current cut lesson: reusing the operator output-level amplitude curve for 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. 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 fde0d66..2c26d90 100644 --- a/src/AquariumSynth.Dsl/Dx7SysEx.cs +++ b/src/AquariumSynth.Dsl/Dx7SysEx.cs @@ -58,6 +58,8 @@ public sealed record Dx7RateLevelEnvelopeApproximation( private static string F(float value) => value.ToString("0.######", System.Globalization.CultureInfo.InvariantCulture); } +public sealed record Dx7EnvelopeTracePoint(float TimeSeconds, float Gain, int Stage); + public sealed record Dx7Operator( int Number, Dx7Envelope Envelope, @@ -263,6 +265,30 @@ public static class Dx7SysEx "Approximation: DX7 EG uses four rate/level segments; Aquarium staged envelopes preserve the intermediate target levels."); } + public static IReadOnlyList TraceEnvelope( + Dx7Envelope envelope, + float gateSeconds, + float durationSeconds, + int outputLevel = 99, + int sampleRate = 44100) + { + 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); + for (var sample = 0; sample < sampleCount; sample++) + { + if (sample == gateSample) + { + state.KeyDown(envelope, down: false); + } + state.Advance(envelope); + points.Add(new Dx7EnvelopeTracePoint(sample / (float)sampleRate, state.Gain, state.Stage)); + } + + return points; + } + public static Dx7VoiceBank ParseBank(ReadOnlySpan bytes) { var data = PackedBankData(bytes); @@ -479,6 +505,101 @@ public static class Dx7SysEx private static float Level(int value) => Math.Clamp(value, 0, 99) / 99f; + private sealed class Dx7EnvelopeState + { + private const int JumpTarget = 1716; + private readonly int _sampleRate; + private readonly int _outputLevel; + private long _level; + private long _targetLevel; + private bool _rising; + private int _increment; + private bool _down = true; + + private Dx7EnvelopeState(int outputLevel, int sampleRate) + { + _outputLevel = outputLevel; + _sampleRate = sampleRate; + } + + public int Stage { get; private set; } + + public float Gain => + MathF.Pow(2, ((_level / 65536f) - (14 << 8)) / 256f); + + public static Dx7EnvelopeState Start(Dx7Envelope envelope, int outputLevel, int sampleRate) + { + var state = new Dx7EnvelopeState(outputLevel, sampleRate); + state.AdvanceStage(envelope, 0); + return state; + } + + public void KeyDown(Dx7Envelope envelope, bool down) + { + if (_down == down) return; + _down = down; + AdvanceStage(envelope, down ? 0 : 3); + } + + public void Advance(Dx7Envelope envelope) + { + if (Stage >= 3 && !(Stage < 4 && !_down)) return; + + if (_rising) + { + if (_level < ((long)JumpTarget << 16)) + { + _level = (long)JumpTarget << 16; + } + _level += (((17L << 24) - _level) >> 24) * _increment; + if (_level >= _targetLevel) + { + _level = _targetLevel; + AdvanceStage(envelope, Stage + 1); + } + } + else + { + _level -= _increment; + if (_level <= _targetLevel) + { + _level = _targetLevel; + AdvanceStage(envelope, Stage + 1); + } + } + } + + private void AdvanceStage(Dx7Envelope envelope, int stage) + { + Stage = stage; + if (Stage >= 4) return; + + var level = Stage switch + { + 0 => envelope.Level1, + 1 => envelope.Level2, + 2 => envelope.Level3, + _ => envelope.Level4 + }; + var actual = ScaleOutLevel(level) >> 1; + actual = (actual << 6) + (ScaleOutLevel(_outputLevel) << 5) - 4256; + actual = Math.Max(16, actual); + _targetLevel = (long)actual << 16; + _rising = _targetLevel > _level; + + var rate = Stage switch + { + 0 => envelope.Rate1, + 1 => envelope.Rate2, + 2 => envelope.Rate3, + _ => envelope.Rate4 + }; + var qrate = Math.Min((Math.Clamp(rate, 0, 99) * 41) >> 6, 63); + var increment = (4 + (qrate & 3)) << (2 + 6 + (qrate >> 2)); + _increment = (int)((long)increment * 44100 / Math.Max(1, _sampleRate)); + } + } + private static float RatioModeDetuneFactor(int detune, int midiNote) { var logFrequency = MathF.Log2(440f) + (midiNote - 69) / 12f; @@ -516,6 +637,11 @@ public static class Dx7SysEx return curve < 2 ? -scale : scale; } + private static int ScaleOutLevel(int outputLevel) => + outputLevel >= 20 + ? 28 + Math.Clamp(outputLevel, 0, 99) + : LevelLookup[Math.Clamp(outputLevel, 0, 19)]; + private static float SegmentSeconds(int rate, float distance) { var normalizedRate = Math.Clamp(rate, 0, 99) / 99f; @@ -614,6 +740,11 @@ public static class Dx7SysEx 0f, 0.01f, 0.02f, 0.05f, 0.10f, 0.19f, 0.38f, 0.66f ]; + private static readonly int[] LevelLookup = + [ + 0, 5, 9, 13, 17, 20, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 42, 43, 45, 46 + ]; + private static readonly int[] ExpScaleData = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 14, 16, 19, 23, 27, 33, 39, 47, 56, 66, diff --git a/state/evidence.jsonl b/state/evidence.jsonl index d10b194..666496c 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -36,3 +36,4 @@ {"kind":"dx7_topology_aware_route_index","lesson":"The PRC hard target proved DX7 route index cannot key only on ROM edge kind: a direct edge feeding a later summed branch behaves like part of the cascaded/summed stack, not like the isolated two-op branch. `Dx7SysEx.OperatorRouteIndex(topology, edge)` now owns this distinction; PRC no longer has a private route function.","source":"DX7 summed/cascaded route lowering on 2026-05-14"} {"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"} diff --git a/state/memory.json b/state/memory.json index c3b176c..6c9bc0b 100644 --- a/state/memory.json +++ b/state/memory.json @@ -29,6 +29,7 @@ "DX7 ratio detune lowering", "DX7 ROM COM output compensation", "DX7 topology-aware route lowering", + "DX7 envelope trace helper", "staged operator envelope DSL", "DX7 envelope-to-ADSR approximation", "standard ADSR envelope model", @@ -68,9 +69,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, 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. Staged operator envelopes now let Aquarium express four-rate/four-level contours in readable DSL.", - "next": "Follow docs/dx7-calibration-plan.md: solve the DX7 envelope level/time curve with isolated project-authored parity before adding new DSL surface or tuning PRC constants." + "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." }, "note_and_envelope_model": { "rule": "Notes own frequency, gate duration, and host/MIDI source. Envelopes own ADSR level shape.", @@ -85,7 +86,7 @@ }, "last_verified": { "command": "AQUARIUM_DX7_PYTHON= dotnet test AquariumSynthCSharp.slnx --no-restore", - "result": "61 passed; project-authored summed stack and PRC passed", - "commit": "pending project-authored DX7 patch renderer" + "result": "63 passed; DX7 envelope trace artifact generated", + "commit": "pending DX7 envelope trace" } } diff --git a/state/scratch.md b/state/scratch.md index 4b5ffdf..6dbe650 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -15,6 +15,19 @@ Doctrine update: Completed this slice: +- 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 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. +- 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. + +Previous slice: + - Added test-only project-authored Dexed patch rendering through `DexedPyRenderer.RenderPatchAsync`. It builds a `dexed.Patch` from explicit operator specs and renders it without adding any shipped fixture or package diff --git a/state/spine.yaml b/state/spine.yaml index 3db8f4c..5e6274d 100644 --- a/state/spine.yaml +++ b/state/spine.yaml @@ -1,6 +1,6 @@ project: AquariumSynthCSharp spine_version: 1 -updated: 2026-05-14T05:00:00+01:00 +updated: 2026-05-14T05:18:00+01:00 prime_directive: > Build coherent synth machinery. References exist to reveal missing structure, @@ -54,6 +54,7 @@ live_invariants: - 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. - 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. - 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. @@ -69,7 +70,7 @@ reference_targets: priority: 1 purpose: "Structured FM/operator graph pressure test." source: "https://github.com/asb2m10/dexed" - status: "DX7 SysEx parser, public-domain SysEx fixture, dexed-py reference rendering, project-authored Dexed patch rendering, first thresholded rendered parity test for analog1.syx voice 13, hard PRC SYNTH1 probe with listening WAV artifacts and log-mel <= 0.255, project-authored algorithm-8 summed-stack parity, renderable delayed operator feedback, DX7 effective operator-level approximation, measured carrier output amplitude, isolated route index, feedback table, ratio detune lowering, ROM COM output compensation, staged operator envelopes, algorithm topology extraction, envelope-to-ADSR approximation, two Aquarium DSL rebuild attempts, first-class operator graph support, and Aquarium candidate rendering through Faust-generated C# exist." + status: "DX7 SysEx parser, public-domain SysEx fixture, dexed-py reference rendering, project-authored Dexed patch rendering, first thresholded rendered parity test for analog1.syx voice 13, hard PRC SYNTH1 probe with listening WAV artifacts and log-mel <= 0.255, project-authored algorithm-8 summed-stack parity, renderable delayed operator feedback, DX7 effective operator-level approximation, measured carrier output amplitude, isolated route index, feedback table, ratio detune lowering, ROM COM output compensation, staged operator envelopes, DX7 envelope tracing, algorithm topology extraction, envelope-to-ADSR approximation, two Aquarium DSL rebuild attempts, first-class operator graph support, and Aquarium candidate rendering through Faust-generated C# exist." first_slice: - "Add a harder public-domain DX7 parity target that audibly needs operator routing." zynaddsubfx: @@ -113,7 +114,8 @@ 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. + still failed PRC log-mel. Use `Dx7SysEx.TraceEnvelope` and the + `dx7-envelope-trace` artifact to design the next envelope model. must_read: - AGENTS.md - docs/audio-doctrine.md @@ -126,6 +128,14 @@ next_agent_start_here: - "dotnet test AquariumSynthCSharp.slnx --no-restore" completed_slices: + - date: 2026-05-14 + summary: > + Added `Dx7SysEx.TraceEnvelope` and an envelope trace comparison artifact. + The trace shows DX7 EG behavior that current `env=rl` cannot express: + an initial gain spike above 1 followed by millisecond-scale collapse to a + tiny sustain. A first `env=dx7` runtime lowering attempt was cut because + matching the local trace did not match Dexed plugin audio. + verification: "dotnet test AquariumSynthCSharp.slnx --no-restore --filter \"ProjectAuthoredDx7EnvelopeTraceWritesComparisonArtifact|TracesDx7EnvelopeInternalGainShape\": passed" - date: 2026-05-14 summary: > Added test-only project-authored Dexed patch rendering and an independent diff --git a/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs b/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs index fcc647c..380d42a 100644 --- a/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs @@ -181,6 +181,43 @@ public sealed class Dx7ReferenceParityTests Assert.True(comparison.Score >= 0.35f, ParityReport(comparison)); } + [Fact] + public void ProjectAuthoredDx7EnvelopeTraceWritesComparisonArtifact() + { + var envelope = new Dx7Envelope( + Rate1: 98, + Rate2: 64, + Rate3: 48, + Rate4: 55, + Level1: 99, + Level2: 76, + Level3: 43, + Level4: 0); + var dx7 = Dx7SysEx.TraceEnvelope(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 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"); + 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(aquarium[i]), + dx7[i].Stage.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + + var shape = NormalizedDistance( + dx7.Select(point => point.Gain).ToArray(), + aquarium); + Assert.True(shape > 0.75f, $"expected current Aquarium envelope to visibly differ; shape distance {shape}, artifact: {path}"); + } + private static string FixturePath(params string[] parts) => Path.Combine([AppContext.BaseDirectory, "Fixtures", .. parts]); @@ -219,7 +256,6 @@ public sealed class Dx7ReferenceParityTests { var level = Dx7SysEx.ApproximateOperatorLevel(op).LinearLevel * Dx7SysEx.OperatorOutputCompensation(topology, op.Number); - var envelope = ScaledEnvelope(Dx7SysEx.ApproximateRateLevelEnvelope(op.Envelope), envelopeScale, gateSeconds); builder.AppendLine($"operator name=op{op.Number}"); builder.AppendLine($" ratio={F(Dx7SysEx.OperatorFrequencyRatio(op))}"); builder.AppendLine($" level={F(level)}"); @@ -227,7 +263,7 @@ public sealed class Dx7ReferenceParityTests { builder.AppendLine($" feedback={F(Dx7SysEx.OperatorFeedbackAmount(voice.Feedback))}"); } - builder.AppendLine($" {envelope.ToScriptSpec()}"); + builder.AppendLine($" {ScaledEnvelope(Dx7SysEx.ApproximateRateLevelEnvelope(op.Envelope), envelopeScale, gateSeconds).ToScriptSpec()}"); builder.AppendLine(); } @@ -308,6 +344,64 @@ public sealed class Dx7ReferenceParityTests }; } + private static float[] TraceRateLevelEnvelope(RateLevelEnvelope envelope, float gateSeconds, float durationSeconds, int sampleRate = 44100) + { + var count = Math.Max(1, (int)MathF.Round(durationSeconds * sampleRate)); + var values = new float[count]; + for (var sample = 0; sample < values.Length; sample++) + { + 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) + : age < envelope.Rate1Seconds + envelope.Rate2Seconds + ? Segment(age, envelope.Rate1Seconds, envelope.Rate2Seconds, envelope.Level1, envelope.Level2) + : age < envelope.Rate1Seconds + envelope.Rate2Seconds + envelope.Rate3Seconds + ? Segment(age, envelope.Rate1Seconds + envelope.Rate2Seconds, envelope.Rate3Seconds, envelope.Level2, envelope.Level3) + : age < releaseStart + ? envelope.Level3 + : age < releaseStart + envelope.Rate4Seconds + ? Segment(age, releaseStart, envelope.Rate4Seconds, envelope.Level3, envelope.Level4) + : envelope.Level4; + } + + return values; + } + + private static float Segment(float time, float start, float duration, float from, float to) + { + var t = Math.Clamp((time - start) / Math.Max(0.0001f, duration), 0, 1); + return from + (to - from) * t; + } + + private static float NormalizedDistance(IReadOnlyList reference, IReadOnlyList candidate) + { + var length = Math.Max(1, Math.Max(reference.Count, candidate.Count)); + var error = 0f; + var scale = 0f; + for (var i = 0; i < length; i++) + { + var a = ResampledAt(reference, i, length); + var b = ResampledAt(candidate, i, length); + var delta = a - b; + error += delta * delta; + scale += a * a + b * b; + } + + return MathF.Sqrt(error / Math.Max(float.Epsilon, scale)); + } + + private static float ResampledAt(IReadOnlyList values, int index, int targetLength) + { + if (values.Count == 0) return 0; + if (values.Count == 1 || targetLength <= 1) return values[0]; + var position = index * (values.Count - 1f) / (targetLength - 1); + var left = (int)MathF.Floor(position); + var right = Math.Min(left + 1, values.Count - 1); + var t = position - left; + return values[left] * (1 - t) + values[right] * t; + } + private static void WriteListeningArtifacts( string directory, IReadOnlyList reference, diff --git a/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs b/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs index af6844c..76a16c8 100644 --- a/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/Dx7SysExTests.cs @@ -292,6 +292,30 @@ public sealed class Dx7SysExTests Assert.Contains("intermediate target levels", approximation.Notes); } + [Fact] + public void TracesDx7EnvelopeInternalGainShape() + { + var trace = Dx7SysEx.TraceEnvelope( + 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.True(trace[0].Gain > 1.9f); + Assert.InRange(trace[(int)(0.005f * 44100)].Gain, 0.05f, 0.08f); + Assert.InRange(trace[(int)(0.02f * 44100)].Gain, 0.014f, 0.017f); + Assert.Equal(3, trace[(int)(0.2f * 44100)].Stage); + Assert.Equal(4, trace[(int)(0.76f * 44100)].Stage); + Assert.True(trace[(int)(0.9f * 44100)].Gain < 0.001f); + } + private static byte[] InitVoice(string name, int algorithm, int feedback) { var data = new byte[Dx7SysEx.VoiceEditBufferLength];