diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index ec00a24..c04c649 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -84,11 +84,14 @@ a named invariant that the native runtime cannot protect yet. fixed Goertzel bins, then feeds the same de Bruijn triplet timeline-anchor machine. The detector scores dechirped bin energy directly, caches chirp kernels per sample rate, and uses a widened 32-symbol codebook so sub-frame - timing error does not masquerade as neighboring symbol identity. Hybrid emits - this as low-gain half-second bursts every two seconds only while passive - confidence is weak. Use `--chirp-bin-self-test` to prove the codebook/decoder - and `--hybrid-sync-self-test` to prove that the analyzer can recover a - fractional delay from a one-second rolling-buffer chirp-bin window. + timing error does not masquerade as neighboring symbol identity. The matched + chirp-bin peak is refined below one sample and reports/states expose delay in + microseconds as well as fractional samples. Hybrid emits this as low-gain + half-second bursts every two seconds only while passive confidence is weak. + Use `--chirp-bin-self-test` to prove the codebook/decoder and + `--hybrid-sync-self-test` to prove that the analyzer can recover a fractional + delay from a one-second rolling-buffer chirp-bin window. The current synthetic + microsecond proof recovers a 317.375-sample delay with 0.369 us error. - `MimirVideoFrameDescriptor` for dimensions, pixel format, stride, device timestamp, and native/GPU handle metadata. - `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` as the live diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 831e148..7c21189 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -106,9 +106,11 @@ needs a longer program-audio window, while chirp-bin fallback can decode short pilot windows once at least a code-valid triplet is present. The chirp-bin detector now proposes events from dechirped bin energy rather than broadband RMS and uses a widened symbol spacing to keep sub-frame timing error from becoming -symbol substitution. `Mimir.BufferSmoke --hybrid-sync-self-test` proves the -analyzer path with a one-second rolling-buffer window and a recovered -317-sample delay. +symbol substitution. Chirp-bin frame timing is refined with a local matched-peak +fit below one sample, and reports/states expose `delayUs` next to fractional +sample delay. `Mimir.BufferSmoke --hybrid-sync-self-test` proves the analyzer +path with a one-second rolling-buffer window and a recovered 317.375-sample +delay at 0.369 us error. 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 fc82ccf..6500277 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -86,7 +86,9 @@ Get-Content .\state\evidence.jsonl -Tail 8 confidence is weak. Hybrid chirp-bin fallback now has its own short-window analyzer floor instead of inheriting the passive two-second gate, and `Mimir.BufferSmoke --hybrid-sync-self-test` proves a one-second rolling-buffer - window recovers a 317-sample delay from code-valid chirp-bin anchors. Actual + window recovers a 317.375-sample fractional delay with 0.369 us error from + code-valid chirp-bin anchors. Reports and sync states now expose `delayUs`. + Actual Mimir.App testing proves Aquarium audio can wake Scarlett loopback, keep mic buffers live, and produce confident online passive sync states. The latest live hybrid smoke did not prove acoustic chirp-bin decode diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index 9ba2087..224982a 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -80,13 +80,13 @@ var reports = hub.AnalyzeAudioSynchronization(syncReference, syncMode); foreach (var report in reports.OrderBy(report => report.SourceId, StringComparer.Ordinal)) { Console.WriteLine( - $"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}"); + $"sync {report.ReferenceSourceId}->{report.SourceId}: evidence={report.EvidenceKind} delaySamples={report.DelaySamples} fractionalDelaySamples={report.FractionalDelaySamples:0.000000} delayUs={report.DelayMicroseconds: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) { Console.WriteLine( - $"sync-state {state.ReferenceSourceId}->{state.SourceId}: smoothedDelaySamples={state.SmoothedDelaySamples:0.000} delayMs={state.DelayMilliseconds:0.000} sroPpm={state.SamplingRateOffsetPpm:0.000} confidence={state.Confidence:0.000} bands={DescribeBands(state.BandResponses)}"); + $"sync-state {state.ReferenceSourceId}->{state.SourceId}: smoothedDelaySamples={state.SmoothedDelaySamples:0.000000} delayUs={state.DelayMicroseconds:0.000} delayMs={state.DelayMilliseconds:0.000} sroPpm={state.SamplingRateOffsetPpm:0.000} confidence={state.Confidence:0.000} bands={DescribeBands(state.BandResponses)}"); } foreach (var trace in hub.AudioSynchronizationDecodeTraces.OrderBy(trace => trace.SourceId, StringComparer.Ordinal)) @@ -260,15 +260,14 @@ static int RunHybridSyncSelfTest() { const string referenceSourceId = "loopback-test"; const string candidateSourceId = "mic-test"; - const int delaySamples = 317; + const double delaySamples = 317.375; var firstSegment = MimirChirpBinTimeline.Default.RenderSegmentMonoFloat(0); var secondSegment = MimirChirpBinTimeline.Default.RenderSegmentMonoFloat(1); var reference = new float[firstSegment.Length + secondSegment.Length]; Array.Copy(firstSegment, 0, reference, 0, firstSegment.Length); Array.Copy(secondSegment, 0, reference, firstSegment.Length, secondSegment.Length); - var candidate = new float[reference.Length]; - Array.Copy(reference, 0, candidate, delaySamples, reference.Length - delaySamples); + var candidate = ApplyFractionalDelay(reference, delaySamples); var referenceBuffer = new MimirRollingStreamBuffer( new MimirStreamDescriptor(referenceSourceId, MimirStreamKind.Audio, MimirStreamOrigin.LocalDevice), @@ -297,15 +296,34 @@ static int RunHybridSyncSelfTest() var error = Math.Abs(report.FractionalDelaySamples - delaySamples); Console.WriteLine( - $"hybrid-sync-self-test evidence={report.EvidenceKind} delaySamples={report.FractionalDelaySamples:0.000} expected={delaySamples} error={error:0.000} confidence={report.Confidence:0.000} events={report.TimelineMatchedEvents} compared={report.ComparedSamples}"); + $"hybrid-sync-self-test evidence={report.EvidenceKind} delaySamples={report.FractionalDelaySamples:0.000000} delayUs={report.DelayMicroseconds:0.000} expected={delaySamples:0.000000} errorSamples={error:0.000000} errorUs={error * 1_000_000.0 / report.SampleRate:0.000} confidence={report.Confidence:0.000} events={report.TimelineMatchedEvents} compared={report.ComparedSamples}"); return string.Equals(report.EvidenceKind, "chirp-bin", StringComparison.Ordinal) && report.TimelineMatchedEvents >= 3 && report.Confidence > 0.70 && - error < 1.0 + error * 1_000_000.0 / report.SampleRate < 1.0 ? 0 : 1; } +static float[] ApplyFractionalDelay(float[] source, double delaySamples) +{ + var delayed = new float[source.Length]; + for (var index = 0; index < delayed.Length; index++) + { + var sourcePosition = index - delaySamples; + if (sourcePosition < 0.0 || sourcePosition >= source.Length - 1) + { + continue; + } + + var left = (int)Math.Floor(sourcePosition); + var fraction = sourcePosition - left; + delayed[index] = (float)(source[left] + (source[left + 1] - source[left]) * fraction); + } + + return delayed; +} + static void AppendFloatBlock(MimirRollingStreamBuffer buffer, string sourceId, float[] samples, int sampleRate) { var bytes = new byte[samples.Length * sizeof(float)]; diff --git a/src/Mimir.Runtime/MimirRuntime.cs b/src/Mimir.Runtime/MimirRuntime.cs index 8d132b7..83ff864 100644 --- a/src/Mimir.Runtime/MimirRuntime.cs +++ b/src/Mimir.Runtime/MimirRuntime.cs @@ -283,13 +283,13 @@ 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} 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}"); + $"mimir-sync-report {report.ReferenceSourceId}->{report.SourceId} evidence={report.EvidenceKind} delaySamples={report.FractionalDelaySamples:0.000000} delayUs={report.DelayMicroseconds: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) { Console.WriteLine( - $"mimir-sync-state {state.ReferenceSourceId}->{state.SourceId} delaySamples={state.SmoothedDelaySamples:0.000} delayMs={state.DelayMilliseconds:0.000} sroPpm={state.SamplingRateOffsetPpm:0.000} confidence={state.Confidence:0.000}"); + $"mimir-sync-state {state.ReferenceSourceId}->{state.SourceId} delaySamples={state.SmoothedDelaySamples:0.000000} delayUs={state.DelayMicroseconds:0.000} delayMs={state.DelayMilliseconds:0.000} sroPpm={state.SamplingRateOffsetPpm:0.000} confidence={state.Confidence:0.000}"); } foreach (var trace in synchronization.AudioSynchronizationDecodeTraces.OrderBy(trace => trace.SourceId, StringComparer.Ordinal)) @@ -383,7 +383,7 @@ public sealed class MimirRuntime : IAquariumRuntime 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} {report.EvidenceKind} events={report.TimelineMatchedEvents}")); + : string.Join(" | ", reports.Select(report => $"{report.SourceId}: {report.FractionalDelaySamples:0.000} samples {report.DelayMicroseconds:0.0}us c={report.Confidence:0.00} {report.EvidenceKind} events={report.TimelineMatchedEvents}")); } private string DescribeAlignedAudio() @@ -399,6 +399,6 @@ public sealed class MimirRuntime : IAquariumRuntime var states = synchronization.AudioSynchronizationStates; return states.Count == 0 ? "no sync state" - : string.Join(" | ", states.Select(state => $"{state.SourceId}: {state.SmoothedDelaySamples:0.0} samples sro={state.SamplingRateOffsetPpm:0.0}ppm c={state.Confidence:0.00}")); + : string.Join(" | ", states.Select(state => $"{state.SourceId}: {state.SmoothedDelaySamples:0.000} samples {state.DelayMicroseconds:0.0}us sro={state.SamplingRateOffsetPpm:0.0}ppm c={state.Confidence:0.00}")); } } diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs index f3a0b33..e3534d0 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationReport.cs @@ -15,4 +15,7 @@ public sealed record MimirAudioSynchronizationReport( ulong SourceSequence, int TimelineMatchedEvents = 0, double TimelineConfidence = 0.0, - string EvidenceKind = "chirplet"); + string EvidenceKind = "chirplet") +{ + public double DelayMicroseconds => FractionalDelaySamples * 1_000_000.0 / SampleRate; +} diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationState.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationState.cs index 819d464..21fbb5c 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationState.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationState.cs @@ -12,7 +12,10 @@ public sealed record MimirAudioSynchronizationState( IReadOnlyList BandResponses, long UpdatedAtNs, ulong ReferenceSequence, - ulong SourceSequence); + ulong SourceSequence) +{ + public double DelayMicroseconds => SmoothedDelaySamples * 1_000_000.0 / SampleRate; +} public sealed class MimirAudioSynchronizationStateTracker { diff --git a/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs b/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs index b378445..c118f46 100644 --- a/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs +++ b/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs @@ -192,7 +192,10 @@ public sealed class MimirChirpBinTimeline return null; } - return new MimirChirpletTransformFrame(bestOffset, bestCandidates); + var refinedOffset = RefineOffset(samples, sampleRate, bestOffset, bestCandidates[0].SymbolId, chirpSamples); + return new MimirChirpletTransformFrame( + refinedOffset, + bestCandidates.Select(candidate => candidate with { SampleOffset = refinedOffset }).ToArray()); } private static MimirChirpletSymbolCandidate[] ScoreBins( @@ -251,6 +254,49 @@ public sealed class MimirChirpBinTimeline return 2.0 * best / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy); } + private static double ScoreSymbolEnergy(ReadOnlySpan samples, int sampleRate, int symbolId) + { + var kernels = KernelSets.GetOrAdd(sampleRate, BuildKernelSet); + var sampleEnergy = 0.0; + for (var index = 0; index < samples.Length; index++) + { + sampleEnergy += samples[index] * samples[index]; + } + + if (sampleEnergy <= 1.0e-12 || kernels.ReferenceEnergy <= 1.0e-12) + { + return 0.0; + } + + var score = DechirpedBin(samples, kernels.Symbols[symbolId]); + return 2.0 * score / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy); + } + + private static double RefineOffset( + ReadOnlySpan samples, + int sampleRate, + int bestOffset, + int symbolId, + int chirpSamples) + { + if (bestOffset <= 0 || bestOffset >= samples.Length - chirpSamples - 1) + { + return bestOffset; + } + + var left = ScoreSymbolEnergy(samples.Slice(bestOffset - 1, chirpSamples), sampleRate, symbolId); + var center = ScoreSymbolEnergy(samples.Slice(bestOffset, chirpSamples), sampleRate, symbolId); + var right = ScoreSymbolEnergy(samples.Slice(bestOffset + 1, chirpSamples), sampleRate, symbolId); + var denominator = left - 2.0 * center + right; + if (Math.Abs(denominator) <= 1.0e-12) + { + return bestOffset; + } + + var delta = 0.5 * (left - right) / denominator; + return bestOffset + Math.Clamp(delta, -0.5, 0.5); + } + private static double DechirpedBin(ReadOnlySpan samples, ChirpBinKernel kernel) { var real = 0.0; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index d132856..b959665 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -59,3 +59,4 @@ {"ts": "2026-05-22T19:49:43+01:00", "type": "implementation", "status": "partial", "note": "Built the first chirp-bin active watermark machine. MimirChirpBinTimeline renders a fixed-slope/window 32-bin chirp codebook and decodes with one dechirp plus fixed Goertzel bin scoring, then feeds de Bruijn triplet anchors and clock fitting. Hybrid fallback now renders/decodes chirp-bin evidence instead of the old dense chirplet matcher. Synthetic --chirp-bin-self-test passed with 23 frames, 21 anchors, 48000 Hz clock, and zero MAE; old --chirplet-self-test still passed. A real hybrid app run emitted chirp-bin batches, but the current probe config's 30s capture limit left loopback/mic windows stale before acoustic chirp-bin reports could be proven."} {"ts": "2026-05-22T19:58:44+01:00", "type": "implementation", "status": "ok", "note": "Fixed hybrid watermark being obtrusive. Root causes: Aquarium applied EnqueuePcm16Base64 gain twice, Mimir treated immediate audio chunks like scheduled future segments and caught up missed hybrid segments as audible backlog, and probe configs stopped WASAPI capture after 30s. Aquarium now applies queued PCM gain once; Mimir hybrid uses separate low watermarkGain default 0.035, emits one 0.5s chirp-bin burst every 2s only while passive confidence is weak, and skips missed segments instead of catch-up dumping. Probe audio durations are now 3600s. Short hybrid app run showed batches at firstSegment 0,4,8,12 with gain 0.035."} {"ts": "2026-05-22T20:32:10+01:00", "type": "verification", "status": "ok", "note": "Hybrid chirp-bin analyzer no longer inherits passive 2s gate: short-window self-test feeds rolling buffers with 1s chirp-bin loopback/candidate audio and recovers a 317-sample delay exactly with 5 matched events and 0.854 confidence. Live app smoke after the fix did not prove acoustic decode because Scarlett loopback stalled after one block, so that run is loopback freshness evidence rather than duration evidence."} +{"ts": "2026-05-23T10:26:32+01:00", "type": "verification", "status": "ok", "note": "Chirp-bin hybrid analyzer now proves microsecond-scale fractional timing in memory: --hybrid-sync-self-test uses a 317.375-sample delayed rolling-buffer candidate and recovers 317.392716 samples, 0.017716 samples / 0.369 us error, with 5 matched chirp-bin events and 0.851 confidence. Reports and sync states now expose delayUs alongside fractional samples."} diff --git a/state/map.yaml b/state/map.yaml index 97b933b..b98fe88 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -104,15 +104,17 @@ accepted_design: confidence is capped below certainty until repeated state earns it. `MimirChirpBinTimeline` is the active hybrid watermark path: one fixed chirp slope/window, 32 widened symbol frequency bins, dechirped bin-energy - proposal scoring, cached per-sample-rate kernels, then the existing - de Bruijn triplet anchor and clock-fit machine. Hybrid emits it as low-gain - half-second bursts every two seconds while passive confidence is weak, never - as catch-up backlog. The analyzer no longer applies the passive two-second - window floor to chirp-bin fallback; `dotnet run --project + proposal scoring, cached per-sample-rate kernels, sub-sample matched-peak + refinement, then the existing de Bruijn triplet anchor and clock-fit + machine. Reports and sync states expose delay in microseconds as well as + fractional samples. Hybrid emits it as low-gain half-second bursts every two + seconds while passive confidence is weak, never as catch-up backlog. The + analyzer no longer applies the passive two-second window floor to chirp-bin + fallback; `dotnet run --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --hybrid-sync-self-test` proves a one-second rolling-buffer chirp-bin window can recover a - 317-sample fractional delay from code-valid anchors. The synthetic codebook - proof remains `dotnet run --project + 317.375-sample fractional delay from code-valid anchors with 0.369 us + error. The synthetic codebook proof remains `dotnet run --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --chirp-bin-self-test`. - `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` are the live seam for Leap, Media Foundation, DirectShow, libusb, LeapC, or shared