From d18e86003019d6978a5cc36a521690bccb57f25f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 22 May 2026 20:34:12 +0100 Subject: [PATCH] Fix hybrid chirp-bin analyzer windowing --- docs/implementation-plan.md | 10 +- notes/current-system-map.md | 8 + notes/fresh-workspace-handoff.md | 13 +- src/Mimir.BufferSmoke/Program.cs | 81 +++++++++ .../MimirAudioSynchronizationAnalyzer.cs | 166 +++++++++++------- .../Synchronization/MimirChirpBinTimeline.cs | 164 +++++++++++------ state/evidence.jsonl | 1 + state/map.yaml | 14 +- 8 files changed, 331 insertions(+), 126 deletions(-) diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 5a51ebb..ec00a24 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -82,9 +82,13 @@ a named invariant that the native runtime cannot protect yet. - `MimirChirpBinTimeline` is the active hybrid watermark path. It renders a fixed-slope chirp-bin codebook and decodes symbols with one dechirp plus fixed Goertzel bins, then feeds the same de Bruijn triplet timeline-anchor - machine. 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 - this path without hardware. + 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. - `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 81bb6f0..831e148 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -101,6 +101,14 @@ path. 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. +Hybrid does not inherit the passive two-second analysis floor: passive still +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. 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 b7e7836..fc82ccf 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -83,10 +83,15 @@ Get-Content .\state\evidence.jsonl -Tail 8 passive. Audio sync mode is runtime-owned: `chirp-only` emits active 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 + 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 + 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 + because Scarlett loopback stalled after one block in that run; treat that as + loopback freshness evidence, not duration evidence. PS3 Eye audio is enumeration/runtime-fragile: one run saw both mic buffers empty while both cameras were live, then a replug made both PS3 Eye mic buffers emit 480-frame WASAPI blocks again. diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index 5e20472..9ba2087 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -15,6 +15,11 @@ if (args.Any(arg => string.Equals(arg, "--passive-sync-self-test", StringCompari return RunPassiveSyncSelfTest(); } +if (args.Any(arg => string.Equals(arg, "--hybrid-sync-self-test", StringComparison.OrdinalIgnoreCase))) +{ + return RunHybridSyncSelfTest(); +} + 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)); @@ -251,6 +256,82 @@ static int RunPassiveSyncSelfTest() return 0; } +static int RunHybridSyncSelfTest() +{ + const string referenceSourceId = "loopback-test"; + const string candidateSourceId = "mic-test"; + const int delaySamples = 317; + + 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 referenceBuffer = new MimirRollingStreamBuffer( + new MimirStreamDescriptor(referenceSourceId, MimirStreamKind.Audio, MimirStreamOrigin.LocalDevice), + TimeSpan.FromSeconds(5)); + var candidateBuffer = new MimirRollingStreamBuffer( + new MimirStreamDescriptor(candidateSourceId, MimirStreamKind.Audio, MimirStreamOrigin.LocalDevice), + TimeSpan.FromSeconds(5)); + + AppendFloatBlock(referenceBuffer, referenceSourceId, reference, MimirChirpBinTimeline.SampleRate); + AppendFloatBlock(candidateBuffer, candidateSourceId, candidate, MimirChirpBinTimeline.SampleRate); + + var analyzer = new MimirAudioSynchronizationAnalyzer(); + var reports = analyzer.Analyze([referenceBuffer, candidateBuffer], referenceSourceId, MimirAudioSyncMode.Hybrid); + var report = reports.SingleOrDefault(); + foreach (var trace in analyzer.LastDecodeTraces) + { + Console.WriteLine( + $"hybrid-sync-trace {trace.ReferenceSourceId}->{trace.SourceId}: status={trace.Status} compared={trace.ComparedSamples} refFrames={trace.ReferenceFrames} refAnchors={trace.ReferenceAnchors} candFrames={trace.CandidateFrames} candAnchors={trace.CandidateAnchors} matched={trace.MatchedEvents} confidence={trace.Confidence:0.000}"); + } + + if (report == null) + { + Console.Error.WriteLine("hybrid sync self-test failed: analyzer did not report from a short chirp-bin window"); + return 1; + } + + 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}"); + return string.Equals(report.EvidenceKind, "chirp-bin", StringComparison.Ordinal) && + report.TimelineMatchedEvents >= 3 && + report.Confidence > 0.70 && + error < 1.0 + ? 0 + : 1; +} + +static void AppendFloatBlock(MimirRollingStreamBuffer buffer, string sourceId, float[] samples, int sampleRate) +{ + var bytes = new byte[samples.Length * sizeof(float)]; + for (var index = 0; index < samples.Length; index++) + { + BitConverter.TryWriteBytes(bytes.AsSpan(index * sizeof(float), sizeof(float)), samples[index]); + } + + buffer.Append(new MimirStreamSample( + sourceId, + MimirStreamKind.Audio, + MimirStreamOrigin.LocalDevice, + 1_000_000_000L, + 1_000_000_000L, + 1, + 0, + bytes.Length, + bytes, + AudioBlock: new MimirAudioBlockDescriptor( + sampleRate, + 1, + MimirAudioSampleFormat.Float32, + samples.Length, + 1_000_000_000L))); +} + internal sealed class DisposableConfiguration : IDisposable { private readonly List ownedSources; diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs index 635eab7..5eee296 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs @@ -5,7 +5,9 @@ namespace Mimir.Runtime.Synchronization; public sealed class MimirAudioSynchronizationAnalyzer { private const int MaxWindowSamples = 48_000 * 2; - private const double MinDecodeWindowSeconds = 2.0; + private const double MinPassiveWindowSeconds = 2.0; + private const double MinChirpletWindowSeconds = 2.0; + private const double MinChirpBinWindowSeconds = 0.40; private const double PassiveReportConfidence = 0.08; private readonly List lastDecodeTraces = []; private readonly MimirPassiveAudioSynchronizationEstimator passiveEstimator = new(); @@ -83,73 +85,85 @@ public sealed class MimirAudioSynchronizationAnalyzer candidateSamples = ResampleToRate(candidateSamples, candidateBlock.SampleRate, activeReferenceBlock.SampleRate); 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, - activeReferenceBlock.SampleRate, - compared, - 0, - 0, - 0.0, - 0.0, - 0, - 0, - 0.0, - 0.0, - 0, - 0.0, - "insufficient-window")); - continue; - } - var referenceWindow = alignedReferenceSamples.AsSpan(^compared..); var candidateWindow = candidateSamples.AsSpan(^compared..); if (mode != MimirAudioSyncMode.ChirpOnly) { - var passive = passiveEstimator.Estimate(referenceWindow, candidateWindow, activeReferenceBlock.SampleRate); - lastDecodeTraces.Add(new MimirAudioSynchronizationDecodeTrace( + var minPassiveSamples = MinWindowSamples(activeReferenceBlock.SampleRate, MinPassiveWindowSeconds); + if (compared >= minPassiveSamples) + { + 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; + } + } + else + { + lastDecodeTraces.Add(InsufficientWindowTrace( + reference.Descriptor.SourceId, + buffer.Descriptor.SourceId, + activeReferenceBlock.SampleRate, + compared, + "passive-insufficient-window")); + if (mode == MimirAudioSyncMode.Passive) + { + continue; + } + } + } + + var activeMinSeconds = mode == MimirAudioSyncMode.Hybrid + ? MinChirpBinWindowSeconds + : MinChirpletWindowSeconds; + var minActiveSamples = MinWindowSamples(activeReferenceBlock.SampleRate, activeMinSeconds); + if (compared < minActiveSamples) + { + lastDecodeTraces.Add(InsufficientWindowTrace( 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; - } + compared, + mode == MimirAudioSyncMode.Hybrid + ? "chirp-bin-insufficient-window" + : "chirplet-insufficient-window")); + continue; } var comparedReferenceDecode = mode == MimirAudioSyncMode.Hybrid @@ -205,6 +219,36 @@ public sealed class MimirAudioSynchronizationAnalyzer return reports; } + private static int MinWindowSamples(int sampleRate, double seconds) + { + return Math.Min(MaxWindowSamples, (int)Math.Ceiling(sampleRate * seconds)); + } + + private static MimirAudioSynchronizationDecodeTrace InsufficientWindowTrace( + string referenceSourceId, + string candidateSourceId, + int sampleRate, + int comparedSamples, + string status) + { + return new MimirAudioSynchronizationDecodeTrace( + referenceSourceId, + candidateSourceId, + sampleRate, + comparedSamples, + 0, + 0, + 0.0, + 0.0, + 0, + 0, + 0.0, + 0.0, + 0, + 0.0, + status); + } + private static double BestFrameEnergy(MimirChirpletStreamDecode decode) { return decode.Frames.Count == 0 diff --git a/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs b/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs index d3d425c..b378445 100644 --- a/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs +++ b/src/Mimir.Runtime/Synchronization/MimirChirpBinTimeline.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Numerics; namespace Mimir.Runtime.Synchronization; @@ -6,6 +7,14 @@ public sealed record MimirChirpBinSymbolDefinition( int SymbolId, double OffsetHz); +internal sealed record ChirpBinKernel( + double[] Real, + double[] Imaginary); + +internal sealed record ChirpBinKernelSet( + ChirpBinKernel[] Symbols, + double ReferenceEnergy); + public sealed class MimirChirpBinTimeline { public const int SampleRate = 48_000; @@ -17,14 +26,16 @@ public sealed class MimirChirpBinTimeline private const double EventSpacingSeconds = 0.125; private const double ChirpDurationSeconds = 0.064; private const double BaseStartHz = 7_600.0; - private const double BaseEndHz = 14_800.0; - private const double BinSpacingHz = 62.5; + private const double BaseEndHz = 13_600.0; + private const double BinSpacingHz = 450.0; private const double Gain = 0.070; - private const int MaxSymbolCandidatesPerFrame = 6; + private const int MaxSymbolCandidatesPerFrame = 1; + private const int MaxTimingBinShift = 4; private static readonly int[] TimelineSymbols = RotateToDistinctOpening(BuildDeBruijn(SymbolCount, TimelineOrder)); private static readonly Dictionary TripleToIndex = BuildTripleIndex(TimelineSymbols); private static readonly MimirChirpBinSymbolDefinition[] Symbols = BuildSymbols(); + private static readonly ConcurrentDictionary KernelSets = new(); public static MimirChirpBinTimeline Default { get; } = new(); @@ -105,8 +116,8 @@ public sealed class MimirChirpBinTimeline return []; } - var hopSamples = Math.Max(1, sampleRate / 400); - var energyTrace = BuildEnergyTrace(samples, chirpSamples, hopSamples); + var hopSamples = Math.Max(1, sampleRate / 1_200); + var energyTrace = BuildDechirpedEnergyTrace(samples, sampleRate, chirpSamples, hopSamples); var threshold = AdaptiveThreshold(energyTrace); var proposals = new List(); for (var index = 1; index < energyTrace.Length - 1; index++) @@ -154,7 +165,7 @@ public sealed class MimirChirpBinTimeline { var candidates = ScoreBins(samples.Slice(offset, chirpSamples), sampleRate, offset); var energy = candidates.Length == 0 ? 0.0 : candidates[0].Energy; - if (energy > bestEnergy) + if (energy > bestEnergy || (energy >= bestEnergy * 0.995 && offset > bestOffset)) { bestEnergy = energy; bestOffset = offset; @@ -168,7 +179,7 @@ public sealed class MimirChirpBinTimeline { var candidates = ScoreBins(samples.Slice(offset, chirpSamples), sampleRate, offset); var energy = candidates.Length == 0 ? 0.0 : candidates[0].Energy; - if (energy > bestEnergy) + if (energy > bestEnergy || (energy >= bestEnergy * 0.995 && offset > bestOffset)) { bestEnergy = energy; bestOffset = offset; @@ -176,7 +187,7 @@ public sealed class MimirChirpBinTimeline } } - if (bestCandidates.Length == 0 || bestEnergy < 0.11) + if (bestCandidates.Length == 0 || bestEnergy < 0.055) { return null; } @@ -189,29 +200,26 @@ public sealed class MimirChirpBinTimeline int sampleRate, int sampleOffset) { + var kernels = KernelSets.GetOrAdd(sampleRate, BuildKernelSet); var scores = new MimirChirpletSymbolCandidate[Symbols.Length]; var sampleEnergy = 0.0; - var referenceEnergy = 0.0; for (var index = 0; index < samples.Length; index++) { sampleEnergy += samples[index] * samples[index]; - var normalized = samples.Length <= 1 ? 1.0 : index / (double)(samples.Length - 1); - var window = 0.5 - 0.5 * Math.Cos(2.0 * Math.PI * normalized); - referenceEnergy += window * window * 0.5; } - if (sampleEnergy <= 1.0e-12 || referenceEnergy <= 1.0e-12) + if (sampleEnergy <= 1.0e-12 || kernels.ReferenceEnergy <= 1.0e-12) { return []; } for (var symbol = 0; symbol < Symbols.Length; symbol++) { - var score = GoertzelDechirpedBin(samples, sampleRate, Symbols[symbol].OffsetHz); + var score = DechirpedBin(samples, kernels.Symbols[symbol]); scores[symbol] = new MimirChirpletSymbolCandidate( symbol, sampleOffset, - 2.0 * score / Math.Sqrt(sampleEnergy * referenceEnergy)); + 2.0 * score / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy)); } return scores @@ -220,21 +228,37 @@ public sealed class MimirChirpBinTimeline .ToArray(); } - private static double GoertzelDechirpedBin(ReadOnlySpan samples, int sampleRate, double offsetHz) + private static double ScoreBestBinEnergy(ReadOnlySpan samples, int sampleRate) + { + 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 best = 0.0; + foreach (var kernel in kernels.Symbols) + { + best = Math.Max(best, DechirpedBin(samples, kernel)); + } + + return 2.0 * best / Math.Sqrt(sampleEnergy * kernels.ReferenceEnergy); + } + + private static double DechirpedBin(ReadOnlySpan samples, ChirpBinKernel kernel) { var real = 0.0; var imaginary = 0.0; for (var index = 0; index < samples.Length; index++) { - var t = index / (double)sampleRate; - var normalized = samples.Length <= 1 ? 1.0 : index / (double)(samples.Length - 1); - var window = 0.5 - 0.5 * Math.Cos(2.0 * Math.PI * normalized); - var basePhase = BasePhase(t); - var binPhase = 2.0 * Math.PI * offsetHz * t; - var phase = -(basePhase + binPhase); - var value = samples[index] * window; - real += value * Math.Cos(phase); - imaginary += value * Math.Sin(phase); + real += samples[index] * kernel.Real[index]; + imaginary += samples[index] * kernel.Imaginary[index]; } return Math.Sqrt(real * real + imaginary * imaginary); @@ -264,14 +288,19 @@ public sealed class MimirChirpBinTimeline foreach (var first in firstFrame.Candidates) foreach (var second in secondFrame.Candidates) foreach (var third in thirdFrame.Candidates) + for (var timingBinShift = -MaxTimingBinShift; timingBinShift <= MaxTimingBinShift; timingBinShift++) { - var code = TripleCode(first.SymbolId, second.SymbolId, third.SymbolId); + var code = TripleCode( + ShiftSymbol(first.SymbolId, -timingBinShift), + ShiftSymbol(second.SymbolId, -timingBinShift), + ShiftSymbol(third.SymbolId, -timingBinShift)); if (!TripleToIndex.TryGetValue(code, out var eventIndex)) { continue; } var firstEvent = Default.EventForIndex((ulong)eventIndex); + var correctedFirstOffset = first.SampleOffset - timingBinShift * BinShiftSamples(sampleRate); var measuredGapA = (second.SampleOffset - first.SampleOffset) / sampleRate; var measuredGapB = (third.SampleOffset - second.SampleOffset) / sampleRate; var gapError = Math.Abs(measuredGapA - EventSpacingSeconds) + Math.Abs(measuredGapB - EventSpacingSeconds); @@ -285,12 +314,12 @@ public sealed class MimirChirpBinTimeline candidates.Add(new MimirChirpletTimelineAnchor( (ulong)eventIndex, firstEvent.StartSeconds, - first.SampleOffset, - gapConfidence * 0.60 + energyConfidence * 0.40, + correctedFirstOffset, + (gapConfidence * 0.60 + energyConfidence * 0.40) / (1.0 + Math.Abs(timingBinShift) * 0.15), [ - new MimirChirpletSymbolObservation(first.SymbolId, first.SampleOffset, first.Energy), - new MimirChirpletSymbolObservation(second.SymbolId, second.SampleOffset, second.Energy), - new MimirChirpletSymbolObservation(third.SymbolId, third.SampleOffset, third.Energy), + new MimirChirpletSymbolObservation(ShiftSymbol(first.SymbolId, -timingBinShift), correctedFirstOffset, first.Energy), + new MimirChirpletSymbolObservation(ShiftSymbol(second.SymbolId, -timingBinShift), second.SampleOffset - timingBinShift * BinShiftSamples(sampleRate), second.Energy), + new MimirChirpletSymbolObservation(ShiftSymbol(third.SymbolId, -timingBinShift), third.SampleOffset - timingBinShift * BinShiftSamples(sampleRate), third.Energy), ])); } } @@ -405,31 +434,13 @@ public sealed class MimirChirpBinTimeline meanAbsoluteError); } - private static float[] BuildEnergyTrace(ReadOnlySpan samples, int windowSamples, int hopSamples) + private static float[] BuildDechirpedEnergyTrace(ReadOnlySpan samples, int sampleRate, int windowSamples, int hopSamples) { var output = new float[1 + (samples.Length - windowSamples) / hopSamples]; - var energy = 0.0; - for (var index = 0; index < windowSamples; index++) + for (var frame = 0; frame < output.Length; frame++) { - energy += samples[index] * samples[index]; - } - - output[0] = (float)Math.Sqrt(energy / windowSamples); - for (var frame = 1; frame < output.Length; frame++) - { - var previousStart = (frame - 1) * hopSamples; - var nextStart = frame * hopSamples; - for (var index = previousStart; index < nextStart; index++) - { - energy -= samples[index] * samples[index]; - } - - for (var index = previousStart + windowSamples; index < nextStart + windowSamples; index++) - { - energy += samples[index] * samples[index]; - } - - output[frame] = (float)Math.Sqrt(Math.Max(0.0, energy) / windowSamples); + var offset = frame * hopSamples; + output[frame] = (float)ScoreBestBinEnergy(samples.Slice(offset, windowSamples), sampleRate); } return output; @@ -494,18 +505,63 @@ public sealed class MimirChirpBinTimeline var normalized = frameCount <= 1 ? 1.0 : frame / (double)(frameCount - 1); var t = frame / (double)sampleRate; - var envelope = 0.5 - 0.5 * Math.Cos(2.0 * Math.PI * normalized); + var envelope = Envelope(normalized); var phase = BasePhase(t) + 2.0 * Math.PI * symbol.OffsetHz * t; samples[outputFrame] += (float)(Math.Sin(phase) * envelope * Gain); } } + private static double Envelope(double normalized) + { + var attack = Math.Clamp(normalized / 0.10, 0.0, 1.0); + var release = Math.Clamp((1.0 - normalized) / 0.90, 0.0, 1.0); + return attack * Math.Sqrt(release); + } + private static double BasePhase(double t) { var slope = (BaseEndHz - BaseStartHz) / ChirpDurationSeconds; return 2.0 * Math.PI * (BaseStartHz * t + 0.5 * slope * t * t); } + private static int ShiftSymbol(int symbolId, int shift) => + (symbolId + shift + SymbolCount) % SymbolCount; + + private static double BinShiftSamples(int sampleRate) + { + var slope = (BaseEndHz - BaseStartHz) / ChirpDurationSeconds; + return BinSpacingHz * sampleRate / slope; + } + + private static ChirpBinKernelSet BuildKernelSet(int sampleRate) + { + var chirpSamples = Math.Max(1, (int)Math.Round(ChirpDurationSeconds * sampleRate)); + var symbolKernels = new ChirpBinKernel[Symbols.Length]; + var referenceEnergy = 0.0; + for (var symbol = 0; symbol < Symbols.Length; symbol++) + { + var real = new double[chirpSamples]; + var imaginary = new double[chirpSamples]; + for (var index = 0; index < chirpSamples; index++) + { + var t = index / (double)sampleRate; + var normalized = chirpSamples <= 1 ? 1.0 : index / (double)(chirpSamples - 1); + var window = Envelope(normalized); + var phase = -(BasePhase(t) + 2.0 * Math.PI * Symbols[symbol].OffsetHz * t); + real[index] = window * Math.Cos(phase); + imaginary[index] = window * Math.Sin(phase); + if (symbol == 0) + { + referenceEnergy += window * window * 0.5; + } + } + + symbolKernels[symbol] = new ChirpBinKernel(real, imaginary); + } + + return new ChirpBinKernelSet(symbolKernels, referenceEnergy); + } + private static MimirChirpBinSymbolDefinition[] BuildSymbols() { var symbols = new MimirChirpBinSymbolDefinition[SymbolCount]; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index ff2e228..d132856 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -58,3 +58,4 @@ {"ts": "2026-05-22T19:33:21+01:00", "type": "verification", "status": "ok", "note": "Fixed passive sync confidence bug. Negative passive lags now produce status=passive-negative-lag with confidence=0, single-window passive confidence is capped at 0.85, and hub invalidates cached reports/state for negative-lag traces. Passive self-test now proves both positive delay recovery and reversed-input zero confidence. A 14s live passive smoke showed negative Focusrite evidence at confidence 0 without leaving a report/state, while positive passive reports stayed capped at 0.85."} {"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."} diff --git a/state/map.yaml b/state/map.yaml index 296c3d8..97b933b 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -103,10 +103,16 @@ accepted_design: contradictory evidence and carry zero confidence; single-window passive confidence is capped below certainty until repeated state earns it. `MimirChirpBinTimeline` is the active hybrid watermark path: one fixed chirp - slope/window, 32 symbol frequency bins, dechirp plus fixed Goertzel bin - scoring, 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 synthetic proof is `dotnet run --project + 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 + .\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 .\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