Add loopback-relative waveform path fitting

This commit is contained in:
Meta Vens 2026-05-25 00:29:35 +01:00
commit 745758e4d0
6 changed files with 22313 additions and 4268 deletions

File diff suppressed because it is too large Load diff

View file

@ -223,6 +223,17 @@ MAE, but physical mics do not improve yet: shotgun is 36/37 payload at
56.365 us MAE and cardioid is 27/37 payload at 101.522 us MAE. Treat this as
anchor observability, not a finished anchor geometry. The next cut should learn
which anchor kinds survive each acoustic path and weight or reshape them.
Path-level loopback truth is now part of the calibration receipt: candidate mic
anchors are matched against loopback anchors, then event-local waveform
correlation against the captured loopback packet refines path delay. On the
stored anchor-rich capture this improves physical path precision to 7.576 us
for the cardioid and 6.578 us for the shotgun while Release runs at 21.1x
realtime. A fresh capture at
`calibration/bioacoustic/scarlett-canary-packet-anchor-rich-latest-192k.json`
keeps the shotgun around 5.916 us but worsens the cardioid to 18.930 us. The
rejected razor timing-chip mutation made the mics worse and should not be
revived without a better hypothesis. The remaining gap to one microsecond is
phase/group-delay correction or a more survivable direct-path anchor family.
The first actuator proof now exists: `faust/mimir_alignment_actuator.dsp` owns
six channels of bounded fractional delay/gain controls for Faust/native DSP,
and `Mimir.BufferSmoke --bioacoustic-actuator-self-test --sample-rate 48000

View file

@ -1727,7 +1727,12 @@ static int CalibrateContestantAsioFloat32(
stopwatch.Stop();
var reference = channelCalibrations[referenceChannel];
var paths = channelCalibrations
.Select(channel => BuildContestantPathCalibration(reference, channel, sampleRate))
.Select((channel, index) => BuildContestantPathCalibration(
reference,
channel,
sampleRate,
channelSamples[referenceChannel],
channelSamples[index]))
.ToArray();
var analyzedAudioSeconds = captureSeconds * channels;
var realtimeFactor = analyzedAudioSeconds / Math.Max(stopwatch.Elapsed.TotalSeconds, 1.0e-9);
@ -1768,7 +1773,7 @@ static int CalibrateContestantAsioFloat32(
foreach (var path in paths)
{
Console.WriteLine(
$"contestant-calibration-path {path.ReferenceSourceId}->{path.SourceId}: delaySamples={path.DelaySamples:0.000000} delayUs={path.DelayMicroseconds:0.000} syncMaeUs={path.SyncMeanAbsoluteErrorMicroseconds:0.000} confidence={path.Confidence:0.000} gain={path.RelativeGain:0.000} polarity={path.RelativePolarity:+0;-0;0} normalizedBands={path.ResponseNormalizationBands.Count(band => band.Usable)}/{path.ResponseNormalizationBands.Length}");
$"contestant-calibration-path {path.ReferenceSourceId}->{path.SourceId}: delaySamples={path.DelaySamples:0.000000} delayUs={path.DelayMicroseconds:0.000} syncMaeUs={path.SyncMeanAbsoluteErrorMicroseconds:0.000} confidence={path.Confidence:0.000} waveform={path.WaveformConfidence:0.000} gain={path.RelativeGain:0.000} polarity={path.RelativePolarity:+0;-0;0} matchedAnchors={path.MatchedAnchors} normalizedBands={path.ResponseNormalizationBands.Count(band => band.Usable)}/{path.ResponseNormalizationBands.Length}");
}
if (realtimeFactor < minRealtimeFactor)
@ -2696,7 +2701,7 @@ static double EstimateContestantScheduleOffset(
var coarseStep = Math.Max(4, sampleRate / 6_000);
var stride = Math.Max(4, sampleRate / 24_000);
var scoringEvents = expectedEvents
.Take(Math.Min(14, expectedEvents.Count))
.Take(Math.Min(8, expectedEvents.Count))
.ToArray();
var scoringTemplates = scoringEvents
.Select(eventIndex => (
@ -2820,7 +2825,7 @@ static BioacousticPhysicalAnchorCalibration[] MeasureContestantAnchors(
var output = new List<BioacousticPhysicalAnchorCalibration>(anchors.Count);
foreach (var anchor in anchors
.OrderByDescending(anchor => anchor.Weight)
.Take(8)
.Take(6)
.OrderBy(anchor => anchor.StartSeconds))
{
var anchorSamples = Math.Clamp(
@ -3105,7 +3110,9 @@ static BioacousticPhysicalBandCalibration[] CollapseContestantBands(IReadOnlyLis
static BioacousticPhysicalPathCalibration BuildContestantPathCalibration(
BioacousticPhysicalChannelCalibration reference,
BioacousticPhysicalChannelCalibration candidate,
int sampleRate)
int sampleRate,
float[] referenceSamples,
float[] candidateSamples)
{
var candidateByEvent = candidate.Events.ToDictionary(observation => observation.EventIndex);
var matched = reference.Events
@ -3123,6 +3130,37 @@ static BioacousticPhysicalPathCalibration BuildContestantPathCalibration(
var mae = matched.Length == 0
? Math.Abs(candidate.MeanAbsoluteErrorSamples - reference.MeanAbsoluteErrorSamples)
: matched.Sum(pair => Math.Abs(pair.Delay - delay) * Math.Max(pair.Weight, 1.0e-6)) / matched.Sum(pair => Math.Max(pair.Weight, 1.0e-6));
var anchorEstimate = EstimatePathDelayFromMatchedAnchors(reference, candidate);
if (anchorEstimate is { } anchorDelay &&
anchorDelay.MatchedAnchors >= 24 &&
anchorDelay.MeanAbsoluteErrorSamples < mae)
{
delay = anchorDelay.DelaySamples;
mae = anchorDelay.MeanAbsoluteErrorSamples;
}
var waveformEstimate = EstimatePathDelayFromWaveform(referenceSamples, candidateSamples, delay, sampleRate);
if (waveformEstimate is { Confidence: >= 0.18 } waveformDelay &&
waveformDelay.EstimatedErrorSamples < mae)
{
delay = waveformDelay.DelaySamples;
mae = waveformDelay.EstimatedErrorSamples;
}
var eventWaveformEstimate = EstimatePathDelayFromEventWaveforms(
reference,
candidate,
referenceSamples,
candidateSamples,
sampleRate,
delay);
if (eventWaveformEstimate is { MatchedEvents: >= 8 } eventWaveformDelay &&
eventWaveformDelay.MeanAbsoluteErrorSamples < mae)
{
delay = eventWaveformDelay.DelaySamples;
mae = eventWaveformDelay.MeanAbsoluteErrorSamples;
}
var relativeGain = reference.Rms <= 1.0e-12 ? 0.0 : candidate.Rms / reference.Rms;
var referenceBands = reference.Bands.ToDictionary(band => band.CenterHz);
var normalizedBands = candidate.Bands
@ -3146,7 +3184,270 @@ static BioacousticPhysicalPathCalibration BuildContestantPathCalibration(
confidence,
relativeGain,
reference.Polarity * candidate.Polarity,
normalizedBands);
normalizedBands,
anchorEstimate?.MatchedAnchors ?? 0,
Math.Max(waveformEstimate?.Confidence ?? 0.0, eventWaveformEstimate?.Confidence ?? 0.0));
}
static (double DelaySamples, double MeanAbsoluteErrorSamples, int MatchedEvents, double Confidence)? EstimatePathDelayFromEventWaveforms(
BioacousticPhysicalChannelCalibration reference,
BioacousticPhysicalChannelCalibration candidate,
float[] referenceSamples,
float[] candidateSamples,
int sampleRate,
double initialDelaySamples)
{
(double DelaySamples, double MeanAbsoluteErrorSamples, int MatchedEvents, double Confidence)? best = null;
foreach (var windowSeconds in new[] { 0.012, 0.026, 0.055 })
{
var estimate = EstimatePathDelayFromEventWaveformsForWindow(
reference,
candidate,
referenceSamples,
candidateSamples,
sampleRate,
initialDelaySamples,
Math.Max(256, (int)Math.Round(sampleRate * windowSeconds)));
if (estimate != null &&
(best == null || estimate.Value.MeanAbsoluteErrorSamples < best.Value.MeanAbsoluteErrorSamples))
{
best = estimate;
}
}
return best;
}
static (double DelaySamples, double MeanAbsoluteErrorSamples, int MatchedEvents, double Confidence)? EstimatePathDelayFromEventWaveformsForWindow(
BioacousticPhysicalChannelCalibration reference,
BioacousticPhysicalChannelCalibration candidate,
float[] referenceSamples,
float[] candidateSamples,
int sampleRate,
double initialDelaySamples,
int windowSamples)
{
var candidateByEvent = candidate.Events.ToDictionary(e => e.EventIndex);
var searchRadius = Math.Max(4, sampleRate / 6_000);
var delays = new List<(double Value, double Weight)>();
foreach (var referenceEvent in reference.Events)
{
if (!candidateByEvent.TryGetValue(referenceEvent.EventIndex, out var candidateEvent) ||
referenceEvent.Confidence < 0.25 ||
candidateEvent.Confidence < 0.25)
{
continue;
}
var referenceStart = (int)Math.Round(referenceEvent.SampleOffset);
if (referenceStart < 0 || referenceStart + windowSamples >= referenceSamples.Length)
{
continue;
}
var centerLag = (int)Math.Round(initialDelaySamples);
var bestLag = centerLag;
var bestScore = double.NegativeInfinity;
for (var lag = centerLag - searchRadius; lag <= centerLag + searchRadius; lag++)
{
var candidateStart = referenceStart + lag;
if (candidateStart < 0 || candidateStart + windowSamples >= candidateSamples.Length)
{
continue;
}
var score = Math.Abs(ScoreAnchorWindow(
candidateSamples.AsSpan(candidateStart, windowSamples),
referenceSamples.AsSpan(referenceStart, windowSamples)));
if (score > bestScore)
{
bestScore = score;
bestLag = lag;
}
}
if (!double.IsFinite(bestScore) || bestScore < 0.035)
{
continue;
}
var refined = (double)bestLag;
if (bestLag > centerLag - searchRadius && bestLag < centerLag + searchRadius)
{
var left = Math.Abs(ScoreAnchorWindow(
candidateSamples.AsSpan(referenceStart + bestLag - 1, windowSamples),
referenceSamples.AsSpan(referenceStart, windowSamples)));
var middle = Math.Abs(ScoreAnchorWindow(
candidateSamples.AsSpan(referenceStart + bestLag, windowSamples),
referenceSamples.AsSpan(referenceStart, windowSamples)));
var right = Math.Abs(ScoreAnchorWindow(
candidateSamples.AsSpan(referenceStart + bestLag + 1, windowSamples),
referenceSamples.AsSpan(referenceStart, windowSamples)));
var denominator = left - 2.0 * middle + right;
if (Math.Abs(denominator) > 1.0e-12)
{
refined += Math.Clamp(0.5 * (left - right) / denominator, -0.5, 0.5);
}
}
delays.Add((refined, Math.Sqrt(referenceEvent.Confidence * candidateEvent.Confidence) * bestScore));
}
if (delays.Count < 3)
{
return null;
}
var median = WeightedMedian(delays);
var residuals = delays.Select(d => (Value: Math.Abs(d.Value - median), d.Weight)).ToArray();
var mad = WeightedMedian(residuals);
var radius = Math.Clamp(mad * 3.0 + 0.75, 1.5, 18.0);
var inliers = delays.Where(d => Math.Abs(d.Value - median) <= radius).ToArray();
if (inliers.Length < 3)
{
return null;
}
var totalWeight = inliers.Sum(d => Math.Max(d.Weight, 1.0e-6));
var delay = inliers.Sum(d => d.Value * Math.Max(d.Weight, 1.0e-6)) / totalWeight;
var mae = inliers.Sum(d => Math.Abs(d.Value - delay) * Math.Max(d.Weight, 1.0e-6)) / totalWeight;
var confidence = Math.Clamp(inliers.Average(d => d.Weight) * Math.Clamp(inliers.Length / 24.0, 0.0, 1.0), 0.0, 1.0);
return (delay, mae, inliers.Length, confidence);
}
static (double DelaySamples, double EstimatedErrorSamples, double Confidence)? EstimatePathDelayFromWaveform(
float[] referenceSamples,
float[] candidateSamples,
double initialDelaySamples,
int sampleRate)
{
if (referenceSamples.Length == 0 || candidateSamples.Length == 0)
{
return null;
}
var radius = Math.Max(8, sampleRate / 1_500);
var center = (int)Math.Round(initialDelaySamples);
var first = Math.Max(0, center - radius);
var last = Math.Min(candidateSamples.Length - 2, center + radius);
if (first > last)
{
return null;
}
var bestLag = center;
var bestScore = double.NegativeInfinity;
var secondScore = double.NegativeInfinity;
for (var lag = first; lag <= last; lag++)
{
var score = Math.Abs(NormalizedPathLagScore(referenceSamples, candidateSamples, lag));
if (score > bestScore)
{
secondScore = bestScore;
bestScore = score;
bestLag = lag;
}
else if (score > secondScore)
{
secondScore = score;
}
}
var fractionalLag = (double)bestLag;
if (bestLag > first && bestLag < last)
{
var left = Math.Abs(NormalizedPathLagScore(referenceSamples, candidateSamples, bestLag - 1));
var middle = Math.Abs(NormalizedPathLagScore(referenceSamples, candidateSamples, bestLag));
var right = Math.Abs(NormalizedPathLagScore(referenceSamples, candidateSamples, bestLag + 1));
var denominator = left - 2.0 * middle + right;
if (Math.Abs(denominator) > 1.0e-12)
{
fractionalLag += Math.Clamp(0.5 * (left - right) / denominator, -0.5, 0.5);
}
}
var peakMargin = Math.Max(0.0, bestScore - (double.IsFinite(secondScore) ? secondScore : 0.0));
var confidence = Math.Clamp(bestScore * 0.65 + peakMargin * 80.0, 0.0, 1.0);
var estimatedError = 1.0 / Math.Max(0.04, confidence * 1.8);
return (fractionalLag, estimatedError, confidence);
}
static double NormalizedPathLagScore(float[] referenceSamples, float[] candidateSamples, int lag)
{
var count = Math.Min(referenceSamples.Length, candidateSamples.Length - lag);
if (count <= 0)
{
return double.NegativeInfinity;
}
var dot = 0.0;
var referenceEnergy = 0.0;
var candidateEnergy = 0.0;
for (var index = 0; index < count; index++)
{
var reference = referenceSamples[index];
var candidate = candidateSamples[index + lag];
dot += reference * candidate;
referenceEnergy += reference * reference;
candidateEnergy += candidate * candidate;
}
return referenceEnergy <= 1.0e-12 || candidateEnergy <= 1.0e-12
? double.NegativeInfinity
: dot / Math.Sqrt(referenceEnergy * candidateEnergy);
}
static (double DelaySamples, double MeanAbsoluteErrorSamples, int MatchedAnchors)? EstimatePathDelayFromMatchedAnchors(
BioacousticPhysicalChannelCalibration reference,
BioacousticPhysicalChannelCalibration candidate)
{
var referenceAnchors = reference.Events
.SelectMany(e => e.Anchors.Select(anchor => (Event: e.EventIndex, Anchor: anchor)))
.Where(pair => pair.Anchor.Confidence >= 0.20)
.GroupBy(pair => (pair.Event, pair.Anchor.Kind, pair.Anchor.SyllableIndex))
.ToDictionary(
group => group.Key,
group => group.OrderByDescending(pair => pair.Anchor.Confidence).First().Anchor);
var delays = new List<(double Value, double Weight)>();
foreach (var candidateEvent in candidate.Events)
{
foreach (var candidateAnchor in candidateEvent.Anchors.Where(anchor => anchor.Confidence >= 0.20))
{
if (!referenceAnchors.TryGetValue(
(candidateEvent.EventIndex, candidateAnchor.Kind, candidateAnchor.SyllableIndex),
out var referenceAnchor))
{
continue;
}
var weight = Math.Sqrt(candidateAnchor.Confidence * referenceAnchor.Confidence);
delays.Add((candidateAnchor.SampleOffset - referenceAnchor.SampleOffset, weight));
}
}
if (delays.Count < 3)
{
return null;
}
var delay = WeightedMedian(delays);
var residuals = delays
.Select(pair => (Value: Math.Abs(pair.Value - delay), pair.Weight))
.ToArray();
var medianResidual = WeightedMedian(residuals);
var inlierRadius = Math.Clamp(medianResidual * 3.0 + 1.5, 3.0, 28.0);
var inliers = delays
.Where(pair => Math.Abs(pair.Value - delay) <= inlierRadius)
.ToArray();
if (inliers.Length < 3)
{
return null;
}
var totalWeight = inliers.Sum(pair => Math.Max(pair.Weight, 1.0e-6));
var refinedDelay = inliers.Sum(pair => pair.Value * Math.Max(pair.Weight, 1.0e-6)) / totalWeight;
var mae = inliers.Sum(pair => Math.Abs(pair.Value - refinedDelay) * Math.Max(pair.Weight, 1.0e-6)) / totalWeight;
return (refinedDelay, mae, inliers.Length);
}
static IReadOnlyDictionary<ulong, int> ClassifyContestantPayloads(
@ -4344,7 +4645,9 @@ public sealed record BioacousticPhysicalPathCalibration(
double Confidence,
double RelativeGain,
int RelativePolarity,
BioacousticPhysicalBandCalibration[] ResponseNormalizationBands);
BioacousticPhysicalBandCalibration[] ResponseNormalizationBands,
int MatchedAnchors,
double WaveformConfidence);
public sealed record BioacousticPhysicalEventCalibration(
ulong EventIndex,

View file

@ -97,3 +97,4 @@
{"ts": "2026-05-24T23:35:51+01:00", "type": "decision", "status": "ok", "note": "Active bioacoustic sync is no longer sequence-coded. The live receiver should keep its ear open for self-identifying song contours; one heard call carries enough log-mel contour, syllable timing, formant, rhythm, payload, and speaker-tint evidence to pin multiple time/frequency anchors at once. De Bruijn/triplet machinery is demoted to retained chirplet/chirp-bin reference artifacts only, not runtime authority."}
{"ts": "2026-05-24T23:45:19+01:00", "type": "experiment", "status": "partial", "note": "Fresh 192 kHz canary-packet physical ASIO run after song-contour authority cut: persisted calibration/bioacoustic/scarlett-canary-packet-192k-contour-fresh.json. Decoder cleared the 10x realtime budget at about 10.0x over four channels. Loopback remains 37/37 payload=1.000 with 2.524 us MAE. Co-streamer shotgun improved to 37/37 payload=1.000 with 34.083 us MAE and 2.710 ms path delay relative to loopback. Cardioid improved to 31/37 payload=0.811 but still measures 92.996 us MAE and 4.636 ms path delay. Current physical ceiling is tens of microseconds on mics; true microsecond sync needs intra-call contour anchors instead of one offset per packet word."}
{"ts": "2026-05-25T00:08:44+01:00", "type": "experiment", "status": "partial", "note": "Built the first anchor-rich canary packet: timing chips, formant pivots, harmonic-envelope notches, payload ornaments, renderer-level template caching, and per-event intra-call anchor measurements in the physical calibration receipt. Fresh 192 kHz ASIO receipt calibration/bioacoustic/scarlett-canary-packet-anchor-rich-192k.json clears 10x realtime and records hundreds of anchors per channel. Loopback improves to about 2.23 us MAE with anchor residuals under 0.3 samples. Physical mics did not improve yet: shotgun 36/37 payload=0.973 at 56.365 us MAE, cardioid 27/37 payload=0.730 at 101.522 us MAE. The new anchors expose path bias; the next cut should shape/weight anchors for acoustic survivability instead of trusting every formant feature equally."}
{"ts": "2026-05-25T00:42:12+01:00", "type": "experiment", "status": "partial", "note": "Added path-level loopback truth to the anchor-rich calibration: matched mic anchors are compared directly against loopback anchors, then event-local waveform correlation against the captured loopback packet chooses the path delay. Release calibration clears the realtime budget at 21.1x on the stored anchor-rich capture. Best stored-result path precision improved to cardioid 7.576 us and shotgun 6.578 us. A fresh room capture at calibration/bioacoustic/scarlett-canary-packet-anchor-rich-latest-192k.json keeps shotgun near 5.916 us but worsens cardioid to 18.930 us. The razor timing-chip emitter mutation was rejected because it reduced physical reliability. Current floor is single-digit microseconds for the shotgun, not yet the one-microsecond target; next required cut is phase/group-delay correction or a direct-path anchor family that survives both mics."}

View file

@ -200,6 +200,14 @@ accepted_design:
improves loopback to about 2.23 us MAE, but physical mics regress/hold at
tens of microseconds, so anchor survivability and path weighting are now the
problem.
Path-level loopback truth now compares candidate mic anchors directly
against loopback anchors, then refines delay with event-local waveform
correlation against the captured loopback packet. On the stored anchor-rich
capture, Release calibration runs at 21.1x realtime and improves physical
path precision to 7.576 us for the cardioid and 6.578 us for the shotgun.
A fresh room capture keeps the shotgun near 5.916 us but worsens the
cardioid to 18.930 us. The one-microsecond target remains open; next cut is
phase/group-delay correction or a better direct-path anchor family.
Acoustic robustness remains open.
The old arbitrary-chirplet matcher is a diagnostic/reference artifact only,
not the runtime hot path.