Add bioacoustic contestant harness

This commit is contained in:
Meta Vens 2026-05-24 19:10:06 +01:00
commit 503356cb43
4 changed files with 760 additions and 2 deletions

2
.gitignore vendored
View file

@ -8,6 +8,8 @@ quartz-site/
calibration/runs/
artifacts/drivers/
artifacts/asio/
artifacts/bioacoustic-contestants/
artifacts/birdsong-reference/
tools/drivers/
tools/obs-spout2-plugin/
tools/src/

View file

@ -0,0 +1,118 @@
# Bioacoustic Contestants 2026-05-24
## Purpose
This pass moves the harness from "one current song, many decoder knobs" toward
actual contestants: different generated birdcall word shapes fight against the
same indexed cepstral decoder family and the same cepstral warp/blur damage.
The score is intentionally brutal:
```text
performance = sqrt(clamp(realtime / 50x, 0..1) * convergence)
anchor = sqrt(timing_accuracy * frequency_accuracy)
score = performance * anchor
```
- `convergence` is clock confidence times anchor coverage.
- `timing_accuracy` falls with clock-fit residual in samples.
- `frequency_accuracy` is current word identity precision; exact word identity
stands in for the emitted frequency contour until the decoder exposes
per-formant residuals.
- `realtime` is managed harness speed, not the final native SIMD/DSP shape.
## Contestants
- `current-birdcall`: current four-syllable formant word.
- `redpoll-trill`: fast repeated chips with strong temporal onsets.
- `robin-warble`: softer irregular phrase, wider curved formant motion.
- `thrush-ladder`: repeated interval ladder with a shifted reply.
- `thornbill-zigzag`: high-band fast zig-zag syllables.
- `nightingale-cascade`: dense pretty cascade; not yet in the fast receipt.
The first fast panel intentionally tested only the first four contestants,
two decoders, and clean/blur degradations so the loop could produce receipts
inside one turn.
## Fast Receipt
Run:
```powershell
dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --bioacoustic-contestants --seconds 0.5 --max-songs 4 --max-decoders 2 --max-degradations 2 --output artifacts/bioacoustic-contestants
```
Receipt:
`artifacts/bioacoustic-contestants/contestants-20260524-180639/contestant-summary.json`
Best result:
```text
song=robin-warble
decoder=compact-fast-index
degradation=blur-light
score=0.178
performance=0.178
anchor=1.000
timing=1.000
frequency=1.000
convergence=0.485
realtime=3.3x
correct=2/3
```
Read: `robin-warble` produces fewer anchors in the short window, but the anchors
that survive are clean. The current score rewards that more than many sloppy
anchors. This may be correct for clock acquisition, but the next pass should
separate "lock fast" from "lock beautifully once found" so the harness cannot
overvalue sparse perfection.
## Lessons
- The old decoder recognized words but emitted coarse proposal offsets. Timing
residuals were thousands of samples even when identity was correct.
- Adding waveform refinement around the winning word fixed some anchor cases
but was too slow when done as a one-sample brute scan.
- The current refiner is a two-stage phrase search: coarse scan, then fine
snap near the best basin. It is still managed and expensive, but it turns
feature identity into a real timing anchor for some contestants.
- `robin-warble` currently gives the best anchor accuracy under light blur.
- `current-birdcall` and `redpoll-trill` still identify words but often anchor
inside the motif instead of at the canonical motif start.
- The next scoring improvement should expose per-formant/frequency residuals
directly instead of using word identity as a proxy.
## Real Bird References
Xeno-canto API v3 now requires an API key, so this pass pulled Wikimedia Commons
mirrors of Xeno-canto recordings instead. Local reference files are under
`artifacts/birdsong-reference/`; they are research inputs and should not be
committed as repo source.
Downloaded references:
- Wattled Guan, `XC250442`, Niels Krabbe, CC BY-SA 3.0, Wikimedia Commons /
Xeno-canto mirror.
- Lesser Redpoll, `XC482789`, Pascal Christe, CC BY-SA 4.0, Wikimedia Commons /
Xeno-canto mirror.
- Brown Thornbill, `XC446870`, Wikimedia Commons / Xeno-canto mirror fetch was
attempted but the downloaded file was only 1990 bytes and should be treated
as invalid until re-fetched.
FFmpeg is not installed on this workstation, so these MP3/OGG references were
not decoded into mel-cepstral matrices in this pass. The generated contestants
encode observations from the metadata and known birdcall structure first:
redpoll-like trills, robin-like warbles, thrush-like interval ladders,
thornbill-like high zig-zags, and nightingale-like cascades.
## Next Cut
1. Install or vendor a decode path for Commons/Xeno-canto MP3/OGG references.
2. Extract real mel-cepstral contours: syllable onset density, frequency glide
slope, formant spacing, rhythm variance, and motif repetition.
3. Add per-formant frequency residual to the contestant score.
4. Promote the two-stage refiner into a streaming state model: predict next
expected word time from the current clock and only search a narrow basin.
5. Run the full contestant panel and keep mutating the top two shapes until
score improves rather than spreading attention across ornamental variants.

View file

@ -44,6 +44,17 @@ if (args.Any(arg => string.Equals(arg, "--bioacoustic-train", StringComparison.O
ParseStringOption(args, "--output", "artifacts/bioacoustic-training")).ConfigureAwait(false);
}
if (args.Any(arg => string.Equals(arg, "--bioacoustic-contestants", StringComparison.OrdinalIgnoreCase)))
{
return await RunBioacousticContestantsAsync(
ParseIntOption(args, "--sample-rate", MimirBioacousticTimeline.SampleRate),
ParseDoubleOption(args, "--seconds", 1.25),
ParseStringOption(args, "--output", "artifacts/bioacoustic-contestants"),
ParseIntOption(args, "--max-songs", MimirBioacousticContestants.BuiltIn.Count),
ParseIntOption(args, "--max-decoders", MimirBioacousticDecoderConfiguration.BuiltInProfiles.Count),
ParseIntOption(args, "--max-degradations", CepstralTrainingDegradationSettings().Count)).ConfigureAwait(false);
}
if (args.Any(arg => string.Equals(arg, "--bioacoustic-actuator-self-test", StringComparison.OrdinalIgnoreCase)))
{
return RunBioacousticActuatorSelfTest(
@ -699,6 +710,130 @@ static async Task<int> RunBioacousticTrainingAsync(int sampleRate, double second
return 0;
}
static async Task<int> RunBioacousticContestantsAsync(
int sampleRate,
double seconds,
string outputRoot,
int maxSongs,
int maxDecoders,
int maxDegradations)
{
var started = DateTimeOffset.UtcNow;
var runId = $"contestants-{started:yyyyMMdd-HHmmss}";
var runDirectory = Path.GetFullPath(Path.Combine(outputRoot, runId));
Directory.CreateDirectory(runDirectory);
var degradations = CepstralTrainingDegradationSettings().Take(Math.Max(1, maxDegradations)).ToArray();
var decoders = BioacousticTrainingHypotheses().Take(Math.Max(1, maxDecoders)).ToArray();
var results = new List<BioacousticContestantResult>();
foreach (var profile in MimirBioacousticContestants.BuiltIn.Take(Math.Max(1, maxSongs)))
{
var renderer = new MimirBioacousticContestantRenderer(profile);
var source = renderer.RenderSequenceMonoFloat(seconds, sampleRate);
var expectedEvents = renderer.ExpectedEvents(source.Length / (double)sampleRate);
var contestantDirectory = Path.Combine(runDirectory, profile.Id);
Directory.CreateDirectory(contestantDirectory);
WriteWave(Path.Combine(contestantDirectory, "source.wav"), source, sampleRate);
foreach (var decoder in decoders)
{
var index = BuildCepstralContestantWordIndex(sampleRate, decoder.Decoder, renderer);
foreach (var degradation in degradations)
{
var degraded = RoundTripThroughDegradedCepstrum(source, sampleRate, degradation, out var analysis);
var stamp = Stopwatch.GetTimestamp();
var observations = DecodeCepstralIndexedWordsWithContestantIndex(
degraded,
sampleRate,
expectedEvents.Count,
decoder.Decoder,
index,
renderer);
var decodeMs = Stopwatch.GetElapsedTime(stamp).TotalMilliseconds;
var correct = observations.Count(observation => expectedEvents.Contains(observation.EventIndex));
var precision = observations.Count == 0 ? 0.0 : correct / (double)observations.Count;
var recall = expectedEvents.Count == 0 ? 0.0 : correct / (double)expectedEvents.Count;
var confidence = observations.Count == 0 ? 0.0 : observations.Average(observation => observation.Confidence);
var clock = FitContestantClockHypothesis(observations, renderer, sampleRate, expectedEvents.Count);
var timingAccuracy = clock == null
? 0.0
: 1.0 / (1.0 + clock.MeanAbsoluteErrorSamples / Math.Max(1.0, sampleRate * 0.00025));
var frequencyAccuracy = precision;
var convergence = clock == null
? 0.0
: Math.Clamp(clock.AnchorCoverage, 0.0, 1.0) * Math.Clamp(clock.Confidence, 0.0, 1.0);
var realtime = decodeMs <= 0.0 ? double.PositiveInfinity : seconds * 1000.0 / decodeMs;
var performance = Math.Sqrt(Math.Clamp(realtime / 50.0, 0.0, 1.0) * Math.Max(0.0, convergence));
var anchorAccuracy = Math.Sqrt(Math.Max(0.0, timingAccuracy) * Math.Max(0.0, frequencyAccuracy));
var contestScore = performance * anchorAccuracy;
var result = new BioacousticContestantResult(
$"{runId}:{profile.Id}:{decoder.Id}:{degradation.Name}",
runId,
profile.Id,
profile.Kind.ToString(),
decoder.Id,
degradation.Name,
sampleRate,
seconds,
expectedEvents.Count,
observations.Count,
correct,
precision,
recall,
confidence,
timingAccuracy,
frequencyAccuracy,
convergence,
realtime,
contestScore,
decodeMs,
analysis.MelBins,
analysis.CepstralCoefficients,
clock == null
? new BioacousticClockHypothesisSnapshot(0, 0, 0, 0, 0, 0, 0)
: new BioacousticClockHypothesisSnapshot(
clock.AnchorCount,
clock.SourceOffsetSamples,
clock.EffectiveSampleRate,
clock.MeanAbsoluteErrorSamples,
clock.Confidence,
clock.Score,
clock.AnchorCoverage),
profile.BeautyNotes);
results.Add(result);
Console.WriteLine(
$"bioacoustic-contestant song={profile.Id} decoder={decoder.Id} degradation={degradation.Name} score={contestScore:0.000} perf={performance:0.000} anchor={anchorAccuracy:0.000} timing={timingAccuracy:0.000} freq={frequencyAccuracy:0.000} convergence={convergence:0.000} realtime={realtime:0.0}x correct={correct}/{expectedEvents.Count} observations={observations.Count} confidence={confidence:0.000}");
}
}
}
var summaryPath = Path.Combine(runDirectory, "contestant-summary.json");
await File.WriteAllTextAsync(
summaryPath,
JsonSerializer.Serialize(new
{
runId,
startedAtUtc = started.ToString("O"),
sampleRate,
seconds,
best = results.OrderByDescending(result => result.ContestScore).FirstOrDefault(),
bySong = results
.GroupBy(result => result.SongId)
.Select(group => new
{
song = group.Key,
average = group.Average(result => result.ContestScore),
best = group.Max(result => result.ContestScore),
worst = group.Min(result => result.ContestScore)
})
.OrderByDescending(row => row.average)
.ToArray(),
results
}, new JsonSerializerOptions { WriteIndented = true })).ConfigureAwait(false);
Console.WriteLine($"bioacoustic-contestants-run path={runDirectory} results={results.Count} best={results.OrderByDescending(result => result.ContestScore).First().SongId} score={results.Max(result => result.ContestScore):0.000}");
return results.Count > 0 && results.Max(result => result.ContestScore) > 0.10 ? 0 : 1;
}
static int RunPassiveSyncSelfTest()
{
const int sampleRate = 48_000;
@ -1719,6 +1854,51 @@ static IReadOnlyList<CepstralWordObservation> DecodeCepstralIndexedWordsWithInde
CepstralWordIndex templateIndex)
{
var motifSamples = MimirBioacousticTimeline.Default.RenderEventMonoFloat(0, sampleRate).Length;
return DecodeCepstralIndexedWordsCore(
samples,
sampleRate,
expectedEventCount,
options,
templateIndex,
motifSamples,
offset => PredictedBioacousticEventIndex(offset, sampleRate));
}
static IReadOnlyList<CepstralWordObservation> DecodeCepstralIndexedWordsWithContestantIndex(
float[] samples,
int sampleRate,
int expectedEventCount,
CepstralDecoderOptions options,
CepstralWordIndex templateIndex,
MimirBioacousticContestantRenderer? contestant)
{
var motifSamples = contestant?.RenderEventMonoFloat(0, sampleRate).Length
?? MimirBioacousticTimeline.Default.RenderEventMonoFloat(0, sampleRate).Length;
return DecodeCepstralIndexedWordsCore(
samples,
sampleRate,
expectedEventCount,
options,
templateIndex,
motifSamples,
offset => contestant == null
? PredictedBioacousticEventIndex(offset, sampleRate)
: PredictedBioacousticContestantEventIndex(offset, sampleRate, contestant.Profile.EventSpacingSeconds),
contestant == null
? null
: (offset, eventIndex, length) => RefineContestantOffset(samples, sampleRate, offset, length, contestant, eventIndex));
}
static IReadOnlyList<CepstralWordObservation> DecodeCepstralIndexedWordsCore(
float[] samples,
int sampleRate,
int expectedEventCount,
CepstralDecoderOptions options,
CepstralWordIndex templateIndex,
int motifSamples,
Func<int, ulong> predictEvent,
Func<int, ulong, int, double>? refineOffset = null)
{
var hopSamples = Math.Max(1, sampleRate / 1_000);
var energyTrace = WindowEnergy(samples, motifSamples, hopSamples);
var threshold = energyTrace.Length == 0
@ -1783,7 +1963,7 @@ static IReadOnlyList<CepstralWordObservation> DecodeCepstralIndexedWordsWithInde
continue;
}
var predictedEvent = PredictedBioacousticEventIndex(offset, sampleRate);
var predictedEvent = predictEvent(offset);
var best = candidateIndexes
.Select(index =>
{
@ -1802,7 +1982,10 @@ static IReadOnlyList<CepstralWordObservation> DecodeCepstralIndexedWordsWithInde
continue;
}
observations.Add(new CepstralWordObservation(best.Template.EventIndex, offset, confidence));
var refinedOffset = refineOffset == null
? offset
: refineOffset(offset, best.Template.EventIndex, motifSamples);
observations.Add(new CepstralWordObservation(best.Template.EventIndex, refinedOffset, confidence));
}
return observations
@ -1821,6 +2004,84 @@ static ulong PredictedBioacousticEventIndex(double sampleOffset, int sampleRate)
return (ulong)Math.Max(0, index);
}
static ulong PredictedBioacousticContestantEventIndex(double sampleOffset, int sampleRate, double eventSpacingSeconds)
{
const double firstEventSeconds = MimirBioacousticContestants.FirstEventSeconds;
var index = (long)Math.Round((sampleOffset / sampleRate - firstEventSeconds) / eventSpacingSeconds);
return (ulong)Math.Max(0, index);
}
static double RefineContestantOffset(
float[] samples,
int sampleRate,
int coarseOffset,
int motifSamples,
MimirBioacousticContestantRenderer contestant,
ulong eventIndex)
{
var template = contestant.RenderEventMonoFloat(eventIndex, sampleRate);
var searchRadius = Math.Max(4, sampleRate / 16);
var start = Math.Max(0, coarseOffset - searchRadius);
var end = Math.Min(samples.Length - motifSamples, coarseOffset + searchRadius);
if (start > end)
{
return coarseOffset;
}
var coarseStep = Math.Max(1, sampleRate / 2_000);
var bestOffset = ScoreContestantOffset(samples, template, start, motifSamples) > ScoreContestantOffset(samples, template, coarseOffset, motifSamples)
? start
: coarseOffset;
var bestScore = ScoreContestantOffset(samples, template, bestOffset, motifSamples);
for (var offset = start; offset <= end; offset += coarseStep)
{
var score = ScoreContestantOffset(samples, template, offset, motifSamples);
if (score > bestScore)
{
bestScore = score;
bestOffset = offset;
}
}
var fineStart = Math.Max(start, bestOffset - coarseStep);
var fineEnd = Math.Min(end, bestOffset + coarseStep);
for (var offset = fineStart; offset <= fineEnd; offset++)
{
var score = ScoreContestantOffset(samples, template, offset, motifSamples);
if (score > bestScore)
{
bestScore = score;
bestOffset = offset;
}
}
return bestOffset;
}
static double ScoreContestantOffset(float[] samples, float[] template, int offset, int motifSamples)
{
if (offset < 0 || offset + motifSamples > samples.Length)
{
return double.NegativeInfinity;
}
var dot = 0.0;
var sampleEnergy = 0.0;
var templateEnergy = 0.0;
for (var index = 0; index < Math.Min(motifSamples, template.Length); index++)
{
var sample = samples[offset + index];
var expected = template[index];
dot += sample * expected;
sampleEnergy += sample * sample;
templateEnergy += expected * expected;
}
return sampleEnergy <= 1.0e-12 || templateEnergy <= 1.0e-12
? double.NegativeInfinity
: dot / Math.Sqrt(sampleEnergy * templateEnergy);
}
static CepstralWordIndex BuildCepstralWordIndex(int sampleRate, CepstralDecoderOptions options)
{
var templates = new List<CepstralWordTemplate>(MimirBioacousticTimeline.SymbolCount);
@ -1836,6 +2097,34 @@ static CepstralWordIndex BuildCepstralWordIndex(int sampleRate, CepstralDecoderO
}
}
return BuildCepstralWordIndexFromTemplates(templates, options);
}
static CepstralWordIndex BuildCepstralContestantWordIndex(
int sampleRate,
CepstralDecoderOptions options,
MimirBioacousticContestantRenderer contestant)
{
var templates = new List<CepstralWordTemplate>(MimirBioacousticTimeline.SymbolCount);
for (ulong eventIndex = 0; eventIndex < MimirBioacousticTimeline.SymbolCount; eventIndex++)
{
var samples = contestant.RenderEventMonoFloat(eventIndex, sampleRate);
foreach (var setting in options.TemplateAugmentations)
{
var templateSamples = setting.BlurPasses == 0 && setting.WarpFrames == 0.0 && setting.WarpCoefficients == 0.0
? samples
: RoundTripThroughDegradedCepstrum(samples, sampleRate, setting, out _);
templates.Add(new CepstralWordTemplate(eventIndex, CepstralFingerprintWithOptions(templateSamples, sampleRate, options)));
}
}
return BuildCepstralWordIndexFromTemplates(templates, options);
}
static CepstralWordIndex BuildCepstralWordIndexFromTemplates(
List<CepstralWordTemplate> templates,
CepstralDecoderOptions options)
{
var buckets = new Dictionary<(int Table, int Hash), List<int>>();
for (var index = 0; index < templates.Count; index++)
{
@ -1951,6 +2240,68 @@ static MimirBioacousticClockHypothesis? FitBioacousticClockHypothesis(
sampleRate,
observations.Count);
static MimirBioacousticClockHypothesis? FitContestantClockHypothesis(
IReadOnlyList<CepstralWordObservation> observations,
MimirBioacousticContestantRenderer contestant,
int sampleRate,
int expectedEventCount)
{
var anchors = observations
.Select(observation => new MimirBioacousticClockAnchor(
observation.EventIndex,
contestant.EventStartSeconds(observation.EventIndex),
observation.SampleOffset,
Math.Clamp(observation.Confidence, 0.001, 1.0)))
.OrderByDescending(anchor => anchor.Confidence)
.Take(24)
.ToArray();
if (anchors.Length == 0)
{
return null;
}
var totalWeight = anchors.Sum(anchor => Math.Max(1.0e-6, anchor.Confidence));
var meanTimeline = anchors.Sum(anchor => anchor.TimelineSeconds * Math.Max(1.0e-6, anchor.Confidence)) / totalWeight;
var meanSample = anchors.Sum(anchor => anchor.SampleOffset * Math.Max(1.0e-6, anchor.Confidence)) / totalWeight;
var covariance = 0.0;
var variance = 0.0;
foreach (var anchor in anchors)
{
var weight = Math.Max(1.0e-6, anchor.Confidence);
var dt = anchor.TimelineSeconds - meanTimeline;
covariance += weight * dt * (anchor.SampleOffset - meanSample);
variance += weight * dt * dt;
}
var effectiveRate = anchors.Length >= 3 && variance > 1.0e-12 ? covariance / variance : sampleRate;
if (!double.IsFinite(effectiveRate) || effectiveRate < sampleRate * 0.98 || effectiveRate > sampleRate * 1.02)
{
effectiveRate = sampleRate;
}
var sourceOffset = meanSample - effectiveRate * meanTimeline;
var residual = anchors.Sum(anchor =>
{
var predicted = sourceOffset + anchor.TimelineSeconds * effectiveRate;
return Math.Abs(anchor.SampleOffset - predicted) * Math.Max(1.0e-6, anchor.Confidence);
}) / totalWeight;
var residualConfidence = 1.0 / (1.0 + residual / Math.Max(1.0, sampleRate * 0.001));
var countConfidence = Math.Clamp(anchors.Length / 5.0, 0.0, 1.0);
var anchorConfidence = Math.Clamp(anchors.Average(anchor => anchor.Confidence), 0.0, 1.0);
var confidence = residualConfidence * 0.35 + countConfidence * 0.45 + anchorConfidence * 0.20;
var coverage = expectedEventCount <= 0 ? 0.0 : anchors.Length / (double)expectedEventCount;
var score = confidence + Math.Min(anchors.Length, 8) * 0.15 - residual / Math.Max(1.0, sampleRate * 0.010);
return new MimirBioacousticClockHypothesis(
sourceOffset,
effectiveRate,
anchors.Length,
coverage,
residual,
confidence,
score,
anchors);
}
static double CepstralDistance(IReadOnlyList<double> first, IReadOnlyList<double> second)
{
var sum = 0.0;
@ -2666,3 +3017,29 @@ public sealed record BioacousticTrainingObservation(
[property: Key(0)] ulong EventIndex,
[property: Key(1)] double SampleOffset,
[property: Key(2)] double Confidence);
public sealed record BioacousticContestantResult(
string ResultId,
string RunId,
string SongId,
string SongKind,
string DecoderId,
string DegradationName,
int SampleRate,
double Seconds,
int ExpectedEvents,
int ObservedEvents,
int CorrectEvents,
double Precision,
double Recall,
double Confidence,
double TimingAccuracy,
double FrequencyAccuracy,
double Convergence,
double RealtimeFactor,
double ContestScore,
double DecodeMilliseconds,
int RoundTripMelBins,
int RoundTripCepstralCoefficients,
BioacousticClockHypothesisSnapshot ClockHypothesis,
string BeautyNotes);

View file

@ -0,0 +1,261 @@
namespace Mimir.Runtime.Synchronization;
public enum MimirBioacousticContestantKind
{
CurrentBirdcall,
RedpollTrill,
RobinWarble,
ThrushLadder,
ThornbillZigZag,
NightingaleCascade
}
public sealed record MimirBioacousticContestantProfile(
string Id,
string Description,
MimirBioacousticContestantKind Kind,
int SyllableCount,
double MotifDurationSeconds,
double EventSpacingSeconds,
double LowestRootHz,
double HighestRootHz,
double Gain,
string BeautyNotes);
public static class MimirBioacousticContestants
{
public const double FirstEventSeconds = 0.08;
public const int WordCount = 128;
public const int SpeakerCount = 2;
public const int SymbolCount = WordCount * SpeakerCount;
public static MimirBioacousticContestantProfile CurrentBirdcall { get; } = new(
"current-birdcall",
"The current four-syllable formant word.",
MimirBioacousticContestantKind.CurrentBirdcall,
SyllableCount: 4,
MotifDurationSeconds: 0.118,
EventSpacingSeconds: 0.160,
LowestRootHz: 2_600.0,
HighestRootHz: 9_600.0,
Gain: 0.030,
"Musical enough, but still sounds like a lab bird with a clipboard.");
public static MimirBioacousticContestantProfile RedpollTrill { get; } = new(
"redpoll-trill",
"Fast repeated chips with tiny frequency steps and strong onset timing.",
MimirBioacousticContestantKind.RedpollTrill,
SyllableCount: 7,
MotifDurationSeconds: 0.126,
EventSpacingSeconds: 0.165,
LowestRootHz: 3_200.0,
HighestRootHz: 10_800.0,
Gain: 0.025,
"Pretty, bright, and temporally sharp; risks weak identity if the trills blur together.");
public static MimirBioacousticContestantProfile RobinWarble { get; } = new(
"robin-warble",
"Irregular soft phrases with curved syllables and wider formant motion.",
MimirBioacousticContestantKind.RobinWarble,
SyllableCount: 6,
MotifDurationSeconds: 0.142,
EventSpacingSeconds: 0.185,
LowestRootHz: 2_200.0,
HighestRootHz: 8_600.0,
Gain: 0.024,
"Most plausible room sound; slower lock and softer onsets are the price.");
public static MimirBioacousticContestantProfile ThrushLadder { get; } = new(
"thrush-ladder",
"Repeated interval ladders: two crisp notes, a shifted reply, then a flourish.",
MimirBioacousticContestantKind.ThrushLadder,
SyllableCount: 5,
MotifDurationSeconds: 0.132,
EventSpacingSeconds: 0.170,
LowestRootHz: 2_400.0,
HighestRootHz: 9_200.0,
Gain: 0.027,
"Good identity geometry: repetition plus interval ratios. Less subtle.");
public static MimirBioacousticContestantProfile ThornbillZigZag { get; } = new(
"thornbill-zigzag",
"Tiny high-band zig-zag syllables inspired by thornbill chatter.",
MimirBioacousticContestantKind.ThornbillZigZag,
SyllableCount: 8,
MotifDurationSeconds: 0.112,
EventSpacingSeconds: 0.155,
LowestRootHz: 4_200.0,
HighestRootHz: 13_200.0,
Gain: 0.021,
"Excellent frequency fingerprint if the path keeps high band alive; fragile on dull mics.");
public static MimirBioacousticContestantProfile NightingaleCascade { get; } = new(
"nightingale-cascade",
"Dense rising and falling cascades with phrase-level frequency punctuation.",
MimirBioacousticContestantKind.NightingaleCascade,
SyllableCount: 9,
MotifDurationSeconds: 0.150,
EventSpacingSeconds: 0.195,
LowestRootHz: 1_800.0,
HighestRootHz: 11_200.0,
Gain: 0.023,
"The prettiest contestant; expensive and easiest to confuse under heavy smearing.");
public static IReadOnlyList<MimirBioacousticContestantProfile> BuiltIn { get; } =
[
CurrentBirdcall,
RedpollTrill,
RobinWarble,
ThrushLadder,
ThornbillZigZag,
NightingaleCascade
];
}
public sealed class MimirBioacousticContestantRenderer(MimirBioacousticContestantProfile profile)
{
public MimirBioacousticContestantProfile Profile { get; } = profile;
public double EventStartSeconds(ulong eventIndex) =>
MimirBioacousticContestants.FirstEventSeconds + eventIndex * Profile.EventSpacingSeconds;
public float[] RenderEventMonoFloat(ulong eventIndex, int sampleRate)
{
var samples = new float[Math.Max(1, (int)Math.Round(Profile.MotifDurationSeconds * sampleRate))];
AddEvent(samples, sampleRate, eventIndex, EventStartSeconds(eventIndex), EventStartSeconds(eventIndex));
return samples;
}
public float[] RenderSequenceMonoFloat(double seconds, int sampleRate)
{
var samples = new float[Math.Max(1, (int)Math.Round(seconds * sampleRate))];
var lastEvent = Math.Max(0, (int)Math.Ceiling((seconds - MimirBioacousticContestants.FirstEventSeconds) / Profile.EventSpacingSeconds) + 2);
for (var eventIndex = 0; eventIndex <= lastEvent; eventIndex++)
{
AddEvent(samples, sampleRate, (ulong)eventIndex, EventStartSeconds((ulong)eventIndex), 0.0);
}
return samples;
}
public int ExpectedEventCount(double seconds) =>
Math.Max(0, (int)Math.Floor((seconds - MimirBioacousticContestants.FirstEventSeconds) / Profile.EventSpacingSeconds) + 1);
public IReadOnlySet<ulong> ExpectedEvents(double seconds) =>
Enumerable.Range(0, ExpectedEventCount(seconds)).Select(index => (ulong)index).ToHashSet();
private void AddEvent(float[] output, int sampleRate, ulong eventIndex, double eventStartSeconds, double bufferStartSeconds)
{
var symbolId = SymbolForEvent(eventIndex);
var root = RootForSymbol(symbolId);
var rng = Mix(symbolId, (uint)Profile.Kind);
for (var syllable = 0; syllable < Profile.SyllableCount; syllable++)
{
var contour = SyllableContour(symbolId, syllable, root, rng);
var start = eventStartSeconds - bufferStartSeconds + contour.StartSeconds;
AddSyllable(output, sampleRate, start, contour.DurationSeconds, contour.StartHz, contour.EndHz, Profile.Gain * contour.Weight);
}
}
private (double StartSeconds, double DurationSeconds, double StartHz, double EndHz, double Weight) SyllableContour(
int symbolId,
int syllable,
double root,
uint rng)
{
var jitter = (((rng >> (syllable % 12)) & 7) - 3) * 0.0013;
var phase = ((symbolId * 17 + syllable * 31) & 255) / 255.0;
return Profile.Kind switch
{
MimirBioacousticContestantKind.RedpollTrill => (
StartSeconds: syllable * Profile.MotifDurationSeconds / (Profile.SyllableCount + 0.7) + jitter,
DurationSeconds: Profile.MotifDurationSeconds * 0.095,
StartHz: root * (1.0 + 0.018 * syllable + 0.025 * Math.Sin(phase * Math.Tau)),
EndHz: root * (1.0 + 0.030 * syllable + 0.018 * Math.Cos(phase * Math.Tau)),
Weight: syllable % 2 == 0 ? 0.95 : 0.72),
MimirBioacousticContestantKind.RobinWarble => (
StartSeconds: syllable * Profile.MotifDurationSeconds / (Profile.SyllableCount + 0.35) + jitter * 1.4,
DurationSeconds: Profile.MotifDurationSeconds * (0.115 + 0.015 * ((symbolId + syllable) % 3)),
StartHz: root * Ratio(0.72 + 0.08 * ((symbolId >> (syllable % 5)) & 3)),
EndHz: root * Ratio(1.05 + 0.10 * ((symbolId + syllable * 3) & 3)),
Weight: 0.62 + 0.30 * Math.Sin((phase + 0.2) * Math.Tau) * Math.Sin((phase + 0.2) * Math.Tau)),
MimirBioacousticContestantKind.ThrushLadder => (
StartSeconds: syllable * Profile.MotifDurationSeconds / (Profile.SyllableCount + 0.5),
DurationSeconds: Profile.MotifDurationSeconds * 0.13,
StartHz: root * Ratio(0.75 + 0.16 * ((syllable + (symbolId & 3)) % 5)),
EndHz: root * Ratio(0.78 + 0.16 * ((syllable + 1 + ((symbolId >> 2) & 3)) % 5)),
Weight: syllable is 0 or 2 ? 1.0 : 0.70),
MimirBioacousticContestantKind.ThornbillZigZag => (
StartSeconds: syllable * Profile.MotifDurationSeconds / (Profile.SyllableCount + 0.2) + jitter * 0.6,
DurationSeconds: Profile.MotifDurationSeconds * 0.075,
StartHz: root * (syllable % 2 == 0 ? 0.88 : 1.18) * (1.0 + 0.010 * (symbolId & 7)),
EndHz: root * (syllable % 2 == 0 ? 1.22 : 0.92) * (1.0 + 0.012 * ((symbolId >> 3) & 7)),
Weight: 0.75),
MimirBioacousticContestantKind.NightingaleCascade => (
StartSeconds: syllable * Profile.MotifDurationSeconds / (Profile.SyllableCount + 0.55) + jitter,
DurationSeconds: Profile.MotifDurationSeconds * 0.095,
StartHz: root * Ratio(0.62 + 0.09 * ((symbolId + syllable) % 8)),
EndHz: root * Ratio(1.20 - 0.07 * ((symbolId / 3 + syllable) % 7)),
Weight: syllable is 2 or 5 or 8 ? 0.95 : 0.58),
_ => (
StartSeconds: syllable * Profile.MotifDurationSeconds / (Profile.SyllableCount + 0.6) + jitter,
DurationSeconds: Profile.MotifDurationSeconds * 0.11,
StartHz: root * Ratio(0.80 + 0.11 * ((symbolId + syllable) & 3)),
EndHz: root * Ratio(0.92 + 0.10 * (((symbolId >> 2) + syllable * 2) & 3)),
Weight: syllable is 0 or 3 ? 0.92 : 0.68)
};
}
private static int SymbolForEvent(ulong eventIndex) =>
(int)((eventIndex * 73UL + eventIndex / 5UL * 19UL) % MimirBioacousticContestants.SymbolCount);
private double RootForSymbol(int symbolId)
{
var t = symbolId / (double)(MimirBioacousticContestants.SymbolCount - 1);
var logMin = Math.Log(Profile.LowestRootHz);
var logMax = Math.Log(Profile.HighestRootHz);
return Math.Exp(logMin + (logMax - logMin) * t);
}
private static double Ratio(double semitones) => Math.Pow(2.0, semitones / 12.0);
private static uint Mix(int symbolId, uint salt)
{
var value = (uint)symbolId * 0x9E3779B9u + salt * 0x85EBCA6Bu;
value ^= value >> 16;
value *= 0x7FEB352Du;
value ^= value >> 15;
return value;
}
private static void AddSyllable(
float[] output,
int sampleRate,
double startSeconds,
double durationSeconds,
double startHz,
double endHz,
double gain)
{
var startSample = Math.Max(0, (int)Math.Floor(startSeconds * sampleRate));
var endSample = Math.Min(output.Length, (int)Math.Ceiling((startSeconds + durationSeconds) * sampleRate));
if (endSample <= startSample)
{
return;
}
var phase = 0.0;
var previousFrequency = startHz;
for (var sample = startSample; sample < endSample; sample++)
{
var t = (sample / (double)sampleRate - startSeconds) / durationSeconds;
var curved = t * t * (3.0 - 2.0 * t);
var frequency = startHz + (endHz - startHz) * curved;
phase += Math.Tau * (previousFrequency + frequency) * 0.5 / sampleRate;
previousFrequency = frequency;
var envelope = Math.Sin(Math.PI * Math.Clamp(t, 0.0, 1.0));
var harmonic = 0.28 * Math.Sin(phase * 2.0 + 0.25) + 0.12 * Math.Sin(phase * 3.0 + 0.7);
output[sample] += (float)(gain * envelope * (Math.Sin(phase) + harmonic));
}
}
}