diff --git a/AquaSynth.sln b/AquaSynth.sln index 1f71899..f0f9da0 100644 --- a/AquaSynth.sln +++ b/AquaSynth.sln @@ -13,6 +13,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AquaSynth.Dsl.Tests", "tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj", "{D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BirdSyrinxGolf", "tools\BirdSyrinxGolf\BirdSyrinxGolf.csproj", "{A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -59,6 +63,18 @@ Global {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}.Release|x64.Build.0 = Release|Any CPU {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}.Release|x86.ActiveCfg = Release|Any CPU {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}.Release|x86.Build.0 = Release|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x64.Build.0 = Debug|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x86.Build.0 = Debug|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|Any CPU.Build.0 = Release|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x64.ActiveCfg = Release|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x64.Build.0 = Release|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x86.ActiveCfg = Release|Any CPU + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -67,5 +83,6 @@ Global {43E2BCEB-0E0E-4E02-AE3D-4A1D0EBC2B31} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {10EDBE53-4957-44AB-90C9-82C2ABD526CD} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} EndGlobalSection EndGlobal diff --git a/research/bird-syrinx-golf/README.md b/research/bird-syrinx-golf/README.md new file mode 100644 index 0000000..45db440 --- /dev/null +++ b/research/bird-syrinx-golf/README.md @@ -0,0 +1,44 @@ +# Bird Syrinx Golf + +This sidequest uses Creative Commons bird recordings as a reality check for the graph-native syrinx path. The goal is not to make species-accurate bird impersonations yet. The goal is to force the paired-source syrinx graph to meet real calls, emit listenable WAVs, and expose which controls currently matter. + +## Source Set + +All references are Wikimedia Commons mirrors of xeno-canto recordings, with Commons file pages used as the license/provenance anchor and Commons MP3 transcodes used for robust local decoding. + +| id | species | call | author | license | source | +| --- | --- | --- | --- | --- | --- | +| `common-iora-xc125847` | Common Iora (`Aegithina tiphia`) | song | Sudipto Roy | CC BY-SA 3.0 | | +| `bohemian-waxwing-xc132884` | Bohemian Waxwing (`Bombycilla garrulus`) | flight call | Bushman | CC BY-SA 3.0 | | +| `california-quail-xc109825` | California Quail (`Callipepla californica`) | natural calls | Jonathon Jongsma | CC BY-SA 3.0 | | +| `american-crow-xc115429` | American Crow (`Corvus brachyrhynchos`) | soft rattling calls | Jonathon Jongsma | CC BY-SA 3.0 | | + +## Tool + +`tools/BirdSyrinxGolf` downloads the sources, extracts the loudest 1.2 second window, renders a small grid of graph-native Aqua syrinx candidates, and writes: + +- `reference-clip.wav` +- `candidate-syrinx.wav` +- `candidate-syrinx.aqua` +- `source.json` +- `report.txt` +- run-level `summary.md` + +The generated audio lives under `artifacts/bird-syrinx-golf//`, which is intentionally ignored by git. + +## First Run + +Run: `artifacts/bird-syrinx-golf/20260528T141443104` + +| bird | score | logMelCosine | best coarse control | +| --- | ---: | ---: | --- | +| Common Iora | 0.2423 | 0.2356 | `freq=1050`, high beak opening | +| Bohemian Waxwing | 0.2785 | 0.2778 | `freq=3000`, narrow labial opening | +| California Quail | 0.1888 | 0.3035 | `freq=760`, wider labial opening | +| American Crow | 0.2225 | 0.3654 | `freq=760`, wider labial opening | + +## Interpretation + +This proves the current graph source path can render paired-labium syrinx candidates against real CC bird audio. It does not prove the model is good. The search grid is deliberately coarse and mostly static; it cannot yet match call envelopes, syllable timing, pitch sweeps, side-to-side alternation, beak articulation, or turbulence bursts with enough authority. + +The useful finding is that the syrinx controls now form an inspectable fitting surface. The next coherent step is not a larger brute-force grid. It is time-varying control curves over the same graph: pressure envelopes, labial tension sweeps, independent left/right gating, beak opening, and possibly tract morphology changes when the reference call has obvious articulatory motion. diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 38495d3..50351c6 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -203,3 +203,4 @@ {"evidence":"Changed graph turbulence/release reservoir drive to use directed upstream-minus-downstream pressure at ordinary two-port path nodes (`max(0, upstream_incoming - downstream_incoming)`), with positive local incident pressure as the fallback for boundaries or more complex nodes. Focused structural/Faust checks, accepted utterance smoke, and static PT graph smoke passed. Latest utterance artifact `artifacts/parity/pink-trombone-utterance-logmel/20260528T115452268`; latest static artifact `artifacts/parity/pink-trombone-logmel/20260528T115719882`. Metrics still did not move.","claim":"Source-local reservoir direction is no longer the main explanation for weak plosives. The graph needs a contact/closure primitive that participates in scattering and flow, rather than a separate source pulse injected after the node law.","timestamp":"2026-05-28T13:05:00+01:00","topic":"acoustic-graph-directed-reservoir-drive"} {"evidence":"Removed legacy vocal audio authorities: `TractPropagationMode` now only accepts graph lowering, parser legacy values fail fast, the Faust `Voice.Tract` resonator/waveguide renderers were deleted, the acoustic response proxy fallback was removed, `WaveguideLoss` became graph `PropagationLoss`, `substeps` was rejected, and the Pink Trombone built-in plus graph tests now route through typed `AcousticPortNetwork` lowering. Verification: stale-symbol scan only finds historical evidence and explicit rejection tests; full DSL test suite passed 180 tests.","claim":"Vocal acoustics now have one live authority: the typed acoustic graph. `Voice.Tract`, PT-shaped commands, and built-ins are authoring sugar that populate graph records; they cannot secretly render old proxy/waveguide audio when the graph is missing or weak.","timestamp":"2026-05-28T13:40:00+01:00","topic":"legacy-vocal-renderer-cut"} {"evidence":"Added `AcousticSourcePort.Impedance`, parser aliases `impedance`/`load`/`source_impedance`, load-aware graph source lowering using node incident pressure, graph contact terminals with named closure/reservoir/release locals, generated tract contact terminals, a syrinx structural test, TractGraphRenderer `mode=syrinx`, and `patches/advanced/bird-syrinx.aqua`. Rendered `artifacts/audition/syrinx-graph-20260528b.wav` and `artifacts/audition/tract-contact-graph-20260528b.wav`; focused graph/PT parity smokes passed.","claim":"Source-tract coupling and closure storage are now graph-owned reusable semantics, not Pink Trombone-shaped gain hacks. A syrinx is expressible as paired loaded labial source ports feeding one acoustic graph through a merge junction and beak radiation, giving Mimir a differentiable bird-voice target surface.","timestamp":"2026-05-28T14:20:00+01:00","topic":"graph-source-load-contact-syrinx"} +{"evidence":"Added `tools/BirdSyrinxGolf`, a CC birdcall sidequest tool that downloads Commons/xeno-canto mirrored bird recordings, extracts loudest 1.2 second clips, renders graph-native paired-labium syrinx candidates through Faust, and writes reference/candidate WAVs plus reports under `artifacts/bird-syrinx-golf/`. First run `20260528T141443104` produced candidate WAVs for Common Iora, Bohemian Waxwing, California Quail, and American Crow with log-mel cosine similarities from 0.2356 to 0.3654.","claim":"The syrinx graph now has a real bird-audio fitting surface, but static coarse candidates are not enough for species-like calls. Next improvement should add time-varying pressure, labial tension, left/right gating, beak opening, and morphology curves over the same graph rather than a larger static brute-force grid.","timestamp":"2026-05-28T15:20:00+01:00","topic":"bird-syrinx-golf"} diff --git a/state/map.yaml b/state/map.yaml index bf91a37..50b48fa 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -20,6 +20,7 @@ surfaces: utterance_parity_research: docs/utterance-parity-research.md pink_trombone_parity: docs/pink-trombone-parity.md pink_trombone_dsl_parity_plan: docs/pink-trombone-dsl-parity-plan.md + bird_syrinx_golf_research: research/bird-syrinx-golf/README.md wet_voice_witness_fixture: tests/AquaSynth.Dsl.Tests/Fixtures/Speech/WetVoice01 faust_toolchain_boundary: docs/faust-toolchain-boundary.md dx7_public_domain_fixtures: tests/AquaSynth.Dsl.Tests/Fixtures/Dx7/PublicDomain @@ -31,6 +32,7 @@ surfaces: zyn_voice_reference_renderer: tools/zyn-reference/ZynVoiceReference.cpp vocal_tract_playground: tools/vocal-tract-playground/index.html tract_graph_renderer: tools/TractGraphRenderer/TractGraphRenderer.csproj + bird_syrinx_golf_tool: tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj zyn_reference_build_patches: tools/zyn-reference/patches zyn_project_fixtures: tests/AquaSynth.Dsl.Tests/Fixtures/ZynAddSubFX/ProjectAuthored core_package: AquaSynth.Core 0.1.0-alpha.3 @@ -75,6 +77,7 @@ modules: vocal_tract_learning_tests: tests/AquaSynth.Dsl.Tests/VocalTractLearningTests.cs vocal_tract_playground: tools/vocal-tract-playground tract_graph_renderer: tools/TractGraphRenderer + bird_syrinx_golf_tool: tools/BirdSyrinxGolf sfxr: src/AquaSynth.Core/SfxrParams.cs analysis: src/AquaSynth.Core/AudioAnalysis.cs mel_cepstral_warp_effect: src/AquaSynth.Core/MelCepstralWarpEffect.cs diff --git a/tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj b/tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj new file mode 100644 index 0000000..68bccc5 --- /dev/null +++ b/tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + Exe + net10.0 + enable + enable + + + diff --git a/tools/BirdSyrinxGolf/Program.cs b/tools/BirdSyrinxGolf/Program.cs new file mode 100644 index 0000000..a7654ae --- /dev/null +++ b/tools/BirdSyrinxGolf/Program.cs @@ -0,0 +1,474 @@ +using System.Globalization; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using AquaSynth.Dsl; +using AquaSynth.Faust; +using NAudio.Wave; +using NVorbis; + +var root = RepositoryRoot(); +var timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssfff", CultureInfo.InvariantCulture); +var runRoot = Path.Combine(root, "artifacts", "bird-syrinx-golf", timestamp); +var sourceRoot = Path.Combine(runRoot, "sources"); +var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; +BirdSource[] sources = +[ + new( + "common-iora-xc125847", + "Common Iora", + "Aegithina tiphia", + "song", + BirdKind.HarmonicSong, + "Sudipto Roy", + "CC BY-SA 3.0", + "https://creativecommons.org/licenses/by-sa/3.0", + "https://commons.wikimedia.org/wiki/File:Aegithina_tiphia_-_Common_Iora_XC125847.ogg", + "https://upload.wikimedia.org/wikipedia/commons/transcoded/7/7c/Aegithina_tiphia_-_Common_Iora_XC125847.ogg/Aegithina_tiphia_-_Common_Iora_XC125847.ogg.mp3", + "https://upload.wikimedia.org/wikipedia/commons/7/7c/Aegithina_tiphia_-_Common_Iora_XC125847.ogg"), + new( + "bohemian-waxwing-xc132884", + "Bohemian Waxwing", + "Bombycilla garrulus", + "flight call", + BirdKind.HighCall, + "Bushman", + "CC BY-SA 3.0", + "https://creativecommons.org/licenses/by-sa/3.0", + "https://commons.wikimedia.org/wiki/File:Bombycilla_garrulus_-_Bohemian_Waxwing_XC132884.ogg", + "https://upload.wikimedia.org/wikipedia/commons/transcoded/4/46/Bombycilla_garrulus_-_Bohemian_Waxwing_XC132884.ogg/Bombycilla_garrulus_-_Bohemian_Waxwing_XC132884.ogg.mp3", + "https://upload.wikimedia.org/wikipedia/commons/4/46/Bombycilla_garrulus_-_Bohemian_Waxwing_XC132884.ogg"), + new( + "california-quail-xc109825", + "California Quail", + "Callipepla californica", + "natural calls", + BirdKind.LowCall, + "Jonathon Jongsma", + "CC BY-SA 3.0", + "https://creativecommons.org/licenses/by-sa/3.0", + "https://commons.wikimedia.org/wiki/File:Callipepla_californica_-_California_Quail_-_XC109825.ogg", + "https://upload.wikimedia.org/wikipedia/commons/transcoded/3/3c/Callipepla_californica_-_California_Quail_-_XC109825.ogg/Callipepla_californica_-_California_Quail_-_XC109825.ogg.mp3", + "https://upload.wikimedia.org/wikipedia/commons/3/3c/Callipepla_californica_-_California_Quail_-_XC109825.ogg"), + new( + "american-crow-xc115429", + "American Crow", + "Corvus brachyrhynchos", + "soft rattling calls", + BirdKind.LowCall, + "Jonathon Jongsma", + "CC BY-SA 3.0", + "https://creativecommons.org/licenses/by-sa/3.0", + "https://commons.wikimedia.org/wiki/File:Corvus_brachyrhynchos_-_American_Crow_-_XC115429.ogg", + "https://upload.wikimedia.org/wikipedia/commons/transcoded/9/90/Corvus_brachyrhynchos_-_American_Crow_-_XC115429.ogg/Corvus_brachyrhynchos_-_American_Crow_-_XC115429.ogg.mp3", + "https://upload.wikimedia.org/wikipedia/commons/9/90/Corvus_brachyrhynchos_-_American_Crow_-_XC115429.ogg") +]; +Directory.CreateDirectory(sourceRoot); + +if (FaustCompiler.FindFaust() is null) +{ + Console.Error.WriteLine("Faust was not found on PATH or FAUST_HOME; cannot render Aqua syrinx candidates."); + return 2; +} + +using var http = new HttpClient(); +http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("AquaSynthBirdSyrinxGolf", "0.1")); +http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("(https://github.com/GameCult/AquaSynth)")); +http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/ogg")); +http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg")); + +var rows = new List(); +foreach (var source in sources) +{ + Console.WriteLine($"Fetching {source.Id} {source.CommonName}"); + var sourceDir = Path.Combine(sourceRoot, source.Id); + Directory.CreateDirectory(sourceDir); + var referencePath = Path.Combine(sourceDir, "reference.mp3"); + var downloadedFrom = source.FileUrls[0]; + if (!File.Exists(referencePath)) + { + downloadedFrom = await DownloadFirstAvailableAsync(http, source, referencePath); + } + + var decoded = DecodeMono(referencePath, downloadedFrom); + var target = LoudestWindow(decoded.Samples, decoded.SampleRate, 1.2f); + var target44 = Resample(target, decoded.SampleRate, 44100); + NormalizePeak(target44, 0.9f); + WriteWav(Path.Combine(sourceDir, "reference-clip.wav"), target44, 44100); + File.WriteAllText(Path.Combine(sourceDir, "source.json"), JsonSerializer.Serialize(new SourceSnapshot(source, downloadedFrom), jsonOptions)); + + var best = default(CandidateResult?); + var candidateIndex = 0; + foreach (var candidate in CandidateGrid(source)) + { + candidateIndex++; + var script = SyrinxScript(candidate, target44.Length / 44100f); + var export = FaustEmitter.EmitScript(script, new FaustExportOptions("bird_syrinx_candidate")); + var render = await FaustCompiler.RenderAsync(export.Source, new FaustRenderOptions(44100, target44.Length / 44100f)); + if (render is null || render.Samples.Length == 0) + { + Console.WriteLine($" candidate {candidateIndex:00}: render failed {render?.Stderr}"); + continue; + } + + var candidateSamples = MatchLength(render.Samples, target44.Length); + NormalizePeak(candidateSamples, 0.9f); + var comparison = AudioAnalyzer.CompareAudio(target44, candidateSamples); + var result = new CandidateResult(candidate, candidateSamples, comparison, script); + if (best is null || result.Comparison.Score > best.Comparison.Score) + { + best = result; + } + + Console.WriteLine(FormattableString.Invariant( + $" candidate {candidateIndex:00}: score={comparison.Score:0.0000} logMel={comparison.LogMelCosineSimilarity:0.0000} {candidate}")); + } + + if (best is null) + { + rows.Add(new ResultRow(source.Id, source.CommonName, "no-render", 0, 0, 0, 0, "")); + continue; + } + + WriteWav(Path.Combine(sourceDir, "candidate-syrinx.wav"), best.Samples, 44100); + File.WriteAllText(Path.Combine(sourceDir, "candidate-syrinx.aqua"), best.Script); + File.WriteAllText(Path.Combine(sourceDir, "report.txt"), Report(source, downloadedFrom, best)); + rows.Add(new ResultRow( + source.Id, + source.CommonName, + source.CallType, + best.Comparison.Score, + best.Comparison.LogMelCosineSimilarity, + best.Comparison.LogMelDistance, + best.Comparison.CentroidRatio, + best.Candidate.ToString())); +} + +File.WriteAllText(Path.Combine(runRoot, "summary.md"), Summary(rows)); +Console.WriteLine(runRoot); +return 0; + +static IEnumerable CandidateGrid(BirdSource source) +{ + var bases = source.Kind switch + { + BirdKind.HarmonicSong => new[] { 750f, 1050f, 1400f }, + BirdKind.HighCall => new[] { 1400f, 2200f, 3000f }, + BirdKind.LowCall => new[] { 260f, 480f, 760f }, + _ => new[] { 800f, 1300f, 2100f } + }; + var tensions = source.Kind == BirdKind.LowCall ? new[] { 0.28f, 0.5f } : new[] { 0.38f, 0.62f }; + var openings = source.Kind == BirdKind.HighCall ? new[] { 0.14f, 0.28f } : new[] { 0.20f, 0.38f }; + var loads = new[] { 0.85f }; + + foreach (var frequency in bases) + foreach (var tension in tensions) + foreach (var opening in openings) + foreach (var load in loads) + { + yield return new SyrinxCandidate( + frequency, + Pressure: source.Kind == BirdKind.LowCall ? 0.74f : 0.82f, + RightPressure: source.Kind == BirdKind.LowCall ? 0.62f : 0.70f, + Tension: tension, + RightTension: Math.Clamp(tension + 0.07f, 0, 1), + Opening: opening, + RightOpening: Math.Max(0.05f, opening * 0.88f), + Load: load, + BeakOpening: source.Kind == BirdKind.LowCall ? 0.75f : 0.95f, + Gain: source.Kind == BirdKind.LowCall ? 0.42f : 0.32f); + } +} + +static string SyrinxScript(SyrinxCandidate candidate, float durationSeconds) => + $$""" + patch gain=0.42 soft_clip=true + + path name=left_bronchus length_cm=3.8 diameters=.22,.30,.36,.42 + path name=right_bronchus length_cm=3.6 diameters=.20,.28,.34,.40 + path name=trachea length_cm=8.4 diameters=.38,.48,.56,.46 + + source_port name=left_labium path=left_bronchus kind=syrinx position=0 pressure={{F(candidate.Pressure)}} tension={{F(candidate.Tension)}} opening={{F(candidate.Opening)}} noise=.025 impedance={{F(candidate.Load)}} + source_port name=right_labium path=right_bronchus kind=syrinx position=0 pressure={{F(candidate.RightPressure)}} tension={{F(candidate.RightTension)}} opening={{F(candidate.RightOpening)}} noise=.02 balance=.96 impedance={{F(candidate.Load)}} + + terminal name=left_merge path=left_bronchus position=1 kind=junction area_scale=1 + terminal name=right_merge path=right_bronchus position=1 kind=junction area_scale=1 + terminal name=trachea_base path=trachea position=0 kind=junction area_scale=1 + connect name=syrinx_merge terminals=left_merge,right_merge,trachea_base law=area_scatter coupling=1 + + radiation_port name=beak path=trachea kind=beak position=1 opening={{F(candidate.BeakOpening)}} reflection=-.72 + wave_clock name=bird_clock strategy=linear max_delay=1024 smoothing_ms=2 + acoustic_network name=bird_syrinx path=trachea wave_clock=bird_clock sources=left_labium,right_labium radiation=beak terminals=left_merge,right_merge,trachea_base connections=syrinx_merge + acoustic network=bird_syrinx freq={{F(candidate.Frequency)}} gain={{F(candidate.Gain)}} sustain={{F(Math.Max(0.05f, durationSeconds - 0.12f))}} decay=.08 + """; + +static string Report(BirdSource source, string downloadedFrom, CandidateResult best) => + $""" + # {source.CommonName} ({source.ScientificName}) + + Source: {source.DescriptionUrl} + Downloaded file: {downloadedFrom} + License: {source.LicenseName} ({source.LicenseUrl}) + Author: {source.Author} + Call type: {source.CallType} + + Best candidate: + {best.Candidate} + + Metrics: + score={best.Comparison.Score:0.0000} + logMelCosine={best.Comparison.LogMelCosineSimilarity:0.0000} + logMelDistance={best.Comparison.LogMelDistance:0.0000} + rmsRatio={best.Comparison.RmsRatio:0.0000} + centroidRatio={best.Comparison.CentroidRatio:0.0000} + articulation={best.Comparison.Articulation.ArticulationScore:0.0000} + + This is a first graph-native syrinx golf pass, not an accepted species model. + """; + +static string Summary(IEnumerable rows) +{ + var builder = new StringBuilder(); + builder.AppendLine("# Bird Syrinx Golf"); + builder.AppendLine(); + builder.AppendLine("All references are Creative Commons files mirrored on Wikimedia Commons from xeno-canto. Candidates are graph-native Aqua syrinx patches using paired labial source ports."); + builder.AppendLine(); + builder.AppendLine("| id | bird | call | score | logMelCosine | logMelDistance | centroidRatio | candidate |"); + builder.AppendLine("| --- | --- | --- | ---: | ---: | ---: | ---: | --- |"); + foreach (var row in rows) + { + builder.AppendLine(CultureInfo.InvariantCulture, $"| {row.Id} | {row.Bird} | {row.Call} | {row.Score:0.0000} | {row.LogMelCosine:0.0000} | {row.LogMelDistance:0.0000} | {row.CentroidRatio:0.0000} | `{row.Candidate}` |"); + } + return builder.ToString(); +} + +static DecodedAudio DecodeMono(string path, string sourceUrl) +{ + if (sourceUrl.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) + { + return DecodeMp3Mono(path); + } + + return DecodeOggMono(path); +} + +static DecodedAudio DecodeMp3Mono(string path) +{ + using var reader = new AudioFileReader(path); + var interleaved = new float[4096 * reader.WaveFormat.Channels]; + var mono = new List(); + int read; + while ((read = reader.Read(interleaved, 0, interleaved.Length)) > 0) + { + for (var i = 0; i < read; i += reader.WaveFormat.Channels) + { + var sum = 0f; + for (var channel = 0; channel < reader.WaveFormat.Channels && i + channel < read; channel++) + { + sum += interleaved[i + channel]; + } + mono.Add(sum / reader.WaveFormat.Channels); + } + } + + return new DecodedAudio(reader.WaveFormat.SampleRate, mono.ToArray()); +} + +static DecodedAudio DecodeOggMono(string path) +{ + using var reader = new VorbisReader(path); + var interleaved = new float[4096 * reader.Channels]; + var mono = new List(); + int read; + while ((read = reader.ReadSamples(interleaved, 0, interleaved.Length)) > 0) + { + for (var i = 0; i < read; i += reader.Channels) + { + var sum = 0f; + for (var channel = 0; channel < reader.Channels && i + channel < read; channel++) + { + sum += interleaved[i + channel]; + } + mono.Add(sum / reader.Channels); + } + } + return new DecodedAudio(reader.SampleRate, mono.ToArray()); +} + +static async Task DownloadFirstAvailableAsync(HttpClient http, BirdSource source, string targetPath) +{ + Exception? lastError = null; + foreach (var url in source.FileUrls) + { + for (var attempt = 1; attempt <= 3; attempt++) + { + try + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); + if ((int)response.StatusCode == 429 && attempt < 3) + { + await Task.Delay(TimeSpan.FromSeconds(attempt * 2)); + continue; + } + + response.EnsureSuccessStatusCode(); + await using var remote = await response.Content.ReadAsStreamAsync(); + await using var local = File.Create(targetPath); + await remote.CopyToAsync(local); + return url; + } + catch (Exception ex) when (attempt < 3) + { + lastError = ex; + await Task.Delay(TimeSpan.FromSeconds(attempt * 2)); + } + catch (Exception ex) + { + lastError = ex; + break; + } + } + } + + throw new InvalidOperationException($"Could not download {source.Id} from any configured source URL.", lastError); +} + +static float[] LoudestWindow(IReadOnlyList samples, int sampleRate, float seconds) +{ + var length = Math.Min(samples.Count, Math.Max(1, (int)MathF.Round(sampleRate * seconds))); + if (samples.Count <= length) return samples.ToArray(); + + var hop = Math.Max(1, length / 8); + var bestStart = 0; + var bestEnergy = -1f; + for (var start = 0; start + length <= samples.Count; start += hop) + { + var energy = 0f; + for (var i = start; i < start + length; i++) energy += samples[i] * samples[i]; + if (energy > bestEnergy) + { + bestEnergy = energy; + bestStart = start; + } + } + + var window = new float[length]; + for (var i = 0; i < length; i++) window[i] = samples[bestStart + i]; + return window; +} + +static float[] Resample(IReadOnlyList samples, int sourceRate, int targetRate) +{ + if (sourceRate == targetRate) return samples.ToArray(); + var result = new float[Math.Max(1, (int)Math.Round(samples.Count * (double)targetRate / sourceRate))]; + for (var i = 0; i < result.Length; i++) + { + var position = i * (sourceRate / (double)targetRate); + var left = Math.Clamp((int)Math.Floor(position), 0, samples.Count - 1); + var right = Math.Clamp(left + 1, 0, samples.Count - 1); + var t = (float)(position - left); + result[i] = samples[left] * (1 - t) + samples[right] * t; + } + return result; +} + +static float[] MatchLength(IReadOnlyList samples, int length) +{ + var result = new float[length]; + for (var i = 0; i < result.Length && i < samples.Count; i++) result[i] = samples[i]; + return result; +} + +static void NormalizePeak(IList samples, float peak) +{ + var current = samples.Select(Math.Abs).DefaultIfEmpty(0).Max(); + if (current <= 0) return; + var gain = peak / current; + for (var i = 0; i < samples.Count; i++) samples[i] *= gain; +} + +static void WriteWav(string path, IReadOnlyList samples, int sampleRate) +{ + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var stream = File.Create(path); + using var writer = new BinaryWriter(stream, Encoding.ASCII); + var dataSize = samples.Count * sizeof(short); + writer.Write("RIFF"u8); + writer.Write(36 + dataSize); + 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(dataSize); + foreach (var sample in samples) + { + writer.Write((short)Math.Clamp(MathF.Round(sample * short.MaxValue), short.MinValue, short.MaxValue)); + } +} + +static string RepositoryRoot() +{ + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "AquaSynth.sln"))) + { + directory = directory.Parent; + } + return directory?.FullName ?? AppContext.BaseDirectory; +} + +static string F(float value) => value.ToString("0.######", CultureInfo.InvariantCulture); + +public enum BirdKind { HarmonicSong, HighCall, LowCall } + +public sealed record BirdSource( + string Id, + string CommonName, + string ScientificName, + string CallType, + BirdKind Kind, + string Author, + string LicenseName, + string LicenseUrl, + string DescriptionUrl, + params string[] FileUrls); + +public sealed record SourceSnapshot(BirdSource Source, string DownloadedFrom); + +public sealed record SyrinxCandidate( + float Frequency, + float Pressure, + float RightPressure, + float Tension, + float RightTension, + float Opening, + float RightOpening, + float Load, + float BeakOpening, + float Gain) +{ + public override string ToString() => + string.Create( + CultureInfo.InvariantCulture, + $"freq={Frequency:0.#} pressure={Pressure:0.###}/{RightPressure:0.###} tension={Tension:0.###}/{RightTension:0.###} opening={Opening:0.###}/{RightOpening:0.###} load={Load:0.###} beak={BeakOpening:0.###} gain={Gain:0.###}"); +} + +public sealed record CandidateResult(SyrinxCandidate Candidate, float[] Samples, AudioComparison Comparison, string Script); + +public sealed record ResultRow( + string Id, + string Bird, + string Call, + float Score, + float LogMelCosine, + float LogMelDistance, + float CentroidRatio, + string Candidate); + +public sealed record DecodedAudio(int SampleRate, float[] Samples);