From 643581a22e469a33e018a9bf548839b935e0d2a7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 22 May 2026 13:24:38 +0100 Subject: [PATCH] Make chirplet sync continuous --- docs/audio-field.md | 75 ++-- docs/implementation-plan.md | 17 +- notes/current-system-map.md | 22 +- notes/fresh-workspace-handoff.md | 22 +- src/Mimir.Runtime/MimirRuntime.cs | 37 +- .../MimirAudioSynchronizationAnalyzer.cs | 6 +- .../MimirChirpletCalibrationPhrase.cs | 324 ------------------ .../Synchronization/MimirChirpletTimeline.cs | 319 +++++++++++++++++ state/evidence.jsonl | 1 + state/map.yaml | 30 +- 10 files changed, 413 insertions(+), 440 deletions(-) delete mode 100644 src/Mimir.Runtime/Synchronization/MimirChirpletCalibrationPhrase.cs create mode 100644 src/Mimir.Runtime/Synchronization/MimirChirpletTimeline.cs diff --git a/docs/audio-field.md b/docs/audio-field.md index fa020df..923f314 100644 --- a/docs/audio-field.md +++ b/docs/audio-field.md @@ -49,24 +49,22 @@ loopback audio is actively playing. One PS3 Eye mic previously enumerated but produced zero WASAPI packets until that Eye was unplugged and replugged. The full probe runtime config now enables sample-bearing blocks for every local -audio source. `MimirChirpletCalibrationPhrase` owns the emitted calibration -phrase and the matched-filter shape used to analyze it. The default timeline is -a stateless 16-phrase cycle. Phrase `N` is generated directly from `N`, with no -registry or remembered random state. Each phrase is a spread-out asymmetric -motif: six short chirplets over about 0.85 seconds, with nonuniform gaps and -high-frequency bands. A new phrase fires every 2.25 seconds through Aquarium -audio. The point is not ornament. The timing code is carried by both frequency -and rhythm, so it behaves more like a small birdsong signature than a repeated -sweep. The indexed phrase sequence has lower ambiguity when remote feeds add -network/encoding latency. +audio source. `MimirChirpletTimeline` owns the emitted calibration stream and +the matched-filter shape used to analyze it. The default timeline is +deterministic and unbounded: event `N` is generated directly from `N`, with no +registry, remembered random state, or repeat cycle. Mimir queues half-second PCM +segments ahead of the audio cursor, and each segment contains short asymmetric +chirplets chosen from a harmonic high-frequency vocabulary. The point is not +ornament. The timing code is carried by both frequency and rhythm, so it behaves +more like a quiet birdsong texture than a repeated sweep. `MimirAudioSynchronizationAnalyzer` resamples candidate mic windows into the -loopback sample-rate timeline, projects loopback and candidate windows through -the same phrase, contrast-normalizes the resulting energy traces, and estimates -current delay against `loopback-scarlett-speakers`. The lag search is wide -enough for ordinary remote/network delay, not just local speaker-to-mic delay. -Reports carry both rounded integer delay and fractional delay from parabolic -peak interpolation over the chirplet correlation peak. +loopback sample-rate timeline, projects loopback and candidate windows through a +continuous chirplet atom bank, contrast-normalizes the resulting energy traces, +and estimates current delay against `loopback-scarlett-speakers`. The lag search +is wide enough for ordinary remote/network delay, not just local speaker-to-mic +delay. Reports carry both rounded integer delay and fractional delay from +parabolic peak interpolation over the chirplet correlation peak. `MimirSynchronizationHub.BuildAlignedAudioFrame` returns a provisional aligned mono frame: loopback is always channel zero, and other channels enter only when @@ -77,32 +75,33 @@ candidate mic is late relative to loopback. The current chirplet trace uses a still rounds to integer samples; the fractional estimate exists so the next actuator can drive a real fractional-delay line. -The same phrase also starts the frequency-response path. Each report includes -per-band matched energy for the phrase tones. That is not a finished room/mic +The same timeline also starts the frequency-response path. Each report includes +per-band matched energy for the chirplet atoms. That is not a finished room/mic normalizer yet, but it is the live surface that will become response-curve estimation: loopback carries what was emitted, each mic carries what survived -speaker, air, room, and capsule, and the ratio over repeated chirplet phrases -becomes gain/phase correction evidence. +speaker, air, room, and capsule, and the ratio over the continuous chirplet +timeline becomes gain/phase correction evidence. -`MimirAudioSynchronizationStateTracker` turns per-phrase observations into +`MimirAudioSynchronizationStateTracker` turns continuous observations into state. It confidence-gates reports, smooths fractional delay per source, and estimates delay slope as sampling-rate offset in ppm. This is the control input for the coming actuator. The state can survive a brief weak report, but it is -not a license to run blind: loopback must keep receiving the emitted phrase or +not a license to run blind: loopback must keep receiving the emitted timeline or fresh reports will stop. -The actual Mimir app path now runs this online: `MimirRuntime.Update` emits the -phrase sequence, polls sources, and updates sync analysis on a fixed cadence. +The actual Mimir app path now runs this online: `MimirRuntime.Update` keeps the +chirplet timeline queued, polls sources, and updates sync analysis on a fixed cadence. `MIMIR_SYNC_TELEMETRY_SECONDS` enables console telemetry for live tests. Current -runtime testing proves Aquarium output wakes the Scarlett loopback and the mic -buffers stay live, but the app has not yet produced a confident acoustic lock. -That next failure is calibration, not plumbing. +runtime testing proves Aquarium output wakes the Scarlett loopback, the mic +buffers stay live, and the continuous timeline can produce confident online sync +states in the app. The next failure is no longer lock/no-lock; it is stabilizing +state filtering enough for the actuator. ## Chirplet Calibration Model ```mermaid flowchart TD - A["MimirChirpletCalibrationPhrase"] --> B["Aquarium audio output"] + A["MimirChirpletTimeline"] --> B["Aquarium audio output"] B --> C["Scarlett speaker loopback"] B --> D["room + speakers + mics"] C --> E["loopback rolling buffer"] @@ -116,26 +115,18 @@ flowchart TD I --> K["frequency response normalization"] ``` -The calibration phrase owns three facts: +The chirplet timeline owns three facts: - **Emission**: the PCM that Aquarium sends to the speakers. -- **Timing witness**: the matched-filter kernel used to find the phrase in +- **Timing witness**: the matched-filter atom bank used to find the stream in loopback and mic buffers. -- **Response witness**: the per-tone kernels used to measure how strongly each +- **Response witness**: the per-band atoms used to measure how strongly each mic hears each emitted band. -One chirplet phrase gives a delay estimate. Repeated phrases give drift/SRO by -watching delay change over time. Per-band energy over many phrases gives the +Continuous chirplet evidence gives both the current delay and the drift/SRO by +watching delay change over time. Per-band energy over the same stream gives the normalization curve. The important constraint is that all three measurements -must be tied to the same emitted phrase, not three separately invented probes. - -The phrase is no longer static. Mimir currently rotates a deterministic -16-phrase cycle and the analyzer searches that cycle. That is enough for a -first timeline fingerprint and ordinary remote/network delay. For higher-latency -or recorded/replayed sources, the next extension should lengthen the code or -make the phrase index explicitly recoverable from the chirplet rhythm so Mimir -can distinguish phrase N from phrase N+16 without relying only on wall-clock -arrival. +must be tied to the same emitted timeline, not three separately invented probes. Next, replace the diagnostic bridge with native audio capture workers that append typed blocks into `Mimir.Runtime`, then expose buffer depth, clock state, diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 7a23fa1..3fe0f8c 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -42,11 +42,10 @@ a named invariant that the native runtime cannot protect yet. - `native/probes/wasapi_audio_cadence` captures WASAPI mic or render-loopback block metadata and emits `audio-block` JSON events for the diagnostic runtime adapter. -- `MimirChirpletCalibrationPhrase` owns the structured birdsong-like calibration - phrase, PCM rendering, matched timing trace, and per-band response kernels. - The default timeline is a stateless 16-phrase cycle; phrase `N` is generated - from `N`, spreads six chirplets across about 0.85 seconds, and fires every - 2.25 seconds to reduce repeated-sweep ambiguity. +- `MimirChirpletTimeline` owns the structured birdsong-like calibration stream, + PCM segment rendering, matched timing trace, and per-band response kernels. + The default timeline is deterministic and unbounded: chirplet event `N` is + generated from `N`, with no repeat cycle or remembered random state. - `MimirAudioSynchronizationAnalyzer` ports the first live sync measurement: sample-bearing audio blocks are resampled into the Scarlett loopback timeline and compared by chirplet-energy delay estimation with fractional peak @@ -59,8 +58,8 @@ a named invariant that the native runtime cannot protect yet. response evidence, and delay-slope/SRO estimate in ppm. - `MimirRuntime` updates audio sync analysis online and can emit live sync telemetry with `MIMIR_SYNC_TELEMETRY_SECONDS`. -- `MimirRuntime` emits short calibration chirplets through Aquarium audio so the - loopback and acoustic mic buffers carry a shared timing witness. +- `MimirRuntime` continuously queues chirplet timeline PCM through Aquarium + audio so the loopback and acoustic mic buffers carry a shared timing witness. - `MimirVideoFrameDescriptor` for dimensions, pixel format, stride, device timestamp, and native/GPU handle metadata. - `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` as the live @@ -98,8 +97,8 @@ a named invariant that the native runtime cannot protect yet. fractional delay line per non-reference stream from the smoothed `MimirAudioSynchronizationState`. The current aligned frame is integer-delay only and should not pretend to be the final DSP path. - First, make the live app acoustic lock robust enough to populate sync state - from the online chirplet timeline, not just from smoke harnesses. + First, harden the online state filter so the continuous chirplet lock stops + producing jumpy delay estimates. 5. Bind Aquarium UI to the synchronization hub so buffer depth, stream cadence, source timestamps, and output settings are visible and adjustable. 6. 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 f9aecb2..5a08594 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -91,20 +91,20 @@ not become the synchronized program authority. The six-microphone path is separate from the bridge. Scarlett speaker loopback is the current timing authority when calibration chirplets are playing. -`MimirChirpletCalibrationPhrase` owns the birdsong-like timeline fingerprint: -a stateless 16-phrase cycle where phrase `N` is generated from `N`; each phrase -spreads six asymmetric chirplets across about 0.85 seconds and fires every 2.25 -seconds. Mimir emits that phrase sequence through Aquarium audio, compares mic -buffers against loopback by chirplet-energy delay estimation, and can build a -provisional aligned mono frame for channels that clear the confidence gate. +`MimirChirpletTimeline` owns the birdsong-like timeline fingerprint: a +deterministic unbounded chirplet stream where event `N` is generated from `N`, +with no repeat cycle or remembered random state. Mimir continuously queues that +timeline through Aquarium audio, compares mic buffers against loopback by +chirplet-energy delay estimation, and can build a provisional aligned mono +frame for channels that clear the confidence gate. Reports now carry fractional delay and per-band matched energy. The hub also owns smoothed per-source sync state with delay-slope/SRO in ppm. `MimirRuntime` runs the analysis online and can print live telemetry with -`MIMIR_SYNC_TELEMETRY_SECONDS`. Current app testing proves loopback wakeup and -live mic buffers, but not yet a confident acoustic lock. Camera mics are -spatial/context witnesses; Focusrite devices are dialogue anchors. The current -aligned frame is integer-delay only; fractional delay and the hot resampler -still belong in Faust/native DSP. +`MIMIR_SYNC_TELEMETRY_SECONDS`. Current app testing proves loopback wakeup, live +mic buffers, and confident online sync states, but delay estimates are still +jumpy. Camera mics are spatial/context witnesses; Focusrite devices are dialogue +anchors. The current aligned frame is integer-delay only; fractional delay and +the hot resampler still belong in Faust/native DSP. ## Visual Fusion diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 3e7e6d4..8839e1f 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -63,22 +63,22 @@ Get-Content .\state\evidence.jsonl -Tail 8 640x480@60, and 81.10 fps when the PS3 Eye runs 320x240@187. The regular Kiyo and second PS3 Eye were absent, so six-camera viability is not proven. - Current chirplet-backed smoke uses Scarlett speaker loopback as timing - authority. `MimirChirpletCalibrationPhrase` owns the structured birdsong-like - timeline fingerprint: a stateless 16-phrase cycle where phrase `N` is - generated from `N`; each phrase has six asymmetric chirplets over about 0.85 - seconds and fires every 2.25 seconds. The phrase owns Aquarium PCM rendering, - matched timing trace, and per-band response hooks. Sync reports now include + authority. `MimirChirpletTimeline` owns the structured birdsong-like timeline + fingerprint: deterministic unbounded chirplet events where event `N` is + generated from `N`, with no repeat cycle or remembered random state. The + timeline owns Aquarium PCM segment rendering, matched timing trace, and + per-band response hooks. Sync reports now include fractional delay and per-band matched energy. `MimirAudioSynchronizationState` now tracks smoothed delay and delay-slope/SRO ppm. Actual Mimir.App testing - proves Aquarium audio wakes Scarlett loopback and keeps mic buffers live, but - the online acoustic report has not cleared the confidence gate yet. PS3 Eye audio is + proves Aquarium audio wakes Scarlett loopback, keeps mic buffers live, and + produces confident online sync states, but delay estimates are still jumpy. + 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. ## Immediate Re-entry Instruction -Make the actual Mimir.App path produce a confident online acoustic lock from the -chirplet timeline, then turn those delay reports into a smoothed -SRO/fractional-delay actuator. Keep loopback as timing authority. Do not restore -deleted script infrastructure because a stale doc once missed it. +Harden the online sync state filter, then turn those delay reports into a +smoothed SRO/fractional-delay actuator. Keep loopback as timing authority. Do +not restore deleted script infrastructure because a stale doc once missed it. diff --git a/src/Mimir.Runtime/MimirRuntime.cs b/src/Mimir.Runtime/MimirRuntime.cs index b31beb9..a43f10c 100644 --- a/src/Mimir.Runtime/MimirRuntime.cs +++ b/src/Mimir.Runtime/MimirRuntime.cs @@ -20,9 +20,7 @@ public sealed class MimirRuntime : IAquariumRuntime private float runtimeSeconds; private float nextAudioSyncSeconds = AudioSyncUpdateIntervalSeconds; private float nextTelemetrySeconds; - private float nextCalibrationChirpSeconds = (float)MimirChirpletCalibrationPhrase.Default.FirstFireSeconds; - private ulong calibrationPhraseIndex; - private readonly Dictionary calibrationPhraseCache = new(); + private ulong calibrationSegmentIndex; private IReadOnlyList lastAudioSynchronizationReports = []; public MimirRuntime(AquariumRuntimeOptions options) @@ -90,7 +88,7 @@ public sealed class MimirRuntime : IAquariumRuntime public void Update(float deltaSeconds, InputState input) { runtimeSeconds += Math.Max(deltaSeconds, 0.0f); - QueueCalibrationChirps(); + QueueCalibrationTimeline(); lastPollCount = synchronization.PollSources(); UpdateAudioSynchronization(); EmitTelemetry(); @@ -132,37 +130,26 @@ public sealed class MimirRuntime : IAquariumRuntime }); } - private void QueueCalibrationChirps() + private void QueueCalibrationTimeline() { - while (runtimeSeconds >= nextCalibrationChirpSeconds) + var queuedUntilSeconds = calibrationSegmentIndex * MimirChirpletTimeline.SegmentSeconds; + var targetSeconds = runtimeSeconds + (float)MimirChirpletTimeline.QueueLeadSeconds; + while (queuedUntilSeconds < targetSeconds) { - var cycleIndex = calibrationPhraseIndex % MimirChirpletCalibrationPhrase.PhraseCycleLength; - var phrase = MimirChirpletCalibrationPhrase.ForIndex(cycleIndex); visualRuntime.Audio.EnqueuePcm16Base64( - Pcm16Base64ForPhrase(cycleIndex, phrase), - phrase.SampleRate, + MimirChirpletTimeline.Default.RenderSegmentPcm16Base64(calibrationSegmentIndex), + MimirChirpletTimeline.SampleRate, channels: 1, gain: 1.0f); - calibrationPhraseIndex++; - nextCalibrationChirpSeconds += (float)phrase.IntervalSeconds; + calibrationSegmentIndex++; + queuedUntilSeconds = calibrationSegmentIndex * MimirChirpletTimeline.SegmentSeconds; } } - private string Pcm16Base64ForPhrase(ulong cycleIndex, MimirChirpletCalibrationPhrase phrase) - { - if (!calibrationPhraseCache.TryGetValue(cycleIndex, out var pcm16Base64)) - { - pcm16Base64 = phrase.RenderPcm16Base64(); - calibrationPhraseCache[cycleIndex] = pcm16Base64; - } - - return pcm16Base64; - } - private string DescribeChirpletReference() { - var phrase = MimirChirpletCalibrationPhrase.Default; - return $"{DefaultAudioSyncReference} every {phrase.IntervalSeconds:0.00}s code {calibrationPhraseIndex % MimirChirpletCalibrationPhrase.PhraseCycleLength}/{MimirChirpletCalibrationPhrase.PhraseCycleLength}"; + var queuedUntilSeconds = calibrationSegmentIndex * MimirChirpletTimeline.SegmentSeconds; + return $"{DefaultAudioSyncReference} continuous timeline {MimirChirpletTimeline.SegmentSeconds:0.00}s segments queued to {queuedUntilSeconds:0.00}s"; } private string DescribeBuffers() diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs index b1bc455..df44eda 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs @@ -65,8 +65,8 @@ public sealed class MimirAudioSynchronizationAnalyzer var referenceWindow = referenceSamples.AsSpan(^compared..); var candidateWindow = candidateSamples.AsSpan(^compared..); - var referenceSync = MimirChirpletCalibrationPhrase.BuildTimelineEnergyTrace(referenceWindow, referenceBlock.SampleRate, ChirpletHopSamples); - var candidateSync = MimirChirpletCalibrationPhrase.BuildTimelineEnergyTrace(candidateWindow, referenceBlock.SampleRate, ChirpletHopSamples); + var referenceSync = MimirChirpletTimeline.Default.BuildTimelineEnergyTrace(referenceWindow, referenceBlock.SampleRate, ChirpletHopSamples); + var candidateSync = MimirChirpletTimeline.Default.BuildTimelineEnergyTrace(candidateWindow, referenceBlock.SampleRate, ChirpletHopSamples); if (referenceSync.Length < 16 || candidateSync.Length < 16) { continue; @@ -76,7 +76,7 @@ public sealed class MimirAudioSynchronizationAnalyzer var (delayHops, confidence) = EstimateDelay(referenceSync, candidateSync, maxLag); var fractionalDelaySamples = delayHops * ChirpletHopSamples; var delaySamples = (int)Math.Round(fractionalDelaySamples); - var bandResponses = MimirChirpletCalibrationPhrase.Default.EstimateBandResponse(candidateWindow, referenceBlock.SampleRate); + var bandResponses = MimirChirpletTimeline.Default.EstimateBandResponse(candidateWindow, referenceBlock.SampleRate); reports.Add(new MimirAudioSynchronizationReport( reference.Descriptor.SourceId, buffer.Descriptor.SourceId, diff --git a/src/Mimir.Runtime/Synchronization/MimirChirpletCalibrationPhrase.cs b/src/Mimir.Runtime/Synchronization/MimirChirpletCalibrationPhrase.cs deleted file mode 100644 index b65fed5..0000000 --- a/src/Mimir.Runtime/Synchronization/MimirChirpletCalibrationPhrase.cs +++ /dev/null @@ -1,324 +0,0 @@ -namespace Mimir.Runtime.Synchronization; - -public sealed record MimirChirpletTone( - double StartSeconds, - double DurationSeconds, - double StartHz, - double EndHz, - double Gain = 1.0) -{ - public double CenterHz => (StartHz + EndHz) * 0.5; -} - -public sealed record MimirChirpletBandResponse( - double CenterHz, - double Energy); - -public sealed class MimirChirpletCalibrationPhrase -{ - public const int PhraseCycleLength = 16; - private readonly float[] kernel; - private readonly IReadOnlyList toneKernels; - - public MimirChirpletCalibrationPhrase( - int sampleRate, - double intervalSeconds, - double firstFireSeconds, - double gain, - IReadOnlyList tones) - { - SampleRate = sampleRate; - IntervalSeconds = intervalSeconds; - FirstFireSeconds = firstFireSeconds; - Gain = gain; - Tones = tones; - DurationSeconds = tones.Count == 0 - ? 0.0 - : tones.Max(tone => tone.StartSeconds + tone.DurationSeconds); - kernel = RenderMonoFloat(sampleRate); - toneKernels = tones.Select(tone => RenderToneKernel(tone, sampleRate, DurationSeconds)).ToArray(); - } - - public static MimirChirpletCalibrationPhrase Default { get; } = ForIndex(0); - - public static IReadOnlyList AnalysisCycle { get; } = - Enumerable.Range(0, PhraseCycleLength) - .Select(index => ForIndex((ulong)index)) - .ToArray(); - - public static MimirChirpletCalibrationPhrase ForIndex(ulong phraseIndex) => new( - sampleRate: 48_000, - intervalSeconds: 2.25, - firstFireSeconds: 0.75, - gain: 0.13, - tones: GenerateTones(phraseIndex)); - - public static float[] BuildTimelineEnergyTrace(ReadOnlySpan samples, int sampleRate, int hopSamples) - { - var traces = new List(); - foreach (var phrase in AnalysisCycle) - { - var trace = phrase.BuildEnergyTrace(samples, sampleRate, hopSamples); - if (trace.Length > 0) - { - traces.Add(trace); - } - } - - if (traces.Count == 0) - { - return []; - } - - var length = traces.Min(trace => trace.Length); - var output = new float[length]; - for (var index = 0; index < length; index++) - { - output[index] = traces.Max(trace => trace[index]); - } - - return output; - } - - public int SampleRate { get; } - - public double IntervalSeconds { get; } - - public double FirstFireSeconds { get; } - - public double Gain { get; } - - public double DurationSeconds { get; } - - public IReadOnlyList Tones { get; } - - public string RenderPcm16Base64() - { - var samples = RenderMonoFloat(SampleRate); - var bytes = new byte[samples.Length * sizeof(short)]; - for (var index = 0; index < samples.Length; index++) - { - var sample = (short)Math.Round(Math.Clamp(samples[index], -1.0f, 1.0f) * short.MaxValue); - bytes[index * sizeof(short)] = (byte)(sample & 0xff); - bytes[index * sizeof(short) + 1] = (byte)((sample >> 8) & 0xff); - } - - return Convert.ToBase64String(bytes); - } - - public float[] BuildEnergyTrace(ReadOnlySpan samples, int sampleRate, int hopSamples) - { - var analysisKernel = sampleRate == SampleRate ? kernel : RenderMonoFloat(sampleRate); - return BuildMatchedEnergyTrace(samples, analysisKernel, hopSamples); - } - - public IReadOnlyList EstimateBandResponse(ReadOnlySpan samples, int sampleRate) - { - if (samples.Length == 0 || Tones.Count == 0) - { - return []; - } - - var responses = new List(Tones.Count); - for (var index = 0; index < Tones.Count; index++) - { - var tone = Tones[index]; - var toneKernel = sampleRate == SampleRate - ? toneKernels[index] - : RenderToneKernel(tone, sampleRate, DurationSeconds); - var energy = MaxMatchedEnergy(samples, toneKernel, Math.Max(1, sampleRate / 1_000)); - responses.Add(new MimirChirpletBandResponse(tone.CenterHz, energy)); - } - - return responses; - } - - private float[] RenderMonoFloat(int sampleRate) - { - var frameCount = Math.Max(1, (int)Math.Ceiling(DurationSeconds * sampleRate)); - var samples = new float[frameCount]; - foreach (var tone in Tones) - { - AddTone(samples, sampleRate, tone); - } - - var peak = samples.Select(Math.Abs).DefaultIfEmpty(0.0f).Max(); - if (peak <= 1.0e-9f) - { - return samples; - } - - var scale = (float)(Gain / peak); - for (var index = 0; index < samples.Length; index++) - { - samples[index] *= scale; - } - - return samples; - } - - private static IReadOnlyList GenerateTones(ulong phraseIndex) - { - var baseTones = new[] - { - new MimirChirpletTone(0.000, 0.060, 7_040.0, 7_680.0, 0.80), - new MimirChirpletTone(0.125, 0.055, 9_600.0, 8_800.0, 0.75), - new MimirChirpletTone(0.260, 0.065, 11_800.0, 12_800.0, 0.90), - new MimirChirpletTone(0.435, 0.055, 8_200.0, 9_000.0, 0.60), - new MimirChirpletTone(0.610, 0.075, 14_500.0, 15_800.0, 0.80), - new MimirChirpletTone(0.790, 0.060, 10_800.0, 10_200.0, 0.70), - }; - var tones = new List(baseTones.Length); - var previousEnd = -1.0; - for (var index = 0; index < baseTones.Length; index++) - { - var baseTone = baseTones[index]; - var seed = Mix(phraseIndex ^ ((ulong)index * 0x9E3779B97F4A7C15UL)); - var timeJitter = Unit(seed) * 0.030 - 0.015; - var durationJitter = Unit(seed >> 11) * 0.020 - 0.010; - var bandJitter = Unit(seed >> 22) * 480.0 - 240.0; - var glideScale = 0.88 + Unit(seed >> 33) * 0.24; - var gainScale = 0.85 + Unit(seed >> 44) * 0.30; - var flips = ((seed >> 57) & 1UL) != 0; - var duration = Math.Clamp(baseTone.DurationSeconds + durationJitter, 0.045, 0.115); - var start = Math.Max(baseTone.StartSeconds + timeJitter, previousEnd + 0.060); - var center = Math.Clamp(baseTone.CenterHz + bandJitter, 6_800.0, 16_200.0); - var halfWidth = Math.Abs(baseTone.EndHz - baseTone.StartHz) * 0.5 * glideScale; - var low = Math.Clamp(center - halfWidth, 6_700.0, 16_400.0); - var high = Math.Clamp(center + halfWidth, 6_700.0, 16_400.0); - tones.Add(flips - ? new MimirChirpletTone(start, duration, high, low, baseTone.Gain * gainScale) - : new MimirChirpletTone(start, duration, low, high, baseTone.Gain * gainScale)); - previousEnd = start + duration; - } - - return tones; - } - - private static ulong Mix(ulong value) - { - value += 0x9E3779B97F4A7C15UL; - value = (value ^ (value >> 30)) * 0xBF58476D1CE4E5B9UL; - value = (value ^ (value >> 27)) * 0x94D049BB133111EBUL; - return value ^ (value >> 31); - } - - private static double Unit(ulong value) => - (value & ((1UL << 53) - 1)) / (double)(1UL << 53); - - private static float[] RenderToneKernel(MimirChirpletTone tone, int sampleRate, double phraseDurationSeconds) - { - var frameCount = Math.Max(1, (int)Math.Ceiling(phraseDurationSeconds * sampleRate)); - var samples = new float[frameCount]; - AddTone(samples, sampleRate, tone); - return samples; - } - - private static void AddTone(float[] samples, int sampleRate, MimirChirpletTone tone) - { - var startFrame = Math.Max(0, (int)Math.Round(tone.StartSeconds * sampleRate)); - var frameCount = Math.Max(1, (int)Math.Round(tone.DurationSeconds * sampleRate)); - for (var frame = 0; frame < frameCount && startFrame + frame < samples.Length; frame++) - { - 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 phase = 2.0 * Math.PI * (tone.StartHz * t + 0.5 * (tone.EndHz - tone.StartHz) * t * normalized); - samples[startFrame + frame] += (float)(Math.Sin(phase) * envelope * tone.Gain); - } - } - - private static float[] BuildMatchedEnergyTrace(ReadOnlySpan samples, ReadOnlySpan kernel, int hopSamples) - { - if (samples.Length < kernel.Length || kernel.Length == 0) - { - return []; - } - - var output = new float[1 + (samples.Length - kernel.Length) / hopSamples]; - for (var frame = 0; frame < output.Length; frame++) - { - var offset = frame * hopSamples; - output[frame] = (float)MatchedEnergy(samples.Slice(offset, kernel.Length), kernel); - } - - return ContrastNormalize(output); - } - - private static double MatchedEnergy(ReadOnlySpan samples, ReadOnlySpan kernel) - { - var count = Math.Min(samples.Length, kernel.Length); - if (count == 0) - { - return 0.0; - } - - var dot = 0.0; - var sampleEnergy = 0.0; - var kernelEnergy = 0.0; - for (var index = 0; index < count; index++) - { - var sample = samples[index]; - var basis = kernel[index]; - dot += sample * basis; - sampleEnergy += sample * sample; - kernelEnergy += basis * basis; - } - - var denominator = Math.Sqrt(sampleEnergy * kernelEnergy); - return denominator > 1.0e-12 ? Math.Abs(dot) / denominator : 0.0; - } - - private static double MaxMatchedEnergy(ReadOnlySpan samples, ReadOnlySpan kernel, int hopSamples) - { - if (samples.Length < kernel.Length || kernel.Length == 0) - { - return 0.0; - } - - var best = 0.0; - for (var offset = 0; offset <= samples.Length - kernel.Length; offset += hopSamples) - { - best = Math.Max(best, MatchedEnergy(samples.Slice(offset, kernel.Length), kernel)); - } - - return best; - } - - private static float[] ContrastNormalize(float[] samples) - { - if (samples.Length == 0) - { - return samples; - } - - var mean = 0.0; - for (var index = 0; index < samples.Length; index++) - { - mean += samples[index]; - } - - mean /= samples.Length; - var variance = 0.0; - for (var index = 0; index < samples.Length; index++) - { - var centered = samples[index] - mean; - variance += centered * centered; - } - - var deviation = Math.Sqrt(variance / samples.Length); - if (deviation <= 1.0e-12) - { - return samples; - } - - var output = new float[samples.Length]; - for (var index = 0; index < samples.Length; index++) - { - var z = (samples[index] - mean) / deviation; - output[index] = z > 0.0 ? (float)(z * z) : 0.0f; - } - - return output; - } -} diff --git a/src/Mimir.Runtime/Synchronization/MimirChirpletTimeline.cs b/src/Mimir.Runtime/Synchronization/MimirChirpletTimeline.cs new file mode 100644 index 0000000..061e0ea --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirChirpletTimeline.cs @@ -0,0 +1,319 @@ +namespace Mimir.Runtime.Synchronization; + +public sealed record MimirChirpletTone( + double StartSeconds, + double DurationSeconds, + double StartHz, + double EndHz, + double Gain = 1.0) +{ + public double CenterHz => (StartHz + EndHz) * 0.5; +} + +public sealed record MimirChirpletBandResponse( + double CenterHz, + double Energy); + +public sealed class MimirChirpletTimeline +{ + public const int SampleRate = 48_000; + public const double SegmentSeconds = 0.5; + public const double QueueLeadSeconds = 1.0; + private const double FirstEventSeconds = 0.08; + private const double EventStrideSeconds = 0.118; + private const double MaxEventDurationSeconds = 0.110; + private const double Gain = 0.095; + + private static readonly MimirChirpletTone[] AnalysisAtoms = + [ + new(0.0, 0.050, 6_900.0, 7_500.0, 0.70), + new(0.0, 0.055, 8_000.0, 8_900.0, 0.75), + new(0.0, 0.060, 9_600.0, 8_800.0, 0.75), + new(0.0, 0.060, 10_600.0, 11_700.0, 0.85), + new(0.0, 0.065, 12_400.0, 13_500.0, 0.90), + new(0.0, 0.070, 14_400.0, 15_800.0, 0.80), + ]; + private static readonly double[] HarmonicRatios = + [ + 1.0, + 9.0 / 8.0, + 5.0 / 4.0, + 4.0 / 3.0, + 3.0 / 2.0, + 5.0 / 3.0, + 15.0 / 8.0, + 2.0, + 9.0 / 4.0, + 5.0 / 2.0, + ]; + + private readonly IReadOnlyList atomKernels; + + private MimirChirpletTimeline() + { + atomKernels = AnalysisAtoms.Select(atom => RenderToneKernel(atom, SampleRate)).ToArray(); + } + + public static MimirChirpletTimeline Default { get; } = new(); + + public float[] RenderSegmentMonoFloat(ulong segmentIndex) + { + var segmentStartSeconds = segmentIndex * SegmentSeconds; + var samples = new float[(int)Math.Round(SegmentSeconds * SampleRate)]; + foreach (var tone in TonesOverlapping(segmentStartSeconds, SegmentSeconds)) + { + AddTone(samples, SampleRate, tone, segmentStartSeconds); + } + + var peak = samples.Select(Math.Abs).DefaultIfEmpty(0.0f).Max(); + if (peak <= 1.0e-9f) + { + return samples; + } + + var scale = (float)(Gain / peak); + for (var index = 0; index < samples.Length; index++) + { + samples[index] *= scale; + } + + return samples; + } + + public string RenderSegmentPcm16Base64(ulong segmentIndex) + { + var samples = RenderSegmentMonoFloat(segmentIndex); + var bytes = new byte[samples.Length * sizeof(short)]; + for (var index = 0; index < samples.Length; index++) + { + var sample = (short)Math.Round(Math.Clamp(samples[index], -1.0f, 1.0f) * short.MaxValue); + bytes[index * sizeof(short)] = (byte)(sample & 0xff); + bytes[index * sizeof(short) + 1] = (byte)((sample >> 8) & 0xff); + } + + return Convert.ToBase64String(bytes); + } + + public float[] BuildTimelineEnergyTrace(ReadOnlySpan samples, int sampleRate, int hopSamples) + { + var traces = new List(); + for (var index = 0; index < AnalysisAtoms.Length; index++) + { + var atom = AnalysisAtoms[index]; + var kernel = sampleRate == SampleRate ? atomKernels[index] : RenderToneKernel(atom, sampleRate); + var trace = BuildMatchedEnergyTrace(samples, kernel, hopSamples); + if (trace.Length > 0) + { + traces.Add(trace); + } + } + + if (traces.Count == 0) + { + return []; + } + + var length = traces.Min(trace => trace.Length); + var output = new float[length]; + for (var frame = 0; frame < length; frame++) + { + var best = 0.0f; + foreach (var trace in traces) + { + best = Math.Max(best, trace[frame]); + } + + output[frame] = best; + } + + return ContrastNormalize(output); + } + + public IReadOnlyList EstimateBandResponse(ReadOnlySpan samples, int sampleRate) + { + if (samples.Length == 0) + { + return []; + } + + var responses = new List(AnalysisAtoms.Length); + for (var index = 0; index < AnalysisAtoms.Length; index++) + { + var atom = AnalysisAtoms[index]; + var kernel = sampleRate == SampleRate ? atomKernels[index] : RenderToneKernel(atom, sampleRate); + var energy = MaxMatchedEnergy(samples, kernel, Math.Max(1, sampleRate / 1_000)); + responses.Add(new MimirChirpletBandResponse(atom.CenterHz, energy)); + } + + return responses; + } + + private static IEnumerable TonesOverlapping(double startSeconds, double durationSeconds) + { + var endSeconds = startSeconds + durationSeconds; + var firstIndex = Math.Max(0, (long)Math.Floor((startSeconds - FirstEventSeconds - MaxEventDurationSeconds) / EventStrideSeconds) - 2); + var lastIndex = Math.Max(firstIndex, (long)Math.Ceiling((endSeconds - FirstEventSeconds) / EventStrideSeconds) + 2); + for (var eventIndex = firstIndex; eventIndex <= lastIndex; eventIndex++) + { + var tone = ToneForEvent((ulong)eventIndex); + if (tone.StartSeconds < endSeconds && tone.StartSeconds + tone.DurationSeconds > startSeconds) + { + yield return tone; + } + } + } + + private static MimirChirpletTone ToneForEvent(ulong eventIndex) + { + var seed = Mix(eventIndex); + var startJitter = Unit(seed) * 0.034 - 0.017; + var duration = 0.045 + Unit(seed >> 10) * 0.052; + var octaveJitter = Unit(seed >> 20) * 0.028 - 0.014; + var glideScale = 0.72 + Unit(seed >> 31) * 0.66; + var gain = 0.72 + Unit(seed >> 42) * 0.34; + var descending = ((seed >> 57) & 1UL) != 0; + var degree = (int)((seed >> 58) % 10); + var center = Math.Clamp(6_800.0 * HarmonicRatios[degree] * (1.0 + octaveJitter), 6_500.0, 16_300.0); + var halfWidth = Math.Clamp(center * 0.035 * glideScale, 220.0, 820.0); + var low = Math.Clamp(center - halfWidth, 6_300.0, 16_500.0); + var high = Math.Clamp(center + halfWidth, 6_300.0, 16_500.0); + var start = FirstEventSeconds + eventIndex * EventStrideSeconds + startJitter; + return descending + ? new MimirChirpletTone(start, duration, high, low, gain) + : new MimirChirpletTone(start, duration, low, high, gain); + } + + private static ulong Mix(ulong value) + { + value += 0x9E3779B97F4A7C15UL; + value = (value ^ (value >> 30)) * 0xBF58476D1CE4E5B9UL; + value = (value ^ (value >> 27)) * 0x94D049BB133111EBUL; + return value ^ (value >> 31); + } + + private static double Unit(ulong value) => + (value & ((1UL << 53) - 1)) / (double)(1UL << 53); + + private static float[] RenderToneKernel(MimirChirpletTone tone, int sampleRate) + { + var frameCount = Math.Max(1, (int)Math.Ceiling(tone.DurationSeconds * sampleRate)); + var samples = new float[frameCount]; + AddTone(samples, sampleRate, tone with { StartSeconds = 0.0 }, segmentStartSeconds: 0.0); + return samples; + } + + private static void AddTone(float[] samples, int sampleRate, MimirChirpletTone tone, double segmentStartSeconds) + { + var relativeStartSeconds = tone.StartSeconds - segmentStartSeconds; + var startFrame = (int)Math.Round(relativeStartSeconds * sampleRate); + var frameCount = Math.Max(1, (int)Math.Round(tone.DurationSeconds * sampleRate)); + for (var frame = 0; frame < frameCount; frame++) + { + var outputFrame = startFrame + frame; + if (outputFrame < 0 || outputFrame >= samples.Length) + { + continue; + } + + 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 phase = 2.0 * Math.PI * (tone.StartHz * t + 0.5 * (tone.EndHz - tone.StartHz) * t * normalized); + samples[outputFrame] += (float)(Math.Sin(phase) * envelope * tone.Gain); + } + } + + private static float[] BuildMatchedEnergyTrace(ReadOnlySpan samples, ReadOnlySpan kernel, int hopSamples) + { + if (samples.Length < kernel.Length || kernel.Length == 0) + { + return []; + } + + var output = new float[1 + (samples.Length - kernel.Length) / hopSamples]; + for (var frame = 0; frame < output.Length; frame++) + { + var offset = frame * hopSamples; + output[frame] = (float)MatchedEnergy(samples.Slice(offset, kernel.Length), kernel); + } + + return output; + } + + private static double MatchedEnergy(ReadOnlySpan samples, ReadOnlySpan kernel) + { + var count = Math.Min(samples.Length, kernel.Length); + if (count == 0) + { + return 0.0; + } + + var dot = 0.0; + var sampleEnergy = 0.0; + var kernelEnergy = 0.0; + for (var index = 0; index < count; index++) + { + var sample = samples[index]; + var basis = kernel[index]; + dot += sample * basis; + sampleEnergy += sample * sample; + kernelEnergy += basis * basis; + } + + var denominator = Math.Sqrt(sampleEnergy * kernelEnergy); + return denominator > 1.0e-12 ? Math.Abs(dot) / denominator : 0.0; + } + + private static double MaxMatchedEnergy(ReadOnlySpan samples, ReadOnlySpan kernel, int hopSamples) + { + if (samples.Length < kernel.Length || kernel.Length == 0) + { + return 0.0; + } + + var best = 0.0; + for (var offset = 0; offset <= samples.Length - kernel.Length; offset += hopSamples) + { + best = Math.Max(best, MatchedEnergy(samples.Slice(offset, kernel.Length), kernel)); + } + + return best; + } + + private static float[] ContrastNormalize(float[] samples) + { + if (samples.Length == 0) + { + return samples; + } + + var mean = 0.0; + for (var index = 0; index < samples.Length; index++) + { + mean += samples[index]; + } + + mean /= samples.Length; + var variance = 0.0; + for (var index = 0; index < samples.Length; index++) + { + var centered = samples[index] - mean; + variance += centered * centered; + } + + var deviation = Math.Sqrt(variance / samples.Length); + if (deviation <= 1.0e-12) + { + return samples; + } + + var output = new float[samples.Length]; + for (var index = 0; index < samples.Length; index++) + { + var z = (samples[index] - mean) / deviation; + output[index] = z > 0.0 ? (float)(z * z) : 0.0f; + } + + return output; + } +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index ef9d325..3f7143b 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -38,3 +38,4 @@ {"ts":"2026-05-22T12:46:18+01:00","type":"implementation","status":"ok","note":"Added MimirAudioSynchronizationStateTracker and MimirAudioSynchronizationState. The hub now updates confidence-gated per-source sync state from chirplet reports, smoothing fractional delay and estimating delay-slope/SRO in ppm. Mimir.BufferSmoke polls sync during the run and prints sync-state lines; Aquarium UI exposes the smoothed state. Verification built cleanly and a phrase-backed smoke printed sync-state loopback-scarlett-speakers->mic-usb-camera-0 smoothedDelaySamples=47.397 delayMs=1.075 sroPpm=0.000 confidence=0.216. Final fresh reports can still disappear when loopback rendering stops or falls outside the shared buffer edge, so active loopback remains a live precondition."} {"ts":"2026-05-22T12:53:02+01:00","type":"implementation","status":"ok","note":"Changed chirplet calibration from a single repeated motif to a stateless timeline fingerprint. MimirChirpletCalibrationPhrase.ForIndex(N) deterministically generates phrase N; runtime emits N mod 16 every 3.25 seconds, and the analyzer searches the 16-phrase cycle. Each phrase is a birdsong-like asymmetric motif with six chirplets spread over about 1.38 seconds. Mimir.slnx built cleanly. A short BufferSmoke run completed without analyzer errors, but loopback emitted zero packets during that smoke, so it verified plumbing only, not fresh delay estimates."} {"ts":"2026-05-22T13:12:32+01:00","type":"verification","status":"partial","note":"Actual Mimir.App runtime test with MIMIR_RUNTIME_CONFIG=config/mimir-runtime.probes.example.json and MIMIR_SYNC_TELEMETRY_SECONDS enabled proved Aquarium WASAPI output wakes the Scarlett loopback in the real app path. Headless run showed loopbackCount rising to 57 with mic buffers live; visible-window run showed loopbackCount 77 with Focusrite/Kiyo/Kiyo Pro/PS3 Eye mic buffers live. The runtime now updates sync analysis on a 0.5s cadence and telemetry prints loopback, reports, states, and audio buffer counts. No confident acoustic sync state locked in these app runs: reports were absent until enough phrase audio accumulated, then a live report appeared with confidence 0.000. Treat this as online emission/capture proven, online acoustic lock not yet solved."} +{"ts":"2026-05-22T13:34:00+01:00","type":"implementation","status":"ok","note":"Replaced the discrete 16-phrase chirplet cycle with MimirChirpletTimeline, a deterministic unbounded chirplet stream. MimirRuntime now continuously queues uncached 0.5-second PCM segments through Aquarium audio with 1 second of lead, and MimirAudioSynchronizationAnalyzer extracts continuous chirplet atom energy traces from loopback and mic windows rather than searching a finite phrase cycle. Short headless Mimir.App telemetry runs proved the actual runtime path now locks online: loopback and all six audio buffers were live, reports were produced, and sync states appeared for Focusrite, Kiyo, Kiyo Pro, and both PS3 Eye mics. Delay estimates are still jumpy enough that the fractional-delay/SRO actuator should wait for better state filtering."} diff --git a/state/map.yaml b/state/map.yaml index f64f7ff..ff6e312 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -65,13 +65,13 @@ accepted_design: runtime rolling buffers; it does not carry pixels/audio payloads or own the final local-device hot path. - The diagnostic audio path can optionally carry base64 float sample payloads - for sync smoke tests. `MimirChirpletCalibrationPhrase` owns the structured - birdsong-like timeline fingerprint: a stateless 16-phrase cycle where - phrase `N` is generated from `N`, plus PCM rendering, matched timing kernel, - and per-band response kernels. `MimirAudioSynchronizationAnalyzer` now - treats `loopback-scarlett-speakers` as timing authority, resamples candidate - mic windows into that timeline, projects loopback and mic windows through - the emitted chirplet phrase cycle, and estimates current delay from + for sync smoke tests. `MimirChirpletTimeline` owns the structured + birdsong-like timeline fingerprint: deterministic unbounded chirplet events + where event `N` is generated from `N`, plus PCM segment rendering, matched + timing atoms, and per-band response kernels. `MimirAudioSynchronizationAnalyzer` + now treats `loopback-scarlett-speakers` as timing authority, resamples + candidate mic windows into that timeline, projects loopback and mic windows + through continuous chirplet energy traces, and estimates current delay from chirplet-energy traces at a shared timestamp edge. Positive delay means the candidate mic is late relative to loopback. Reports include rounded delay, fractional delay, confidence, and per-band matched energy. `MimirAudioSynchronizationStateTracker` @@ -178,14 +178,14 @@ current_status: Kiyo 30.18 fps, PS3 Eye 0 59.66 fps, and PS3 Eye 1 59.95 fps. A mouse in the Leap USB neighborhood does not reproduce the Focusrite-induced collapse. next_action: > - Make the actual Mimir.App path produce a confident online acoustic lock from - the chirplet timeline before adding the synchronization actuator. Current - app testing proves Aquarium WASAPI output wakes Scarlett speaker loopback, - live mic buffers stay populated, and runtime sync analysis runs on cadence, - but the live acoustic report has not cleared the confidence gate. Once that - lock is real, drive variable-rate resampling and fractional-delay correction - per non-reference stream. Replace the diagnostic JSON-line process bridge - with direct native capture drivers that push buffer handles into + Harden the online state filter before adding the synchronization actuator. + Current app testing proves Aquarium WASAPI output wakes Scarlett speaker + loopback, live mic buffers stay populated, runtime sync analysis runs on + cadence, and the continuous chirplet timeline can produce confident sync + states in the app. Delay estimates are still jumpy, so the actuator needs + outlier rejection and better SRO smoothing before it drives variable-rate + resampling and fractional-delay correction per non-reference stream. Replace + the diagnostic JSON-line process bridge with direct native capture drivers that push buffer handles into Mimir.Runtime. Mimir.BufferSmoke still proves loopback-referenced aligned audio for Scarlett loopback, Focusrite mic, Kiyo mic, and Kiyo Pro mic when 9-16 kHz calibration chirplets are playing. Treat PS3 Eye audio as