Build chirp-bin physical calibration model
This commit is contained in:
parent
3a7410d510
commit
488fda5362
18 changed files with 3073 additions and 97 deletions
|
|
@ -23,7 +23,8 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
IEnumerable<MimirRollingStreamBuffer> buffers,
|
||||
string referenceSourceId,
|
||||
MimirAudioSyncMode mode = MimirAudioSyncMode.ChirpOnly,
|
||||
IReadOnlySet<string>? candidateSourceIds = null)
|
||||
IReadOnlySet<string>? candidateSourceIds = null,
|
||||
MimirChirpBinCalibrationModel? calibrationModel = null)
|
||||
{
|
||||
var audioBuffers = buffers
|
||||
.Where(buffer => buffer.Descriptor.Kind == MimirStreamKind.Audio)
|
||||
|
|
@ -168,10 +169,16 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
}
|
||||
|
||||
var comparedReferenceDecode = useChirpBinTimeline
|
||||
? MimirChirpBinTimeline.Default.DecodeStreamWindow(referenceWindow, activeReferenceBlock.SampleRate)
|
||||
? MimirChirpBinTimeline.Default.DecodeStreamWindow(
|
||||
referenceWindow,
|
||||
activeReferenceBlock.SampleRate,
|
||||
calibrationModel?.PathFor(reference.Descriptor.SourceId))
|
||||
: MimirChirpletTimeline.Default.DecodeStreamWindow(referenceWindow, activeReferenceBlock.SampleRate);
|
||||
var candidateDecode = useChirpBinTimeline
|
||||
? MimirChirpBinTimeline.Default.DecodeStreamWindow(candidateWindow, activeReferenceBlock.SampleRate)
|
||||
? MimirChirpBinTimeline.Default.DecodeStreamWindow(
|
||||
candidateWindow,
|
||||
activeReferenceBlock.SampleRate,
|
||||
calibrationModel?.PathFor(buffer.Descriptor.SourceId))
|
||||
: MimirChirpletTimeline.Default.DecodeStreamWindow(candidateWindow, activeReferenceBlock.SampleRate);
|
||||
if (useChirpBinTimeline)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,225 @@
|
|||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Mimir.Runtime.Synchronization;
|
||||
|
||||
public sealed record MimirChirpBinCalibrationModel(
|
||||
string ModelId,
|
||||
DateTimeOffset CreatedAt,
|
||||
int SampleRate,
|
||||
string ReferenceSourceId,
|
||||
IReadOnlyList<MimirChirpBinPathCalibration> Paths)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter() },
|
||||
};
|
||||
|
||||
public MimirChirpBinPathCalibration? PathFor(string sourceId) =>
|
||||
Paths.FirstOrDefault(path => string.Equals(path.SourceId, sourceId, StringComparison.Ordinal));
|
||||
|
||||
public static MimirChirpBinCalibrationModel Load(string path) =>
|
||||
JsonSerializer.Deserialize<MimirChirpBinCalibrationModel>(File.ReadAllText(path), JsonOptions)
|
||||
?? throw new InvalidOperationException($"Could not read chirp-bin calibration model: {path}");
|
||||
|
||||
public void Save(string path)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(path));
|
||||
if (!string.IsNullOrWhiteSpace(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(this, JsonOptions));
|
||||
}
|
||||
|
||||
public static MimirChirpBinCalibrationModel FromDecodes(
|
||||
string referenceSourceId,
|
||||
int sampleRate,
|
||||
IReadOnlyDictionary<string, MimirChirpletStreamDecode> decodes)
|
||||
{
|
||||
var paths = decodes
|
||||
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
|
||||
.Select(pair => MimirChirpBinPathCalibration.FromDecode(pair.Key, sampleRate, pair.Value))
|
||||
.ToArray();
|
||||
return new MimirChirpBinCalibrationModel(
|
||||
$"chirp-bin-{DateTimeOffset.UtcNow:yyyyMMddTHHmmssZ}",
|
||||
DateTimeOffset.UtcNow,
|
||||
sampleRate,
|
||||
referenceSourceId,
|
||||
paths);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record MimirChirpBinPathCalibration(
|
||||
string SourceId,
|
||||
int SampleRate,
|
||||
MimirChirpBinCalibrationProfile Profile,
|
||||
MimirChirpBinCodebookPlan CodebookPlan,
|
||||
IReadOnlyList<MimirChirpBinSymbolCalibration> Symbols,
|
||||
IReadOnlyList<MimirChirpBinConfusionObservation> Confusion,
|
||||
IReadOnlyList<MimirChirpBinDelayHypothesis> DelayHypotheses)
|
||||
{
|
||||
public double SymbolWeight(int symbolId)
|
||||
{
|
||||
var symbol = Symbols.FirstOrDefault(item => item.SymbolId == symbolId);
|
||||
return symbol == null ? 1.0 : Math.Clamp(symbol.Reliability, 0.05, 1.0);
|
||||
}
|
||||
|
||||
public double GroupDelayCorrectionSamples(int symbolId)
|
||||
{
|
||||
var symbol = Symbols.FirstOrDefault(item => item.SymbolId == symbolId);
|
||||
return symbol?.MeanTimingResidualSamples ?? 0.0;
|
||||
}
|
||||
|
||||
public static MimirChirpBinPathCalibration FromDecode(
|
||||
string sourceId,
|
||||
int sampleRate,
|
||||
MimirChirpletStreamDecode decode)
|
||||
{
|
||||
var profile = MimirChirpBinCalibrationProfile.FromDecode(sourceId, sampleRate, decode);
|
||||
var observations = MimirChirpBinTimeline.Default.CalibrationObservations(decode, sampleRate);
|
||||
var symbols = observations
|
||||
.GroupBy(observation => observation.ExpectedSymbolId)
|
||||
.Select(group =>
|
||||
{
|
||||
var items = group.ToArray();
|
||||
var meanConfidence = items.Average(item => item.Confidence);
|
||||
var meanResidual = items.Average(item => item.TimingResidualSamples);
|
||||
var residualSpread = items.Average(item => Math.Abs(item.TimingResidualSamples - meanResidual));
|
||||
var correct = items.Count(item => item.ExpectedSymbolId == item.ObservedSymbolId);
|
||||
var reliability = meanConfidence *
|
||||
(correct / (double)items.Length) *
|
||||
(1.0 / (1.0 + residualSpread / Math.Max(1.0, sampleRate * 0.00025)));
|
||||
var phase = CircularMean(items.Select(item => item.PhaseRadians));
|
||||
return new MimirChirpBinSymbolCalibration(
|
||||
group.Key,
|
||||
reliability,
|
||||
items.Average(item => item.ExpectedCenterHz),
|
||||
items.Average(item => item.ObservedCenterHz),
|
||||
items.Average(item => item.ObservedEnergy),
|
||||
meanResidual,
|
||||
residualSpread,
|
||||
phase,
|
||||
items.Length);
|
||||
})
|
||||
.OrderBy(symbol => symbol.SymbolId)
|
||||
.ToArray();
|
||||
var hypotheses = BuildDelayHypotheses(decode);
|
||||
var plan = MimirChirpBinCodebookPlan.FromSymbols(symbols);
|
||||
return new MimirChirpBinPathCalibration(
|
||||
sourceId,
|
||||
sampleRate,
|
||||
profile,
|
||||
plan,
|
||||
symbols,
|
||||
observations,
|
||||
hypotheses);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpBinDelayHypothesis> BuildDelayHypotheses(MimirChirpletStreamDecode decode)
|
||||
{
|
||||
if (decode.ClockFit == null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var liveHorizonSamples = decode.ClockFit.EffectiveSampleRate * 10.0;
|
||||
var hypotheses = decode.Anchors
|
||||
.GroupBy(anchor => Math.Round(anchor.SampleOffset - anchor.TimelineSeconds * decode.ClockFit.EffectiveSampleRate))
|
||||
.Select(group =>
|
||||
{
|
||||
var delay = group.Average(anchor => anchor.SampleOffset - anchor.TimelineSeconds * decode.ClockFit!.EffectiveSampleRate);
|
||||
var residual = group.Average(anchor => Math.Abs(anchor.SampleOffset - (delay + anchor.TimelineSeconds * decode.ClockFit!.EffectiveSampleRate)));
|
||||
return new MimirChirpBinDelayHypothesis(
|
||||
delay,
|
||||
0,
|
||||
group.Count(),
|
||||
group.Average(anchor => anchor.Confidence),
|
||||
residual);
|
||||
})
|
||||
.Where(hypothesis => Math.Abs(hypothesis.DelaySamples) <= liveHorizonSamples)
|
||||
.OrderByDescending(hypothesis => hypothesis.Confidence * hypothesis.SupportCount)
|
||||
.Take(8)
|
||||
.ToArray();
|
||||
if (hypotheses.Length > 0)
|
||||
{
|
||||
return hypotheses;
|
||||
}
|
||||
|
||||
return Math.Abs(decode.ClockFit.SourceOffsetSamples) <= liveHorizonSamples
|
||||
? [new MimirChirpBinDelayHypothesis(decode.ClockFit.SourceOffsetSamples, 0, decode.ClockFit.AnchorCount, decode.ClockFit.Confidence, decode.ClockFit.MeanAbsoluteErrorSamples)]
|
||||
: [];
|
||||
}
|
||||
|
||||
private static double CircularMean(IEnumerable<double> radians)
|
||||
{
|
||||
var sin = 0.0;
|
||||
var cos = 0.0;
|
||||
var count = 0;
|
||||
foreach (var value in radians)
|
||||
{
|
||||
sin += Math.Sin(value);
|
||||
cos += Math.Cos(value);
|
||||
count++;
|
||||
}
|
||||
|
||||
return count == 0 ? 0.0 : Math.Atan2(sin / count, cos / count);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record MimirChirpBinCodebookPlan(
|
||||
int ReliableSymbolCount,
|
||||
int RecommendedOrder,
|
||||
IReadOnlyList<int> ReliableSymbolIds)
|
||||
{
|
||||
public static MimirChirpBinCodebookPlan FromSymbols(IReadOnlyList<MimirChirpBinSymbolCalibration> symbols)
|
||||
{
|
||||
var reliable = symbols
|
||||
.Where(symbol => symbol.Reliability >= 0.20)
|
||||
.OrderByDescending(symbol => symbol.Reliability)
|
||||
.ThenBy(symbol => symbol.SymbolId)
|
||||
.Select(symbol => symbol.SymbolId)
|
||||
.ToArray();
|
||||
var count = Math.Max(2, reliable.Length);
|
||||
var order = 3;
|
||||
while (Math.Pow(count, order) < 120_000.0 && order < 8)
|
||||
{
|
||||
order++;
|
||||
}
|
||||
|
||||
return new MimirChirpBinCodebookPlan(reliable.Length, order, reliable);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record MimirChirpBinSymbolCalibration(
|
||||
int SymbolId,
|
||||
double Reliability,
|
||||
double ExpectedCenterHz,
|
||||
double ObservedCenterHz,
|
||||
double MeanEnergy,
|
||||
double MeanTimingResidualSamples,
|
||||
double TimingResidualSpreadSamples,
|
||||
double MeanPhaseRadians,
|
||||
int ObservationCount);
|
||||
|
||||
public sealed record MimirChirpBinConfusionObservation(
|
||||
ulong EventIndex,
|
||||
int ExpectedSymbolId,
|
||||
int ObservedSymbolId,
|
||||
double ExpectedCenterHz,
|
||||
double ObservedCenterHz,
|
||||
double ObservedEnergy,
|
||||
double TimingResidualSamples,
|
||||
double Confidence,
|
||||
double DelayHypothesisSamples,
|
||||
double PhaseRadians);
|
||||
|
||||
public sealed record MimirChirpBinDelayHypothesis(
|
||||
double DelaySamples,
|
||||
int BinShift,
|
||||
int SupportCount,
|
||||
double Confidence,
|
||||
double MeanResidualSamples);
|
||||
|
|
@ -71,7 +71,7 @@ public sealed record MimirChirpBinCalibrationProfile(
|
|||
decode.Frames.Count,
|
||||
decode.Anchors.Count,
|
||||
decode.ClockFit?.Confidence ?? 0.0,
|
||||
decode.ClockFit?.MeanAbsoluteErrorSamples ?? double.NaN,
|
||||
decode.ClockFit?.MeanAbsoluteErrorSamples ?? 0.0,
|
||||
bands);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@ internal sealed record ChirpBinKernelSet(
|
|||
ChirpBinKernel[] Symbols,
|
||||
double ReferenceEnergy);
|
||||
|
||||
internal sealed record ChirpBinScore(
|
||||
double Energy,
|
||||
double PhaseRadians);
|
||||
|
||||
public sealed class MimirChirpBinTimeline
|
||||
{
|
||||
public const int SampleRate = 48_000;
|
||||
|
|
@ -57,21 +61,24 @@ public sealed class MimirChirpBinTimeline
|
|||
return samples;
|
||||
}
|
||||
|
||||
public MimirChirpletStreamDecode DecodeStreamWindow(ReadOnlySpan<float> samples, int sampleRate)
|
||||
public MimirChirpletStreamDecode DecodeStreamWindow(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
MimirChirpBinPathCalibration? calibration = null)
|
||||
{
|
||||
if (samples.Length == 0)
|
||||
{
|
||||
return new MimirChirpletStreamDecode([], [], [], null, []);
|
||||
}
|
||||
|
||||
var frames = DetectFrames(samples, sampleRate);
|
||||
var frames = DetectFrames(samples, sampleRate, calibration);
|
||||
var symbols = frames
|
||||
.Select(frame => new MimirChirpletSymbolObservation(
|
||||
frame.BestCandidate.SymbolId,
|
||||
frame.SampleOffset,
|
||||
frame.BestCandidate.Energy))
|
||||
.ToArray();
|
||||
var anchors = DecodeAnchors(frames, sampleRate);
|
||||
var anchors = DecodeAnchors(frames, sampleRate, calibration);
|
||||
var clock = FitClock(anchors, sampleRate);
|
||||
if (clock != null)
|
||||
{
|
||||
|
|
@ -82,6 +89,44 @@ public sealed class MimirChirpBinTimeline
|
|||
return new MimirChirpletStreamDecode(frames, symbols, anchors, clock, EstimateBandResponse(frames));
|
||||
}
|
||||
|
||||
public IReadOnlyList<MimirChirpBinConfusionObservation> CalibrationObservations(
|
||||
MimirChirpletStreamDecode decode,
|
||||
int sampleRate)
|
||||
{
|
||||
if (decode.ClockFit == null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var observations = new List<MimirChirpBinConfusionObservation>(decode.Frames.Count);
|
||||
foreach (var frame in decode.Frames)
|
||||
{
|
||||
if (!TryExpectedEventForSample(frame.SampleOffset, sampleRate, decode.ClockFit, out var timelineEvent))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var best = frame.BestCandidate;
|
||||
var bestBand = best.BandResponses?
|
||||
.OrderByDescending(response => response.Energy)
|
||||
.FirstOrDefault();
|
||||
var expectedSample = decode.ClockFit.SampleForTimelineSeconds(timelineEvent.StartSeconds);
|
||||
observations.Add(new MimirChirpBinConfusionObservation(
|
||||
timelineEvent.Index,
|
||||
timelineEvent.SymbolId,
|
||||
best.SymbolId,
|
||||
SymbolCenterHz(Symbols[timelineEvent.SymbolId]),
|
||||
bestBand?.CenterHz ?? SymbolCenterHz(Symbols[best.SymbolId]),
|
||||
bestBand?.Energy ?? best.Energy,
|
||||
frame.SampleOffset - expectedSample,
|
||||
best.Energy,
|
||||
decode.ClockFit.SourceOffsetSamples,
|
||||
bestBand?.PhaseRadians ?? 0.0));
|
||||
}
|
||||
|
||||
return observations;
|
||||
}
|
||||
|
||||
public MimirChirpletTimelineEvent EventForIndex(ulong eventIndex)
|
||||
{
|
||||
var symbolId = SymbolForEvent(eventIndex);
|
||||
|
|
@ -118,7 +163,10 @@ public sealed class MimirChirpBinTimeline
|
|||
return events;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletTransformFrame> DetectFrames(ReadOnlySpan<float> samples, int sampleRate)
|
||||
private static IReadOnlyList<MimirChirpletTransformFrame> DetectFrames(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
MimirChirpBinPathCalibration? calibration)
|
||||
{
|
||||
var chirpSamples = Math.Max(1, (int)Math.Round(ChirpDurationSeconds * sampleRate));
|
||||
if (samples.Length < chirpSamples)
|
||||
|
|
@ -149,7 +197,7 @@ public sealed class MimirChirpBinTimeline
|
|||
.Take(maxExpectedEvents)
|
||||
.Order())
|
||||
{
|
||||
var frame = ClassifyAt(samples, sampleRate, proposal, sampleRate / 1_000);
|
||||
var frame = ClassifyAt(samples, sampleRate, proposal, sampleRate / 1_000, calibration);
|
||||
if (frame != null)
|
||||
{
|
||||
frames.Add(frame);
|
||||
|
|
@ -163,7 +211,8 @@ public sealed class MimirChirpBinTimeline
|
|||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
int predictedOffset,
|
||||
int searchRadiusSamples)
|
||||
int searchRadiusSamples,
|
||||
MimirChirpBinPathCalibration? calibration)
|
||||
{
|
||||
var chirpSamples = Math.Max(1, (int)Math.Round(ChirpDurationSeconds * sampleRate));
|
||||
if (samples.Length < chirpSamples)
|
||||
|
|
@ -179,7 +228,7 @@ public sealed class MimirChirpBinTimeline
|
|||
var step = Math.Max(2, sampleRate / 4_000);
|
||||
for (var offset = start; offset <= end; offset += step)
|
||||
{
|
||||
var candidates = ScoreBins(samples.Slice(offset, chirpSamples), sampleRate, offset);
|
||||
var candidates = ScoreBins(samples.Slice(offset, chirpSamples), sampleRate, offset, calibration);
|
||||
var energy = candidates.Length == 0 ? 0.0 : candidates[0].Energy;
|
||||
if (energy > bestEnergy || PreferLaterPlateauOffset(sampleRate, energy, bestEnergy, offset, bestOffset))
|
||||
{
|
||||
|
|
@ -194,7 +243,7 @@ public sealed class MimirChirpBinTimeline
|
|||
var localEnd = Math.Min(end, bestOffset + localStep * 4);
|
||||
for (var offset = localStart; offset <= localEnd; offset += localStep)
|
||||
{
|
||||
var candidates = ScoreBins(samples.Slice(offset, chirpSamples), sampleRate, offset);
|
||||
var candidates = ScoreBins(samples.Slice(offset, chirpSamples), sampleRate, offset, calibration);
|
||||
var energy = candidates.Length == 0 ? 0.0 : candidates[0].Energy;
|
||||
if (energy > bestEnergy || PreferLaterPlateauOffset(sampleRate, energy, bestEnergy, offset, bestOffset))
|
||||
{
|
||||
|
|
@ -228,7 +277,8 @@ public sealed class MimirChirpBinTimeline
|
|||
var correctedEnergy = ScoreSymbolEnergy(
|
||||
samples.Slice((int)Math.Round(correctedOffset), chirpSamples),
|
||||
sampleRate,
|
||||
canonicalSymbol);
|
||||
canonicalSymbol) * (calibration?.SymbolWeight(canonicalSymbol) ?? 1.0);
|
||||
correctedOffset -= calibration?.GroupDelayCorrectionSamples(canonicalSymbol) ?? 0.0;
|
||||
correctedCandidates.Add(new MimirChirpletSymbolCandidate(
|
||||
canonicalSymbol,
|
||||
correctedOffset,
|
||||
|
|
@ -247,10 +297,11 @@ public sealed class MimirChirpBinTimeline
|
|||
private static MimirChirpletSymbolCandidate[] ScoreBins(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
int sampleOffset)
|
||||
int sampleOffset,
|
||||
MimirChirpBinPathCalibration? calibration)
|
||||
{
|
||||
var kernels = KernelSets.GetOrAdd(sampleRate, BuildKernelSet);
|
||||
var scores = new double[Symbols.Length];
|
||||
var scores = new ChirpBinScore[Symbols.Length];
|
||||
var sampleEnergy = 0.0;
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
{
|
||||
|
|
@ -265,15 +316,23 @@ public sealed class MimirChirpBinTimeline
|
|||
for (var symbol = 0; symbol < Symbols.Length; symbol++)
|
||||
{
|
||||
var score = DechirpedBin(samples, kernels.Symbols[symbol]);
|
||||
scores[symbol] = 2.0 * score / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy);
|
||||
var energy = 2.0 * score.Energy / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy);
|
||||
scores[symbol] = score with { Energy = energy };
|
||||
}
|
||||
|
||||
var bandResponses = scores
|
||||
.Select((energy, symbol) => new MimirChirpletBandResponse(SymbolCenterHz(Symbols[symbol]), energy))
|
||||
.Select((score, symbol) => new MimirChirpletBandResponse(
|
||||
SymbolCenterHz(Symbols[symbol]),
|
||||
score.Energy,
|
||||
score.PhaseRadians))
|
||||
.ToArray();
|
||||
|
||||
return scores
|
||||
.Select((energy, symbol) => new MimirChirpletSymbolCandidate(symbol, sampleOffset, energy, bandResponses))
|
||||
.Select((score, symbol) => new MimirChirpletSymbolCandidate(
|
||||
symbol,
|
||||
sampleOffset - (calibration?.GroupDelayCorrectionSamples(symbol) ?? 0.0),
|
||||
score.Energy * (calibration?.SymbolWeight(symbol) ?? 1.0),
|
||||
bandResponses))
|
||||
.OrderByDescending(candidate => candidate.Energy)
|
||||
.Take(MaxSymbolCandidatesPerFrame)
|
||||
.ToArray();
|
||||
|
|
@ -294,7 +353,7 @@ public sealed class MimirChirpBinTimeline
|
|||
}
|
||||
|
||||
var score = DechirpedBin(samples, kernels.Symbols[symbolId]);
|
||||
return 2.0 * score / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy);
|
||||
return 2.0 * score.Energy / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy);
|
||||
}
|
||||
|
||||
private static double RefineOffset(
|
||||
|
|
@ -334,7 +393,7 @@ public sealed class MimirChirpBinTimeline
|
|||
offset > bestOffset;
|
||||
}
|
||||
|
||||
private static double DechirpedBin(ReadOnlySpan<float> samples, ChirpBinKernel kernel)
|
||||
private static ChirpBinScore DechirpedBin(ReadOnlySpan<float> samples, ChirpBinKernel kernel)
|
||||
{
|
||||
var real = 0.0;
|
||||
var imaginary = 0.0;
|
||||
|
|
@ -344,12 +403,15 @@ public sealed class MimirChirpBinTimeline
|
|||
imaginary += samples[index] * kernel.Imaginary[index];
|
||||
}
|
||||
|
||||
return Math.Sqrt(real * real + imaginary * imaginary);
|
||||
return new ChirpBinScore(
|
||||
Math.Sqrt(real * real + imaginary * imaginary),
|
||||
Math.Atan2(imaginary, real));
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletTimelineAnchor> DecodeAnchors(
|
||||
IReadOnlyList<MimirChirpletTransformFrame> frames,
|
||||
int sampleRate)
|
||||
int sampleRate,
|
||||
MimirChirpBinPathCalibration? calibration)
|
||||
{
|
||||
if (frames.Count < TimelineOrder)
|
||||
{
|
||||
|
|
@ -402,12 +464,13 @@ public sealed class MimirChirpBinTimeline
|
|||
}
|
||||
}
|
||||
|
||||
return SelectCoherentAnchorPath(candidates, sampleRate);
|
||||
return SelectCoherentAnchorPath(candidates, sampleRate, calibration);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletTimelineAnchor> SelectCoherentAnchorPath(
|
||||
IReadOnlyList<MimirChirpletTimelineAnchor> candidates,
|
||||
int sampleRate)
|
||||
int sampleRate,
|
||||
MimirChirpBinPathCalibration? calibration)
|
||||
{
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
|
|
@ -416,9 +479,8 @@ public sealed class MimirChirpBinTimeline
|
|||
|
||||
List<MimirChirpletTimelineAnchor> bestPath = [];
|
||||
var bestScore = double.NegativeInfinity;
|
||||
foreach (var seed in candidates.OrderByDescending(anchor => anchor.Confidence).Take(64))
|
||||
foreach (var seedOffset in CandidateDelaySeeds(candidates, sampleRate, calibration))
|
||||
{
|
||||
var seedOffset = seed.SampleOffset - seed.TimelineSeconds * sampleRate;
|
||||
var path = candidates
|
||||
.Where(anchor => Math.Abs((anchor.SampleOffset - anchor.TimelineSeconds * sampleRate) - seedOffset) <= sampleRate * 0.006)
|
||||
.GroupBy(anchor => anchor.EventIndex)
|
||||
|
|
@ -453,6 +515,27 @@ public sealed class MimirChirpBinTimeline
|
|||
.ToArray();
|
||||
}
|
||||
|
||||
private static IEnumerable<double> CandidateDelaySeeds(
|
||||
IReadOnlyList<MimirChirpletTimelineAnchor> candidates,
|
||||
int sampleRate,
|
||||
MimirChirpBinPathCalibration? calibration)
|
||||
{
|
||||
if (calibration != null)
|
||||
{
|
||||
foreach (var hypothesis in calibration.DelayHypotheses
|
||||
.OrderByDescending(hypothesis => hypothesis.Confidence * hypothesis.SupportCount)
|
||||
.Take(16))
|
||||
{
|
||||
yield return hypothesis.DelaySamples;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var seed in candidates.OrderByDescending(anchor => anchor.Confidence).Take(64))
|
||||
{
|
||||
yield return seed.SampleOffset - seed.TimelineSeconds * sampleRate;
|
||||
}
|
||||
}
|
||||
|
||||
private static MimirChirpletClockFit? FitClock(
|
||||
IReadOnlyList<MimirChirpletTimelineAnchor> anchors,
|
||||
int sampleRate)
|
||||
|
|
@ -738,6 +821,24 @@ public sealed class MimirChirpBinTimeline
|
|||
private static double EventStartSeconds(ulong eventIndex) =>
|
||||
FirstEventSeconds + eventIndex * EventSpacingSeconds;
|
||||
|
||||
private static bool TryExpectedEventForSample(
|
||||
double sampleOffset,
|
||||
int sampleRate,
|
||||
MimirChirpletClockFit clockFit,
|
||||
out MimirChirpletTimelineEvent timelineEvent)
|
||||
{
|
||||
var timelineSeconds = (sampleOffset - clockFit.SourceOffsetSamples) / clockFit.EffectiveSampleRate;
|
||||
var eventIndex = (long)Math.Round((timelineSeconds - FirstEventSeconds) / EventSpacingSeconds);
|
||||
if (eventIndex < 0)
|
||||
{
|
||||
timelineEvent = default!;
|
||||
return false;
|
||||
}
|
||||
|
||||
timelineEvent = Default.EventForIndex((ulong)eventIndex);
|
||||
return Math.Abs(timelineSeconds - timelineEvent.StartSeconds) <= Math.Max(0.012, 6.0 / sampleRate);
|
||||
}
|
||||
|
||||
private static int[] BuildDeBruijn(int alphabetSize, int order)
|
||||
{
|
||||
var a = new int[alphabetSize * order];
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ public sealed record MimirChirpletTone(
|
|||
|
||||
public sealed record MimirChirpletBandResponse(
|
||||
double CenterHz,
|
||||
double Energy);
|
||||
double Energy,
|
||||
double PhaseRadians = 0.0);
|
||||
|
||||
public sealed record MimirChirpletTimelineEvent(
|
||||
ulong Index,
|
||||
|
|
|
|||
|
|
@ -201,6 +201,8 @@ public sealed class MimirAudioSyncConfig
|
|||
|
||||
public float WatermarkGain { get; set; } = float.NaN;
|
||||
|
||||
public string CalibrationModelPath { get; set; } = "";
|
||||
|
||||
public MimirAudioSynchronizationSettings ToSettings(MimirAudioSynchronizationSettings fallback)
|
||||
{
|
||||
return new MimirAudioSynchronizationSettings
|
||||
|
|
@ -215,6 +217,9 @@ public sealed class MimirAudioSyncConfig
|
|||
WatermarkGain = float.IsFinite(WatermarkGain)
|
||||
? Math.Clamp(WatermarkGain, 0.0f, 0.25f)
|
||||
: fallback.WatermarkGain,
|
||||
CalibrationModelPath = string.IsNullOrWhiteSpace(CalibrationModelPath)
|
||||
? fallback.CalibrationModelPath
|
||||
: CalibrationModelPath.Trim(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
private readonly MimirAudioSynchronizationAnalyzer audioSynchronization = new();
|
||||
private readonly MimirAudioSynchronizationStateTracker audioSynchronizationState = new();
|
||||
private readonly Dictionary<string, MimirAudioSynchronizationReport> audioSynchronizationReports = new(StringComparer.Ordinal);
|
||||
private readonly MimirChirpBinCalibrationModel? chirpBinCalibrationModel;
|
||||
private ulong ingestedSamples;
|
||||
private int nextAudioSynchronizationCandidate;
|
||||
|
||||
|
|
@ -13,6 +14,7 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
{
|
||||
Settings = settings;
|
||||
Buffers = new MimirStreamBufferSet(settings.BufferDuration);
|
||||
chirpBinCalibrationModel = TryLoadCalibrationModel(settings.Audio.CalibrationModelPath);
|
||||
foreach (var stream in settings.Streams.Where(stream => stream.Enabled))
|
||||
{
|
||||
Buffers.EnsureBuffer(stream);
|
||||
|
|
@ -85,7 +87,7 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
buffer.Latest?.AudioBlock != null)
|
||||
.Select(buffer => buffer.Descriptor.SourceId)
|
||||
.ToArray();
|
||||
var reports = audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId, mode);
|
||||
var reports = audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId, mode, calibrationModel: chirpBinCalibrationModel);
|
||||
StoreAudioSynchronizationReports(reports, candidates);
|
||||
return reports;
|
||||
}
|
||||
|
|
@ -120,13 +122,24 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
Buffers.Buffers,
|
||||
referenceSourceId,
|
||||
mode,
|
||||
selected);
|
||||
selected,
|
||||
chirpBinCalibrationModel);
|
||||
StoreAudioSynchronizationReports(reports, selected);
|
||||
return reports;
|
||||
}
|
||||
|
||||
private bool disposed;
|
||||
|
||||
private static MimirChirpBinCalibrationModel? TryLoadCalibrationModel(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return MimirChirpBinCalibrationModel.Load(path);
|
||||
}
|
||||
|
||||
private void StoreAudioSynchronizationReports(
|
||||
IReadOnlyList<MimirAudioSynchronizationReport> reports,
|
||||
IEnumerable<string> analyzedCandidateIds)
|
||||
|
|
|
|||
|
|
@ -66,6 +66,8 @@ public sealed class MimirAudioSynchronizationSettings
|
|||
|
||||
public float WatermarkGain { get; init; } = DefaultWatermarkGain;
|
||||
|
||||
public string CalibrationModelPath { get; init; } = "";
|
||||
|
||||
public static MimirAudioSynchronizationSettings FromEnvironment()
|
||||
{
|
||||
return new MimirAudioSynchronizationSettings().WithEnvironmentOverrides();
|
||||
|
|
@ -79,6 +81,7 @@ public sealed class MimirAudioSynchronizationSettings
|
|||
ReferenceSourceId = ReadReferenceSourceId(ReferenceSourceId),
|
||||
CalibrationGain = ReadCalibrationGain(CalibrationGain),
|
||||
WatermarkGain = ReadWatermarkGain(WatermarkGain),
|
||||
CalibrationModelPath = ReadCalibrationModelPath(CalibrationModelPath),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -119,6 +122,12 @@ public sealed class MimirAudioSynchronizationSettings
|
|||
? Math.Clamp(gain, 0.0f, 0.25f)
|
||||
: fallback;
|
||||
}
|
||||
|
||||
private static string ReadCalibrationModelPath(string fallback)
|
||||
{
|
||||
var path = Environment.GetEnvironmentVariable("MIMIR_CHIRP_BIN_CALIBRATION");
|
||||
return string.IsNullOrWhiteSpace(path) ? fallback : path.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
public enum MimirAudioSyncMode
|
||||
|
|
|
|||
Loading…
Reference in a new issue