diff --git a/config/mimir-runtime.probes.example.json b/config/mimir-runtime.probes.example.json index 3b21fa1..fcbe2f7 100644 --- a/config/mimir-runtime.probes.example.json +++ b/config/mimir-runtime.probes.example.json @@ -51,7 +51,8 @@ "{0.0.1.00000000}.{16af9455-4539-4de2-8172-563d991d9e34}", "--seconds", "30", - "--emit-json-blocks" + "--emit-json-blocks", + "--include-samples" ] }, { @@ -68,7 +69,8 @@ "{0.0.1.00000000}.{abc7fd11-3b7d-4cfa-82ee-8767dae13fac}", "--seconds", "30", - "--emit-json-blocks" + "--emit-json-blocks", + "--include-samples" ] }, { @@ -85,7 +87,8 @@ "{0.0.1.00000000}.{ef1fdd6f-c721-4d5a-b183-5bd81dc57c1f}", "--seconds", "30", - "--emit-json-blocks" + "--emit-json-blocks", + "--include-samples" ] }, { @@ -102,7 +105,8 @@ "{0.0.1.00000000}.{57befef3-599c-4c73-a0cd-9539ffc2f54f}", "--seconds", "30", - "--emit-json-blocks" + "--emit-json-blocks", + "--include-samples" ] }, { @@ -119,7 +123,8 @@ "{0.0.1.00000000}.{f26c55af-5018-438a-8cc1-6dbead205a3c}", "--seconds", "30", - "--emit-json-blocks" + "--emit-json-blocks", + "--include-samples" ] }, { @@ -137,7 +142,8 @@ "{0.0.0.00000000}.{defdb2ab-ea1a-4eba-ab59-57038754f387}", "--seconds", "30", - "--emit-json-blocks" + "--emit-json-blocks", + "--include-samples" ] } ] diff --git a/docs/audio-field.md b/docs/audio-field.md index 28d6658..932c8da 100644 --- a/docs/audio-field.md +++ b/docs/audio-field.md @@ -25,9 +25,12 @@ flowchart TD ## Invariants +- Scarlett speaker loopback is the timing authority when calibration chirplets + are playing. - Focusrite dialogue mics are the voice anchors. - Camera mics are spatial/context witnesses. -- Loopback/program audio is timing evidence where available. +- Loopback/program audio is timing evidence where available; it outranks + acoustic mics for clock/timing because it is the emitted program surface. - Distributed inputs must be aligned and resampled before they become program stems. - The five-second runtime window is allowed to be spent on alignment, @@ -45,11 +48,18 @@ USB Camera / PS3 Eye mics, and Scarlett speaker loopback in rolling buffers when loopback audio is actively playing. One PS3 Eye mic previously enumerated but produced zero WASAPI packets until that Eye was unplugged and replugged. -`config/mimir-runtime.sync-smoke.example.json` enables sample-bearing blocks for -the Focusrite reference and one PS3 Eye mic. `MimirAudioSynchronizationAnalyzer` -uses those payloads to estimate current delay by normalized cross-correlation. -This is the measurement half of the old synchronization machine; adaptive -resampling and fractional-delay correction are still the next cut. +The full probe runtime config now enables sample-bearing blocks for every local +audio source. `MimirRuntime` emits short 9-16 kHz calibration chirplets through +Aquarium audio every 1.5 seconds. `MimirAudioSynchronizationAnalyzer` resamples +candidate mic windows into the loopback sample-rate timeline, projects them +through the same chirplet shape, contrast-normalizes the resulting energy +trace, and estimates current delay against `loopback-scarlett-speakers`. + +`MimirSynchronizationHub.BuildAlignedAudioFrame` returns a provisional aligned +mono frame: loopback is always channel zero, and other channels enter only when +their chirplet confidence clears the gate. This is still integer-delay +alignment at 64-sample chirplet-hop granularity. SRO smoothing, fractional-delay +correction, and the hot resampler are the actuator still ahead of us. 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 02412f5..78f4953 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -43,8 +43,13 @@ a named invariant that the native runtime cannot protect yet. block metadata and emits `audio-block` JSON events for the diagnostic runtime adapter. - `MimirAudioSynchronizationAnalyzer` ports the first live sync measurement: - sample-bearing audio blocks can be cross-correlated against - `mic-focusrite-local` to estimate current delay and confidence. + sample-bearing audio blocks are resampled into the Scarlett loopback timeline + and compared by chirplet-energy delay estimation. +- `MimirSynchronizationHub.BuildAlignedAudioFrame` exposes the first + provisional aligned mono frame for loopback-referenced audio channels that + clear the confidence gate. +- `MimirRuntime` emits short calibration chirplets 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 @@ -80,6 +85,8 @@ a named invariant that the native runtime cannot protect yet. workers for local mic, loopback, and network audio feeds. 4. Add the synchronization actuator: smooth delay/SRO estimates, then drive a variable-rate resampler and fractional delay line per non-reference stream. + The current aligned frame is integer-delay only and should not pretend to be + the final DSP path. 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 591145a..12bce49 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -56,6 +56,8 @@ separately controllable audio stems. - `MimirProcessStreamSource`; - `MimirFrameEventProcessStreamSource`; - `MimirVideoFrameDescriptor`; +- `MimirAudioSynchronizationAnalyzer`; +- `MimirAlignedAudioFrame`; - `IMimirVideoCaptureDriver`; - `MimirVideoCaptureDriverSource`. @@ -87,10 +89,14 @@ not become the synchronized program authority. ## Audio Field -The six-microphone path is separate from the bridge. The live version aligns mic -and loopback blocks into one presentation timeline, feeds Faust/native DSP, and -emits synchronized stems. Camera mics are spatial/context witnesses; Focusrite -devices are dialogue anchors. +The six-microphone path is separate from the bridge. Scarlett speaker loopback +is the current timing authority when calibration chirplets are playing. Mimir +emits short 9-16 kHz chirplets 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. +Camera mics are spatial/context witnesses; Focusrite devices are dialogue +anchors. The current aligned frame is integer-delay only; SRO smoothing, +fractional delay, and the hot resampler still belong in Faust/native DSP. ## Visual Fusion @@ -106,3 +112,6 @@ fitting, render budgeting, and publication. - OBS SRT reconnection behavior can be fussy. - Direct driver work must prove sustained cadence before it becomes timing authority. +- PS3 Eye audio endpoints can enumerate and later emit packets after replug, + but the current chirplet smoke saw both PS3 Eye mic buffers empty while their + cameras were live. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index e4ddcda..25afeaf 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -27,7 +27,8 @@ Get-Content .\state\evidence.jsonl -Tail 8 - `src/Mimir.App` hosts Aquarium Engine as the windowing/rendering/D3D12 bridge. - `src/Mimir.Runtime` owns `MimirSynchronizationHub`, configurable five-second rolling buffers, stream descriptors, source adapters, direct native ingest, - and the video capture driver seam. + audio chirplet delay estimation, provisional aligned audio frames, and the + video capture driver seam. - Local six-camera ingest should use direct driver adapters. Process-backed sources are bridge/network edges only. - Leap stereo IR is the first timing-camera candidate for direct ingest. @@ -43,6 +44,9 @@ Get-Content .\state\evidence.jsonl -Tail 8 - Implement the first concrete Leap direct capture driver and measure cadence. - Add remaining camera drivers through `IMimirVideoCaptureDriver`. - Add native audio capture workers for mic, loopback, and network audio feeds. +- Turn the current loopback-referenced chirplet measurement into the real + synchronization actuator: smooth delay/SRO, then drive fractional delay and + variable-rate resampling. - Bind Aquarium UI to stream health, buffer depth, timestamps, settings, and output management. - Keep PowerShell/FFmpeg/SRT as bridge utilities until native program output @@ -58,17 +62,16 @@ Get-Content .\state\evidence.jsonl -Tail 8 but Leap drops hard under shared USB load: 40.12 fps when the PS3 Eye runs 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. -- After port swapping, five camera devices / six optical sensors were visible - and pulled at once: LeapUVC's packed stereo IR pair, Kiyo Pro, regular Kiyo, - and two PS3 Eyes. With both Eyes at 320x240@187, the set delivered Leap - stereo 81.05 fps, Kiyo Pro 24.97 fps, Kiyo 30.28 fps, PS3 Eye 0 187.60 fps, - and PS3 Eye 1 187.03 fps. With both Eyes at 640x480@60, Leap rose compared - with the earlier three-device run but still only reached 57.33 fps. Kiyo Pro - still reports high-speed USB, not SuperSpeed. +- Current chirplet-backed smoke uses Scarlett speaker loopback as timing + authority and can build an aligned audio frame containing loopback, Focusrite + mic, Kiyo mic, and Kiyo Pro mic when 9-16 kHz calibration chirplets are + playing. In that run both PS3 Eye mic buffers were empty while both PS3 Eye + camera buffers were live; earlier replug evidence proves the endpoints can + work, so treat PS3 Eye audio as enumeration/runtime-fragile. ## Immediate Re-entry Instruction -Move the raw PS3 Eye cadence probe into `native/probes` or cut the first real -runtime capture driver, then rerun the six-optical-sensor pull from repo probes -after deliberate USB topology changes. Do not restore deleted script +Replace the diagnostic audio JSON process bridge with native audio capture +workers, then turn chirplet 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.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index 0325190..e50287d 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -3,6 +3,7 @@ using Mimir.Runtime.Synchronization; var duration = TimeSpan.FromSeconds(ParseDoubleOption(args, "--seconds", 10.0)); var pollDelay = TimeSpan.FromMilliseconds(ParseDoubleOption(args, "--poll-ms", 10.0)); var requireSamples = args.Any(arg => string.Equals(arg, "--require-samples", StringComparison.OrdinalIgnoreCase)); +var syncReference = ParseStringOption(args, "--sync-reference", "loopback-scarlett-speakers"); using var configuration = new DisposableConfiguration(MimirRuntimeConfiguration.Load()); using var hub = new MimirSynchronizationHub(configuration.Value.Settings); @@ -47,13 +48,25 @@ foreach (var buffer in hub.Buffers.Buffers.OrderBy(buffer => buffer.Descriptor.S } } -var reports = hub.AnalyzeAudioSynchronization("mic-focusrite-local"); +var reports = hub.AnalyzeAudioSynchronization(syncReference); foreach (var report in reports.OrderBy(report => report.SourceId, StringComparer.Ordinal)) { Console.WriteLine( $"sync {report.ReferenceSourceId}->{report.SourceId}: delaySamples={report.DelaySamples} delayMs={report.DelayMilliseconds:0.000} confidence={report.Confidence:0.000} compared={report.ComparedSamples}"); } +var aligned = hub.BuildAlignedAudioFrame(syncReference); +if (aligned != null) +{ + Console.WriteLine( + $"aligned-audio reference={aligned.ReferenceSourceId} sampleRate={aligned.SampleRate} frameCount={aligned.FrameCount} channels={aligned.Channels.Count}"); + foreach (var channel in aligned.Channels) + { + Console.WriteLine( + $"aligned-channel {channel.SourceId}: delaySamples={channel.DelaySamples} confidence={channel.Confidence:0.000}"); + } +} + if (requireSamples && emptyBuffers.Count > 0) { Console.Error.WriteLine($"empty buffers: {string.Join(", ", emptyBuffers)}"); @@ -77,6 +90,20 @@ static double ParseDoubleOption(IReadOnlyList args, string name, double return fallback; } +static string ParseStringOption(IReadOnlyList args, string name, string fallback) +{ + for (var index = 0; index < args.Count - 1; index++) + { + if (string.Equals(args[index], name, StringComparison.OrdinalIgnoreCase) + && !string.IsNullOrWhiteSpace(args[index + 1])) + { + return args[index + 1]; + } + } + + return fallback; +} + internal sealed class DisposableConfiguration : IDisposable { private readonly List ownedSources; diff --git a/src/Mimir.Runtime/MimirRuntime.cs b/src/Mimir.Runtime/MimirRuntime.cs index 99c28a3..ad8d021 100644 --- a/src/Mimir.Runtime/MimirRuntime.cs +++ b/src/Mimir.Runtime/MimirRuntime.cs @@ -10,10 +10,18 @@ namespace Mimir.Runtime; public sealed class MimirRuntime : IAquariumRuntime { + private const string DefaultAudioSyncReference = "loopback-scarlett-speakers"; + private const int CalibrationChirpSampleRate = 48_000; + private const float CalibrationChirpIntervalSeconds = 1.5f; + private const float CalibrationChirpDurationSeconds = 0.08f; + private const float CalibrationChirpGain = 0.125f; private readonly LocalCastRuntime visualRuntime; private readonly MimirSynchronizationHub synchronization; private readonly AquariumUiDocument ui; private int lastPollCount; + private float runtimeSeconds; + private float nextCalibrationChirpSeconds = 0.5f; + private string? calibrationChirpPcm16Base64; public MimirRuntime(AquariumRuntimeOptions options) : this(options, MimirRuntimeConfiguration.Load()) @@ -77,6 +85,8 @@ public sealed class MimirRuntime : IAquariumRuntime public void Update(float deltaSeconds, InputState input) { + runtimeSeconds += Math.Max(deltaSeconds, 0.0f); + QueueCalibrationChirps(); lastPollCount = synchronization.PollSources(); visualRuntime.Update(deltaSeconds, input); } @@ -110,9 +120,45 @@ public sealed class MimirRuntime : IAquariumRuntime panel.Readout("Ingested", () => $"{synchronization.IngestedSamples}"); panel.Readout("Buffer details", DescribeBuffers); panel.Readout("Audio sync", DescribeAudioSync); + panel.Readout("Aligned audio", DescribeAlignedAudio); + panel.Readout("Chirp reference", () => $"{DefaultAudioSyncReference} every {CalibrationChirpIntervalSeconds:0.0}s"); }); } + private void QueueCalibrationChirps() + { + while (runtimeSeconds >= nextCalibrationChirpSeconds) + { + visualRuntime.Audio.EnqueuePcm16Base64( + calibrationChirpPcm16Base64 ??= BuildCalibrationChirpPcm16Base64(), + CalibrationChirpSampleRate, + channels: 1, + gain: 1.0f); + nextCalibrationChirpSeconds += CalibrationChirpIntervalSeconds; + } + } + + private static string BuildCalibrationChirpPcm16Base64() + { + var frameCount = Math.Max(1, (int)Math.Round(CalibrationChirpSampleRate * CalibrationChirpDurationSeconds)); + var bytes = new byte[frameCount * sizeof(short)]; + const double startHz = 9_000.0; + const double endHz = 16_000.0; + for (var frame = 0; frame < frameCount; frame++) + { + var t = frame / (double)CalibrationChirpSampleRate; + var normalized = frameCount <= 1 ? 1.0 : frame / (double)(frameCount - 1); + var phase = 2.0 * Math.PI * (startHz * t + 0.5 * (endHz - startHz) * t * normalized); + var envelope = 0.5 - 0.5 * Math.Cos(2.0 * Math.PI * normalized); + var value = Math.Clamp(Math.Sin(phase) * envelope * CalibrationChirpGain, -1.0, 1.0); + var sample = (short)Math.Round(value * short.MaxValue); + bytes[frame * sizeof(short)] = (byte)(sample & 0xff); + bytes[frame * sizeof(short) + 1] = (byte)((sample >> 8) & 0xff); + } + + return Convert.ToBase64String(bytes); + } + private string DescribeBuffers() { return string.Join(" | ", synchronization.Buffers.Buffers.Select(DescribeBuffer)); @@ -136,9 +182,17 @@ public sealed class MimirRuntime : IAquariumRuntime private string DescribeAudioSync() { - var reports = synchronization.AnalyzeAudioSynchronization("mic-focusrite-local"); + var reports = synchronization.AnalyzeAudioSynchronization(DefaultAudioSyncReference); return reports.Count == 0 ? "no payload windows" : string.Join(" | ", reports.Select(report => $"{report.SourceId}: {report.DelaySamples} samples {report.DelayMilliseconds:0.00}ms c={report.Confidence:0.00}")); } + + private string DescribeAlignedAudio() + { + var frame = synchronization.BuildAlignedAudioFrame(DefaultAudioSyncReference); + return frame == null + ? "no aligned frame" + : $"{frame.Channels.Count}ch {frame.SampleRate}Hz {frame.FrameCount} frames"; + } } diff --git a/src/Mimir.Runtime/Synchronization/MimirAlignedAudioFrame.cs b/src/Mimir.Runtime/Synchronization/MimirAlignedAudioFrame.cs new file mode 100644 index 0000000..f68f9be --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirAlignedAudioFrame.cs @@ -0,0 +1,13 @@ +namespace Mimir.Runtime.Synchronization; + +public sealed record MimirAlignedAudioChannel( + string SourceId, + int DelaySamples, + double Confidence); + +public sealed record MimirAlignedAudioFrame( + string ReferenceSourceId, + int SampleRate, + int FrameCount, + IReadOnlyList Channels, + float[][] Samples); diff --git a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs index eb05039..6e6547b 100644 --- a/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs +++ b/src/Mimir.Runtime/Synchronization/MimirAudioSynchronizationAnalyzer.cs @@ -4,8 +4,12 @@ namespace Mimir.Runtime.Synchronization; public sealed class MimirAudioSynchronizationAnalyzer { - private const int MaxWindowSamples = 4_800; + private const int MaxWindowSamples = 48_000 * 5; private const int MaxLagSamples = 2_400; + private const int ChirpletHopSamples = 64; + private const double ChirpletDurationSeconds = 0.08; + private const double ChirpletStartHz = 9_000.0; + private const double ChirpletEndHz = 16_000.0; public IReadOnlyList Analyze( IEnumerable buffers, @@ -41,21 +45,30 @@ public sealed class MimirAudioSynchronizationAnalyzer continue; } - if (candidateBlock.SampleRate != referenceBlock.SampleRate || - candidateBlock.SampleFormat != MimirAudioSampleFormat.Float32 || + if (candidateBlock.SampleFormat != MimirAudioSampleFormat.Float32 || referenceBlock.SampleFormat != MimirAudioSampleFormat.Float32) { continue; } + candidateSamples = ResampleToRate(candidateSamples, candidateBlock.SampleRate, referenceBlock.SampleRate); + var compared = Math.Min(referenceSamples.Length, candidateSamples.Length); if (compared < 256) { continue; } - var maxLag = Math.Min(MaxLagSamples, compared / 2); - var (delaySamples, confidence) = EstimateDelay(referenceSamples.AsSpan(^compared..), candidateSamples.AsSpan(^compared..), maxLag); + var referenceSync = BuildChirpletEnergyTrace(referenceSamples.AsSpan(^compared..), referenceBlock.SampleRate); + var candidateSync = BuildChirpletEnergyTrace(candidateSamples.AsSpan(^compared..), referenceBlock.SampleRate); + if (referenceSync.Length < 16 || candidateSync.Length < 16) + { + continue; + } + + var maxLag = Math.Min(MaxLagSamples / ChirpletHopSamples, Math.Min(referenceSync.Length, candidateSync.Length) / 2); + var (delaySamples, confidence) = EstimateDelay(referenceSync, candidateSync, maxLag); + delaySamples *= ChirpletHopSamples; reports.Add(new MimirAudioSynchronizationReport( reference.Descriptor.SourceId, buffer.Descriptor.SourceId, @@ -71,6 +84,70 @@ public sealed class MimirAudioSynchronizationAnalyzer return reports; } + public MimirAlignedAudioFrame? BuildAlignedFrame( + IEnumerable buffers, + string referenceSourceId, + int frameCount = 4_800, + double minimumConfidence = 0.10) + { + var audioBuffers = buffers + .Where(buffer => buffer.Descriptor.Kind == MimirStreamKind.Audio) + .ToDictionary(buffer => buffer.Descriptor.SourceId, StringComparer.Ordinal); + if (!audioBuffers.TryGetValue(referenceSourceId, out var reference)) + { + return null; + } + + var referenceSamples = ExtractMonoWindow(reference, out var referenceBlock); + if (referenceSamples.Length < frameCount || referenceBlock == null) + { + return null; + } + + var reports = Analyze(audioBuffers.Values, referenceSourceId) + .Where(report => report.Confidence >= minimumConfidence) + .ToDictionary(report => report.SourceId, StringComparer.Ordinal); + var channels = new List + { + new(referenceSourceId, 0, 1.0), + }; + var samples = new List + { + Tail(referenceSamples, frameCount), + }; + + foreach (var report in reports.Values.OrderBy(report => report.SourceId, StringComparer.Ordinal)) + { + if (!audioBuffers.TryGetValue(report.SourceId, out var buffer)) + { + continue; + } + + var candidateSamples = ExtractMonoWindow(buffer, out var candidateBlock); + if (candidateBlock == null || + candidateBlock.SampleFormat != MimirAudioSampleFormat.Float32) + { + continue; + } + + candidateSamples = ResampleToRate(candidateSamples, candidateBlock.SampleRate, referenceBlock.SampleRate); + if (candidateSamples.Length < frameCount + Math.Abs(report.DelaySamples)) + { + continue; + } + + samples.Add(AlignedTail(candidateSamples, frameCount, report.DelaySamples)); + channels.Add(new MimirAlignedAudioChannel(report.SourceId, report.DelaySamples, report.Confidence)); + } + + return new MimirAlignedAudioFrame( + referenceSourceId, + referenceBlock.SampleRate, + frameCount, + channels, + samples.ToArray()); + } + private static float[] ExtractMonoWindow(MimirRollingStreamBuffer buffer, out MimirAudioBlockDescriptor? latestBlock) { latestBlock = buffer.Latest?.AudioBlock; @@ -119,6 +196,125 @@ public sealed class MimirAudioSynchronizationAnalyzer return samples; } + private static float[] Tail(float[] samples, int frameCount) + { + var output = new float[frameCount]; + Array.Copy(samples, samples.Length - frameCount, output, 0, frameCount); + return output; + } + + private static float[] ResampleToRate(float[] samples, int sourceRate, int targetRate) + { + if (samples.Length == 0 || sourceRate == targetRate) + { + return samples; + } + + var outputLength = Math.Max(1, (int)Math.Round(samples.Length * (double)targetRate / sourceRate)); + var output = new float[outputLength]; + var scale = sourceRate / (double)targetRate; + for (var index = 0; index < output.Length; index++) + { + var sourcePosition = index * scale; + var left = (int)Math.Floor(sourcePosition); + if (left >= samples.Length - 1) + { + output[index] = samples[^1]; + continue; + } + + var fraction = sourcePosition - left; + output[index] = (float)(samples[left] + (samples[left + 1] - samples[left]) * fraction); + } + + return output; + } + + private static float[] BuildChirpletEnergyTrace(ReadOnlySpan samples, int sampleRate) + { + var kernelLength = Math.Max(8, (int)Math.Round(sampleRate * ChirpletDurationSeconds)); + if (samples.Length < kernelLength) + { + return []; + } + + var output = new float[1 + (samples.Length - kernelLength) / ChirpletHopSamples]; + for (var frame = 0; frame < output.Length; frame++) + { + var offset = frame * ChirpletHopSamples; + var real = 0.0; + var imag = 0.0; + var energy = 0.0; + for (var index = 0; index < kernelLength; index++) + { + var normalized = kernelLength <= 1 ? 1.0 : index / (double)(kernelLength - 1); + var time = index / (double)sampleRate; + var envelope = 0.5 - 0.5 * Math.Cos(2.0 * Math.PI * normalized); + var phase = 2.0 * Math.PI * (ChirpletStartHz * time + 0.5 * (ChirpletEndHz - ChirpletStartHz) * time * normalized); + var sample = samples[offset + index] * envelope; + real += sample * Math.Cos(phase); + imag -= sample * Math.Sin(phase); + energy += sample * sample; + } + + var magnitude = Math.Sqrt(real * real + imag * imag); + output[frame] = energy > 1.0e-12 ? (float)(magnitude / Math.Sqrt(energy)) : 0.0f; + } + + return ContrastNormalize(output); + } + + 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; + } + + private static float[] AlignedTail(float[] samples, int frameCount, int delaySamples) + { + var output = new float[frameCount]; + var endExclusive = samples.Length - Math.Max(0, delaySamples); + var start = endExclusive - frameCount; + if (start < 0) + { + return output; + } + + Array.Copy(samples, start, output, 0, frameCount); + return output; + } + private static (int DelaySamples, double Confidence) EstimateDelay(ReadOnlySpan reference, ReadOnlySpan candidate, int maxLag) { var bestLag = 0; diff --git a/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs b/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs index 2d726d6..7fdd18f 100644 --- a/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs +++ b/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs @@ -64,6 +64,19 @@ public sealed class MimirSynchronizationHub : IDisposable return audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId); } + public MimirAlignedAudioFrame? BuildAlignedAudioFrame( + string referenceSourceId, + int frameCount = 4_800, + double minimumConfidence = 0.10) + { + ObjectDisposedException.ThrowIf(disposed, this); + return audioSynchronization.BuildAlignedFrame( + Buffers.Buffers, + referenceSourceId, + frameCount, + minimumConfidence); + } + private bool disposed; public void Dispose() diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 16df361..566717c 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -30,3 +30,4 @@ {"ts":"2026-05-22T05:50:00+00:00","type":"verification","status":"partial","note":"Correlated the two PS3 Eye audio endpoints to their USB parents. The working endpoint is Microphone (5- USB Camera-B4.09.24.1), MMDEVAPI {57befef3-599c-4c73-a0cd-9539ffc2f54f}, parent USB\\VID_1415&PID_2000&MI_01\\9&35158e62&0&0001 / composite USB\\VID_1415&PID_2000\\8&29c54ea8&0&4; its camera interface MI_00 is bound to libusbK and WASAPI emits 480-frame blocks. The silent endpoint is Microphone (4- USB Camera-B4.09.24.1), MMDEVAPI {f26c55af-5018-438a-8cc1-6dbead205a3c}, parent USB\\VID_1415&PID_2000&MI_01\\9&11052345&0&0001 / composite USB\\VID_1415&PID_2000\\8&2efe0359&0&1; its camera interface MI_00 is bound to WinUSB/libwdi and standalone WASAPI capture opens but emits zero packets. Both MI_01 audio devices report Microsoft usbaudio OK, so the failure is stream data, not endpoint enumeration."} {"ts":"2026-05-22T06:05:00+00:00","type":"verification","status":"ok","note":"After the other PS3 Eye was unplugged/replugged, the previously silent Microphone (4- USB Camera-B4.09.24.1) endpoint started emitting 480-frame WASAPI blocks even though its MI_00 camera interface remained on oem26.inf / WinUSB/libwdi. Full Mimir.BufferSmoke with --require-samples proved 11 non-empty buffers: five camera buffers, Focusrite mic, Kiyo mic, Kiyo Pro mic, both PS3 Eye mics, and active Scarlett speaker loopback. The earlier driver-as-cause hypothesis is weakened; the failure was fixed by device re-enumeration without changing the camera-side driver binding."} {"ts":"2026-05-22T06:25:00+00:00","type":"implementation","status":"ok","note":"Ported the first synchronization measurement loop into the current runtime. WASAPI probe can emit base64 sample payloads with audio-block JSON, MimirFrameEventProcessStreamSource decodes them into MimirStreamSample.Data, and MimirAudioSynchronizationAnalyzer estimates delay by normalized cross-correlation against mic-focusrite-local. Two-mic sync smoke with sample payloads proved both buffers and reported mic-focusrite-local->mic-usb-camera-0 delaySamples=2138, delayMs=44.542, confidence=0.393 over 4800 compared samples. This is measurement only; SRO smoothing, adaptive resampling, and fractional-delay correction are still next."} +{"ts":"2026-05-22T11:39:31+01:00","type":"verification","status":"partial","note":"Chirplet-backed sync smoke used Scarlett speaker loopback as timing authority with 9-16 kHz calibration chirps playing, resampled 48 kHz mics into the 44.1 kHz loopback timeline, and built an aligned audio frame with 4 channels: loopback, mic-focusrite-local delaySamples=-768 confidence=0.160, mic-kiyo delaySamples=-256 confidence=0.119, and mic-kiyo-pro delaySamples=-1664 confidence=0.118. Both PS3 Eye audio buffers were empty in this run while both PS3 Eye camera buffers were live, so PS3 Eye audio remains enumeration/runtime-fragile rather than solved."} diff --git a/state/map.yaml b/state/map.yaml index 51a72ce..847674b 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -65,9 +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. `MimirAudioSynchronizationAnalyzer` estimates current - delay against `mic-focusrite-local` from those payload-bearing rolling - buffers. + for sync smoke tests. `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 shape, and estimates current delay from chirplet-energy + traces. `MimirSynchronizationHub.BuildAlignedAudioFrame` exposes the first + provisional loopback-referenced aligned mono frame for channels that clear + the confidence gate. - `IMimirVideoCaptureDriver` and `MimirVideoCaptureDriverSource` are the live seam for Leap, Media Foundation, DirectShow, libusb, LeapC, or shared texture capture. @@ -164,17 +168,16 @@ 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: > - Add the synchronization actuator after the current measurement loop: - smooth delay/SRO estimates, then 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 Mimir.Runtime. Current - Mimir.BufferSmoke with `--require-samples` proves all five declared local - optical buffers plus Focusrite mic, Kiyo Pro mic, Kiyo mic, one USB Camera - mic, both PS3 Eye mics, and active Scarlett speaker loopback receive - samples. One PS3 Eye mic previously enumerated OK but emitted zero WASAPI - packets; unplug/replug fixed the audio stream without changing that Eye's - MI_00 camera binding from WinUSB/libwdi to libusbK. A two-mic payload sync - smoke reports live Focusrite-to-PS3-Eye delay by cross-correlation. Keep the - Focusrite away from the Leap USB neighborhood and treat Kiyo Pro as a ~25 - fps source until its SuperSpeed negotiation is fixed. + Add the synchronization actuator after the current chirplet measurement + loop: smooth delay/SRO estimates, then 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 Mimir.Runtime. Current chirplet-backed + Mimir.BufferSmoke proves loopback-referenced aligned audio for Scarlett + loopback, Focusrite mic, Kiyo mic, and Kiyo Pro mic when 9-16 kHz + calibration chirplets are playing; both PS3 Eye audio endpoints were empty + in that run despite their camera buffers being live. A prior replug proved + both PS3 Eye mics can emit WASAPI packets, so treat current silence as + device enumeration/runtime fragility rather than missing endpoint + inventory. Keep the Focusrite away from the Leap USB neighborhood and treat + Kiyo Pro as a ~25 fps source until its SuperSpeed negotiation is fixed.