Use quadrature chirplet timing

This commit is contained in:
Meta Vens 2026-05-22 16:46:50 +01:00
commit bd9659e9d2
8 changed files with 134 additions and 85 deletions

View file

@ -100,9 +100,10 @@ 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. The next failure is decoder precision: symbol separation and
sub-frame timing must make canonical anchors stable enough to drive the
actuator directly.
buffers stay live. The decoder now uses quadrature chirplet atoms so symbol
classification is phase-invariant at the transform layer. The next failure is
physical capture proof: the same canonical anchors need to stay stable through
loopback, room mics, device clocks, and codec/network paths.
## Chirplet Calibration Model
@ -143,11 +144,15 @@ contribute so poor mic frequency response does not erase the whole code.
`MimirChirpletSymbolCodebook` owns the symbol definitions so timeline ordering
does not smuggle acoustic shape decisions into bit arithmetic. Every symbol has
a unique chirp shape; rhythm remains additional evidence, not a substitute for
symbol separability. A synthetic runtime check rendered two seconds of canonical
timeline audio and decoded all 15 emitted chirps into 13 possible triplet
anchors, events 0 through 12, with a fitted clock near 48 kHz. Real device runs
still depend on loopback capture staying live; the local Scarlett loopback has
intermittently stopped advancing during short headless sniffs.
symbol separability. The transform uses sine/cosine chirplet kernels for each
symbol, so timing does not depend on the receiver preserving the emitter's
absolute phase. Run `dotnet run --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --chirplet-self-test`
to render two seconds of canonical timeline audio and decode it back to
timeline anchors. Current synthetic proof detects all 15 emitted chirps, keeps
13 possible triplet anchors for events 0 through 12, fits the clock at
47999.999990 Hz, and holds mean absolute anchor error to 0.000014 samples. Real
device runs still depend on loopback capture staying live; the local Scarlett
loopback has intermittently stopped advancing during short headless sniffs.
Next, replace the diagnostic bridge with native audio capture workers that
append typed blocks into `Mimir.Runtime`, then expose buffer depth, clock state,

View file

@ -38,7 +38,9 @@ a named invariant that the native runtime cannot protect yet.
the same camera set once per stream.
- `src/Mimir.BufferSmoke` loads the runtime config, polls the synchronization
hub, and prints the actual rolling buffers. Use `--require-samples` when an
empty declared sensor buffer should fail the run.
empty declared sensor buffer should fail the run. Use `--chirplet-self-test`
to render the canonical timeline into memory and verify that the constrained
decoder recovers sub-frame anchors without hardware.
- `native/probes/wasapi_audio_cadence` captures WASAPI mic or render-loopback
block metadata and emits `audio-block` JSON events for the diagnostic runtime
adapter.
@ -53,9 +55,9 @@ a named invariant that the native runtime cannot protect yet.
a unique chirp shape, with inter-chirp rhythm as additional code evidence.
- `MimirChirpletStreamDecoder` is the first constrained chirplet-transform
receiver. It owns a bounded PCM window, emits transform frames with multiple
symbol candidates and per-candidate refined sample offsets, decodes code-valid
triplet anchors through a local trellis that requires gap and clock coherence,
and fits a per-source sample clock from those anchors.
phase-invariant symbol candidates and per-candidate refined sample offsets,
decodes code-valid triplet anchors through a local trellis that requires gap
and clock coherence, and fits a per-source sample clock from those anchors.
- `MimirAudioSynchronizationAnalyzer` ports the first live sync measurement:
sample-bearing audio blocks are resampled into the Scarlett loopback timeline.
The analyzer derives delay only from matched decoded triplet timeline anchors.
@ -105,9 +107,10 @@ a named invariant that the native runtime cannot protect yet.
workers for local mic, loopback, and network audio feeds.
4. Add the synchronization actuator: drive a variable-rate resampler and
fractional delay line per non-reference stream from the smoothed
`MimirAudioSynchronizationState`. First, finish the constrained chirplet-transform decoder so every correctly
heard triplet becomes a deterministic timeline anchor and the state tracker no
longer has to launder ambiguous lag guesses.
`MimirAudioSynchronizationState`. First, prove the constrained chirplet
decoder through real loopback and microphone paths so every correctly heard
triplet becomes a deterministic timeline anchor before the actuator moves
samples.
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

View file

@ -101,19 +101,21 @@ 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`
is the constrained chirplet-transform receiver: it turns a bounded PCM window
into transform frames with multiple symbol candidates and refined per-candidate
sample offsets, code-valid triplet anchors selected through gap/clock coherence,
and an affine source clock fit. The analyzer only emits timing reports from
into transform frames with multiple phase-invariant symbol candidates and
refined per-candidate sample offsets, code-valid triplet anchors selected
through gap/clock coherence, and an affine source clock fit. The synthetic
`Mimir.BufferSmoke --chirplet-self-test` path renders canonical timeline audio
into memory and currently recovers events 0-12 with a 47999.999990 Hz clock fit
and 0.000014 sample MAE. The analyzer only emits timing reports from
matched canonical anchors. The hub also owns cached reports plus smoothed
per-source sync state with delay-slope/SRO in ppm. `MimirRuntime` runs analysis
online as a bounded rotating service and can print live telemetry with
`MIMIR_SYNC_TELEMETRY_SECONDS`. UI and telemetry are passive readers of cached
sync state; they must not invoke the analyzer. Current app testing proves
loopback wakeup, live mic buffers, and confident online sync states, but the
decoder is not finished until arbitrary valid triplets produce stable anchors in
real mic streams. Camera mics are spatial/context witnesses; Focusrite devices
are dialogue anchors. Fractional delay and the hot resampler belong in
Faust/native DSP.
next proof is stable canonical anchors through real mic streams. Camera mics are
spatial/context witnesses; Focusrite devices are dialogue anchors. Fractional
delay and the hot resampler belong in Faust/native DSP.
## Visual Fusion

View file

@ -73,9 +73,12 @@ Get-Content .\state\evidence.jsonl -Tail 8
now tracks smoothed delay and delay-slope/SRO ppm. `MimirChirpletSymbolCodebook`
owns separable symbol definitions, and `MimirChirpletStreamDecoder` is the
constrained chirplet-transform receiver: it emits transform frames with
multiple symbol candidates and refined per-candidate sample offsets, selects
code-valid triplet anchors through gap/clock coherence, and fits a source
clock from a bounded PCM window. `MimirRuntime` runs sync analysis as a bounded rotating
multiple phase-invariant symbol candidates and refined per-candidate sample
offsets, selects code-valid triplet anchors through gap/clock coherence, and
fits a source clock from a bounded PCM window. The canonical synthetic check is
`dotnet run --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --chirplet-self-test`;
it currently detects all 15 emitted chirps and recovers 13 anchors for events
0-12 with a 47999.999990 Hz clock fit and 0.000014 sample MAE. `MimirRuntime` runs sync analysis as a bounded rotating
service and caches reports/states for UI and telemetry; readouts must stay
passive. Actual Mimir.App testing proves Aquarium audio wakes Scarlett
loopback, keeps mic buffers live, and produces confident online sync states,
@ -87,7 +90,8 @@ Get-Content .\state\evidence.jsonl -Tail 8
## Immediate Re-entry Instruction
Finish the constrained chirplet-transform decoder, then turn decoded clock fits
into the SRO/fractional-delay actuator. Keep loopback as timing authority. Do
not call synchronization analysis from UI/telemetry readouts. Do not restore
deleted script infrastructure because a stale doc once missed it.
Prove the constrained chirplet-transform decoder through real loopback and mic
paths, then turn decoded clock fits into the SRO/fractional-delay actuator. Keep
loopback as timing authority. Do not call synchronization analysis from
UI/telemetry readouts. Do not restore deleted script infrastructure because a
stale doc once missed it.

View file

@ -1,5 +1,10 @@
using Mimir.Runtime.Synchronization;
if (args.Any(arg => string.Equals(arg, "--chirplet-self-test", StringComparison.OrdinalIgnoreCase)))
{
return RunChirpletSelfTest();
}
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));
@ -112,6 +117,39 @@ static string DescribeBands(IReadOnlyList<MimirChirpletBandResponse> bands)
: string.Join(",", bands.Select(band => $"{band.CenterHz:0}Hz:{band.Energy:0.000}"));
}
static int RunChirpletSelfTest()
{
var timeline = MimirChirpletTimeline.Default;
var decoder = new MimirChirpletStreamDecoder(windowDuration: TimeSpan.FromSeconds(2));
MimirChirpletStreamDecode decode = new([], [], [], null);
for (ulong segment = 0; segment < 4; segment++)
{
decode = decoder.Append(timeline.RenderSegmentMonoFloat(segment));
}
var meanAbsoluteError = decode.ClockFit?.MeanAbsoluteErrorSamples ?? double.PositiveInfinity;
Console.WriteLine(
$"chirplet-self-test frames={decode.Frames.Count} symbols={decode.Symbols.Count} anchors={decode.Anchors.Count} " +
$"clock={(decode.ClockFit is null ? "none" : decode.ClockFit.EffectiveSampleRate.ToString("0.000000"))} " +
$"confidence={(decode.ClockFit?.Confidence ?? 0.0):0.000} mae={meanAbsoluteError:0.000000}");
foreach (var anchor in decode.Anchors)
{
var expected = timeline.EventForIndex(anchor.EventIndex).StartSeconds * MimirChirpletTimeline.SampleRate;
Console.WriteLine(
$"chirplet-anchor event={anchor.EventIndex} actual={anchor.SampleOffset:0.000} expected={expected:0.000} " +
$"error={anchor.SampleOffset - expected:0.000} confidence={anchor.Confidence:0.000}");
}
if (decode.ClockFit == null || decode.Anchors.Count < 12 || meanAbsoluteError > 0.25)
{
Console.Error.WriteLine("chirplet self-test failed: canonical timeline did not decode to sub-frame anchors");
return 1;
}
return 0;
}
internal sealed class DisposableConfiguration : IDisposable
{
private readonly List<IMimirStreamSource> ownedSources;

View file

@ -41,7 +41,7 @@ public sealed class MimirChirpletTimeline
private static readonly MimirChirpletSymbolCodebook Codebook = MimirChirpletSymbolCodebook.Default;
private static readonly double[] PeriodEventStarts = BuildPeriodEventStarts(TimelineSymbols);
private static readonly double PeriodDurationSeconds = PeriodEventStarts[^1] + Codebook[TimelineSymbols[^1]].GapSeconds;
private readonly IReadOnlyList<float[]> symbolKernels;
private readonly IReadOnlyList<MimirChirpletToneKernel> symbolKernels;
private MimirChirpletTimeline()
{
@ -59,16 +59,9 @@ public sealed class MimirChirpletTimeline
AddTone(samples, SampleRate, timelineEvent.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;
samples[index] *= (float)Gain;
}
return samples;
@ -215,7 +208,7 @@ public sealed class MimirChirpletTimeline
var step = Math.Max(4, searchRadiusSamples / 16);
for (var offset = start; offset <= end; offset += step)
{
var energy = DirectionalMatchedEnergy(samples.Slice(offset, kernel.Length), kernel);
var energy = MatchedEnergy(samples.Slice(offset, kernel.Length), kernel);
if (energy > bestEnergy)
{
bestEnergy = energy;
@ -227,7 +220,7 @@ public sealed class MimirChirpletTimeline
var localEnd = Math.Min(end, bestOffset + step);
for (var offset = localStart; offset <= localEnd; offset++)
{
var energy = DirectionalMatchedEnergy(samples.Slice(offset, kernel.Length), kernel);
var energy = MatchedEnergy(samples.Slice(offset, kernel.Length), kernel);
if (energy > bestEnergy)
{
bestEnergy = energy;
@ -238,7 +231,7 @@ public sealed class MimirChirpletTimeline
if (bestEnergy >= 0.08)
{
var refinedOffset = RefineMatchedOffset(samples, kernel, bestOffset, start, end);
var refinedEnergy = DirectionalMatchedEnergy(
var refinedEnergy = MatchedEnergy(
samples.Slice((int)Math.Round(refinedOffset), kernel.Length),
kernel);
candidates.Add(new MimirChirpletSymbolCandidate(symbol, refinedOffset, Math.Max(bestEnergy, refinedEnergy)));
@ -266,7 +259,7 @@ public sealed class MimirChirpletTimeline
private static double RefineMatchedOffset(
ReadOnlySpan<float> samples,
ReadOnlySpan<float> kernel,
MimirChirpletToneKernel kernel,
int offset,
int start,
int end)
@ -277,9 +270,9 @@ public sealed class MimirChirpletTimeline
return center;
}
var left = DirectionalMatchedEnergy(samples.Slice(center - 1, kernel.Length), kernel);
var middle = DirectionalMatchedEnergy(samples.Slice(center, kernel.Length), kernel);
var right = DirectionalMatchedEnergy(samples.Slice(center + 1, kernel.Length), kernel);
var left = MatchedEnergy(samples.Slice(center - 1, kernel.Length), kernel);
var middle = MatchedEnergy(samples.Slice(center, kernel.Length), kernel);
var right = MatchedEnergy(samples.Slice(center + 1, kernel.Length), kernel);
var denominator = left - 2.0 * middle + right;
if (Math.Abs(denominator) <= 1.0e-12)
{
@ -596,15 +589,22 @@ public sealed class MimirChirpletTimeline
private static int TripleCode(int first, int second, int third) =>
first * SymbolCount * SymbolCount + second * SymbolCount + third;
private static float[] RenderToneKernel(MimirChirpletTone tone, int sampleRate)
private static MimirChirpletToneKernel 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;
var sine = new float[frameCount];
var cosine = new float[frameCount];
AddTone(sine, sampleRate, tone with { StartSeconds = 0.0 }, segmentStartSeconds: 0.0, phaseOffsetRadians: 0.0);
AddTone(cosine, sampleRate, tone with { StartSeconds = 0.0 }, segmentStartSeconds: 0.0, phaseOffsetRadians: Math.PI * 0.5);
return new MimirChirpletToneKernel(sine, cosine);
}
private static void AddTone(float[] samples, int sampleRate, MimirChirpletTone tone, double segmentStartSeconds)
private static void AddTone(
float[] samples,
int sampleRate,
MimirChirpletTone tone,
double segmentStartSeconds,
double phaseOffsetRadians = 0.0)
{
var relativeStartSeconds = tone.StartSeconds - segmentStartSeconds;
var startFrame = (int)Math.Round(relativeStartSeconds * sampleRate);
@ -621,11 +621,11 @@ public sealed class MimirChirpletTimeline
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);
samples[outputFrame] += (float)(Math.Sin(phase + phaseOffsetRadians) * envelope * tone.Gain);
}
}
private static double MatchedEnergy(ReadOnlySpan<float> samples, ReadOnlySpan<float> kernel)
private static double MatchedEnergy(ReadOnlySpan<float> samples, MimirChirpletToneKernel kernel)
{
var count = Math.Min(samples.Length, kernel.Length);
if (count == 0)
@ -633,44 +633,30 @@ public sealed class MimirChirpletTimeline
return 0.0;
}
var dot = 0.0;
var sineDot = 0.0;
var cosineDot = 0.0;
var sampleEnergy = 0.0;
var kernelEnergy = 0.0;
var sineEnergy = 0.0;
var cosineEnergy = 0.0;
for (var index = 0; index < count; index++)
{
var sample = samples[index];
var basis = kernel[index];
dot += sample * basis;
var sine = kernel.Sine[index];
var cosine = kernel.Cosine[index];
sineDot += sample * sine;
cosineDot += sample * cosine;
sampleEnergy += sample * sample;
kernelEnergy += basis * basis;
sineEnergy += sine * sine;
cosineEnergy += cosine * cosine;
}
var denominator = Math.Sqrt(sampleEnergy * kernelEnergy);
return denominator > 1.0e-12 ? Math.Abs(dot) / denominator : 0.0;
}
private static double DirectionalMatchedEnergy(ReadOnlySpan<float> samples, ReadOnlySpan<float> kernel)
{
var count = Math.Min(samples.Length, kernel.Length);
if (count == 0)
var denominator = Math.Sqrt(sampleEnergy * Math.Max(sineEnergy, cosineEnergy));
if (denominator <= 1.0e-12)
{
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.Max(0.0, dot / denominator) : 0.0;
return Math.Min(1.0, Math.Sqrt(sineDot * sineDot + cosineDot * cosineDot) / denominator);
}
private static float[] BuildEnvelopeEnergyTrace(ReadOnlySpan<float> samples, int sampleRate, int hopSamples)
@ -709,7 +695,7 @@ public sealed class MimirChirpletTimeline
return output;
}
private static double MaxMatchedEnergy(ReadOnlySpan<float> samples, ReadOnlySpan<float> kernel, int hopSamples)
private static double MaxMatchedEnergy(ReadOnlySpan<float> samples, MimirChirpletToneKernel kernel, int hopSamples)
{
if (samples.Length < kernel.Length || kernel.Length == 0)
{
@ -761,4 +747,9 @@ public sealed class MimirChirpletTimeline
return output;
}
private sealed record MimirChirpletToneKernel(float[] Sine, float[] Cosine)
{
public int Length => Sine.Length;
}
}

View file

@ -47,3 +47,4 @@
{"ts":"2026-05-22T16:35:00+01:00","type":"implementation","status":"partial","note":"Replaced one-best-symbol triplet placement with a constrained transform/trellis pass. DecodeStreamWindow now emits transform frames with multiple symbol candidates per chirp, enumerates candidate triplets through the de Bruijn map, scores measured inter-chirp gaps, and keeps the coherent local clock path rather than accepting any random valid triplet. Synthetic two-second emitted timeline check improved from one anchor to 11 coherent anchors, including events 0-9, with fitted clock 47978.350 Hz, confidence 0.885, and 8.741 sample MAE. This is the right decoder shape; remaining work is symbol/codebook separation and sub-frame timing precision so the fit lands exactly at 48000 Hz and covers every emitted triplet."}
{"ts":"2026-05-22T17:05:00+01:00","type":"implementation","status":"ok","note":"Removed the legacy synchronization pipelines from live code. MimirAudioSynchronizationAnalyzer no longer contains chirplet-energy lag search, normalized cross-correlation, approximate runtime clock placement, known-event observation, or integer aligned-frame construction; it only emits timing reports from at least three matched decoded timeline anchors. Deleted MimirAlignedAudioFrame and removed BuildAlignedAudioFrame from MimirSynchronizationHub and BufferSmoke. MimirChirpletTimeline no longer exposes DecodeReferenceWindow, ObserveKnownEvents, BuildTimelineEnergyTrace, or one-best-symbol triplet placement. approximateTimelineSeconds was removed from sync analysis signatures because canonical chirplet anchors now own placement."}
{"ts":"2026-05-22T17:35:00+01:00","type":"implementation","status":"ok","note":"Separated chirplet symbol ownership into MimirChirpletSymbolCodebook and added per-candidate refined sample offsets to transform frames. The codebook now guarantees each of the 32 symbols has a unique chirp shape; rhythm is additional code evidence rather than an acoustic alias. ClassifySymbolsAt now does coarse dictionary search, local sample-resolution search, and parabolic sub-sample refinement per symbol candidate. Synthetic two-second emitted timeline check now detects all 15 emitted chirps, decodes 13 possible triplet anchors for events 0-12, and fits clock=48001.819 Hz with confidence=0.952 and MAE=5.171 samples, improved from 11 anchors / 47978.350 Hz / MAE=8.741."}
{"ts":"2026-05-22T17:45:00+01:00","type":"implementation","status":"ok","note":"Replaced single-phase chirplet matching with quadrature sine/cosine kernels and fixed emitted timeline segment gain so canonical chirps are not amplitude-renormalized per half-second segment. Added `Mimir.BufferSmoke --chirplet-self-test` as a first-class synthetic invariant check. The check renders two seconds of canonical timeline audio, detects all 15 emitted chirps, keeps 13 triplet anchors for events 0-12, fits clock=47999.999990 Hz with confidence=1.000, and holds anchor MAE to 0.000014 samples. The next proof is the same deterministic anchor stability through actual loopback and microphone paths."}

View file

@ -75,9 +75,14 @@ accepted_design:
owns the 32 symbol definitions so every symbol has a unique chirp shape, with
rhythm as additional evidence. `MimirChirpletStreamDecoder` is the first
constrained chirplet-transform receiver: it owns a bounded PCM window, emits
transform frames with multiple symbol candidates and refined per-candidate
sample offsets, decodes code-valid triplet anchors through gap/clock coherence, and fits a
per-source sample clock from those anchors. `MimirAudioSynchronizationAnalyzer`
transform frames with multiple phase-invariant symbol candidates and refined
per-candidate sample offsets, decodes code-valid triplet anchors through
gap/clock coherence, and fits a per-source sample clock from those anchors.
The canonical synthetic smoke path is `dotnet run --project
.\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --chirplet-self-test`.
It currently decodes all 15 emitted chirps in a two-second window into 13
anchors for events 0-12 with a 47999.999990 Hz clock fit and 0.000014 sample
MAE. `MimirAudioSynchronizationAnalyzer`
now treats `loopback-scarlett-speakers` as timing authority and derives
delay only from matched decoded timeline anchors. Positive delay means
the candidate mic is late relative to loopback. Reports include rounded
@ -185,8 +190,8 @@ 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: >
Finish the constrained chirplet-transform decoder before adding the
synchronization actuator.
Prove the constrained chirplet-transform decoder through real loopback and
microphone paths before adding the synchronization actuator.
Current app testing proves Aquarium WASAPI output wakes Scarlett speaker
loopback, live mic buffers stay populated, runtime sync analysis now runs as
a bounded rotating service without UI/telemetry re-entry, and the continuous