diff --git a/src/AquaSynth.Core/FaustExport.VocalLadder.cs b/src/AquaSynth.Core/FaustExport.VocalLadder.cs new file mode 100644 index 0000000..ae06b70 --- /dev/null +++ b/src/AquaSynth.Core/FaustExport.VocalLadder.cs @@ -0,0 +1,149 @@ +using System.Text; + +namespace AquaSynth.Dsl; + +// The vocal_network resonator: a Kelly-Lochbaum ladder per waveguide path, one cell per sample (cell length c / sample +// rate), written as a Faust `letrec` so every wave variable is a one-sample state. Cell areas come from the morphology +// rest shape deformed by the path's area control (the same Gaussian model the acoustic graph uses). A branch port whose +// two paths are both in the network becomes a three-port parallel junction (Pink Trombone's velum: ports are the oral +// cells either side of the join and the branch path's first cell, whose area is the branch opening). +public static partial class FaustEmitter +{ + // Reflection at the closed glottal end of a path that carries a source. + private const float LadderGlottalReflection = 0.75f; + // Full-open velum diameter in cm, as in Pink Trombone's velum target. + private const float VelumOpenDiameterCentimeters = 0.4f; + + private sealed record LadderPath( + WaveguidePath Path, + AreaFunction Area, + int AreaIndex, + int PathIndex, + string Prefix, + int Cells, + RadiationLoad? Radiation, + int RadiationIndex) + { + public string A(int i) => $"{Prefix}_A{i}"; + public string R(int i) => $"{Prefix}_R{i}"; + public string L(int i) => $"{Prefix}_L{i}"; + public string Refl(int i) => $"{Prefix}_r{i}"; + } + + private sealed record LadderJunction(LadderPath Oral, LadderPath Branch, int Interface, string Velum, string Left, string Right, string Nose); + + private static int LadderCells(WaveguidePath path, TractAreaFunction shape, FaustExportOptions options) => + Math.Max(3, (int)MathF.Round(shape.LengthMeters * options.SampleRate / Math.Max(1f, path.PropagationSpeedMetersPerSecond))); + + /// + /// Emits the area, reflection and junction definitions and the recursive ladder for , and returns, + /// per path, the identifier of its lip output (the right-going wave leaving its last cell). + /// + private static IReadOnlyDictionary EmitVocalLadder( + StringBuilder source, + SynthPatch patch, + VocalNetwork network, + string name, + IReadOnlyList members, + IReadOnlyDictionary inputs, + IReadOnlyDictionary admittances, + ParameterMap parameters, + List warnings) + { + var junctions = new List(); + foreach (var branchName in network.Branches) + { + var branch = patch.BranchPorts.FirstOrDefault(candidate => candidate.Name.Equals(branchName, StringComparison.OrdinalIgnoreCase)); + var oral = branch is null ? null : members.FirstOrDefault(member => member.Path.Name.Equals(branch.FromPath, StringComparison.OrdinalIgnoreCase)); + var nasal = branch is null ? null : members.FirstOrDefault(member => member.Path.Name.Equals(branch.ToPath, StringComparison.OrdinalIgnoreCase)); + if (branch is null || oral is null || nasal is null || oral == nasal) + { + continue; + } + + var cell = Math.Clamp((int)MathF.Round(Math.Clamp(branch.FromPosition, 0, 1) * oral.Cells), 1, oral.Cells - 2); + if (junctions.Any(existing => existing.Oral == oral && existing.Interface == cell) || junctions.Any(existing => existing.Branch == nasal)) + { + warnings.Add($"{name}: branch `{branch.Name}` shares a junction cell or target path with another branch; ignored by the ladder"); + continue; + } + + var velum = $"{name}_primitive_branch_{SafeIdentifier(branch.Name)}_velum_area"; + source.AppendLine($" {velum} = max(0.000001, pow({admittances[branch.Name]} * {F(VelumOpenDiameterCentimeters)}, 2.0));"); + var sum = $"({oral.A(cell)} + {oral.A(cell + 1)} + {velum})"; + var key = $"{name}_primitive_branch_{SafeIdentifier(branch.Name)}"; + source.AppendLine($" {key}_refl_left = (2.0 * {oral.A(cell)} - {sum}) / {sum};"); + source.AppendLine($" {key}_refl_right = (2.0 * {oral.A(cell + 1)} - {sum}) / {sum};"); + source.AppendLine($" {key}_refl_nose = (2.0 * {velum} - {sum}) / {sum};"); + junctions.Add(new LadderJunction(oral, nasal, cell, velum, $"{key}_refl_left", $"{key}_refl_right", $"{key}_refl_nose")); + } + + var targets = junctions.ToDictionary(junction => junction.Branch); + var joinedAt = junctions.ToDictionary(junction => (junction.Oral, junction.Interface)); + var equations = new StringBuilder(); + + foreach (var member in members) + { + var targetJunction = targets.GetValueOrDefault(member); + for (var i = 0; i < member.Cells; i++) + { + if (i == 0 && targetJunction is not null) + { + source.AppendLine($" {member.A(0)} = {targetJunction.Velum};"); + continue; + } + + var area = DeformedAreaExpression(parameters, member.Area.Shape, member.Area.Deformation, $"/vocal/areas/{member.AreaIndex}/area", (i + 0.5f) / member.Cells); + source.AppendLine($" {member.A(i)} = max(0.000001, {area});"); + } + + for (var i = 1; i < member.Cells; i++) + { + source.AppendLine($" {member.Refl(i)} = ({member.A(i - 1)} - {member.A(i)}) / ({member.A(i - 1)} + {member.A(i)});"); + } + + var loss = $"clip01({parameters.Expression(OwnerField($"/vocal/paths/{member.PathIndex}", "loss"), member.Path.Loss)})"; + var lipReflection = member.Radiation is { } load + ? parameters.Expression(OwnerField($"/vocal/radiation/{member.RadiationIndex}", "reflection"), load.Reflection) + : F(new RadiationLoad("", "").Reflection); + var last = member.Cells - 1; + + equations.AppendLine(targetJunction is { } entering + ? $" '{member.R(0)} = ({entering.Oral.L(entering.Interface)} + {entering.Oral.R(entering.Interface - 1)}) * (1.0 + {entering.Nose}) * {loss} + {entering.Nose} * {member.L(0)} * {loss};" + : $" '{member.R(0)} = ({member.L(0)} * {F(LadderGlottalReflection)} + {(inputs.TryGetValue(member.Path.Name, out var input) ? input : "0.0")}) * {loss};"); + for (var i = 1; i < member.Cells; i++) + { + equations.AppendLine(joinedAt.TryGetValue((member, i), out var join) + ? $" '{member.R(i)} = ({join.Right} * {member.L(i)} + (1.0 + {join.Right}) * ({member.R(i - 1)} + {join.Branch.L(0)})) * {loss};" + : $" '{member.R(i)} = ({member.R(i - 1)} - {member.Refl(i)} * ({member.R(i - 1)} + {member.L(i)})) * {loss};"); + } + + for (var i = 0; i < last; i++) + { + equations.AppendLine(joinedAt.TryGetValue((member, i + 1), out var join) + ? $" '{member.L(i)} = ({join.Left} * {member.R(i)} + (1.0 + {join.Left}) * ({join.Branch.L(0)} + {member.L(i + 1)})) * {loss};" + : $" '{member.L(i)} = ({member.L(i + 1)} + {member.Refl(i + 1)} * ({member.R(i)} + {member.L(i + 1)})) * {loss};"); + } + + equations.AppendLine($" '{member.L(last)} = {member.R(last)} * ({lipReflection}) * {loss};"); + } + + var outputs = string.Join(", ", members.Select(member => member.R(member.Cells - 1))); + var ladder = $"{name}_primitive_ladder"; + source.AppendLine($" {ladder} = ({outputs}) letrec {{"); + source.Append(equations); + source.AppendLine(" };"); + + var lips = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (var m = 0; m < members.Count; m++) + { + var lip = $"{members[m].Prefix}_lip"; + source.AppendLine(members.Count == 1 + ? $" {lip} = {ladder};" + : $" {lip} = {ladder} : ba.selector({m}, {members.Count});"); + lips[members[m].Path.Name] = lip; + } + + return lips; + } +} diff --git a/src/AquaSynth.Core/FaustExport.cs b/src/AquaSynth.Core/FaustExport.cs index cfe1a47..01fd6e3 100644 --- a/src/AquaSynth.Core/FaustExport.cs +++ b/src/AquaSynth.Core/FaustExport.cs @@ -4,11 +4,11 @@ using System.Text; namespace AquaSynth.Dsl; -public sealed record FaustExportOptions(string Name = "aquasynth_patch", bool Stereo = false, bool DebugProbeUi = false); +public sealed record FaustExportOptions(string Name = "aquasynth_patch", bool Stereo = false, bool DebugProbeUi = false, int SampleRate = 48000); public sealed record FaustExport(string Source, IReadOnlyList Warnings); -public static class FaustEmitter +public static partial class FaustEmitter { public static FaustExport EmitScript(string script, FaustExportOptions? options = null) => Emit(PatchScript.Parse(script), options ?? new FaustExportOptions()); @@ -575,6 +575,7 @@ public static class FaustEmitter var radiated = new List(); source.AppendLine($"{name}_primitive_drive = 1.0;"); + var members = new List(); foreach (var pathName in network.Paths) { if (!paths.TryGetValue(pathName, out var path)) @@ -588,24 +589,27 @@ public static class FaustEmitter continue; } - var safePath = SafeIdentifier(path.Name); - var areaIndex = AreaFunctionIndex(patch, area); - var pathIndex = WaveguidePathIndex(patch, path); - var pathField = $"/vocal/paths/{pathIndex}"; - var representativeArea = $"{name}_primitive_path_{safePath}_area"; - var delay = $"{name}_primitive_path_{safePath}_delay"; - var input = $"{name}_primitive_path_{safePath}_input"; - var incoming = $"{name}_primitive_path_{safePath}_incoming_wave"; - var wave = $"{name}_primitive_path_{safePath}_wave"; - var energyIn = $"{name}_primitive_path_{safePath}_energy_in"; - var energyOut = $"{name}_primitive_path_{safePath}_energy_out"; - var passivity = $"{name}_primitive_path_{safePath}_passivity_ratio"; - var loss = $"clip01({parameters.Expression(OwnerField(pathField, "loss"), path.Loss)})"; - source.AppendLine($" {representativeArea} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/area", PrimitiveAreaExpression(patch, parameters, area, areaIndex), 0, 8)};"); - source.AppendLine($" {delay} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/delay", $"({F(area.Shape.LengthMeters)} / max(1.0, {parameters.Expression(OwnerField(pathField, "speed"), path.PropagationSpeedMetersPerSecond)})) * ma.SR", 0, path.MaxDelaySamples)};"); - keepAlive.Add(representativeArea); - keepAlive.Add(delay); + var load = network.Radiation + .Select(loadName => radiation.TryGetValue(loadName, out var candidate) && candidate.Path.Equals(path.Name, StringComparison.OrdinalIgnoreCase) ? candidate : null) + .FirstOrDefault(candidate => candidate is not null); + members.Add(new LadderPath( + path, + area, + AreaFunctionIndex(patch, area), + WaveguidePathIndex(patch, path), + $"{name}_primitive_path_{SafeIdentifier(path.Name)}", + LadderCells(path, area.Shape, options), + load, + load is null ? 0 : RadiationLoadIndex(patch, load))); + } + // Per-path drive: sources, contact release and branch exchange sum into the path input. A branch whose two paths + // are both in this network is a ladder junction instead and exchanges no flow term. + var memberNames = members.Select(member => member.Path.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); + var inputs = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var member in members) + { + var path = member.Path; var sourceTerms = network.Sources .Select(sourceName => sourcePorts.TryGetValue(sourceName, out var port) && port.Path.Equals(path.Name, StringComparison.OrdinalIgnoreCase) ? PrimitiveSourceExpression(source, patch, name, port, frequency, parameters, options, keepAlive) @@ -621,20 +625,52 @@ public static class FaustEmitter .Cast() .ToList(); var branchTerms = network.Branches - .Select(branchName => branches.TryGetValue(branchName, out var branch) && branch.FromPath.Equals(path.Name, StringComparison.OrdinalIgnoreCase) + .Select(branchName => branches.TryGetValue(branchName, out var branch) && branch.FromPath.Equals(path.Name, StringComparison.OrdinalIgnoreCase) && !memberNames.Contains(branch.ToPath) ? PrimitiveBranchExpression(source, patch, name, branch, parameters, options, keepAlive) : null) .Where(term => term is not null) .Cast() .ToList(); var pathInputs = sourceTerms.Concat(contactTerms).Concat(branchTerms).ToList(); + var input = $"{member.Prefix}_input"; source.AppendLine($" {input} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/input_flow", pathInputs.Count == 0 ? "0.0" : string.Join(" + ", pathInputs), -4, 4)};"); - source.AppendLine($" {incoming} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/incoming_wave", input, -4, 4)};"); - source.AppendLine($" {wave} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/outgoing_wave", $"({incoming}) : {PrimitiveDelayExpression(path, path.MaxDelaySamples, delay)} * {loss}", -4, 4)};"); + inputs[path.Name] = input; + keepAlive.Add(input); + } + + var admittances = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var branchName in network.Branches) + { + if (branches.TryGetValue(branchName, out var branch) && memberNames.Contains(branch.FromPath) && memberNames.Contains(branch.ToPath)) + { + admittances[branch.Name] = PrimitiveBranchAdmittance(source, patch, name, branch, parameters, options, keepAlive); + } + } + + var lips = members.Count == 0 + ? new Dictionary() + : EmitVocalLadder(source, patch, network, name, members, inputs, admittances, parameters, warnings); + + foreach (var member in members) + { + var path = member.Path; + var representativeArea = $"{member.Prefix}_area"; + var delay = $"{member.Prefix}_delay"; + var incoming = $"{member.Prefix}_incoming_wave"; + var wave = $"{member.Prefix}_wave"; + var energyIn = $"{member.Prefix}_energy_in"; + var energyOut = $"{member.Prefix}_energy_out"; + var passivity = $"{member.Prefix}_passivity_ratio"; + var meanArea = $"({string.Join(" + ", Enumerable.Range(0, member.Cells).Select(member.A))}) / {member.Cells}.0"; + source.AppendLine($" {representativeArea} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/area", meanArea, 0, 8)};"); + source.AppendLine($" {delay} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/delay", $"{member.Cells}.0", 0, member.Cells)};"); + source.AppendLine($" {incoming} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/incoming_wave", inputs[path.Name], -4, 4)};"); + source.AppendLine($" {wave} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/outgoing_wave", lips[path.Name], -4, 4)};"); source.AppendLine($" {energyIn} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/energy_in", $"{representativeArea} * pow({incoming}, 2.0)", 0, 8)};"); source.AppendLine($" {energyOut} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/energy_out", $"{representativeArea} * pow({wave}, 2.0)", 0, 8)};"); source.AppendLine($" {passivity} = {ProbeSignal(options, $"/debug/{name}/path/{path.Name}/passivity_ratio", $"{energyOut} / max(0.000001, {energyIn})", 0, 2)};"); - keepAlive.Add(input); + keepAlive.Add(representativeArea); + keepAlive.Add(delay); keepAlive.Add(incoming); keepAlive.Add(wave); keepAlive.Add(energyIn); @@ -660,32 +696,6 @@ public static class FaustEmitter return $"{name}_primitive_radiated"; } - private static string PrimitiveAreaExpression(SynthPatch patch, ParameterMap parameters, AreaFunction area, int areaIndex) - { - var baseDiameter = area.Shape.AverageDiameter(0, 1); - if (area.Deformation is null) - { - return F(baseDiameter * baseDiameter); - } - - var areaPath = $"/vocal/areas/{areaIndex}"; - var tongue = parameters.Expression(OwnerField(areaPath, "area/tongue_diameter"), area.Deformation.TongueDiameter); - var constriction = parameters.Expression(OwnerField(areaPath, "area/constriction_diameter"), area.Deformation.ConstrictionDiameter); - var lip = parameters.Expression(OwnerField(areaPath, "area/lip_opening"), area.Deformation.LipOpening); - return $"pow(max(0.0001, ({F(baseDiameter)} + ({tongue}) * 0.10 + ({lip}) * 0.08 + min(0.0, ({constriction}) - 1.0) * 0.35)), 2.0)"; - } - - private static string PrimitiveDelayExpression(WaveguidePath path, int maxDelay, string delay) => - path.DelayStrategy switch - { - WaveClockDelayStrategy.UnitGrid => $"de.delay({maxDelay}, int(max(1.0, {delay})))", - WaveClockDelayStrategy.HalfSampleGrid => $"de.fdelay({maxDelay}, round(max(0.5, {delay}) * 2.0) * 0.5)", - WaveClockDelayStrategy.FractionalLagrange => $"de.fdelayltv({Math.Clamp(path.DelayOrder, 1, 5)}, {maxDelay}, max({F((Math.Clamp(path.DelayOrder, 1, 5) - 1) * 0.5f)}, {delay}))", - WaveClockDelayStrategy.FractionalThiran => $"de.fdelay{Math.Clamp(path.DelayOrder, 1, 4)}a({maxDelay}, max({F(Math.Clamp(path.DelayOrder, 1, 4) - 0.5f)}, {delay}))", - WaveClockDelayStrategy.CrossfadedVariable => $"de.fdelayltv({Math.Clamp(path.DelayOrder, 1, 5)}, {maxDelay}, max({F((Math.Clamp(path.DelayOrder, 1, 5) - 1) * 0.5f)}, {delay}))", - _ => $"de.fdelay({maxDelay}, max(0.5, {delay}))" - }; - private static string PrimitiveSourceExpression( StringBuilder source, SynthPatch patch, @@ -743,6 +753,24 @@ public static class FaustEmitter return released; } + // Open fraction of a branch port: the ladder reads it as the velum area when the branch joins two paths of the network, + // otherwise it scales the flow term PrimitiveBranchExpression exchanges. + private static string PrimitiveBranchAdmittance( + StringBuilder source, + SynthPatch patch, + string voiceName, + BranchPort branch, + ParameterMap parameters, + FaustExportOptions options, + List keepAlive) + { + var owner = $"/vocal/branches/{BranchPortIndex(patch, branch)}"; + var admittance = $"{voiceName}_primitive_branch_{SafeIdentifier(branch.Name)}_admittance"; + source.AppendLine($" {admittance} = {ProbeSignal(options, $"/debug/{voiceName}/branch/{branch.Name}/admittance", $"clip01({parameters.Expression(OwnerField(owner, "opening"), branch.Opening)}) * clip01({parameters.Expression(OwnerField(owner, "coupling"), branch.Coupling)})", 0, 1)};"); + keepAlive.Add(admittance); + return admittance; + } + private static string PrimitiveBranchExpression( StringBuilder source, SynthPatch patch, @@ -752,14 +780,9 @@ public static class FaustEmitter FaustExportOptions options, List keepAlive) { - var index = BranchPortIndex(patch, branch); - var owner = $"/vocal/branches/{index}"; - var safe = SafeIdentifier(branch.Name); - var admittance = $"{voiceName}_primitive_branch_{safe}_admittance"; - var exchanged = $"{voiceName}_primitive_branch_{safe}_exchanged_flow"; - source.AppendLine($" {admittance} = {ProbeSignal(options, $"/debug/{voiceName}/branch/{branch.Name}/admittance", $"clip01({parameters.Expression(OwnerField(owner, "opening"), branch.Opening)}) * clip01({parameters.Expression(OwnerField(owner, "coupling"), branch.Coupling)})", 0, 1)};"); + var admittance = PrimitiveBranchAdmittance(source, patch, voiceName, branch, parameters, options, keepAlive); + var exchanged = $"{voiceName}_primitive_branch_{SafeIdentifier(branch.Name)}_exchanged_flow"; source.AppendLine($" {exchanged} = {ProbeSignal(options, $"/debug/{voiceName}/branch/{branch.Name}/exchanged_flow", $"0.0 - {admittance} * 0.05", -1, 1)};"); - keepAlive.Add(admittance); keepAlive.Add(exchanged); return exchanged; } @@ -1623,50 +1646,44 @@ public static class FaustEmitter return "1.0"; } - var position = Math.Clamp(terminal.Position, 0, 1); - var restDiameter = path.AreaFunction.DiameterAt(position); - if (path.AreaControl is not { } area) - { - return F(Math.Max(0.000001f, restDiameter * restDiameter)); - } - - var pathIndex = AcousticPathIndex(patch, path); - var areaPath = $"/acoustic/paths/{pathIndex}/area"; - var sections = Math.Max(2, path.AreaFunction.Sections); - var index = F(position * (sections - 1)); - var tongueIndex = ScaledAreaIndex(parameters.Expression(OwnerField(areaPath, "tongue_index"), area.TongueIndex), area.IndexScale); - var tongueDiameter = parameters.Expression(OwnerField(areaPath, "tongue_diameter"), area.TongueDiameter); - var tongueWidth = $"max(0.001, {F(area.TongueWidth)} * {F(sections)})"; - var constrictionIndex = ScaledAreaIndex(parameters.Expression(OwnerField(areaPath, "constriction_index"), area.ConstrictionIndex), area.IndexScale); - var constrictionDiameter = parameters.Expression(OwnerField(areaPath, "constriction_diameter"), area.ConstrictionDiameter); - var constrictionWidth = $"max(0.001, {F(area.ConstrictionWidth)} * {F(sections)})"; - var lipOpening = parameters.Expression(OwnerField(areaPath, "lip_opening"), area.LipOpening); - var lipWeight = MathF.Exp(0 - MathF.Pow((1 - position) / Math.Max(0.001f, area.LipWidth), 2)); - var tongueWeight = $"exp(0.0 - pow(({index} - ({tongueIndex})) / ({tongueWidth}), 2.0))"; - var constrictionWeight = $"exp(0.0 - pow(({index} - ({constrictionIndex})) / ({constrictionWidth}), 2.0))"; - var baseDiameter = $"({F(restDiameter)} + (({tongueDiameter}) - {F(restDiameter)}) * ({tongueWeight}) + (({lipOpening}) - {F(restDiameter)}) * {F(lipWeight)})"; - var diameter = $"max(0.0, min({baseDiameter}, ({constrictionDiameter}) + max(0.0, ({baseDiameter}) - ({constrictionDiameter})) * (1.0 - ({constrictionWeight}))))"; - return $"(({diameter}) * ({diameter}))"; - - static string ScaledAreaIndex(string expression, float scale) => - scale == 1 ? expression : $"(({expression}) * {F(scale)})"; + return DeformedAreaExpression( + parameters, + path.AreaFunction, + path.AreaControl, + $"/acoustic/paths/{AcousticPathIndex(patch, path)}/area", + Math.Clamp(terminal.Position, 0, 1)); } private static string SegmentAreaExpression( SynthPatch patch, ParameterMap parameters, - AcousticGraphSegment segment) + AcousticGraphSegment segment) => + DeformedAreaExpression( + parameters, + segment.Path.AreaFunction, + segment.Path.AreaControl, + $"/acoustic/paths/{AcousticPathIndex(patch, segment.Path)}/area", + (segment.StartPosition + segment.EndPosition) * 0.5f); + + /// + /// The one owner of the Gaussian tongue/constriction/lip area deformation: cross-section area (cm^2) of a tract at a + /// normalized position, as a Faust expression over the control surfaces under . Acoustic + /// graph terminals and segments and the vocal ladder's cells all read their area here. + /// + private static string DeformedAreaExpression( + ParameterMap parameters, + TractAreaFunction shape, + AcousticAreaControl? area, + string areaPath, + float position) { - var position = (segment.StartPosition + segment.EndPosition) * 0.5f; - var restDiameter = segment.Path.AreaFunction.DiameterAt(position); - if (segment.Path.AreaControl is not { } area) + var restDiameter = shape.DiameterAt(position); + if (area is null) { return F(Math.Max(0.000001f, restDiameter * restDiameter)); } - var pathIndex = AcousticPathIndex(patch, segment.Path); - var areaPath = $"/acoustic/paths/{pathIndex}/area"; - var sections = Math.Max(2, segment.Path.AreaFunction.Sections); + var sections = Math.Max(2, shape.Sections); var index = F(position * (sections - 1)); var tongueIndex = ScaledAreaIndex(parameters.Expression(OwnerField(areaPath, "tongue_index"), area.TongueIndex), area.IndexScale); var tongueDiameter = parameters.Expression(OwnerField(areaPath, "tongue_diameter"), area.TongueDiameter); diff --git a/src/AquaSynth.Core/IpaGestureExperiment.cs b/src/AquaSynth.Core/IpaGestureExperiment.cs index 146f1ef..6916988 100644 --- a/src/AquaSynth.Core/IpaGestureExperiment.cs +++ b/src/AquaSynth.Core/IpaGestureExperiment.cs @@ -234,10 +234,11 @@ public static class IpaGestureExperiment waveguide_path name=nasal_path morphology=nasal strategy=thiran order=1 max_delay=4096 loss=.997 source_port name=folds path=oral_path kind=glottal position=0 pressure=.66 tension=.54 opening=.42 noise=.04 impedance=.32 flow_scale=.12 branch_port name=velopharynx from=oral_path from_position=.45 to=nasal_path opening=.01 coupling=1 - constriction_contact name=contact path=oral_path position=.92 opening=.5 resistance=.45 stored_pressure=.12 + constriction_contact name=contact path=oral_path position=.92 opening=1 resistance=.45 stored_pressure=.12 radiation_load name=mouth path=oral_path kind=lip position=1 aperture=.8 reflection=-.82 impedance=.28 + radiation_load name=nostril path=nasal_path kind=lip position=1 aperture=.8 reflection=-.82 impedance=.28 probe_timeline name=flow network=voice blocks=12 block_size=64 - vocal_network name=voice paths=oral_path,nasal_path sources=folds contacts=contact branches=velopharynx radiation=mouth probe=flow + vocal_network name=voice paths=oral_path,nasal_path sources=folds contacts=contact branches=velopharynx radiation=mouth,nostril probe=flow {{string.Join("\n", gestureLines)}} vocal network=voice freq={{Format(frequency)}} gain=.7 sustain={{Format(sustain)}} """; diff --git a/src/AquaSynth.Faust/NativeFaustRuntime.cs b/src/AquaSynth.Faust/NativeFaustRuntime.cs index 99bc288..b84e3a8 100644 --- a/src/AquaSynth.Faust/NativeFaustRuntime.cs +++ b/src/AquaSynth.Faust/NativeFaustRuntime.cs @@ -511,7 +511,7 @@ public sealed class AquaSynthNativeCompiler : IDisposable ObjectDisposedException.ThrowIf(disposed, this); var patch = PatchScript.Parse(identity.Script); var faustName = SafeFaustName(identity.FaustName); - var export = FaustEmitter.Emit(patch, new FaustExportOptions(faustName)); + var export = FaustEmitter.Emit(patch, new FaustExportOptions(faustName, SampleRate: options.SampleRate)); var duration = EstimateDuration(patch, options); var sourcePath = WriteDspSource(identity.Id, export.Source, options.DspSourceDirectory); return CompileSource(identity, faustName, export.Source, duration, sourcePath, ControlSurfaceCatalog.FromPatch(patch)); diff --git a/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs b/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs index 15156d8..5d43dea 100644 --- a/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs +++ b/tests/AquaSynth.Dsl.Tests/GlottalSourceSpectrumTests.cs @@ -6,6 +6,7 @@ namespace AquaSynth.Dsl.Tests; // The primitive vocal network has no resonators, so the rendered spectrum is the glottal source's own: harmonics of the // pitch with a tilt-controlled rolloff. These tests render through the native Faust path and measure by DFT. +[Collection("NativeFaust")] public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output) { private const int Rate = 48000; @@ -21,7 +22,7 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output) """; // 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) + private float[]? Render(float tilt, float pitch = Pitch, int skip = 4800) { var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch)), new FaustExportOptions("glottal_spectrum")).Source; using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate)); @@ -39,8 +40,8 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output) using (patch) { var samples = patch!.Render(1.0f); - Assert.True(samples.Length >= Rate + 4800, $"render too short: {samples.Length}"); - return samples.Skip(4800).Take(Rate).ToArray(); + Assert.True(samples.Length >= Rate + skip, $"render too short: {samples.Length}"); + return samples.Skip(skip).Take(Rate).ToArray(); } } @@ -97,16 +98,18 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output) [Fact] public void BrightestHighPitchedSourceDoesNotAlias() { - // The threshold sits between the measured band-limited saw (-97 dB) and a naive saw (-78 dB). At 2744 Hz (48 kHz is 17.49 periods) a naive saw folds partials above Nyquist onto the frequencies between true harmonics. + // 2744 Hz is 17.49 samples per period, and 48000 and 2744 share a factor of 8, so a naive saw folds its partials above + // Nyquist onto multiples of 8 Hz that are not harmonics of the pitch; the band-limited saw leaves them 44.8 dB down (worst bin, measured) and a naive saw 18.9 dB down. The threshold sits between. const float pitch = 2744f; - var window = Render(0f, pitch); + // The tract rings for a few hundred ms after the note starts; that decaying transient is not periodic and would fill the gaps between harmonics, so the window starts after it. + var window = Render(0f, pitch, skip: 16800); if (window is null) return; - var fundamental = Magnitude(window, pitch); - var between = Enumerable.Range(0, 7).Select(k => Magnitude(window, pitch * k + pitch / 2)).ToArray(); - var worst = Db(between.Max() / fundamental); - output.WriteLine($"tilt 0 pitch {pitch}: worst inter-harmonic level {worst:F1} dB re fundamental"); - Assert.True(worst < -90, $"inter-harmonic energy {worst:F1} dB re fundamental"); + // The vocal tract shapes the harmonics, so the reference is the strongest of them rather than the fundamental. + var strongest = Enumerable.Range(1, 6).Max(k => Magnitude(window, pitch * k)); + var worst = Db(Enumerable.Range(100, 900).Where(n => n % 343 != 0).Max(n => Magnitude(window, 8.0 * n)) / strongest); + output.WriteLine($"tilt 0 pitch {pitch}: worst non-harmonic level 800-8000 Hz {worst:F1} dB re strongest harmonic"); + Assert.True(worst < -32, $"non-harmonic energy {worst:F1} dB re strongest harmonic"); } [Fact] diff --git a/tests/AquaSynth.Dsl.Tests/NativeFaustRuntimeTests.cs b/tests/AquaSynth.Dsl.Tests/NativeFaustRuntimeTests.cs index 3e83ced..6c3ff1a 100644 --- a/tests/AquaSynth.Dsl.Tests/NativeFaustRuntimeTests.cs +++ b/tests/AquaSynth.Dsl.Tests/NativeFaustRuntimeTests.cs @@ -3,6 +3,7 @@ using AquaSynth.Faust; namespace AquaSynth.Dsl.Tests; +[Collection("NativeFaust")] public sealed class NativeFaustRuntimeTests { [Fact] @@ -169,7 +170,7 @@ public sealed class NativeFaustRuntimeTests var samples = patch.Render(controls); Assert.Contains("/vocal/sources/0/pressure", controls.Keys); - Assert.DoesNotContain("/vocal/radiation/0/reflection", controls.Keys); + Assert.Contains("/vocal/radiation/0/reflection", controls.Keys); Assert.True(samples.Length > 1024); Assert.Contains(samples, sample => MathF.Abs(sample) > 0.0001f); } diff --git a/tests/AquaSynth.Dsl.Tests/PatchScriptTests.cs b/tests/AquaSynth.Dsl.Tests/PatchScriptTests.cs index 9ace5ec..5e4eec0 100644 --- a/tests/AquaSynth.Dsl.Tests/PatchScriptTests.cs +++ b/tests/AquaSynth.Dsl.Tests/PatchScriptTests.cs @@ -316,7 +316,7 @@ public sealed class PatchScriptTests Assert.Contains("primitive_contact_voices_0_constriction", faust); Assert.Contains("primitive_branch_voices_0_velopharynx", faust); Assert.Contains("primitive_radiation_voices_0_lip", faust); - Assert.Contains("de.fdelay1a", faust); + Assert.Contains("primitive_ladder", faust); Assert.DoesNotContain("graph_loop ~ si.bus", faust); Assert.DoesNotContain("graph_terminal_area_voices_0_area_", faust); Assert.DoesNotContain("tract_lf", faust); @@ -462,7 +462,7 @@ public sealed class PatchScriptTests var export = FaustEmitter.Emit(patch, new FaustExportOptions("primitive_vocal", DebugProbeUi: true)); Assert.Contains("primitive_radiated", export.Source); - Assert.Contains("de.fdelay1a", export.Source); + Assert.Contains("primitive_ladder", export.Source); Assert.Contains("/debug/voice_0/path/oral/delay", export.Source); Assert.Contains("/debug/voice_0/path/oral/incoming_wave", export.Source); Assert.Contains("/debug/voice_0/path/oral/outgoing_wave", export.Source); @@ -986,7 +986,7 @@ public sealed class PatchScriptTests var export = FaustEmitter.Emit(patch, new FaustExportOptions("tract_graph")); Assert.Contains("primitive_radiated", export.Source); - Assert.Contains("de.fdelay1a", export.Source); + Assert.Contains("primitive_ladder", export.Source); Assert.Contains("primitive_source_voices_0_source", export.Source); Assert.Contains("primitive_radiation_voices_0_lip", export.Source); Assert.DoesNotContain("acoustic_graph_radiated", export.Source); @@ -1180,7 +1180,7 @@ public sealed class PatchScriptTests Assert.Contains("primitive_path_voices_0_oral", faust); Assert.Contains("primitive_branch_voices_0_velopharynx", faust); Assert.Contains("primitive_contact_voices_0_constriction", faust); - Assert.Contains("de.fdelay1a", faust); + Assert.Contains("primitive_ladder", faust); Assert.DoesNotContain("graph_loop ~ si.bus", faust); Assert.DoesNotContain("_wg_", faust); } diff --git a/tests/AquaSynth.Dsl.Tests/VocalTractFormantTests.cs b/tests/AquaSynth.Dsl.Tests/VocalTractFormantTests.cs new file mode 100644 index 0000000..ec7d20a --- /dev/null +++ b/tests/AquaSynth.Dsl.Tests/VocalTractFormantTests.cs @@ -0,0 +1,194 @@ +using AquaSynth.Dsl; +using AquaSynth.Faust; +using Xunit.Abstractions; + +namespace AquaSynth.Dsl.Tests; + +// The vocal_network resonator is a Kelly-Lochbaum ladder, so the same glottal source gives different vowels as the area +// function moves. These tests render through the native Faust path with a 10 Hz glottal source (a 10 Hz line spectrum +// samples the tract's response densely) and read formants as local maxima of the harmonic lines, flattened by the saw's 1/f. +// Expected values are the ladder prototype's impulse-response peaks (proto/kl.mjs, the same area model and constants). +[Collection("NativeFaust")] +public sealed class VocalTractFormantTests(ITestOutputHelper output) +{ + private const int Rate = 48000; + private const float Pitch = 10f; + + private static string Script(float tongueIndex, float tongueDiameter, float lipOpening, float velum = .01f) => $$""" + morphology name=oral length_cm=17 diameters=.55,.75,1.05,1.45,1.25,.8 tongue_index={{tongueIndex}} tongue_diameter={{tongueDiameter}} constriction_index=4 constriction_diameter=4 lip_opening={{lipOpening}} + morphology name=nasal length_cm=12 diameters=.04,.28,.52,.72 + waveguide_path name=oral_path morphology=oral loss=.998 + waveguide_path name=nasal_path morphology=nasal loss=.997 + source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.5 noise=0 impedance=.3 flow_scale=.12 tilt=0 + branch_port name=velopharynx from=oral_path from_position=.45 to=nasal_path opening={{velum}} coupling=1 + radiation_load name=mouth path=oral_path aperture=.8 reflection=-.82 impedance=.28 + radiation_load name=nostril path=nasal_path aperture=.8 reflection=-.82 impedance=.28 + vocal_network name=voice paths=oral_path,nasal_path sources=folds branches=velopharynx radiation=mouth,nostril + vocal network=voice freq={{Pitch}} min_freq=5 gain=.5 sustain=1.5 + """; + + // Three seconds of the 10 Hz source would be wasteful: one second after the attack is ten whole periods, so every + // harmonic of Pitch sits exactly on a DFT bin. + private float[]? Render(string script) + { + var source = FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions("vocal_formants", SampleRate: Rate)).Source; + using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate)); + if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("vocal_formants", "vocal_formants", ""), source, 1.4f, 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($"vocal formant compile failed: {error}"); + } + + using (patch) + { + var samples = patch!.Render(1.0f); + Assert.True(samples.Length >= Rate + 4800, $"render too short: {samples.Length}"); + return samples.Skip(4800).Take(Rate).ToArray(); + } + } + + // Harmonic line magnitudes of the saw, multiplied by frequency to undo its 1/f slope. + private static double[] Lines(float[] window) + { + var n = 1 << 16; + var re = new double[n]; + var im = new double[n]; + for (var i = 0; i < window.Length; i++) re[i] = window[i] * (0.5 - 0.5 * Math.Cos(2 * Math.PI * i / window.Length)); + Fft(re, im); + var lines = new double[(int)(5000 / Pitch) + 1]; + for (var k = 1; k < lines.Length; k++) + { + var bin = (int)Math.Round(k * Pitch * n / Rate); + lines[k] = Math.Sqrt(re[bin] * re[bin] + im[bin] * im[bin]) * k; + } + + return lines; + } + + // Local maxima of the flattened lines that are tallest within +-40 Hz and above 10% of the tallest, in ascending Hz. + private static double[] Peaks(float[] window) + { + var lines = Lines(window); + var span = (int)(40 / Pitch); + var floor = 0.1 * lines.Max(); + var peaks = new List(); + for (var k = (int)(150 / Pitch); k < lines.Length - span; k++) + { + if (lines[k] < floor) continue; + var tallest = true; + for (var j = k - span; j <= k + span; j++) tallest &= lines[j] <= lines[k]; + if (tallest) peaks.Add(k * Pitch); + } + + return peaks.ToArray(); + } + + private static void Fft(double[] re, double[] im) + { + var n = re.Length; + for (int i = 1, j = 0; i < n; i++) + { + var bit = n >> 1; + for (; (j & bit) != 0; bit >>= 1) j ^= bit; + j ^= bit; + if (i < j) { (re[i], re[j]) = (re[j], re[i]); (im[i], im[j]) = (im[j], im[i]); } + } + + for (var len = 2; len <= n; len <<= 1) + { + var angle = -2 * Math.PI / len; + for (var i = 0; i < n; i += len) + { + for (var k = 0; k < len / 2; k++) + { + double wr = Math.Cos(angle * k), wi = Math.Sin(angle * k); + var a = i + k; + var b = i + k + len / 2; + var vr = re[b] * wr - im[b] * wi; + var vi = re[b] * wi + im[b] * wr; + (re[b], im[b]) = (re[a] - vr, im[a] - vi); + (re[a], im[a]) = (re[a] + vr, im[a] + vi); + } + } + } + } + + public static TheoryData Vowels => new() + { + { "i", 3f, .15f, 2.2f, 271, 2313 }, + { "schwa", 2f, 1.2f, .6f, 497, 1503 }, + { "a", 1.5f, .5f, 2.2f, 731, 1257 }, + }; + + private double[]? FirstTwo(string name, float ti, float td, float lo) + { + var window = Render(Script(ti, td, lo)); + if (window is null) return null; + var peaks = Peaks(window); + output.WriteLine($"{name}: peaks " + string.Join(" ", peaks.Select(p => p.ToString("F0")))); + Assert.True(peaks.Length >= 2, $"{name}: fewer than two spectral peaks"); + return peaks; + } + + [Theory] + [MemberData(nameof(Vowels))] + public void VowelAreaFunctionsPlaceF1AndF2WhereThePrototypePlacedThem(string name, float ti, float td, float lo, double f1, double f2) + { + var peaks = FirstTwo(name, ti, td, lo); + if (peaks is null) return; + + Assert.InRange(peaks[0], f1 * .92, f1 * 1.08); + Assert.InRange(peaks[1], f2 * .92, f2 * 1.08); + } + + [Fact] + public void VowelsDifferInTheirFormants() + { + var i = FirstTwo("i", 3f, .15f, 2.2f); + var schwa = FirstTwo("schwa", 2f, 1.2f, .6f); + var a = FirstTwo("a", 1.5f, .5f, 2.2f); + if (i is null || schwa is null || a is null) return; + + // F1 rises i < schwa < a as the jaw opens; F2 falls i > schwa > a as the constriction moves back. + Assert.True(i[0] + 100 < schwa[0] && schwa[0] + 100 < a[0], $"F1 {i[0]} {schwa[0]} {a[0]}"); + Assert.True(i[1] > schwa[1] + 300 && schwa[1] > a[1] + 100, $"F2 {i[1]} {schwa[1]} {a[1]}"); + } + + [Fact] + public void LadderStaysBoundedForASecondWithTheVelumOpen() + { + foreach (var (ti, td, lo, velum) in new[] { (3f, .15f, 2.2f, .01f), (1.5f, .5f, 2.2f, 1f), (2f, 1.2f, .6f, 1f) }) + { + var window = Render(Script(ti, td, lo, velum)); + if (window is null) return; + var quarter = window.Length / 4; + var rms = Enumerable.Range(0, 4).Select(q => Math.Sqrt(window.Skip(q * quarter).Take(quarter).Sum(x => (double)x * x) / quarter)).ToArray(); + output.WriteLine($"velum {velum} ti {ti}: peak {window.Max(Math.Abs):F3} rms by quarter {string.Join(" ", rms.Select(r => r.ToString("E2")))}"); + Assert.All(window, sample => Assert.True(float.IsFinite(sample) && Math.Abs(sample) < 4, $"sample {sample}")); + Assert.True(rms[0] > 1e-4, $"silent: rms {rms[0]}"); + Assert.True(rms[3] < 2 * rms[0] + 1e-6 && rms[3] > rms[0] / 2, $"rms drifted {rms[0]:E2} -> {rms[3]:E2}"); + } + } + + private static double Rms(float[] window) => Math.Sqrt(window.Sum(x => (double)x * x) / window.Length); + + [Fact] + public void WithTheMouthClosedOnlyAnOpenVelumLetsSoundOutThroughTheNose() + { + // constriction_diameter .001 at tract index 4 shuts the oral ladder; the only way out is the junction into the nasal ladder. + string Closed(float velum) => Script(1.5f, .5f, 2.2f, velum) + .Replace("constriction_diameter=4", "constriction_diameter=.001", StringComparison.Ordinal) + .Replace("diameters=.04,.28,.52,.72", "diameters=.9,1.3,1.5,1.2", StringComparison.Ordinal); + var shut = Render(Closed(.01f)); + var open = Render(Closed(1f)); + if (shut is null || open is null) return; + + output.WriteLine($"mouth shut: velum closed rms {Rms(shut):E2}, velum open rms {Rms(open):E2}; open peaks {string.Join(" ", Peaks(open).Select(p => p.ToString("F0")))}"); + Assert.True(Rms(open) > 5 * Rms(shut), $"nasal output rms {Rms(open):E2} vs velum-closed {Rms(shut):E2}"); + } +}