diff --git a/src/AquaSynth.Core/FaustExport.cs b/src/AquaSynth.Core/FaustExport.cs index 51ae72a..c48c1cf 100644 --- a/src/AquaSynth.Core/FaustExport.cs +++ b/src/AquaSynth.Core/FaustExport.cs @@ -758,14 +758,21 @@ public static partial class FaustEmitter // Harmonic glottal source: a band-limited saw through a one-pole lowpass. Tilt 0 is the brightest source and 1 the // steepest rolloff; the cutoff sweeps five octaves, 6400 Hz down to 200 Hz, and sits below Nyquist. var cutoff = $"min(0.45 * ma.SR, 200.0 * pow(2.0, (1.0 - clip01({parameters.Expression(OwnerField(owner, "tilt"), port.Tilt)})) * 5.0))"; - source.AppendLine($" {voiced} = (os.sawtooth(({frequency}) * {pitchRatio}) : fi.lowpass(1, {cutoff})) * clip01({opening}) * clip01(0.25 + {tension});"); - source.AppendLine($" {flow} = {ProbeSignal(options, $"/debug/{voiceName}/source/{port.Name}/flow", $"({flowScale}) * (({voiced}) * ma.tanh((({pressure}) * (0.5 + {tension})) / max(0.05, {impedance})) + 0.08 * no.noise * {parameters.Expression(OwnerField(owner, "noise"), port.Noise)})", -2, 2)};"); + var wave = port.Pulse == GlottalPulse.Rosenberg ? RosenbergPulse($"(({frequency}) * {pitchRatio})") : $"os.sawtooth(({frequency}) * {pitchRatio})"; + source.AppendLine($" {voiced} = ({wave} : fi.lowpass(1, {cutoff})) * clip01({opening}) * clip01(0.25 + {tension});"); + source.AppendLine($" {flow} = {ProbeSignal(options, $"/debug/{voiceName}/source/{port.Name}/flow", $"({flowScale}) * (({voiced}) * ma.tanh((({pressure}) * (0.5 + {tension})) / max(0.05, {impedance})) + 0.08 * {(port.NoiseHighPassHz > 0 ? $"(no.noise : fi.highpass(2, {port.NoiseHighPassHz.ToString("0.###", CultureInfo.InvariantCulture)}))" : "no.noise")} * {parameters.Expression(OwnerField(owner, "noise"), port.Noise)})", -2, 2)};"); keepAlive.Add(load); keepAlive.Add(voiced); keepAlive.Add(flow); return flow; } + // Rosenberg C flow pulse of one period (phase p of 0..1): opening 0.5 (1 - cos(pi p / 0.4)) for p < 0.4, return cos(pi/2 (p - 0.4) / 0.16) + // for the next 0.16, closed after. Its mean is 0.4 / 2 + 0.16 * 2 / pi = 0.301859 and its rms about that mean is 0.372667; it is made zero-mean + // and scaled by 0.57735 / 0.372667 = 1.549 to the rms of os.sawtooth (1 / sqrt 3), so a swap of the pulse leaves the SOURCE level where it was (the rendered level moves: the pulse has no strong upper harmonics for the tract to pass). + public static string RosenbergPulse(string frequency) => + $"(((os.lf_sawpos({frequency}) : (\\(p).(select2(p < 0.4, select2(p < 0.56, 0.0, cos(ma.PI * 0.5 * (p - 0.4) / 0.16)), 0.5 * (1.0 - cos(ma.PI * p / 0.4)))))) - 0.301859) * 1.549)"; + private static (string Released, string Burst) PrimitiveContactExpression( StringBuilder source, SynthPatch patch, diff --git a/src/AquaSynth.Core/Model.cs b/src/AquaSynth.Core/Model.cs index 175bdfa..ba38129 100644 --- a/src/AquaSynth.Core/Model.cs +++ b/src/AquaSynth.Core/Model.cs @@ -474,7 +474,17 @@ public sealed record SourcePort( float Impedance = 0.35f, float FlowScale = 0.02f, float Tilt = 0.5f, - float PitchRatio = 1f); + float PitchRatio = 1f, + GlottalPulse Pulse = GlottalPulse.Saw, + float NoiseHighPassHz = 0f); + +// The glottal flow waveform of a primitive source port. Saw is the band-limited saw the tilt lowpass shapes; Rosenberg is the +// Rosenberg C pulse (open phase 0.4 of the period, return phase 0.16), zero-mean and scaled to the saw's rms at the source. The rendered level still differs: the tract passes less of the pulse (-2.5 dB output rms on /ɑmi/, measured -2.54). +public enum GlottalPulse +{ + Saw, + Rosenberg +} public sealed record ConstrictionContact( string Name, diff --git a/src/AquaSynth.Core/PatchScript.cs b/src/AquaSynth.Core/PatchScript.cs index 7b5a89e..2fd43ec 100644 --- a/src/AquaSynth.Core/PatchScript.cs +++ b/src/AquaSynth.Core/PatchScript.cs @@ -968,7 +968,9 @@ public static class PatchScript GetBoundFloat(fields, line, 0.35f, $"/vocal/sources/{_sourcePorts.Count}/impedance", "impedance", "load", "source_impedance"), GetBoundFloat(fields, line, 0.02f, $"/vocal/sources/{_sourcePorts.Count}/flow_scale", "flow_scale", "scale"), GetBoundFloat(fields, line, 0.5f, $"/vocal/sources/{_sourcePorts.Count}/tilt", "tilt", "spectral_tilt"), - GetBoundFloat(fields, line, 1f, $"/vocal/sources/{_sourcePorts.Count}/pitch_ratio", "pitch_ratio", "f0_ratio")); + GetBoundFloat(fields, line, 1f, $"/vocal/sources/{_sourcePorts.Count}/pitch_ratio", "pitch_ratio", "f0_ratio"), + ParseGlottalPulse(GetAny(fields, ["pulse", "glottal_pulse"], "saw"), line), + Math.Clamp(GetFloat(fields, line, 0f, "noise_highpass", "noise_hp"), 0f, 8000f)); _sourcePorts.Add(port); _sourcePortsByName[name] = port; RegisterSourcePortSurfaces(_sourcePorts.Count - 1, port); @@ -4443,6 +4445,13 @@ public static class PatchScript _ => throw new PatchScriptException(line, $"unknown tract propagation mode `{value}`") }; + private static GlottalPulse ParseGlottalPulse(string value, int line) => value.ToLowerInvariant() switch + { + "saw" or "sawtooth" => GlottalPulse.Saw, + "rosenberg" => GlottalPulse.Rosenberg, + _ => throw new PatchScriptException(line, $"unknown glottal pulse `{value}` (saw, rosenberg)") + }; + private static AcousticSourceKind ParseAcousticSourceKind(string value, int line) => value.ToLowerInvariant() switch { "glottal" or "glottis" or "larynx" => AcousticSourceKind.Glottal, diff --git a/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs b/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs index 5d43dea..d1125f6 100644 --- a/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs +++ b/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs @@ -12,19 +12,19 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output) private const int Rate = 48000; private const float Pitch = 137f; - private static string Script(float tilt, float pitch) => $$""" + private static string Script(float tilt, float pitch, string extra = "") => $$""" morphology name=oral length_cm=17 diameters=.6,.8,1.2,1.5,.9 waveguide_path name=oral_path morphology=oral loss=.998 - source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.45 noise=0 impedance=.3 tilt={{tilt}} + source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.45 noise=0 impedance=.3 tilt={{tilt}} {{extra}} radiation_load name=mouth path=oral_path aperture=.8 reflection=-.82 impedance=.28 vocal_network name=voice paths=oral_path sources=folds radiation=mouth vocal network=voice freq={{pitch}} gain=.2 sustain=1.5 """; // One second of steady output, so every harmonic of Pitch and every other integer-Hz frequency sits on its own DFT bin. - private float[]? Render(float tilt, float pitch = Pitch, int skip = 4800) + private float[]? Render(float tilt, float pitch = Pitch, int skip = 4800, string extra = "") { - var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch)), new FaustExportOptions("glottal_spectrum")).Source; + var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch, extra)), new FaustExportOptions("glottal_spectrum")).Source; using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate)); if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("glottal_spectrum", "glottal_spectrum", ""), source, 1.4f, out var patch, out var error)) { @@ -122,4 +122,133 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output) var defaulted = PatchScript.Parse(Script(.8f, Pitch).Replace("tilt=0.8", "", StringComparison.Ordinal)); Assert.Equal(.5f, Assert.Single(defaulted.SourcePorts).Tilt, 5); } + + [Fact] + public void PulseAndNoiseHighPassAreAuthoredSourceFieldsDefaultingToSawAndWhite() + { + var port = Assert.Single(PatchScript.Parse(Script(.5f, Pitch, "pulse=rosenberg noise_hp=2000")).SourcePorts); + Assert.Equal(GlottalPulse.Rosenberg, port.Pulse); + Assert.Equal(2000f, port.NoiseHighPassHz); + var defaulted = Assert.Single(PatchScript.Parse(Script(.5f, Pitch)).SourcePorts); + Assert.Equal(GlottalPulse.Saw, defaulted.Pulse); + Assert.Equal(0f, defaulted.NoiseHighPassHz); + Assert.Throws(() => PatchScript.Parse(Script(.5f, Pitch, "pulse=triangle"))); + } + + [Fact] + public void OnlyTheRosenbergPulseEmitsThePhasorAndOnlyAHighPassedSourceEmitsTheNoiseFilter() + { + string Emit(string extra) => FaustEmitter.Emit(PatchScript.Parse(Script(.5f, Pitch, extra)), new FaustExportOptions("pulse_emit")).Source; + Assert.DoesNotContain("lf_sawpos", Emit(""), StringComparison.Ordinal); + Assert.Contains("lf_sawpos", Emit("pulse=rosenberg"), StringComparison.Ordinal); + Assert.DoesNotContain("fi.highpass(2, 2000", Emit(""), StringComparison.Ordinal); + Assert.Contains("fi.highpass(2, 2000", Emit("noise_hp=2000"), StringComparison.Ordinal); + } + + [Fact] + public void RosenbergPulseIsPeriodicAtThePitchAndRendersWithinSixDbOfTheSaw() + { + var saw = Render(.5f); + var pulse = Render(.5f, extra: "pulse=rosenberg"); + if (saw is null || pulse is null) return; + + double Rms(float[] w) => Math.Sqrt(w.Sum(v => (double)v * v) / w.Length); + var difference = Db(Rms(pulse) / Rms(saw)); + output.WriteLine($"rosenberg rms {Rms(pulse):E3} saw rms {Rms(saw):E3} ({difference:F2} dB)"); + // The source rms is matched, the rendered level is not: the tract passes the saw's strong upper harmonics and the pulse has none (-3.2 dB here, -2.5 dB on /ɑmi/, measured -2.54). + Assert.InRange(difference, -6, 0); + var fundamental = Magnitude(pulse, Pitch); + var between = Magnitude(pulse, Pitch * 1.5); + Assert.True(Db(between / fundamental) < -30, $"energy between harmonics {Db(between / fundamental):F1} dB re the fundamental"); + } + + // One expression compiled alone as a one-output DSP. The pulse is run at 100 Hz, which divides the rate (480 samples a period), so every sample + // sits at a known phase; the patch path scales a bare signal by a constant, so levels are read against os.sawtooth through the same path. + // Expected values are Rosenberg C written out here, independent of the emitted formula's spelling. + private float[]? RenderBare(string expression, double seconds) + { + var dsp = $"import(\"stdfaust.lib\");\nprocess = {expression};\n"; + using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate)); + if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("pulse_bare", "pulse_bare", ""), dsp, (float)seconds + .1f, out var patch, out var error)) + { + if (error?.Contains("Faust toolchain not found", StringComparison.OrdinalIgnoreCase) == true || + error?.Contains("Faust DLL not found", StringComparison.OrdinalIgnoreCase) == true) + { + return null; + } + + Assert.Fail($"bare pulse compile failed: {error}"); + } + + using (patch) return patch!.Render((float)seconds); + } + + private static double RosenbergC(double p) => + p < 0.4 ? 0.5 * (1 - Math.Cos(Math.PI * p / 0.4)) : p < 0.56 ? Math.Cos(Math.PI * 0.5 * (p - 0.4) / 0.16) : 0; + + [Fact] + public void RosenbergPulseIsTheDocumentedRosenbergCZeroMeanAtTheSawsRms() + { + const int period = 480; + var pulse = RenderBare(FaustEmitter.RosenbergPulse("100.0"), 0.5); + var saw = RenderBare("os.sawtooth(100.0)", 0.5); + if (pulse is null || saw is null) return; + var cycle = pulse.Skip(period).Take(period).ToArray(); + double Rms(IEnumerable w) => Math.Sqrt(w.Sum(v => (double)v * v) / w.Count()); + // Calibrate the path's scale on the saw (rms 1/sqrt3 at the source): read every pulse sample back at source level. + var scale = Rms(saw.Skip(period).Take(period)) / (1 / Math.Sqrt(3)); + cycle = cycle.Select(v => (float)(v / scale)).ToArray(); + + // Rosenberg C has mean 0.301859 and rms 0.372667 about it; the emitted pulse is that, zero-mean, scaled to the saw's rms. + Assert.InRange(cycle.Average(), -0.003, 0.003); + var rms = Rms(cycle); + output.WriteLine($"pulse rms {rms:F5} (saw 1/sqrt3 = {1 / Math.Sqrt(3):F5}), path scale {scale:F4}, peak {cycle.Max():F4}, floor {cycle.Min():F4}"); + Assert.InRange(Db(rms / (1 / Math.Sqrt(3))), -0.05, 0.05); + + // Shape at every phase point. The phasor's alignment to the sample grid is not part of the contract, so find the shift that fits, + // then hold every point to the closed form: opening cosine, return cosine, closed plateau. A linear opening, another scale or no return phase all miss. + double Expected(int n, int shift) => (RosenbergC(((n + shift) % period) / (double)period) - 0.301859) * 1.549; + var shift = Enumerable.Range(0, period).MinBy(k => Enumerable.Range(0, period).Sum(n => Math.Pow(cycle[n] - Expected(n, k), 2))); + var worst = Enumerable.Range(0, period).Max(n => Math.Abs(cycle[n] - Expected(n, shift))); + output.WriteLine($"best shift {shift} samples, worst deviation from Rosenberg C {worst:E2}"); + Assert.True(worst < 0.01, $"worst deviation from Rosenberg C {worst:E2} at shift {shift}"); + // The regions by value: the opening peaks at p = 0.4 at (1 - mean) * 1.549, the closed floor is -mean * 1.549 and holds for 0.44 of the period (plus the tail of the return cosine inside the tolerance). + Assert.InRange(cycle.Max(), (1 - 0.301859) * 1.549 - 0.01, (1 - 0.301859) * 1.549 + 0.01); + Assert.InRange(cycle.Min(), -0.301859 * 1.549 - 0.01, -0.301859 * 1.549 + 0.01); + Assert.InRange(cycle.Count(v => Math.Abs(v - (-0.301859 * 1.549)) < 0.01), (int)(0.44 * period) - 15, (int)(0.44 * period) + 15); + } + + [Fact] + public void NoiseHighPassCornerIsTheAuthoredHertz() + { + // The source's noise alone (pressure 0 silences the voiced part), white and through fi.highpass(2, fc): band energy against the white render tells the corner. + // A 2 kHz corner leaves almost nothing under 700 Hz, passes 3-3.8 kHz whole and takes a few dB off 1.6-2.4 kHz; a 1 kHz corner passes the middle band; a 4 kHz corner cuts it. + double Band(float[] w, double lo, double hi) + { + double sum = 0; + for (var hz = lo; hz < hi; hz += 25) sum += Math.Pow(Magnitude(w, hz), 2); + return sum; + } + + double[] Shape(string extra) + { + var window = Render(.5f, extra: "pressure=0 noise=2 " + extra); + return window is null ? [] : [Band(window, 100, 700), Band(window, 1600, 2400), Band(window, 3000, 3800)]; + } + + var white = Shape(""); + var at2k = Shape("noise_hp=2000 pulse=saw"); + if (white.Length == 0 || at2k.Length == 0) return; + var at1k = Shape("noise_hp=1000"); + var at4k = Shape("noise_hp=4000"); + output.WriteLine($"band energies (100-700, 1600-2400, 3000-3800 Hz) white {string.Join(" ", white.Select(b => b.ToString("E2")))}"); + foreach (var (name, shape) in new[] { ("1k", at1k), ("2k", at2k), ("4k", at4k) }) output.WriteLine($"hp {name}: " + string.Join(" ", shape.Select(b => b.ToString("E2")))); + double Rel(double[] shape, int band) => Db(Math.Sqrt(shape[band] / white[band])); + Assert.True(Rel(at2k, 0) < -18, $"2 kHz corner leaves {Rel(at2k, 0):F1} dB at 100-700 Hz"); + Assert.InRange(Rel(at2k, 1), -6, -1.5); + Assert.True(Rel(at2k, 2) > -1.5, $"2 kHz corner leaves {Rel(at2k, 2):F1} dB at 3-3.8 kHz"); + // A 1 kHz corner passes the 1.6-2.4 kHz band nearly whole; a 4 kHz corner cuts it hard. + Assert.True(Rel(at1k, 1) > -2, $"1 kHz corner: {Rel(at1k, 1):F1} dB at 1.6-2.4 kHz"); + Assert.True(Rel(at4k, 1) < -9, $"4 kHz corner: {Rel(at4k, 1):F1} dB at 1.6-2.4 kHz"); + } } diff --git a/tools/WordRender/Program.cs b/tools/WordRender/Program.cs index 32e01c8..7360e1b 100644 --- a/tools/WordRender/Program.cs +++ b/tools/WordRender/Program.cs @@ -8,12 +8,17 @@ using AquaSynth.Faust; // Offline probe: one word, segmented by Weksa (the phones line of `weksa lower --phones`), as a run of IPA gestures on the // IpaGestureExperiment scaffold, rendered through the native libfaust path to a mono 16-bit WAV plus script.aqua, source.dsp // and manifest.json. It measures peak, rms and NaN; it cannot say how the word sounds. -// usage: WordRender