Start passive program audio synchronization
This commit is contained in:
parent
c325545fba
commit
4b76b846c5
13 changed files with 373 additions and 71 deletions
|
|
@ -6,13 +6,16 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
{
|
||||
private const int MaxWindowSamples = 48_000 * 2;
|
||||
private const double MinDecodeWindowSeconds = 2.0;
|
||||
private const double PassiveReportConfidence = 0.08;
|
||||
private readonly List<MimirAudioSynchronizationDecodeTrace> lastDecodeTraces = [];
|
||||
private readonly MimirPassiveAudioSynchronizationEstimator passiveEstimator = new();
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationDecodeTrace> LastDecodeTraces => lastDecodeTraces;
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationReport> Analyze(
|
||||
IEnumerable<MimirRollingStreamBuffer> buffers,
|
||||
string referenceSourceId,
|
||||
MimirAudioSyncMode mode = MimirAudioSyncMode.ChirpOnly,
|
||||
IReadOnlySet<string>? candidateSourceIds = null)
|
||||
{
|
||||
var audioBuffers = buffers
|
||||
|
|
@ -54,7 +57,19 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
}
|
||||
|
||||
var commonEndNs = Math.Min(referenceLatest.Value.TimestampNs, buffer.Latest?.TimestampNs ?? 0);
|
||||
var candidateSamples = ExtractMonoWindow(buffer, out var candidateBlock);
|
||||
MimirAudioBlockDescriptor? activeReferenceBlock = referenceBlock;
|
||||
var alignedReferenceSamples = referenceSamples;
|
||||
if (commonEndNs < referenceLatest.Value.TimestampNs)
|
||||
{
|
||||
alignedReferenceSamples = ExtractMonoWindow(reference, out activeReferenceBlock, commonEndNs);
|
||||
}
|
||||
|
||||
if (alignedReferenceSamples.Length == 0 || activeReferenceBlock == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var candidateSamples = ExtractMonoWindow(buffer, out var candidateBlock, commonEndNs);
|
||||
if (candidateSamples.Length == 0 || candidateBlock == null)
|
||||
{
|
||||
continue;
|
||||
|
|
@ -65,16 +80,16 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
continue;
|
||||
}
|
||||
|
||||
candidateSamples = ResampleToRate(candidateSamples, candidateBlock.SampleRate, referenceBlock.SampleRate);
|
||||
candidateSamples = ResampleToRate(candidateSamples, candidateBlock.SampleRate, activeReferenceBlock.SampleRate);
|
||||
|
||||
var compared = Math.Min(referenceSamples.Length, candidateSamples.Length);
|
||||
var minDecodeSamples = Math.Min(MaxWindowSamples, (int)Math.Ceiling(referenceBlock.SampleRate * MinDecodeWindowSeconds));
|
||||
var compared = Math.Min(alignedReferenceSamples.Length, candidateSamples.Length);
|
||||
var minDecodeSamples = Math.Min(MaxWindowSamples, (int)Math.Ceiling(activeReferenceBlock.SampleRate * MinDecodeWindowSeconds));
|
||||
if (compared < minDecodeSamples)
|
||||
{
|
||||
lastDecodeTraces.Add(new MimirAudioSynchronizationDecodeTrace(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
referenceBlock.SampleRate,
|
||||
activeReferenceBlock.SampleRate,
|
||||
compared,
|
||||
0,
|
||||
0,
|
||||
|
|
@ -90,15 +105,60 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
continue;
|
||||
}
|
||||
|
||||
var referenceWindow = referenceSamples.AsSpan(^compared..);
|
||||
var referenceWindow = alignedReferenceSamples.AsSpan(^compared..);
|
||||
var candidateWindow = candidateSamples.AsSpan(^compared..);
|
||||
var comparedReferenceDecode = MimirChirpletTimeline.Default.DecodeStreamWindow(referenceWindow, referenceBlock.SampleRate);
|
||||
var candidateDecode = MimirChirpletTimeline.Default.DecodeStreamWindow(candidateWindow, referenceBlock.SampleRate);
|
||||
if (mode != MimirAudioSyncMode.ChirpOnly)
|
||||
{
|
||||
var passive = passiveEstimator.Estimate(referenceWindow, candidateWindow, activeReferenceBlock.SampleRate);
|
||||
lastDecodeTraces.Add(new MimirAudioSynchronizationDecodeTrace(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
activeReferenceBlock.SampleRate,
|
||||
passive.ComparedSamples,
|
||||
0,
|
||||
0,
|
||||
0.0,
|
||||
passive.NoiseFloor,
|
||||
0,
|
||||
0,
|
||||
0.0,
|
||||
passive.Peak,
|
||||
0,
|
||||
passive.Confidence,
|
||||
passive.Status));
|
||||
if (passive.Confidence >= PassiveReportConfidence || mode == MimirAudioSyncMode.Passive)
|
||||
{
|
||||
if (passive.Confidence >= PassiveReportConfidence)
|
||||
{
|
||||
reports.Add(new MimirAudioSynchronizationReport(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
activeReferenceBlock.SampleRate,
|
||||
(int)Math.Round(passive.DelaySamples),
|
||||
passive.DelaySamples,
|
||||
passive.DelaySamples * 1000.0 / activeReferenceBlock.SampleRate,
|
||||
passive.Confidence,
|
||||
[],
|
||||
commonEndNs,
|
||||
compared,
|
||||
reference.Latest?.Sequence ?? 0,
|
||||
buffer.Latest?.Sequence ?? 0,
|
||||
0,
|
||||
passive.Confidence,
|
||||
"passive"));
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
var comparedReferenceDecode = MimirChirpletTimeline.Default.DecodeStreamWindow(referenceWindow, activeReferenceBlock.SampleRate);
|
||||
var candidateDecode = MimirChirpletTimeline.Default.DecodeStreamWindow(candidateWindow, activeReferenceBlock.SampleRate);
|
||||
var deterministicFit = EstimateDelayFromDecodedTimeline(comparedReferenceDecode, candidateDecode);
|
||||
lastDecodeTraces.Add(new MimirAudioSynchronizationDecodeTrace(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
referenceBlock.SampleRate,
|
||||
activeReferenceBlock.SampleRate,
|
||||
compared,
|
||||
comparedReferenceDecode.Frames.Count,
|
||||
comparedReferenceDecode.Anchors.Count,
|
||||
|
|
@ -117,14 +177,14 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
}
|
||||
|
||||
var decodedDelaySamples = deterministicFit.DelaySamples;
|
||||
var bandResponses = MimirChirpletTimeline.Default.EstimateBandResponse(candidateWindow, referenceBlock.SampleRate);
|
||||
var bandResponses = MimirChirpletTimeline.Default.EstimateBandResponse(candidateWindow, activeReferenceBlock.SampleRate);
|
||||
reports.Add(new MimirAudioSynchronizationReport(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
referenceBlock.SampleRate,
|
||||
activeReferenceBlock.SampleRate,
|
||||
(int)Math.Round(decodedDelaySamples),
|
||||
decodedDelaySamples,
|
||||
decodedDelaySamples * 1000.0 / referenceBlock.SampleRate,
|
||||
decodedDelaySamples * 1000.0 / activeReferenceBlock.SampleRate,
|
||||
deterministicFit.Confidence,
|
||||
bandResponses,
|
||||
commonEndNs,
|
||||
|
|
@ -132,7 +192,8 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
reference.Latest?.Sequence ?? 0,
|
||||
buffer.Latest?.Sequence ?? 0,
|
||||
deterministicFit.MatchedEvents,
|
||||
deterministicFit.Confidence));
|
||||
deterministicFit.Confidence,
|
||||
"chirplet"));
|
||||
}
|
||||
|
||||
return reports;
|
||||
|
|
|
|||
|
|
@ -14,4 +14,5 @@ public sealed record MimirAudioSynchronizationReport(
|
|||
ulong ReferenceSequence,
|
||||
ulong SourceSequence,
|
||||
int TimelineMatchedEvents = 0,
|
||||
double TimelineConfidence = 0.0);
|
||||
double TimelineConfidence = 0.0,
|
||||
string EvidenceKind = "chirplet");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,173 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace Mimir.Runtime.Synchronization;
|
||||
|
||||
public sealed record MimirPassiveAudioSynchronizationEstimate(
|
||||
double DelaySamples,
|
||||
double Confidence,
|
||||
double Peak,
|
||||
double NoiseFloor,
|
||||
int ComparedSamples,
|
||||
string Status);
|
||||
|
||||
public sealed class MimirPassiveAudioSynchronizationEstimator
|
||||
{
|
||||
private const int TargetWindowSamples = 32_768;
|
||||
private const double Preemphasis = 0.97;
|
||||
|
||||
public MimirPassiveAudioSynchronizationEstimate Estimate(
|
||||
ReadOnlySpan<float> reference,
|
||||
ReadOnlySpan<float> candidate,
|
||||
int sampleRate)
|
||||
{
|
||||
var compared = Math.Min(reference.Length, candidate.Length);
|
||||
if (compared < 4096 || sampleRate <= 0)
|
||||
{
|
||||
return new MimirPassiveAudioSynchronizationEstimate(0.0, 0.0, 0.0, 0.0, compared, "passive-insufficient-window");
|
||||
}
|
||||
|
||||
var windowSamples = Math.Min(TargetWindowSamples, compared);
|
||||
var fftSize = NextPowerOfTwo(windowSamples * 2);
|
||||
var referenceSpectrum = new Complex[fftSize];
|
||||
var candidateSpectrum = new Complex[fftSize];
|
||||
FillWindow(reference[^windowSamples..], referenceSpectrum, windowSamples);
|
||||
FillWindow(candidate[^windowSamples..], candidateSpectrum, windowSamples);
|
||||
|
||||
FastFourierTransform(referenceSpectrum, inverse: false);
|
||||
FastFourierTransform(candidateSpectrum, inverse: false);
|
||||
for (var index = 0; index < fftSize; index++)
|
||||
{
|
||||
var cross = Complex.Conjugate(referenceSpectrum[index]) * candidateSpectrum[index];
|
||||
var magnitude = cross.Magnitude;
|
||||
referenceSpectrum[index] = magnitude > 1.0e-12 ? cross / magnitude : Complex.Zero;
|
||||
}
|
||||
|
||||
FastFourierTransform(referenceSpectrum, inverse: true);
|
||||
var maxLag = Math.Min(sampleRate, windowSamples / 2);
|
||||
var bestIndex = 0;
|
||||
var best = double.NegativeInfinity;
|
||||
var sum = 0.0;
|
||||
var sumSquares = 0.0;
|
||||
var count = 0;
|
||||
for (var lag = -maxLag; lag <= maxLag; lag++)
|
||||
{
|
||||
var value = CorrelationAt(referenceSpectrum, lag);
|
||||
var abs = Math.Abs(value);
|
||||
sum += abs;
|
||||
sumSquares += abs * abs;
|
||||
count++;
|
||||
if (abs > best)
|
||||
{
|
||||
best = abs;
|
||||
bestIndex = lag;
|
||||
}
|
||||
}
|
||||
|
||||
var mean = sum / Math.Max(1, count);
|
||||
var variance = Math.Max(0.0, sumSquares / Math.Max(1, count) - mean * mean);
|
||||
var sigma = Math.Sqrt(variance);
|
||||
var refinedLag = bestIndex + RefinePeak(referenceSpectrum, bestIndex);
|
||||
var peakRatio = mean > 1.0e-12 ? best / mean : 0.0;
|
||||
var zScore = sigma > 1.0e-12 ? (best - mean) / sigma : 0.0;
|
||||
var confidence = Math.Clamp((peakRatio - 1.5) / 8.0, 0.0, 1.0) *
|
||||
Math.Clamp(zScore / 16.0, 0.0, 1.0);
|
||||
var status = confidence > 0.08 ? "passive-report" : "passive-low-confidence";
|
||||
return new MimirPassiveAudioSynchronizationEstimate(refinedLag, confidence, best, mean, compared, status);
|
||||
}
|
||||
|
||||
private static void FillWindow(ReadOnlySpan<float> source, Complex[] destination, int count)
|
||||
{
|
||||
var mean = 0.0;
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
mean += source[index];
|
||||
}
|
||||
|
||||
mean /= count;
|
||||
var previous = 0.0;
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
var centered = source[index] - mean;
|
||||
var emphasized = centered - previous * Preemphasis;
|
||||
previous = centered;
|
||||
var window = 0.5 - 0.5 * Math.Cos(2.0 * Math.PI * index / Math.Max(1, count - 1));
|
||||
destination[index] = new Complex(emphasized * window, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
private static double CorrelationAt(Complex[] correlation, int lag)
|
||||
{
|
||||
var index = lag >= 0 ? lag : correlation.Length + lag;
|
||||
return correlation[index].Real;
|
||||
}
|
||||
|
||||
private static double RefinePeak(Complex[] correlation, int lag)
|
||||
{
|
||||
var left = Math.Abs(CorrelationAt(correlation, lag - 1));
|
||||
var center = Math.Abs(CorrelationAt(correlation, lag));
|
||||
var right = Math.Abs(CorrelationAt(correlation, lag + 1));
|
||||
var denominator = left - 2.0 * center + right;
|
||||
return Math.Abs(denominator) < 1.0e-12
|
||||
? 0.0
|
||||
: Math.Clamp(0.5 * (left - right) / denominator, -0.5, 0.5);
|
||||
}
|
||||
|
||||
private static int NextPowerOfTwo(int value)
|
||||
{
|
||||
var power = 1;
|
||||
while (power < value)
|
||||
{
|
||||
power <<= 1;
|
||||
}
|
||||
|
||||
return power;
|
||||
}
|
||||
|
||||
private static void FastFourierTransform(Complex[] values, bool inverse)
|
||||
{
|
||||
var n = values.Length;
|
||||
for (int index = 1, swap = 0; index < n; index++)
|
||||
{
|
||||
var bit = n >> 1;
|
||||
for (; (swap & bit) != 0; bit >>= 1)
|
||||
{
|
||||
swap ^= bit;
|
||||
}
|
||||
|
||||
swap ^= bit;
|
||||
if (index < swap)
|
||||
{
|
||||
(values[index], values[swap]) = (values[swap], values[index]);
|
||||
}
|
||||
}
|
||||
|
||||
for (var length = 2; length <= n; length <<= 1)
|
||||
{
|
||||
var angle = 2.0 * Math.PI / length * (inverse ? 1.0 : -1.0);
|
||||
var step = new Complex(Math.Cos(angle), Math.Sin(angle));
|
||||
for (var start = 0; start < n; start += length)
|
||||
{
|
||||
var rotation = Complex.One;
|
||||
var half = length >> 1;
|
||||
for (var offset = 0; offset < half; offset++)
|
||||
{
|
||||
var even = values[start + offset];
|
||||
var odd = values[start + offset + half] * rotation;
|
||||
values[start + offset] = even + odd;
|
||||
values[start + offset + half] = even - odd;
|
||||
rotation *= step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!inverse)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var index = 0; index < n; index++)
|
||||
{
|
||||
values[index] /= n;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -71,16 +71,18 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
}
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationReport> AnalyzeAudioSynchronization(
|
||||
string referenceSourceId)
|
||||
string referenceSourceId,
|
||||
MimirAudioSyncMode mode = MimirAudioSyncMode.ChirpOnly)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var reports = audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId);
|
||||
var reports = audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId, mode);
|
||||
StoreAudioSynchronizationReports(reports);
|
||||
return reports;
|
||||
}
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationReport> AnalyzeAudioSynchronizationStep(
|
||||
string referenceSourceId,
|
||||
MimirAudioSyncMode mode = MimirAudioSyncMode.ChirpOnly,
|
||||
int maxCandidates = 1)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
|
|
@ -107,6 +109,7 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
var reports = audioSynchronization.Analyze(
|
||||
Buffers.Buffers,
|
||||
referenceSourceId,
|
||||
mode,
|
||||
selected);
|
||||
StoreAudioSynchronizationReports(reports);
|
||||
return reports;
|
||||
|
|
|
|||
|
|
@ -88,7 +88,7 @@ public sealed class MimirAudioSynchronizationSettings
|
|||
return value.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"chirp-only" or "chirponly" or "chirp" or "active" => MimirAudioSyncMode.ChirpOnly,
|
||||
"no-chirp" or "nochirp" or "passive" or "passive-only" or "passiveonly" => MimirAudioSyncMode.NoChirp,
|
||||
"passive" or "passive-only" or "passiveonly" or "no-chirp" or "nochirp" => MimirAudioSyncMode.Passive,
|
||||
"hybrid" => MimirAudioSyncMode.Hybrid,
|
||||
_ => fallback,
|
||||
};
|
||||
|
|
@ -113,6 +113,6 @@ public sealed class MimirAudioSynchronizationSettings
|
|||
public enum MimirAudioSyncMode
|
||||
{
|
||||
ChirpOnly,
|
||||
NoChirp,
|
||||
Passive,
|
||||
Hybrid,
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue