From 4b76b846c5de9dc8b6ce3f5be664f8ab000429c6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 22 May 2026 19:09:11 +0100 Subject: [PATCH] Start passive program audio synchronization --- docs/audio-field.md | 25 ++- docs/implementation-plan.md | 23 ++- notes/current-system-map.md | 6 +- notes/fresh-workspace-handoff.md | 6 +- src/Mimir.BufferSmoke/Program.cs | 44 ++++- src/Mimir.Runtime/MimirRuntime.cs | 56 +++--- .../MimirAudioSynchronizationAnalyzer.cs | 87 +++++++-- .../MimirAudioSynchronizationReport.cs | 3 +- ...mirPassiveAudioSynchronizationEstimator.cs | 173 ++++++++++++++++++ .../MimirSynchronizationHub.cs | 7 +- .../MimirSynchronizationSettings.cs | 4 +- state/evidence.jsonl | 2 + state/map.yaml | 8 +- 13 files changed, 373 insertions(+), 71 deletions(-) create mode 100644 src/Mimir.Runtime/Synchronization/MimirPassiveAudioSynchronizationEstimator.cs diff --git a/docs/audio-field.md b/docs/audio-field.md index dd4bb0e..d68e783 100644 --- a/docs/audio-field.md +++ b/docs/audio-field.md @@ -47,22 +47,27 @@ timing evidence Mimir is allowed to emit: - `chirp-only`: emit the deterministic calibration timeline and decode timing only from that active witness. This is the lab/debug mode and the fallback for silent program material. -- `no-chirp`: do not emit calibration audio. This is the passive/program-audio - mode. The runtime exposes it now, but the passive loopback/music estimator is - not wired yet, so current code intentionally reports that no-chirp sync is - unavailable instead of pretending the chirplet decoder can read arbitrary - music. +- `passive`: do not emit calibration audio. Use loopback/program audio as the + timing witness by estimating delay between the loopback buffer and each mic + buffer. - `hybrid`: prefer passive program-audio evidence when confidence is high, then - emit a shaped watermark when confidence falls. Today this still behaves as an - active pilot because the passive estimator and confidence gate have not been - cut. The intended watermark is the dechirp/FFT-friendly chirp-bin codebook - from the decoder research notes, shaped and low-gain enough to sit inside the - program audio instead of announcing itself like a lab sweep. + emit a watermark when confidence falls. Today the passive side uses bounded + GCC-PHAT-style phase correlation and the fallback still uses the old active + chirplet pilot in half-second chunks. The intended watermark is the + dechirp/FFT-friendly chirp-bin codebook from the decoder research notes, + shaped and low-gain enough to sit inside the program audio instead of + announcing itself like a lab sweep. The mode belongs to the runtime, not the decoder. The decoder should consume known timing evidence; it should not decide whether Mimir is allowed to make sound. +The passive estimator is the first real program-audio path, not the final DSP +actuator. It removes DC, pre-emphasizes the window, applies a Hann taper, runs a +PHAT-weighted cross spectrum, and reports the strongest loopback-to-mic lag +inside a bounded window. Positive delay still means the candidate mic is late +relative to loopback. + ## Next Cut The current diagnostic witness is `native/probes/wasapi_audio_cadence`, which diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index f9e850d..8a750a8 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -70,12 +70,15 @@ a named invariant that the native runtime cannot protect yet. service and can emit live sync telemetry with `MIMIR_SYNC_TELEMETRY_SECONDS`. UI and telemetry read cached reports/states; they do not run synchronization analysis. -- `MimirRuntime` continuously queues chirplet timeline PCM through Aquarium - audio so the loopback and acoustic mic buffers carry a shared timing witness. - `MimirAudioSynchronizationSettings.Mode` selects `chirp-only`, `no-chirp`, or - `hybrid`; no-chirp disables active emission until the passive program-audio - estimator exists, and hybrid currently uses the active pilot as the fallback - path. +- `MimirRuntime` queues chirplet timeline PCM through Aquarium audio when the + active timing witness is allowed. `MimirAudioSynchronizationSettings.Mode` + selects `chirp-only`, `passive`, or `hybrid`; passive disables active + emission, and hybrid emits the active pilot only while passive confidence is + below threshold. +- `MimirPassiveAudioSynchronizationEstimator` is the first program-audio timing + path. It estimates loopback-to-mic delay with PHAT-weighted cross-spectrum + correlation so music can act as the default timing witness before any audible + watermark is needed. - `MimirVideoFrameDescriptor` for dimensions, pixel format, stride, device timestamp, and native/GPU handle metadata. - `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` as the live @@ -115,10 +118,10 @@ a named invariant that the native runtime cannot protect yet. decoder through real loopback and microphone paths so every correctly heard triplet becomes a deterministic timeline anchor before the actuator moves samples. -5. Replace the active-pilot-only hybrid path with passive loopback/program-audio - confidence plus shaped watermark emission when confidence drops. The - watermark codebook should be designed for dechirp/FFT or Goertzel - classification, not dense sliding matched filters. +5. Replace the active chirplet fallback in hybrid mode with shaped watermark + emission when passive confidence drops. The watermark codebook should be + designed for dechirp/FFT or Goertzel classification, not dense sliding + matched filters. 6. Bind Aquarium UI to the synchronization hub so buffer depth, stream cadence, source timestamps, and output settings are visible and adjustable. 7. Move GPU feature extraction, fusion, material fitting, render budgeting, and diff --git a/notes/current-system-map.md b/notes/current-system-map.md index b977009..81bb6f0 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -98,9 +98,9 @@ current operating horizon. Mimir continuously queues that timeline through Aquarium audio and decodes timing through the constrained chirplet-transform path. `MimirAudioSynchronizationSettings.Mode` chooses whether active calibration is -allowed: `chirp-only` emits the witness, `no-chirp` stays silent and waits for -the passive program-audio estimator, and `hybrid` currently uses the active -pilot until the passive confidence gate and shaped watermark are built. +allowed: `chirp-only` emits the witness, `passive` stays silent and uses +program-audio phase correlation, and `hybrid` uses passive evidence by default +while emitting active pilot chunks only when passive confidence is weak. Reports now carry fractional delay and per-band matched energy. The first `MimirChirpletSymbolCodebook` owns separable symbol definitions; every symbol has a unique chirp shape, with rhythm as additional evidence. `MimirChirpletStreamDecoder` diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 449ee5b..b7e7836 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -81,9 +81,9 @@ Get-Content .\state\evidence.jsonl -Tail 8 0-12 with a 47999.999990 Hz clock fit and 0.000014 sample MAE. `MimirRuntime` runs sync analysis as a bounded rotating service and caches reports/states for UI and telemetry; readouts must stay passive. Audio sync mode is runtime-owned: `chirp-only` emits active - calibration, `no-chirp` disables emission and awaits passive program-audio - sync, and `hybrid` currently uses the active pilot until shaped watermark - confidence gating exists. Actual Mimir.App testing proves Aquarium audio wakes Scarlett + calibration, `passive` disables emission and uses program-audio phase + correlation, and `hybrid` emits active pilot chunks only when passive + confidence is weak. Actual Mimir.App testing proves Aquarium audio wakes Scarlett loopback, keeps mic buffers live, and produces confident online sync states, but the decoder still needs stronger symbol likelihoods/codebook distance before arbitrary real triplets can drive the actuator directly. PS3 Eye audio is diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index dbaf631..eea14de 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -5,12 +5,18 @@ if (args.Any(arg => string.Equals(arg, "--chirplet-self-test", StringComparison. return RunChirpletSelfTest(); } +if (args.Any(arg => string.Equals(arg, "--passive-sync-self-test", StringComparison.OrdinalIgnoreCase))) +{ + return RunPassiveSyncSelfTest(); +} + var duration = TimeSpan.FromSeconds(ParseDoubleOption(args, "--seconds", 10.0)); var pollDelay = TimeSpan.FromMilliseconds(ParseDoubleOption(args, "--poll-ms", 10.0)); var requireSamples = args.Any(arg => string.Equals(arg, "--require-samples", StringComparison.OrdinalIgnoreCase)); var syncReference = ParseStringOption(args, "--sync-reference", "loopback-scarlett-speakers"); using var configuration = new DisposableConfiguration(MimirRuntimeConfiguration.Load()); using var hub = new MimirSynchronizationHub(configuration.Value.Settings); +var syncMode = configuration.Value.Settings.Audio.Mode; foreach (var source in configuration.Value.Sources) { @@ -25,7 +31,7 @@ while (DateTimeOffset.UtcNow < deadline) hub.PollSources(maxSamplesPerSource: 4096); if (DateTimeOffset.UtcNow >= nextSyncPoll) { - hub.AnalyzeAudioSynchronization(syncReference); + hub.AnalyzeAudioSynchronization(syncReference, syncMode); nextSyncPoll += TimeSpan.FromSeconds(1); } @@ -60,11 +66,11 @@ foreach (var buffer in hub.Buffers.Buffers.OrderBy(buffer => buffer.Descriptor.S } } -var reports = hub.AnalyzeAudioSynchronization(syncReference); +var reports = hub.AnalyzeAudioSynchronization(syncReference, syncMode); foreach (var report in reports.OrderBy(report => report.SourceId, StringComparer.Ordinal)) { Console.WriteLine( - $"sync {report.ReferenceSourceId}->{report.SourceId}: delaySamples={report.DelaySamples} fractionalDelaySamples={report.FractionalDelaySamples:0.000} delayMs={report.DelayMilliseconds:0.000} confidence={report.Confidence:0.000} bands={DescribeBands(report.BandResponses)} compared={report.ComparedSamples}"); + $"sync {report.ReferenceSourceId}->{report.SourceId}: evidence={report.EvidenceKind} delaySamples={report.DelaySamples} fractionalDelaySamples={report.FractionalDelaySamples:0.000} delayMs={report.DelayMilliseconds:0.000} confidence={report.Confidence:0.000} bands={DescribeBands(report.BandResponses)} compared={report.ComparedSamples}"); } foreach (var state in hub.AudioSynchronizationStates) @@ -156,6 +162,38 @@ static int RunChirpletSelfTest() return 0; } +static int RunPassiveSyncSelfTest() +{ + const int sampleRate = 48_000; + const int delaySamples = 1732; + const int sampleCount = 48_000; + var reference = new float[sampleCount]; + var candidate = new float[sampleCount]; + for (var index = 0; index < sampleCount; index++) + { + reference[index] = (float)( + 0.45 * Math.Sin(2.0 * Math.PI * 611.0 * index / sampleRate) + + 0.28 * Math.Sin(2.0 * Math.PI * 1471.0 * index / sampleRate) + + 0.12 * Math.Sin(2.0 * Math.PI * 3253.0 * index / sampleRate)); + var source = index - delaySamples; + candidate[index] = source >= 0 ? reference[source] : 0.0f; + } + + var estimator = new MimirPassiveAudioSynchronizationEstimator(); + var estimate = estimator.Estimate(reference, candidate, sampleRate); + var error = estimate.DelaySamples - delaySamples; + Console.WriteLine( + $"passive-sync-self-test delaySamples={estimate.DelaySamples:0.000} expected={delaySamples} " + + $"error={error:0.000} confidence={estimate.Confidence:0.000} peak={estimate.Peak:0.000000} floor={estimate.NoiseFloor:0.000000} status={estimate.Status}"); + if (Math.Abs(error) > 1.0 || estimate.Confidence < 0.08) + { + Console.Error.WriteLine("passive sync self-test failed: delayed program signal did not produce a confident passive estimate"); + return 1; + } + + return 0; +} + internal sealed class DisposableConfiguration : IDisposable { private readonly List ownedSources; diff --git a/src/Mimir.Runtime/MimirRuntime.cs b/src/Mimir.Runtime/MimirRuntime.cs index d0d1ae8..9a7d49a 100644 --- a/src/Mimir.Runtime/MimirRuntime.cs +++ b/src/Mimir.Runtime/MimirRuntime.cs @@ -12,6 +12,7 @@ namespace Mimir.Runtime; public sealed class MimirRuntime : IAquariumRuntime { private const float DefaultAudioSyncUpdateIntervalSeconds = 0.1f; + private const double HybridPassiveConfidenceThreshold = 0.12; private const double CalibrationStartSeconds = 0.5; private const int CalibrationBatchSegments = 120; private readonly LocalCastRuntime visualRuntime; @@ -27,6 +28,7 @@ public sealed class MimirRuntime : IAquariumRuntime private float nextTelemetrySeconds; private ulong calibrationSegmentIndex; private double lastAudioSyncAnalysisMilliseconds; + private double lastPassiveSynchronizationConfidence; private IReadOnlyList lastAudioSynchronizationReports = []; public MimirRuntime(AquariumRuntimeOptions options) @@ -153,26 +155,27 @@ public sealed class MimirRuntime : IAquariumRuntime return; } - var batch = RenderCalibrationBatchPcm16Base64(calibrationSegmentIndex, CalibrationBatchSegments, out var peak); + var segmentCount = audioSyncSettings.Mode == MimirAudioSyncMode.Hybrid ? 1 : CalibrationBatchSegments; + var batch = RenderCalibrationBatchPcm16Base64(calibrationSegmentIndex, segmentCount, out var peak); visualRuntime.Audio.EnqueuePcm16Base64( batch, MimirChirpletTimeline.SampleRate, channels: 1, gain: calibrationGain); Console.WriteLine( - $"mimir-chirplet-batch firstSegment={calibrationSegmentIndex} segments={CalibrationBatchSegments} seconds={CalibrationBatchSegments * MimirChirpletTimeline.SegmentSeconds:0.00} peak={peak:0.000000} gain={calibrationGain:0.###} base64Bytes={batch.Length}"); - calibrationSegmentIndex += CalibrationBatchSegments; + $"mimir-chirplet-batch firstSegment={calibrationSegmentIndex} segments={segmentCount} seconds={segmentCount * MimirChirpletTimeline.SegmentSeconds:0.00} peak={peak:0.000000} gain={calibrationGain:0.###} base64Bytes={batch.Length}"); + calibrationSegmentIndex += (ulong)segmentCount; } private string DescribeChirpletReference() { if (!ShouldEmitCalibrationTimeline()) { - return $"{audioSyncSettings.ReferenceSourceId} no-chirp mode; calibration emission disabled"; + return $"{audioSyncSettings.ReferenceSourceId} passive mode; calibration emission disabled"; } var emittedUntilSeconds = calibrationSegmentIndex * MimirChirpletTimeline.SegmentSeconds; - return $"{audioSyncSettings.ReferenceSourceId} {DescribeAudioSyncMode()} timeline {MimirChirpletTimeline.SegmentSeconds:0.00}s segments emitted to {emittedUntilSeconds:0.00}s"; + return $"{audioSyncSettings.ReferenceSourceId} {DescribeAudioSyncMode()} timeline {MimirChirpletTimeline.SegmentSeconds:0.00}s segments emitted to {emittedUntilSeconds:0.00}s passiveConfidence={lastPassiveSynchronizationConfidence:0.000}"; } private static string RenderCalibrationBatchPcm16Base64(ulong firstSegment, int segmentCount, out float peak) @@ -208,19 +211,12 @@ public sealed class MimirRuntime : IAquariumRuntime return; } - if (audioSyncSettings.Mode == MimirAudioSyncMode.NoChirp) - { - lastAudioSyncAnalysisMilliseconds = 0.0; - lastAudioSynchronizationReports = []; - nextAudioSyncSeconds = runtimeSeconds + audioSyncUpdateIntervalSeconds; - return; - } - var stopwatch = Stopwatch.StartNew(); - synchronization.AnalyzeAudioSynchronizationStep(audioSyncSettings.ReferenceSourceId); + synchronization.AnalyzeAudioSynchronizationStep(audioSyncSettings.ReferenceSourceId, audioSyncSettings.Mode); stopwatch.Stop(); lastAudioSyncAnalysisMilliseconds = stopwatch.Elapsed.TotalMilliseconds; lastAudioSynchronizationReports = synchronization.AudioSynchronizationReports; + UpdatePassiveSynchronizationConfidence(lastAudioSynchronizationReports); nextAudioSyncSeconds = runtimeSeconds + audioSyncUpdateIntervalSeconds; } @@ -240,7 +236,7 @@ public sealed class MimirRuntime : IAquariumRuntime foreach (var report in lastAudioSynchronizationReports.OrderBy(report => report.SourceId, StringComparer.Ordinal)) { Console.WriteLine( - $"mimir-sync-report {report.ReferenceSourceId}->{report.SourceId} delaySamples={report.FractionalDelaySamples:0.000} delayMs={report.DelayMilliseconds:0.000} confidence={report.Confidence:0.000} timelineEvents={report.TimelineMatchedEvents} timelineConfidence={report.TimelineConfidence:0.000}"); + $"mimir-sync-report {report.ReferenceSourceId}->{report.SourceId} evidence={report.EvidenceKind} delaySamples={report.FractionalDelaySamples:0.000} delayMs={report.DelayMilliseconds:0.000} confidence={report.Confidence:0.000} timelineEvents={report.TimelineMatchedEvents} timelineConfidence={report.TimelineConfidence:0.000}"); } foreach (var state in states) @@ -274,7 +270,13 @@ public sealed class MimirRuntime : IAquariumRuntime private bool ShouldEmitCalibrationTimeline() { - return audioSyncSettings.Mode != MimirAudioSyncMode.NoChirp; + return audioSyncSettings.Mode switch + { + MimirAudioSyncMode.ChirpOnly => true, + MimirAudioSyncMode.Passive => false, + MimirAudioSyncMode.Hybrid => lastPassiveSynchronizationConfidence < HybridPassiveConfidenceThreshold, + _ => true, + }; } private string DescribeAudioSyncMode() @@ -282,8 +284,8 @@ public sealed class MimirRuntime : IAquariumRuntime return audioSyncSettings.Mode switch { MimirAudioSyncMode.ChirpOnly => "chirp-only", - MimirAudioSyncMode.NoChirp => "no-chirp", - MimirAudioSyncMode.Hybrid => "hybrid active-pilot", + MimirAudioSyncMode.Passive => "passive", + MimirAudioSyncMode.Hybrid => "hybrid", _ => audioSyncSettings.Mode.ToString(), }; } @@ -296,6 +298,18 @@ public sealed class MimirRuntime : IAquariumRuntime .Select(buffer => $"{buffer.Descriptor.SourceId}:{buffer.Count}@{buffer.EdgeNs}")); } + private void UpdatePassiveSynchronizationConfidence(IReadOnlyList reports) + { + var passiveConfidence = reports + .Where(report => string.Equals(report.EvidenceKind, "passive", StringComparison.Ordinal)) + .Select(report => report.Confidence) + .DefaultIfEmpty(0.0) + .Max(); + lastPassiveSynchronizationConfidence = passiveConfidence > 0.0 + ? passiveConfidence + : lastPassiveSynchronizationConfidence * 0.95; + } + private static string DescribeBuffer(MimirRollingStreamBuffer buffer) { var latest = buffer.Latest; @@ -314,15 +328,15 @@ public sealed class MimirRuntime : IAquariumRuntime private string DescribeAudioSync() { - if (audioSyncSettings.Mode == MimirAudioSyncMode.NoChirp) + if (audioSyncSettings.Mode == MimirAudioSyncMode.Passive) { - return "no-chirp mode; passive estimator not wired yet"; + return "passive mode; waiting for program-audio coherence"; } var reports = synchronization.AudioSynchronizationReports; return reports.Count == 0 ? "no payload windows" - : string.Join(" | ", reports.Select(report => $"{report.SourceId}: {report.FractionalDelaySamples:0.0} samples {report.DelayMilliseconds:0.00}ms c={report.Confidence:0.00} events={report.TimelineMatchedEvents}")); + : string.Join(" | ", reports.Select(report => $"{report.SourceId}: {report.FractionalDelaySamples:0.0} samples {report.DelayMilliseconds:0.00}ms c={report.Confidence:0.00} {report.EvidenceKind} events={report.TimelineMatchedEvents}")); } private string DescribeAlignedAudio() diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs index 0aeed10..1332ac9 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs @@ -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 lastDecodeTraces = []; + private readonly MimirPassiveAudioSynchronizationEstimator passiveEstimator = new(); public IReadOnlyList LastDecodeTraces => lastDecodeTraces; public IReadOnlyList Analyze( IEnumerable buffers, string referenceSourceId, + MimirAudioSyncMode mode = MimirAudioSyncMode.ChirpOnly, IReadOnlySet? 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; diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs index 5d3415f..f3a0b33 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs @@ -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"); diff --git a/src/Mimir.Runtime/Synchronization/MimirPassiveAudioSynchronizationEstimator.cs b/src/Mimir.Runtime/Synchronization/MimirPassiveAudioSynchronizationEstimator.cs new file mode 100644 index 0000000..accbb9f --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirPassiveAudioSynchronizationEstimator.cs @@ -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 reference, + ReadOnlySpan 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 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; + } + } +} diff --git a/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs b/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs index 619674b..2f1596c 100644 --- a/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs +++ b/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs @@ -71,16 +71,18 @@ public sealed class MimirSynchronizationHub : IDisposable } public IReadOnlyList 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 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; diff --git a/src/Mimir.Runtime/Synchronization/MimirSynchronizationSettings.cs b/src/Mimir.Runtime/Synchronization/MimirSynchronizationSettings.cs index 6d7cb3a..3d93366 100644 --- a/src/Mimir.Runtime/Synchronization/MimirSynchronizationSettings.cs +++ b/src/Mimir.Runtime/Synchronization/MimirSynchronizationSettings.cs @@ -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, } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index b994aa8..29e6baa 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -53,3 +53,5 @@ {"ts": "2026-05-22T18:08:51+01:00", "type": "verification", "status": "partial", "note": "Release live chirplet decoder test: Scarlett loopback->Scarlett mic produced repeated runtime reports in ~230-335 ms per 2s analysis window, typically 3-5 matched timeline events. Pair tests also produced reports for Kiyo mic. Kiyo Pro and both USB Camera mics showed chirplet energy but failed to form valid triplet anchors in this pass. Six-audio-source fan-out exposed process-probe buffer continuity/overlap failures, with many candidates rejected as insufficient-window."} {"ts": "2026-05-22T18:34:16+01:00", "type": "research", "status": "ok", "note": "Archived chirplet decoder research under research/chirplet-sync-decoder. Distilled conclusion: current BuildChirpletEnergyTrace is dense sliding matched filtering; for Mimir's controlled sync beacon, redesign symbol codebook for dechirp+FFT/Goertzel classification so code constraints shape the receiver before expensive scoring."} {"ts": "2026-05-22T18:47:44+01:00", "type": "implementation", "status": "ok", "note": "Added runtime-owned audio sync mode selection for chirp-only, no-chirp, and hybrid. Config/env now expose MIMIR_AUDIO_SYNC_MODE plus audioSync.mode/referenceSourceId/calibrationGain; no-chirp disables active calibration and reports passive sync as not wired yet, while hybrid currently uses the active pilot until passive confidence gating and shaped watermark emission are implemented. dotnet build and chirplet self-test passed."} +{"ts": "2026-05-22T19:08:10+01:00", "type": "implementation", "status": "ok", "note": "Renamed the public no-chirp mode to passive and started the real hybrid sync machine. Added MimirPassiveAudioSynchronizationEstimator using PHAT-weighted cross-spectrum delay estimation over loopback/program audio; MimirAudioSynchronizationAnalyzer now reports passive evidence in passive/hybrid modes and falls back to chirplet anchors when hybrid passive confidence is weak. Hybrid runtime emission now queues short active pilot chunks only while passive confidence stays below threshold. dotnet build, passive sync self-test, and chirplet self-test passed."} +{"ts": "2026-05-22T19:08:56+01:00", "type": "verification", "status": "partial", "note": "Passive live smoke with MIMIR_AUDIO_SYNC_MODE=passive and config/mimir-runtime.probes.example.json emitted no calibration audio and produced loopback/program-audio reports: Focusrite delaySamples=6653 confidence=0.805, Kiyo Pro delaySamples=6804 confidence=0.227, USB Camera 0 delaySamples=-882 confidence=1.000 over 88200 compared 44.1k samples. This proves the passive path can lock on real loopback/music, but the negative Eye delay needs timestamp/window-sign inspection before driving an actuator."} diff --git a/state/map.yaml b/state/map.yaml index f9d0571..93cc23e 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -95,9 +95,11 @@ accepted_design: instead of invoking analysis. `MIMIR_SYNC_TELEMETRY_SECONDS` prints live buffer/report/state telemetry. `MimirAudioSynchronizationSettings.Mode` now owns the active evidence policy: `chirp-only` emits the calibration - witness, `no-chirp` stays silent until passive program-audio sync exists, - and `hybrid` currently uses the active pilot until the passive confidence - gate and shaped watermark are built. + witness, `passive` stays silent and uses program-audio phase correlation, + and `hybrid` emits active pilot chunks only while passive confidence is + weak. `MimirPassiveAudioSynchronizationEstimator` is the first passive path: + it uses PHAT-weighted cross-spectrum correlation between loopback and mic + windows before any watermark is needed. - `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` are the live seam for Leap, Media Foundation, DirectShow, libusb, LeapC, or shared texture capture.