diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 55a9c5a..ffbd6f9 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -66,3 +66,4 @@ {"kind":"pad_spectral_cloud","lesson":"PAD-style layers now have `spectrum layer=... root=... spread=... partials=ratio:gain,...`, recorded as `SpectralBank` and generated as PADsynth-style FFT tables: frequency-domain harmonic spreading, deterministic random phase, one inverse FFT, normalization, then Faust waveform/rdtable playback before ordinary voice treatment. This gives PAD texture rebuilds a real spectral source authority without inflating the voice graph; roots/spreads/partials are authoring-time table shape, not runtime controls. It still does not claim full Zyn PAD harmonic-profile/randomness/pitch-zone behavior.","source":"Zyn PAD spectral-cloud DSL slice on 2026-05-14"} {"kind":"zyn_reference_oracle","lesson":"ZynAddSubFX source is pinned as GPL test/development material under `external/zynaddsubfx` at 3ab608c432996ba4d582176572c0b0f82328c825. Treat it like dexed-py: a parity oracle for tests and artifacts, not Aquarium implementation, runtime dependency, or NuGet package content. Before further Zyn DSL golf, build a test-only PAD renderer/wrapper from this source and compare Aquarium rebuilds against actual Zyn behavior.","source":"Zyn source pinning for parity on 2026-05-14"} {"date":"2026-05-14","area":"zyn-reference","lesson":"Pinned Zyn can build on Windows through MSYS2/MinGW when GUI/plugins are disabled, tests are enabled, Werror is off, and the stale non-async MiddleWare Part constructor call is patched. Apply Zyn compatibility patches to ignored artifact source copies, not the clean pinned submodule.","evidence":"tools/zyn-reference/build-zyn-reference.ps1 copies external/zynaddsubfx to artifacts/zyn-source-msys, applies tools/zyn-reference/patches/0001-msys-part-constructor.patch, builds PadNoteTest, and ctest -R PadNoteTest passes."} +{"date":"2026-05-15","area":"zyn-pad-parity","lesson":"The Zyn PAD oracle now emits real reference material through Zyn PADnoteParameters/PADnote, and the first project-authored PAD comparison is not close: log-mel 0.552296, envelope 0.774501, RMS ratio 0.234763, centroid ratio 1.025735, score 0.236117. Treat this as evidence to isolate source table generation, playback/gain, envelope, and fixture mapping before adding more Zyn DSL syntax.","evidence":"tools/zyn-reference/ZynPadReference.cpp plus tests/AquariumSynth.Dsl.Tests/ZynReferenceParityTests.cs write artifacts/parity/zyn-pad-reference/pad-texture-zyn.wav, pad-texture-aqua.wav, and report.txt when the Zyn artifact renderer is built."} diff --git a/state/map.yaml b/state/map.yaml index 09a3fec..2b5e5af 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -18,7 +18,8 @@ surfaces: dx7_public_domain_fixtures: tests/AquariumSynth.Dsl.Tests/Fixtures/Dx7/PublicDomain zyn_reference_source: external/zynaddsubfx zyn_reference_build_script: tools/zyn-reference/build-zyn-reference.ps1 - zyn_reference_build_patch: tools/zyn-reference/patches/0001-msys-part-constructor.patch + zyn_pad_reference_renderer: tools/zyn-reference/ZynPadReference.cpp + zyn_reference_build_patches: tools/zyn-reference/patches zyn_project_fixtures: tests/AquariumSynth.Dsl.Tests/Fixtures/ZynAddSubFX/ProjectAuthored package: AquariumSynth.Dsl 0.1.0-aquarium.1 modules: diff --git a/state/memory.json b/state/memory.json index 00f871e..e2e6bd0 100644 --- a/state/memory.json +++ b/state/memory.json @@ -84,9 +84,9 @@ "next": "Use the now-validated algorithm-8 route scale, transpose lowering, and fixed-frequency lowering as fixed inputs while isolating remaining community-voice timbre mismatch, then expand to broader public-domain banks." }, "zyn_reference_path": { - "status": "Initial ZynInstrumentReader parses plain XML and gzip-compressed .xiz-shaped XML from project-authored fixtures into ZynInstrument records and ReferencePatch features. First Zyn-style Aquarium rebuilds exist for additive lead, PAD texture, and vocal/formant layer. `ZynInstrumentSurvey` can rank .xiz directories by feature pressure. Named `layer` declarations provide the first Zyn-driven DSL abstraction; additive `harmonics`, PAD `spectrum`, and staged `env=rl` voice envelopes now attach to those layers. The pinned Zyn source now builds as a test-only MSYS2/MinGW oracle through `tools/zyn-reference/build-zyn-reference.ps1`, which patches an ignored artifact source copy and proves `PadNoteTest`.", - "lesson": "Start Zyn as structural classification, not translation. Upstream Zyn presets live in a separate bank submodule and should not be vendored until license/provenance is explicit. The ZynAddSubFX engine source is pinned as GPL test/development material under `external/zynaddsubfx` at 3ab608c432996ba4d582176572c0b0f82328c825; use it as a parity oracle only, never as Aquarium runtime or NuGet package content. Zyn build fixes belong in `tools/zyn-reference/patches/` and apply to ignored artifact copies, not the clean pinned submodule. The hardened reader parses the observed upstream instrument bank at commit e9f64a9: 1358/1358 .xiz files. The worst target is `olivers-100/0032-Drum Kit.xiz`, with 16 enabled kit items, mixed ADD/SUB/PAD engines, 106 envelopes, 25 free envelopes, 73 LFOs, 37 filters, and 3 formant filters. The first rebuilds show Aquarium can sketch small Zyn fixtures with existing voices/macros/formants/noise, and the upstream survey correctly pushed named kit/layer routing first. `layer` owns name, engine tag, optional key range metadata, default gain, and effect-send labels while lowering to ordinary voices. `harmonics` owns authored ratio/gain partial banks under those layers. `spectrum` owns PAD-style root/spread/partial clouds under those layers and generates PADsynth-style FFT wavetables with frequency-domain spreading, deterministic random phase, and one inverse FFT before ordinary voice treatment. Staged `env=rl` now applies to voices as well as operators, preserving Note as gate authority and envelope data as level-shape authority. Aquarium still does not claim Zyn ADDsynth phase/bandwidth details, full Zyn PAD harmonic-profile/randomness/pitch-zone behavior, arbitrary free-envelope point curves, or richer formant morphing.", - "next": "Implement a test-only Zyn PAD renderer/wrapper on top of the proven build, emit reference audio or tables, then compare Aquarium `spectrum` output before further Zyn DSL golf." + "status": "Initial ZynInstrumentReader parses plain XML and gzip-compressed .xiz-shaped XML from project-authored fixtures into ZynInstrument records and ReferencePatch features. First Zyn-style Aquarium rebuilds exist for additive lead, PAD texture, and vocal/formant layer. `ZynInstrumentSurvey` can rank .xiz directories by feature pressure. Named `layer` declarations provide the first Zyn-driven DSL abstraction; additive `harmonics`, PAD `spectrum`, and staged `env=rl` voice envelopes now attach to those layers. The pinned Zyn source now builds as a test-only MSYS2/MinGW oracle through `tools/zyn-reference/build-zyn-reference.ps1`, which patches an ignored artifact source copy, proves `PadNoteTest`, and builds `ZynPadReference`.", + "lesson": "Start Zyn as structural classification, not translation. Upstream Zyn presets live in a separate bank submodule and should not be vendored until license/provenance is explicit. The ZynAddSubFX engine source is pinned as GPL test/development material under `external/zynaddsubfx` at 3ab608c432996ba4d582176572c0b0f82328c825; use it as a parity oracle only, never as Aquarium runtime or NuGet package content. Zyn build fixes belong in `tools/zyn-reference/patches/` and apply to ignored artifact copies, not the clean pinned submodule. The PAD oracle now renders both generated PAD sample tables and note audio through Zyn `PADnoteParameters`/`PADnote`; optional parity artifacts live under `artifacts/parity/zyn-pad-reference`. The first project-authored PAD comparison is intentionally not a passing gate: Zyn vs Aquarium currently reports log-mel 0.552296, envelope 0.774501, RMS ratio 0.234763, centroid ratio 1.025735, score 0.236117. That proves the harness and shows Aquarium `spectrum` is not yet a close Zyn PAD emulation. The hardened reader parses the observed upstream instrument bank at commit e9f64a9: 1358/1358 .xiz files. The worst target is `olivers-100/0032-Drum Kit.xiz`, with 16 enabled kit items, mixed ADD/SUB/PAD engines, 106 envelopes, 25 free envelopes, 73 LFOs, 37 filters, and 3 formant filters. The first rebuilds show Aquarium can sketch small Zyn fixtures with existing voices/macros/formants/noise, and the upstream survey correctly pushed named kit/layer routing first. `layer` owns name, engine tag, optional key range metadata, default gain, and effect-send labels while lowering to ordinary voices. `harmonics` owns authored ratio/gain partial banks under those layers. `spectrum` owns PAD-style root/spread/partial clouds under those layers and generates PADsynth-style FFT wavetables with frequency-domain spreading, deterministic random phase, and one inverse FFT before ordinary voice treatment. Staged `env=rl` now applies to voices as well as operators, preserving Note as gate authority and envelope data as level-shape authority. Aquarium still does not claim Zyn ADDsynth phase/bandwidth details, full Zyn PAD harmonic-profile/randomness/pitch-zone behavior, arbitrary free-envelope point curves, or richer formant morphing.", + "next": "Use the Zyn PAD oracle report to isolate whether the main mismatch is source table generation, note playback/gain, envelope shape, or fixture mapping before adding more Zyn DSL surface." }, "note_and_envelope_model": { "rule": "Notes own frequency, gate duration, and host/MIDI source. Envelopes own ADSR level shape.", @@ -101,7 +101,7 @@ }, "last_verified": { "command": "powershell -NoProfile -ExecutionPolicy Bypass -File tools\\zyn-reference\\build-zyn-reference.ps1; dotnet test AquariumSynthCSharp.slnx --no-restore", - "result": "Zyn source copied to ignored artifact tree, patched, built with MSYS2/MinGW, PadNoteTest passed; C# suite 95 passed and package boundary remains clean", - "commit": "pending Zyn oracle build script" + "result": "Zyn source copied to ignored artifact tree, patched, built with MSYS2/MinGW, PadNoteTest passed, ZynPadReference built; C# suite 96 passed and package boundary remains clean", + "commit": "pending Zyn PAD renderer" } } diff --git a/state/spine.yaml b/state/spine.yaml index b5d8f86..9a19880 100644 --- a/state/spine.yaml +++ b/state/spine.yaml @@ -1,6 +1,6 @@ project: AquariumSynthCSharp spine_version: 1 -updated: 2026-05-14T21:45:00+01:00 +updated: 2026-05-15T00:35:00+01:00 prime_directive: > Build coherent synth machinery. References exist to reveal missing structure, @@ -25,6 +25,7 @@ current_mechanism: dx7_reference_renderer_tests: tests/AquariumSynth.Dsl.Tests/Dx7ReferenceParityTests.cs zyn_reference_source: external/zynaddsubfx zyn_reference_build_script: tools/zyn-reference/build-zyn-reference.ps1 + zyn_pad_reference_renderer: tools/zyn-reference/ZynPadReference.cpp zyn_reference_reader: src/AquariumSynth.Dsl/ZynInstrument.cs zyn_project_fixtures: tests/AquariumSynth.Dsl.Tests/Fixtures/ZynAddSubFX/ProjectAuthored reference_rebuilds: src/AquariumSynth.Dsl/ReferenceRebuilds.cs @@ -100,9 +101,9 @@ reference_targets: priority: 2 purpose: "Additive, subtractive, PAD, formant, kit, and layered-instrument pressure test." source: "https://github.com/zynaddsubfx/zynaddsubfx" - status: "Initial ZynInstrumentReader reads plain or gzip-compressed .xiz XML from project-authored fixtures and classifies active ADD/SUB/PAD engines, enabled kit items, layering, envelopes, free envelopes, LFOs, filters, formants, and effects as ReferencePatch features. First Aquarium rebuilds exist for additive lead, PAD texture, and vocal/formant layer and now use named `layer` declarations. Additive rebuilds can use `harmonics` banks attached to layers, PAD rebuilds can use `spectrum` PADsynth-style FFT wavetable banks attached to layers, and PAD/vocal rebuilds use staged voice `env=rl` envelopes through layer defaults. ZynAddSubFX source is pinned under `external/zynaddsubfx` at 3ab608c432996ba4d582176572c0b0f82328c825 for test-only parity work, and `tools/zyn-reference/build-zyn-reference.ps1` now builds an ignored patched source copy with MSYS2/MinGW and proves `PadNoteTest`. A non-vendored upstream bank survey parsed 1358/1358 .xiz files and identified named kit/layer routing as the first owner abstraction." + status: "Initial ZynInstrumentReader reads plain or gzip-compressed .xiz XML from project-authored fixtures and classifies active ADD/SUB/PAD engines, enabled kit items, layering, envelopes, free envelopes, LFOs, filters, formants, and effects as ReferencePatch features. First Aquarium rebuilds exist for additive lead, PAD texture, and vocal/formant layer and now use named `layer` declarations. Additive rebuilds can use `harmonics` banks attached to layers, PAD rebuilds can use `spectrum` PADsynth-style FFT wavetable banks attached to layers, and PAD/vocal rebuilds use staged voice `env=rl` envelopes through layer defaults. ZynAddSubFX source is pinned under `external/zynaddsubfx` at 3ab608c432996ba4d582176572c0b0f82328c825 for test-only parity work, and `tools/zyn-reference/build-zyn-reference.ps1` now builds an ignored patched source copy with MSYS2/MinGW, proves `PadNoteTest`, and builds `ZynPadReference`. The first optional PAD report against the project-authored fixture emits WAV/listening artifacts and scores poorly but usefully: log-mel 0.552296, envelope 0.774501, score 0.236117. A non-vendored upstream bank survey parsed 1358/1358 .xiz files and identified named kit/layer routing as the first owner abstraction." first_slice: - - "Implement a test-only Zyn PAD renderer/wrapper on top of the proven source build before further Zyn DSL golf." + - "Use the Zyn PAD oracle report to isolate source-table, playback/gain, envelope, and fixture-mapping mismatch before further Zyn DSL golf." - "Use named layers as the owner before promoting richer formant morphing syntax." - "Additive harmonic banks, PAD spectral clouds, and staged voice envelopes now exist; prove any next syntax across more than one target with parity, not parser-only fixtures." - "Do not add all remaining pressures at once." @@ -140,9 +141,12 @@ next_agent_start_here: PADsynth-style FFT wavetable sources, and staged `env=rl` envelopes now work on normal voices/layer defaults. The pinned Zyn source now builds through `tools/zyn-reference/build-zyn-reference.ps1` using an ignored - patched artifact copy. Next pressure is a test-only PAD renderer/wrapper - that emits reference audio or tables for Aquarium `spectrum` parity, then - richer formant/vowel morphing can resume. + patched artifact copy and builds `ZynPadReference`, which emits PAD table + samples or note audio from Zyn. The first optional project-authored PAD + comparison writes WAV/report artifacts under `artifacts/parity/zyn-pad-reference` + and is not close yet: log-mel 0.552296, envelope 0.774501, score 0.236117. + Next pressure is isolating whether the mismatch lives in source-table + generation, note playback/gain, envelope shape, or fixture mapping. must_read: - AGENTS.md - docs/audio-doctrine.md @@ -155,6 +159,20 @@ next_agent_start_here: - "dotnet test AquariumSynthCSharp.slnx --no-restore" completed_slices: + - date: 2026-05-15 + summary: > + Added `ZynPadReference`, a test-only executable copied into the ignored + Zyn artifact source and built by `build-zyn-reference.ps1`. It loads a + `.xiz`, enters a chosen kit item's `PAD_SYNTH_PARAMETERS`, uses Zyn's own + `PADnoteParameters`/`PADnote` path, and writes either generated PAD table + samples or rendered note audio as raw float32. Added an optional C# parity + harness that runs the renderer when the artifact executable exists and + writes Zyn/Aquarium WAVs plus a report under + `artifacts/parity/zyn-pad-reference`. First report: log-mel 0.552296, + envelope 0.774501, RMS ratio 0.234763, centroid ratio 1.025735, score + 0.236117, so the harness works and current Aquarium `spectrum` is not yet + a close PAD emulation. + verification: "powershell -NoProfile -ExecutionPolicy Bypass -File tools\\zyn-reference\\build-zyn-reference.ps1; dotnet test AquariumSynthCSharp.slnx --no-restore: 96 passed" - date: 2026-05-14 summary: > Built the pinned ZynAddSubFX source as a test-only MSYS2/MinGW parity diff --git a/tests/AquariumSynth.Dsl.Tests/ZynReferenceParityTests.cs b/tests/AquariumSynth.Dsl.Tests/ZynReferenceParityTests.cs index b5b174f..e26963b 100644 --- a/tests/AquariumSynth.Dsl.Tests/ZynReferenceParityTests.cs +++ b/tests/AquariumSynth.Dsl.Tests/ZynReferenceParityTests.cs @@ -21,6 +21,77 @@ public sealed class ZynReferenceParityTests Assert.Equal("3ab608c432996ba4d582176572c0b0f82328c825", revision.Stdout.Trim()); } + [Fact] + public async Task ZynPadReferenceRendererWritesListeningArtifactsWhenBuilt() + { + var root = RepositoryRoot(); + var bash = @"C:\msys64\usr\bin\bash.exe"; + var renderer = Path.Combine(root, "artifacts", "zyn-reference-build-msys", "src", "Tests", "ZynPadReference.exe"); + if (!File.Exists(bash) || !File.Exists(renderer)) + { + return; + } + + var artifactDir = Path.Combine(root, "artifacts", "parity", "zyn-pad-reference"); + Directory.CreateDirectory(artifactDir); + + var input = Path.Combine(root, "tests", "AquariumSynth.Dsl.Tests", "Fixtures", "ZynAddSubFX", "ProjectAuthored", "pad-texture.xiz"); + var zynRaw = Path.Combine(artifactDir, "pad-texture-zyn.f32"); + var zynWav = Path.Combine(artifactDir, "pad-texture-zyn.wav"); + var aquaWav = Path.Combine(artifactDir, "pad-texture-aqua.wav"); + var reportPath = Path.Combine(artifactDir, "report.txt"); + + var command = string.Join(' ', [ + "export PATH=/mingw64/bin:/usr/bin:/bin:$PATH;", + $"cd {BashQuote(ToMsysPath(root))};", + "./artifacts/zyn-reference-build-msys/src/Tests/ZynPadReference.exe", + BashQuote(ToMsysPath(input)), + BashQuote(ToMsysPath(zynRaw)), + "0", + "note", + "261.6256", + "1.5" + ]); + var reference = await RunAsync(bash, ["-lc", command]); + Assert.Equal(0, reference.ExitCode); + + var zynSamples = await ReadFloat32Async(zynRaw); + Assert.Equal(66150, zynSamples.Length); + Assert.True(Peak(zynSamples) > 0.001f); + WriteWav(zynWav, zynSamples, 44100, 0.9f); + + var report = new List + { + "Zyn PAD reference renderer", + $"renderer: {renderer}", + $"input: {input}", + $"stdout: {reference.Stdout.Trim()}", + $"zyn_samples: {zynSamples.Length}", + $"zyn_peak: {Peak(zynSamples):0.######}", + $"zyn_rms: {Rms(zynSamples):0.######}" + }; + + var aquaExport = FaustEmitter.EmitScript(BuiltInScripts.ZynStylePadTexture, new FaustExportOptions("zyn_pad_texture")); + var aquaRender = await FaustCompiler.RenderAsync(aquaExport.Source, new FaustRenderOptions(DurationSeconds: 1.5f)); + if (aquaRender is { Samples.Length: > 0 }) + { + WriteWav(aquaWav, aquaRender.Samples, aquaRender.SampleRate, 0.9f); + var comparison = AudioAnalyzer.CompareAudio(zynSamples, aquaRender.Samples); + report.Add($"aqua_samples: {aquaRender.Samples.Length}"); + report.Add($"log_mel_distance: {comparison.LogMelDistance:0.######}"); + report.Add($"envelope_distance: {comparison.EnvelopeDistance:0.######}"); + report.Add($"rms_ratio: {comparison.RmsRatio:0.######}"); + report.Add($"centroid_ratio: {comparison.CentroidRatio:0.######}"); + report.Add($"score: {comparison.Score:0.######}"); + } + else + { + report.Add("aqua_render: skipped; Faust renderer unavailable or failed"); + } + + await File.WriteAllLinesAsync(reportPath, report); + } + private static string RepositoryRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory); @@ -50,4 +121,60 @@ public sealed class ZynReferenceParityTests await process.WaitForExitAsync(); return (process.ExitCode, await stdout, await stderr); } + + private static string ToMsysPath(string path) + { + var full = Path.GetFullPath(path); + if (full.Length < 3 || full[1] != ':' || full[2] != Path.DirectorySeparatorChar) + { + throw new ArgumentException($"cannot convert path to MSYS form: {path}", nameof(path)); + } + + return "/" + char.ToLowerInvariant(full[0]) + full[2..].Replace('\\', '/'); + } + + private static string BashQuote(string value) => "'" + value.Replace("'", "'\\''") + "'"; + + private static async Task ReadFloat32Async(string path) + { + var bytes = await File.ReadAllBytesAsync(path); + var samples = new float[bytes.Length / sizeof(float)]; + Buffer.BlockCopy(bytes, 0, samples, 0, samples.Length * sizeof(float)); + return samples; + } + + private static float Peak(IReadOnlyList samples) => + samples.Select(Math.Abs).DefaultIfEmpty(0).Max(); + + private static float Rms(IReadOnlyList samples) + { + if (samples.Count == 0) return 0; + var sum = 0.0; + foreach (var sample in samples) sum += sample * sample; + return (float)Math.Sqrt(sum / samples.Count); + } + + private static void WriteWav(string path, IReadOnlyList samples, int sampleRate, float scale) + { + using var stream = File.Create(path); + using var writer = new BinaryWriter(stream); + var dataBytes = samples.Count * sizeof(short); + writer.Write("RIFF"u8); + writer.Write(36 + dataBytes); + writer.Write("WAVE"u8); + writer.Write("fmt "u8); + writer.Write(16); + writer.Write((short)1); + writer.Write((short)1); + writer.Write(sampleRate); + writer.Write(sampleRate * sizeof(short)); + writer.Write((short)sizeof(short)); + writer.Write((short)16); + writer.Write("data"u8); + writer.Write(dataBytes); + foreach (var sample in samples) + { + writer.Write((short)Math.Clamp(sample * scale * short.MaxValue, short.MinValue, short.MaxValue)); + } + } } diff --git a/tools/zyn-reference/ZynPadReference.cpp b/tools/zyn-reference/ZynPadReference.cpp new file mode 100644 index 0000000..344c4a7 --- /dev/null +++ b/tools/zyn-reference/ZynPadReference.cpp @@ -0,0 +1,186 @@ +/* + Test-only AquariumSynthCSharp ZynAddSubFX PAD oracle. + + This file links against the pinned ZynAddSubFX reference source in an ignored + artifact build. It is development/parity tooling, not Aquarium runtime code. +*/ + +#include "../globals.h" +#include "../DSP/FFTwrapper.h" +#include "../Misc/Allocator.h" +#include "../Misc/Time.h" +#include "../Misc/Util.h" +#include "../Misc/XMLwrapper.h" +#include "../Params/Controller.h" +#include "../Params/PADnoteParameters.h" +#include "../Synth/PADnote.h" +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace zyn; + +namespace { + +bool enterInstrument(XMLwrapper& xml) +{ + if(xml.enterbranch("INSTRUMENT")) + return true; + + if(xml.enterbranch("MASTER")) { + if(xml.enterbranch("PART", 0) && xml.enterbranch("INSTRUMENT")) + return true; + } + + return false; +} + +int parseInt(const char* text, const char* name) +{ + char* end = nullptr; + const long value = std::strtol(text, &end, 10); + if(end == text || *end != '\0') { + std::cerr << "Invalid " << name << ": " << text << "\n"; + std::exit(2); + } + + return static_cast(value); +} + +void writeFloat32(const std::string& path, const float* samples, int count) +{ + std::ofstream output(path, std::ios::binary); + if(!output) { + std::cerr << "Could not open output file: " << path << "\n"; + std::exit(2); + } + + output.write(reinterpret_cast(samples), sizeof(float) * count); + if(!output) { + std::cerr << "Could not write output file: " << path << "\n"; + std::exit(2); + } +} + +void renderNote( + const PADnoteParameters& parameters, + const SYNTH_T& synth, + const AbsTime& time, + const std::string& path, + float frequency, + float seconds) +{ + Alloc memory; + Controller controller(synth, &time); + const float log2Frequency = std::log2(frequency); + SynthParams synthParams{memory, controller, synth, time, 120, nullptr, log2Frequency, false, prng()}; + PADnote note(¶meters, synthParams, 0, nullptr, nullptr, false); + + const int total = std::max(1, static_cast(seconds * synth.samplerate)); + std::vector rendered(total); + std::vector left(synth.buffersize); + std::vector right(synth.buffersize); + int written = 0; + while(written < total) { + std::fill(left.begin(), left.end(), 0.0f); + std::fill(right.begin(), right.end(), 0.0f); + note.noteout(left.data(), right.data()); + const int count = std::min(synth.buffersize, total - written); + std::copy(left.begin(), left.begin() + count, rendered.begin() + written); + written += count; + } + + writeFloat32(path, rendered.data(), static_cast(rendered.size())); +} + +} + +int main(int argc, char** argv) +{ + if(argc < 3 || argc > 7) { + std::cerr << "Usage: ZynPadReference [kit-index] [sample-index|note] [frequency-hz] [seconds]\n"; + return 2; + } + + const std::string inputPath = argv[1]; + const std::string outputPath = argv[2]; + const int kitIndex = argc >= 4 ? parseInt(argv[3], "kit index") : 0; + const bool renderAudio = argc >= 5 && std::string(argv[4]) == "note"; + const int requestedSample = argc >= 5 && !renderAudio ? parseInt(argv[4], "sample index") : 0; + const float frequency = argc >= 6 ? std::strtof(argv[5], nullptr) : 261.6256f; + const float seconds = argc >= 7 ? std::strtof(argv[6], nullptr) : 1.5f; + + SYNTH_T synth; + synth.samplerate = 44100; + synth.buffersize = 256; + synth.oscilsize = 1024; + synth.alias(false); + + AbsTime time(synth); + FFTwrapper fft(synth.oscilsize); + PADnoteParameters parameters(synth, &fft, &time); + + XMLwrapper xml; + if(xml.loadXMLfile(inputPath) != 0) { + std::cerr << "Could not load Zyn instrument: " << inputPath << "\n"; + return 2; + } + + if(!enterInstrument(xml) || + !xml.enterbranch("INSTRUMENT_KIT") || + !xml.enterbranch("INSTRUMENT_KIT_ITEM", kitIndex) || + !xml.enterbranch("PAD_SYNTH_PARAMETERS")) { + std::cerr << "Could not find PAD_SYNTH_PARAMETERS for kit item " << kitIndex + << " in " << inputPath << "\n"; + return 2; + } + + parameters.getfromXML(xml); + parameters.applyparameters([] { return false; }, 1); + + if(renderAudio) { + renderNote(parameters, synth, time, outputPath, frequency, seconds); + std::cout << "mode=note samples=" << static_cast(seconds * synth.samplerate) + << " frequency=" << frequency << "\n"; + FFT_cleanup(); + return 0; + } + + int sampleIndex = requestedSample; + if(sampleIndex < 0 || sampleIndex >= PAD_MAX_SAMPLES || parameters.sample[sampleIndex].smp == nullptr) { + sampleIndex = -1; + for(int i = 0; i < PAD_MAX_SAMPLES; ++i) { + if(parameters.sample[i].smp != nullptr) { + sampleIndex = i; + break; + } + } + } + + if(sampleIndex < 0) { + std::cerr << "Zyn generated no PAD samples for " << inputPath << "\n"; + return 2; + } + + const auto& sample = parameters.sample[sampleIndex]; + writeFloat32(outputPath, sample.smp, sample.size); + + const int preview = std::min(sample.size, 8); + std::cout << "sampleIndex=" << sampleIndex + << " size=" << sample.size + << " basefreq=" << sample.basefreq + << " preview="; + for(int i = 0; i < preview; ++i) { + if(i) std::cout << ","; + std::cout << sample.smp[i]; + } + std::cout << "\n"; + + FFT_cleanup(); + return 0; +} diff --git a/tools/zyn-reference/build-zyn-reference.ps1 b/tools/zyn-reference/build-zyn-reference.ps1 index 4272b99..bd0e909 100644 --- a/tools/zyn-reference/build-zyn-reference.ps1 +++ b/tools/zyn-reference/build-zyn-reference.ps1 @@ -35,7 +35,8 @@ function Invoke-GitProbe([string[]]$Arguments) { $repoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..")) $zynRoot = Join-Path $repoRoot "external\zynaddsubfx" $workSource = [System.IO.Path]::GetFullPath((Join-Path $repoRoot $SourceDir)) -$patchPath = Join-Path $PSScriptRoot "patches\0001-msys-part-constructor.patch" +$patchRoot = Join-Path $PSScriptRoot "patches" +$referenceSource = Join-Path $PSScriptRoot "ZynPadReference.cpp" $bash = Join-Path $MsysRoot "usr\bin\bash.exe" if (-not (Test-Path $bash)) { @@ -61,19 +62,23 @@ if ($LASTEXITCODE -gt 7) { throw "Failed to copy Zyn source to $workSource" } -$applyCheck = Invoke-GitProbe @("-C", $workSource, "apply", "--check", $patchPath) -if ($applyCheck -eq 0) { - & git -C $workSource apply $patchPath - if ($LASTEXITCODE -ne 0) { throw "Failed to apply Zyn build patch." } - Write-Host "Applied Zyn build patch to artifact source." -} -else { - $reverseCheck = Invoke-GitProbe @("-C", $workSource, "apply", "--reverse", "--check", $patchPath) - if ($reverseCheck -eq 0) { - Write-Host "Zyn artifact source already has build patch." +Copy-Item -LiteralPath $referenceSource -Destination (Join-Path $workSource "src\Tests\ZynPadReference.cpp") -Force + +foreach ($patchPath in Get-ChildItem -LiteralPath $patchRoot -Filter "*.patch" | Sort-Object Name | Select-Object -ExpandProperty FullName) { + $applyCheck = Invoke-GitProbe @("-C", $workSource, "apply", "--check", $patchPath) + if ($applyCheck -eq 0) { + & git -C $workSource apply $patchPath + if ($LASTEXITCODE -ne 0) { throw "Failed to apply Zyn build patch: $patchPath" } + Write-Host "Applied Zyn build patch to artifact source: $(Split-Path $patchPath -Leaf)" } else { - throw "Zyn build patch cannot be applied cleanly to $workSource and is not already applied." + $reverseCheck = Invoke-GitProbe @("-C", $workSource, "apply", "--reverse", "--check", $patchPath) + if ($reverseCheck -eq 0) { + Write-Host "Zyn artifact source already has build patch: $(Split-Path $patchPath -Leaf)" + } + else { + throw "Zyn build patch cannot be applied cleanly to $workSource and is not already applied: $patchPath" + } } } @@ -92,6 +97,7 @@ cmake -S "$sourceUnix" -B "$buildUnix" -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DWerror=OFF cmake --build "$buildUnix" --target PadNoteTest -j 4 +cmake --build "$buildUnix" --target ZynPadReference -j 4 ctest --test-dir "$buildUnix" -R PadNoteTest --output-on-failure "@ diff --git a/tools/zyn-reference/patches/0002-add-zyn-pad-reference-tool.patch b/tools/zyn-reference/patches/0002-add-zyn-pad-reference-tool.patch new file mode 100644 index 0000000..07cf823 --- /dev/null +++ b/tools/zyn-reference/patches/0002-add-zyn-pad-reference-tool.patch @@ -0,0 +1,14 @@ +diff --git a/src/Tests/CMakeLists.txt b/src/Tests/CMakeLists.txt +index 871a0457..567cb3f9 100644 +--- a/src/Tests/CMakeLists.txt ++++ b/src/Tests/CMakeLists.txt +@@ -25,6 +25,9 @@ set(test_lib zynaddsubfx_core ${GUI_LIBRARIES} ${ZLIB_LIBRARY} ${FFTW3F_LIBRARIE + + message(STATUS "Linking tests with: ${test_lib}") + ++add_executable(ZynPadReference ZynPadReference.cpp) ++target_link_libraries(ZynPadReference ${test_lib}) ++ + quick_test(AdNoteTest ${test_lib}) + quick_test(AllocatorTest ${test_lib}) + quick_test(ControllerTest ${test_lib})