Remove legacy sync pipelines
This commit is contained in:
parent
c298e0922d
commit
11fa33d190
12 changed files with 48 additions and 865 deletions
|
|
@ -76,20 +76,11 @@ observed_sample = source_offset + canonical_seconds * effective_sample_rate
|
|||
```
|
||||
|
||||
Delay and sampling-rate offset are derived by comparing the loopback clock fit
|
||||
to each mic clock fit over common canonical time. Wide cross-correlation is only
|
||||
a diagnostic fallback while the transform decoder is being cut over. The state
|
||||
tracker is not allowed to launder invalid codewords into plausible timing.
|
||||
Reports carry rounded integer delay, fractional delay, and the count/confidence
|
||||
of timeline-symbol anchors used to derive the report.
|
||||
|
||||
`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. Delay estimates compare loopback and
|
||||
candidate mic windows at a shared timestamp edge; positive delay means the
|
||||
candidate mic is late relative to loopback. The current chirplet trace uses a
|
||||
16-sample hop and parabolic peak interpolation. The aligned-frame application
|
||||
still rounds to integer samples; the fractional estimate exists so the next
|
||||
actuator can drive a real fractional-delay line.
|
||||
to each mic clock fit over common canonical time. The state tracker is not
|
||||
allowed to launder invalid codewords into plausible timing. If a stream cannot
|
||||
produce at least three matched canonical anchors, it has not decoded timing for
|
||||
that window. Reports carry rounded integer delay, fractional delay, and the
|
||||
count/confidence of timeline-symbol anchors used to derive the report.
|
||||
|
||||
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
|
||||
|
|
@ -108,10 +99,10 @@ fresh reports will stop.
|
|||
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, 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.
|
||||
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.
|
||||
|
||||
## Chirplet Calibration Model
|
||||
|
||||
|
|
@ -150,7 +141,7 @@ The symbol layer is intentionally redundant. It does not rely on one fixed
|
|||
frequency shelf: timing gaps, chirp duration, start band, and glide shape all
|
||||
contribute so poor mic frequency response does not erase the whole code. A
|
||||
synthetic runtime check rendered two seconds of canonical timeline audio and
|
||||
decoded events 9, 10, and 11 back to a zero-second window start. Real device
|
||||
decoded a coherent path containing events 0 through 9 plus event 16. Real device
|
||||
runs still depend on loopback capture staying live; the local Scarlett loopback
|
||||
has intermittently stopped advancing during short headless sniffs.
|
||||
|
||||
|
|
|
|||
|
|
@ -56,12 +56,9 @@ a named invariant that the native runtime cannot protect yet.
|
|||
those anchors.
|
||||
- `MimirAudioSynchronizationAnalyzer` ports the first live sync measurement:
|
||||
sample-bearing audio blocks are resampled into the Scarlett loopback timeline.
|
||||
The analyzer now prefers decoded triplet timeline anchors and derives delay
|
||||
from matched canonical events. The older chirplet-energy lag search remains a
|
||||
diagnostic fallback while the decoder is being cut over.
|
||||
- `MimirSynchronizationHub.BuildAlignedAudioFrame` exposes the first
|
||||
provisional aligned mono frame for loopback-referenced audio channels that
|
||||
clear the confidence gate.
|
||||
The analyzer derives delay only from matched decoded triplet timeline anchors.
|
||||
A source without at least three matched anchors has no timing report for that
|
||||
window.
|
||||
- `MimirAudioSynchronizationStateTracker` owns the first smoothed per-source
|
||||
sync state: latest fractional delay, smoothed delay, confidence, per-band
|
||||
response evidence, and delay-slope/SRO estimate in ppm.
|
||||
|
|
@ -106,9 +103,7 @@ 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`. The current aligned frame is integer-delay
|
||||
only and should not pretend to be the final DSP path.
|
||||
First, finish the constrained chirplet-transform decoder so every correctly
|
||||
`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.
|
||||
5. Bind Aquarium UI to the synchronization hub so buffer depth, stream cadence,
|
||||
|
|
|
|||
|
|
@ -57,7 +57,6 @@ separately controllable audio stems.
|
|||
- `MimirFrameEventProcessStreamSource`;
|
||||
- `MimirVideoFrameDescriptor`;
|
||||
- `MimirAudioSynchronizationAnalyzer`;
|
||||
- `MimirAlignedAudioFrame`;
|
||||
- `IMimirVideoCaptureDriver`;
|
||||
- `MimirVideoCaptureDriverSource`.
|
||||
|
||||
|
|
@ -96,16 +95,14 @@ de Bruijn sequence over 32 time/frequency constellation symbols. Start band,
|
|||
glide shape, duration, and following inter-chirp gap all carry code. Any three
|
||||
consecutive correctly detected symbols identify the event index inside the
|
||||
current operating horizon. Mimir continuously queues that timeline through
|
||||
Aquarium audio, uses coarse chirplet energy for acquisition, refines delay from
|
||||
matched event indices when the symbol decoder succeeds, and can build a
|
||||
provisional aligned mono frame for channels that clear the confidence gate.
|
||||
Aquarium audio and decodes timing through the constrained chirplet-transform
|
||||
path.
|
||||
Reports now carry fractional delay and per-band matched energy. The first
|
||||
`MimirChirpletStreamDecoder` exists as the constrained chirplet-transform
|
||||
receiver: it turns a bounded PCM window into transform frames with multiple
|
||||
symbol candidates, code-valid triplet anchors selected through gap/clock
|
||||
coherence, and an affine source clock fit. The analyzer prefers matched
|
||||
canonical anchors before falling back to the older chirplet-energy lag search.
|
||||
The hub also owns cached reports plus smoothed
|
||||
coherence, and an affine source clock fit. 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
|
||||
|
|
@ -113,8 +110,8 @@ 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. The current aligned frame is integer-delay only;
|
||||
fractional delay and the hot resampler still belong in Faust/native DSP.
|
||||
are dialogue anchors. Fractional delay and the hot resampler belong in
|
||||
Faust/native DSP.
|
||||
|
||||
## Visual Fusion
|
||||
|
||||
|
|
|
|||
|
|
@ -27,8 +27,7 @@ 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,
|
||||
audio chirplet delay estimation, provisional aligned audio frames, and the
|
||||
video capture driver seam.
|
||||
audio chirplet delay estimation, 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.
|
||||
|
|
@ -68,8 +67,8 @@ Get-Content .\state\evidence.jsonl -Tail 8
|
|||
constellation symbols. Start band, glide shape, duration, and following
|
||||
inter-chirp gap all carry code, so any three consecutive correctly detected
|
||||
symbols identify the event index inside the current operating horizon. The
|
||||
timeline owns Aquarium PCM segment rendering, coarse acquisition,
|
||||
symbol/event decoding, and per-band response hooks. Sync reports now include
|
||||
timeline owns Aquarium PCM segment rendering, transform-frame decoding,
|
||||
triplet anchor decoding, 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. `MimirChirpletStreamDecoder`
|
||||
is the first constrained chirplet-transform receiver: it emits transform
|
||||
|
|
@ -80,7 +79,7 @@ Get-Content .\state\evidence.jsonl -Tail 8
|
|||
passive. Actual Mimir.App testing proves Aquarium audio wakes Scarlett
|
||||
loopback, keeps mic buffers live, and produces confident online sync states,
|
||||
but the decoder still needs stronger symbol likelihoods/codebook distance
|
||||
before arbitrary real triplets can replace the lag fallback. PS3 Eye audio is
|
||||
before arbitrary real triplets can drive the actuator directly. 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.
|
||||
|
|
|
|||
|
|
@ -68,18 +68,6 @@ foreach (var state in hub.AudioSynchronizationStates)
|
|||
$"sync-state {state.ReferenceSourceId}->{state.SourceId}: smoothedDelaySamples={state.SmoothedDelaySamples:0.000} delayMs={state.DelayMilliseconds:0.000} sroPpm={state.SamplingRateOffsetPpm:0.000} confidence={state.Confidence:0.000} bands={DescribeBands(state.BandResponses)}");
|
||||
}
|
||||
|
||||
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} fractionalDelaySamples={channel.FractionalDelaySamples:0.000} confidence={channel.Confidence:0.000}");
|
||||
}
|
||||
}
|
||||
|
||||
if (requireSamples && emptyBuffers.Count > 0)
|
||||
{
|
||||
Console.Error.WriteLine($"empty buffers: {string.Join(", ", emptyBuffers)}");
|
||||
|
|
|
|||
|
|
@ -164,7 +164,7 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
return;
|
||||
}
|
||||
|
||||
synchronization.AnalyzeAudioSynchronizationStep(DefaultAudioSyncReference, runtimeSeconds);
|
||||
synchronization.AnalyzeAudioSynchronizationStep(DefaultAudioSyncReference);
|
||||
lastAudioSynchronizationReports = synchronization.AudioSynchronizationReports;
|
||||
nextAudioSyncSeconds += AudioSyncUpdateIntervalSeconds;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
namespace Mimir.Runtime.Synchronization;
|
||||
|
||||
public sealed record MimirAlignedAudioChannel(
|
||||
string SourceId,
|
||||
int DelaySamples,
|
||||
double FractionalDelaySamples,
|
||||
double Confidence);
|
||||
|
||||
public sealed record MimirAlignedAudioFrame(
|
||||
string ReferenceSourceId,
|
||||
int SampleRate,
|
||||
int FrameCount,
|
||||
IReadOnlyList<MimirAlignedAudioChannel> Channels,
|
||||
float[][] Samples);
|
||||
|
|
@ -5,13 +5,10 @@ namespace Mimir.Runtime.Synchronization;
|
|||
public sealed class MimirAudioSynchronizationAnalyzer
|
||||
{
|
||||
private const int MaxWindowSamples = 48_000 * 2;
|
||||
private const int MaxLagSamples = 48_000;
|
||||
private const int ChirpletHopSamples = 16;
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationReport> Analyze(
|
||||
IEnumerable<MimirRollingStreamBuffer> buffers,
|
||||
string referenceSourceId,
|
||||
double approximateTimelineSeconds,
|
||||
IReadOnlySet<string>? candidateSourceIds = null)
|
||||
{
|
||||
var audioBuffers = buffers
|
||||
|
|
@ -76,88 +73,28 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
var referenceDecode = MimirChirpletTimeline.Default.DecodeStreamWindow(referenceWindow, referenceBlock.SampleRate);
|
||||
var candidateDecode = MimirChirpletTimeline.Default.DecodeStreamWindow(candidateWindow, referenceBlock.SampleRate);
|
||||
var deterministicFit = EstimateDelayFromDecodedTimeline(referenceDecode, candidateDecode);
|
||||
if (deterministicFit.MatchedEvents >= 3)
|
||||
{
|
||||
var decodedDelaySamples = deterministicFit.DelaySamples;
|
||||
var decodedBandResponses = MimirChirpletTimeline.Default.EstimateBandResponse(candidateWindow, referenceBlock.SampleRate);
|
||||
reports.Add(new MimirAudioSynchronizationReport(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
referenceBlock.SampleRate,
|
||||
(int)Math.Round(decodedDelaySamples),
|
||||
decodedDelaySamples,
|
||||
decodedDelaySamples * 1000.0 / referenceBlock.SampleRate,
|
||||
deterministicFit.Confidence,
|
||||
decodedBandResponses,
|
||||
commonEndNs,
|
||||
compared,
|
||||
reference.Latest?.Sequence ?? 0,
|
||||
buffer.Latest?.Sequence ?? 0,
|
||||
deterministicFit.MatchedEvents,
|
||||
deterministicFit.Confidence));
|
||||
continue;
|
||||
}
|
||||
|
||||
var referenceWindowStartSample = referenceSamples.Length - compared;
|
||||
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)
|
||||
if (deterministicFit.MatchedEvents < 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var maxLag = Math.Min(MaxLagSamples / ChirpletHopSamples, Math.Min(referenceSync.Length, candidateSync.Length) / 2);
|
||||
var (delayHops, confidence) = EstimateDelay(referenceSync, candidateSync, maxLag);
|
||||
var fractionalDelaySamples = delayHops * ChirpletHopSamples;
|
||||
var timelineMatchedEvents = 0;
|
||||
var timelineConfidence = 0.0;
|
||||
if (confidence >= 0.03 && double.IsFinite(approximateTimelineSeconds))
|
||||
{
|
||||
var referencePlacement = MimirChirpletTimeline.Default.DecodeReferenceWindow(
|
||||
referenceSamples,
|
||||
referenceBlock.SampleRate,
|
||||
approximateTimelineSeconds);
|
||||
var adjustedReferenceObservations = referencePlacement.Observations
|
||||
.Where(observation =>
|
||||
observation.SampleOffset >= referenceWindowStartSample &&
|
||||
observation.SampleOffset < referenceWindowStartSample + compared)
|
||||
.Select(observation => observation with
|
||||
{
|
||||
SampleOffset = observation.SampleOffset - referenceWindowStartSample,
|
||||
})
|
||||
.ToArray();
|
||||
var candidateObservations = MimirChirpletTimeline.Default.ObserveKnownEvents(
|
||||
candidateWindow,
|
||||
referenceBlock.SampleRate,
|
||||
adjustedReferenceObservations,
|
||||
fractionalDelaySamples);
|
||||
var eventFit = FitDelayFromEvents(adjustedReferenceObservations, candidateObservations, referenceBlock.SampleRate);
|
||||
if (eventFit.MatchedEvents >= 3)
|
||||
{
|
||||
fractionalDelaySamples = eventFit.DelaySamples;
|
||||
timelineMatchedEvents = eventFit.MatchedEvents;
|
||||
timelineConfidence = eventFit.Confidence;
|
||||
confidence = Math.Clamp((confidence * 0.35) + (eventFit.Confidence * 0.65), 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
var delaySamples = (int)Math.Round(fractionalDelaySamples);
|
||||
var decodedDelaySamples = deterministicFit.DelaySamples;
|
||||
var bandResponses = MimirChirpletTimeline.Default.EstimateBandResponse(candidateWindow, referenceBlock.SampleRate);
|
||||
reports.Add(new MimirAudioSynchronizationReport(
|
||||
reference.Descriptor.SourceId,
|
||||
buffer.Descriptor.SourceId,
|
||||
referenceBlock.SampleRate,
|
||||
delaySamples,
|
||||
fractionalDelaySamples,
|
||||
fractionalDelaySamples * 1000.0 / referenceBlock.SampleRate,
|
||||
confidence,
|
||||
(int)Math.Round(decodedDelaySamples),
|
||||
decodedDelaySamples,
|
||||
decodedDelaySamples * 1000.0 / referenceBlock.SampleRate,
|
||||
deterministicFit.Confidence,
|
||||
bandResponses,
|
||||
commonEndNs,
|
||||
compared,
|
||||
reference.Latest?.Sequence ?? 0,
|
||||
buffer.Latest?.Sequence ?? 0,
|
||||
timelineMatchedEvents,
|
||||
timelineConfidence));
|
||||
deterministicFit.MatchedEvents,
|
||||
deterministicFit.Confidence));
|
||||
}
|
||||
|
||||
return reports;
|
||||
|
|
@ -218,101 +155,6 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
return (clockDelay, confidence, Math.Min(reference.ClockFit.AnchorCount, candidate.ClockFit.AnchorCount));
|
||||
}
|
||||
|
||||
public MimirAlignedAudioFrame? BuildAlignedFrame(
|
||||
IEnumerable<MimirRollingStreamBuffer> 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, approximateTimelineSeconds: double.PositiveInfinity)
|
||||
.Where(report => report.Confidence >= minimumConfidence)
|
||||
.ToDictionary(report => report.SourceId, StringComparer.Ordinal);
|
||||
var alignedReports = reports.Values
|
||||
.OrderBy(report => report.SourceId, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
var alignedBuffers = alignedReports
|
||||
.Select(report => audioBuffers.TryGetValue(report.SourceId, out var buffer) ? buffer : null)
|
||||
.Where(buffer => buffer != null)
|
||||
.Cast<MimirRollingStreamBuffer>()
|
||||
.ToArray();
|
||||
var commonEndNs = new[] { reference }
|
||||
.Concat(alignedBuffers)
|
||||
.Select(buffer => buffer.Latest?.TimestampNs ?? 0)
|
||||
.Where(timestamp => timestamp > 0)
|
||||
.DefaultIfEmpty(0)
|
||||
.Min();
|
||||
if (commonEndNs <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
referenceSamples = ExtractMonoWindow(reference, out referenceBlock, commonEndNs);
|
||||
if (referenceSamples.Length < frameCount || referenceBlock == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var maxPositiveDelay = Math.Max(0, alignedReports.Select(report => report.DelaySamples).DefaultIfEmpty(0).Max());
|
||||
var channels = new List<MimirAlignedAudioChannel>
|
||||
{
|
||||
new(referenceSourceId, 0, 0.0, 1.0),
|
||||
};
|
||||
var samples = new List<float[]>
|
||||
{
|
||||
TailEndingBefore(referenceSamples, frameCount, maxPositiveDelay),
|
||||
};
|
||||
|
||||
foreach (var report in alignedReports)
|
||||
{
|
||||
if (!audioBuffers.TryGetValue(report.SourceId, out var buffer))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var candidateSamples = ExtractMonoWindow(buffer, out var candidateBlock, commonEndNs);
|
||||
if (candidateBlock == null ||
|
||||
candidateBlock.SampleFormat != MimirAudioSampleFormat.Float32)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
candidateSamples = ResampleToRate(candidateSamples, candidateBlock.SampleRate, referenceBlock.SampleRate);
|
||||
var trimSamples = maxPositiveDelay - report.DelaySamples;
|
||||
if (trimSamples < 0 || candidateSamples.Length < frameCount + trimSamples)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
samples.Add(TailEndingBefore(candidateSamples, frameCount, trimSamples));
|
||||
channels.Add(new MimirAlignedAudioChannel(
|
||||
report.SourceId,
|
||||
report.DelaySamples,
|
||||
report.FractionalDelaySamples,
|
||||
report.Confidence));
|
||||
}
|
||||
|
||||
return new MimirAlignedAudioFrame(
|
||||
referenceSourceId,
|
||||
referenceBlock.SampleRate,
|
||||
frameCount,
|
||||
channels,
|
||||
samples.ToArray());
|
||||
}
|
||||
|
||||
private static float[] ExtractMonoWindow(
|
||||
MimirRollingStreamBuffer buffer,
|
||||
out MimirAudioBlockDescriptor? latestBlock,
|
||||
|
|
@ -366,20 +208,6 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
return samples;
|
||||
}
|
||||
|
||||
private static float[] TailEndingBefore(float[] samples, int frameCount, int trimSamples)
|
||||
{
|
||||
var output = new float[frameCount];
|
||||
var endExclusive = samples.Length - trimSamples;
|
||||
var start = endExclusive - frameCount;
|
||||
if (start < 0)
|
||||
{
|
||||
return output;
|
||||
}
|
||||
|
||||
Array.Copy(samples, start, output, 0, frameCount);
|
||||
return output;
|
||||
}
|
||||
|
||||
private static float[] ResampleToRate(float[] samples, int sourceRate, int targetRate)
|
||||
{
|
||||
if (samples.Length == 0 || sourceRate == targetRate)
|
||||
|
|
@ -406,135 +234,4 @@ public sealed class MimirAudioSynchronizationAnalyzer
|
|||
|
||||
return output;
|
||||
}
|
||||
|
||||
private static (double DelaySamples, double Confidence) EstimateDelay(ReadOnlySpan<float> reference, ReadOnlySpan<float> candidate, int maxLag)
|
||||
{
|
||||
var bestLag = 0;
|
||||
var best = double.NegativeInfinity;
|
||||
var previous = double.NegativeInfinity;
|
||||
var next = double.NegativeInfinity;
|
||||
for (var lag = -maxLag; lag <= maxLag; lag++)
|
||||
{
|
||||
var score = NormalizedCorrelation(reference, candidate, lag);
|
||||
if (score > best)
|
||||
{
|
||||
best = score;
|
||||
bestLag = lag;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestLag > -maxLag)
|
||||
{
|
||||
previous = NormalizedCorrelation(reference, candidate, bestLag - 1);
|
||||
}
|
||||
|
||||
if (bestLag < maxLag)
|
||||
{
|
||||
next = NormalizedCorrelation(reference, candidate, bestLag + 1);
|
||||
}
|
||||
|
||||
var offset = ParabolicPeakOffset(previous, best, next);
|
||||
return (bestLag + offset, Math.Max(0.0, Math.Min(1.0, best)));
|
||||
}
|
||||
|
||||
private static (double DelaySamples, double Confidence, int MatchedEvents) FitDelayFromEvents(
|
||||
IReadOnlyList<MimirChirpletEventObservation> referenceObservations,
|
||||
IReadOnlyList<MimirChirpletEventObservation> candidateObservations,
|
||||
int sampleRate)
|
||||
{
|
||||
if (referenceObservations.Count == 0 || candidateObservations.Count == 0)
|
||||
{
|
||||
return (0.0, 0.0, 0);
|
||||
}
|
||||
|
||||
var candidateByEvent = candidateObservations
|
||||
.GroupBy(observation => observation.EventIndex)
|
||||
.ToDictionary(
|
||||
group => group.Key,
|
||||
group => group.OrderByDescending(observation => observation.Energy).First());
|
||||
var delays = new List<(double Delay, double Weight)>();
|
||||
foreach (var reference in referenceObservations)
|
||||
{
|
||||
if (!candidateByEvent.TryGetValue(reference.EventIndex, out var candidate))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var weight = Math.Sqrt(Math.Max(0.0, reference.Energy) * Math.Max(0.0, candidate.Energy));
|
||||
delays.Add((candidate.SampleOffset - reference.SampleOffset, weight));
|
||||
}
|
||||
|
||||
if (delays.Count < 3)
|
||||
{
|
||||
return (0.0, 0.0, delays.Count);
|
||||
}
|
||||
|
||||
var ordered = delays.OrderBy(pair => pair.Delay).ToArray();
|
||||
var trim = ordered.Length >= 8 ? ordered.Length / 8 : 0;
|
||||
var kept = ordered.Skip(trim).Take(ordered.Length - trim * 2).ToArray();
|
||||
var totalWeight = kept.Sum(pair => pair.Weight);
|
||||
if (totalWeight <= 1.0e-12)
|
||||
{
|
||||
return (0.0, 0.0, kept.Length);
|
||||
}
|
||||
|
||||
var delay = kept.Sum(pair => pair.Delay * pair.Weight) / totalWeight;
|
||||
var meanAbsoluteError = kept.Sum(pair => Math.Abs(pair.Delay - delay) * pair.Weight) / totalWeight;
|
||||
var scatterConfidence = 1.0 / (1.0 + meanAbsoluteError / Math.Max(1.0, sampleRate * 0.002));
|
||||
var countConfidence = Math.Clamp(kept.Length / 12.0, 0.0, 1.0);
|
||||
var energyConfidence = Math.Clamp(totalWeight / kept.Length, 0.0, 1.0);
|
||||
return (delay, scatterConfidence * 0.55 + countConfidence * 0.25 + energyConfidence * 0.20, kept.Length);
|
||||
}
|
||||
|
||||
private static double ParabolicPeakOffset(double left, double center, double right)
|
||||
{
|
||||
if (!double.IsFinite(left) || !double.IsFinite(center) || !double.IsFinite(right))
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
var denominator = left - 2.0 * center + right;
|
||||
if (Math.Abs(denominator) <= 1.0e-12)
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
return Math.Clamp(0.5 * (left - right) / denominator, -0.5, 0.5);
|
||||
}
|
||||
|
||||
private static double NormalizedCorrelation(ReadOnlySpan<float> reference, ReadOnlySpan<float> candidate, int lag)
|
||||
{
|
||||
var startReference = lag < 0 ? -lag : 0;
|
||||
var startCandidate = lag > 0 ? lag : 0;
|
||||
var count = Math.Min(reference.Length - startReference, candidate.Length - startCandidate);
|
||||
if (count < 128)
|
||||
{
|
||||
return double.NegativeInfinity;
|
||||
}
|
||||
|
||||
var sumReference = 0.0;
|
||||
var sumCandidate = 0.0;
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
sumReference += reference[startReference + index];
|
||||
sumCandidate += candidate[startCandidate + index];
|
||||
}
|
||||
|
||||
var meanReference = sumReference / count;
|
||||
var meanCandidate = sumCandidate / count;
|
||||
var cross = 0.0;
|
||||
var energyReference = 0.0;
|
||||
var energyCandidate = 0.0;
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
var a = reference[startReference + index] - meanReference;
|
||||
var b = candidate[startCandidate + index] - meanCandidate;
|
||||
cross += a * b;
|
||||
energyReference += a * a;
|
||||
energyCandidate += b * b;
|
||||
}
|
||||
|
||||
var denominator = Math.Sqrt(energyReference * energyCandidate);
|
||||
return denominator > 1.0e-12 ? cross / denominator : double.NegativeInfinity;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,18 +20,6 @@ public sealed record MimirChirpletTimelineEvent(
|
|||
double StartSeconds,
|
||||
MimirChirpletTone Tone);
|
||||
|
||||
public sealed record MimirChirpletEventObservation(
|
||||
ulong EventIndex,
|
||||
int SymbolId,
|
||||
double TimelineSeconds,
|
||||
double SampleOffset,
|
||||
double Energy);
|
||||
|
||||
public sealed record MimirChirpletTimelinePlacement(
|
||||
double TimelineSecondsAtWindowStart,
|
||||
double Confidence,
|
||||
IReadOnlyList<MimirChirpletEventObservation> Observations);
|
||||
|
||||
public sealed class MimirChirpletTimeline
|
||||
{
|
||||
public const int SampleRate = 48_000;
|
||||
|
|
@ -53,22 +41,11 @@ public sealed class MimirChirpletTimeline
|
|||
private static readonly double[] PeriodEventStarts = BuildPeriodEventStarts(TimelineSymbols);
|
||||
private static readonly double PeriodDurationSeconds = PeriodEventStarts[^1] + GapSecondsForSymbol(TimelineSymbols[^1]);
|
||||
private static readonly MimirChirpletTone[] SymbolTones = BuildSymbolTones();
|
||||
private static readonly MimirChirpletTone[] CoarseTones =
|
||||
[
|
||||
new(0.0, 0.048, 6_700.0, 7_200.0, 0.75),
|
||||
new(0.0, 0.052, 7_700.0, 8_400.0, 0.80),
|
||||
new(0.0, 0.056, 8_900.0, 9_800.0, 0.85),
|
||||
new(0.0, 0.060, 10_300.0, 11_400.0, 0.85),
|
||||
new(0.0, 0.064, 12_100.0, 13_500.0, 0.90),
|
||||
new(0.0, 0.068, 14_200.0, 15_900.0, 0.80),
|
||||
];
|
||||
private readonly IReadOnlyList<float[]> symbolKernels;
|
||||
private readonly IReadOnlyList<float[]> coarseKernels;
|
||||
|
||||
private MimirChirpletTimeline()
|
||||
{
|
||||
symbolKernels = SymbolTones.Select(symbol => RenderToneKernel(symbol, SampleRate)).ToArray();
|
||||
coarseKernels = CoarseTones.Select(tone => RenderToneKernel(tone, SampleRate)).ToArray();
|
||||
}
|
||||
|
||||
public static MimirChirpletTimeline Default { get; } = new();
|
||||
|
|
@ -111,11 +88,6 @@ public sealed class MimirChirpletTimeline
|
|||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
|
||||
public float[] BuildTimelineEnergyTrace(ReadOnlySpan<float> samples, int sampleRate, int hopSamples)
|
||||
{
|
||||
return ContrastNormalize(BuildEnvelopeEnergyTrace(samples, sampleRate, hopSamples));
|
||||
}
|
||||
|
||||
public IReadOnlyList<MimirChirpletBandResponse> EstimateBandResponse(ReadOnlySpan<float> samples, int sampleRate)
|
||||
{
|
||||
if (samples.Length == 0)
|
||||
|
|
@ -154,65 +126,6 @@ public sealed class MimirChirpletTimeline
|
|||
return new MimirChirpletStreamDecode(frames, symbols, anchors, clock);
|
||||
}
|
||||
|
||||
public MimirChirpletTimelinePlacement DecodeReferenceWindow(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
double approximateWindowEndTimelineSeconds)
|
||||
{
|
||||
if (samples.Length == 0)
|
||||
{
|
||||
return new MimirChirpletTimelinePlacement(0.0, 0.0, []);
|
||||
}
|
||||
|
||||
var observed = DetectSymbolEvents(samples, sampleRate, Math.Max(1, sampleRate / 200));
|
||||
var placement = PlaceObservedSymbols(observed, sampleRate);
|
||||
if (placement.Observations.Count >= 3 || !double.IsFinite(approximateWindowEndTimelineSeconds))
|
||||
{
|
||||
return placement;
|
||||
}
|
||||
|
||||
var windowSeconds = samples.Length / (double)sampleRate;
|
||||
var approximateStartSeconds = Math.Max(0.0, approximateWindowEndTimelineSeconds - windowSeconds);
|
||||
var fallback = new List<MimirChirpletEventObservation>();
|
||||
foreach (var timelineEvent in EventsOverlapping(approximateStartSeconds - 0.25, windowSeconds + 0.5))
|
||||
{
|
||||
var predictedSample = (timelineEvent.StartSeconds - approximateStartSeconds) * sampleRate;
|
||||
var observation = ObserveEvent(samples, sampleRate, timelineEvent, predictedSample, searchRadiusSamples: Math.Max(8, sampleRate / 2));
|
||||
if (observation != null)
|
||||
{
|
||||
fallback.Add(observation);
|
||||
}
|
||||
}
|
||||
|
||||
if (fallback.Count < 3)
|
||||
{
|
||||
return new MimirChirpletTimelinePlacement(approximateStartSeconds, 0.0, fallback);
|
||||
}
|
||||
|
||||
return FitTimelinePlacement(fallback, sampleRate);
|
||||
}
|
||||
|
||||
public IReadOnlyList<MimirChirpletEventObservation> ObserveKnownEvents(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
IEnumerable<MimirChirpletEventObservation> referenceObservations,
|
||||
double coarseDelaySamples)
|
||||
{
|
||||
var observations = new List<MimirChirpletEventObservation>();
|
||||
foreach (var reference in referenceObservations)
|
||||
{
|
||||
var timelineEvent = EventForIndex(reference.EventIndex);
|
||||
var predictedSample = reference.SampleOffset + coarseDelaySamples;
|
||||
var observation = ObserveEvent(samples, sampleRate, timelineEvent, predictedSample, searchRadiusSamples: Math.Max(16, sampleRate / 10));
|
||||
if (observation != null)
|
||||
{
|
||||
observations.Add(observation);
|
||||
}
|
||||
}
|
||||
|
||||
return observations;
|
||||
}
|
||||
|
||||
public MimirChirpletTimelineEvent EventForIndex(ulong eventIndex)
|
||||
{
|
||||
var symbolId = SymbolForEvent(eventIndex);
|
||||
|
|
@ -239,46 +152,6 @@ public sealed class MimirChirpletTimeline
|
|||
return events;
|
||||
}
|
||||
|
||||
private IReadOnlyList<MimirChirpletEventObservation> DetectSymbolEvents(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
int hopSamples)
|
||||
{
|
||||
if (samples.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var coarse = ContrastNormalize(BuildEnvelopeEnergyTrace(samples, sampleRate, hopSamples));
|
||||
if (coarse.Length <= 2)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var candidates = new List<MimirChirpletEventObservation>();
|
||||
for (var frame = 1; frame < coarse.Length - 1; frame++)
|
||||
{
|
||||
if (coarse[frame] < 0.055 ||
|
||||
coarse[frame] < coarse[frame - 1] ||
|
||||
coarse[frame] < coarse[frame + 1])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var observation = ClassifySymbolAt(
|
||||
samples,
|
||||
sampleRate,
|
||||
frame * hopSamples,
|
||||
Math.Max(hopSamples * 3, sampleRate / 100));
|
||||
if (observation != null)
|
||||
{
|
||||
candidates.Add(observation);
|
||||
}
|
||||
}
|
||||
|
||||
return SuppressNearbyDetections(candidates, sampleRate);
|
||||
}
|
||||
|
||||
private IReadOnlyList<MimirChirpletTransformFrame> DetectTransformFrames(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
|
|
@ -289,18 +162,18 @@ public sealed class MimirChirpletTimeline
|
|||
return [];
|
||||
}
|
||||
|
||||
var coarse = ContrastNormalize(BuildEnvelopeEnergyTrace(samples, sampleRate, hopSamples));
|
||||
if (coarse.Length <= 2)
|
||||
var envelope = ContrastNormalize(BuildEnvelopeEnergyTrace(samples, sampleRate, hopSamples));
|
||||
if (envelope.Length <= 2)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var frames = new List<MimirChirpletTransformFrame>();
|
||||
for (var frame = 1; frame < coarse.Length - 1; frame++)
|
||||
for (var frame = 1; frame < envelope.Length - 1; frame++)
|
||||
{
|
||||
if (coarse[frame] < 0.055 ||
|
||||
coarse[frame] < coarse[frame - 1] ||
|
||||
coarse[frame] < coarse[frame + 1])
|
||||
if (envelope[frame] < 0.055 ||
|
||||
envelope[frame] < envelope[frame - 1] ||
|
||||
envelope[frame] < envelope[frame + 1])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
|
@ -375,67 +248,6 @@ public sealed class MimirChirpletTimeline
|
|||
ordered.Select(candidate => candidate.Candidate).ToArray());
|
||||
}
|
||||
|
||||
private MimirChirpletEventObservation? ClassifySymbolAt(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
int predictedOffset,
|
||||
int searchRadiusSamples)
|
||||
{
|
||||
var bestSymbol = -1;
|
||||
var bestOffset = predictedOffset;
|
||||
var bestEnergy = 0.0;
|
||||
for (var symbol = 0; symbol < SymbolTones.Length; symbol++)
|
||||
{
|
||||
var tone = SymbolTones[symbol];
|
||||
var kernel = sampleRate == SampleRate ? symbolKernels[symbol] : RenderToneKernel(tone, sampleRate);
|
||||
if (kernel.Length == 0 || samples.Length < kernel.Length)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var start = Math.Max(0, predictedOffset - searchRadiusSamples);
|
||||
var end = Math.Min(samples.Length - kernel.Length, predictedOffset + searchRadiusSamples);
|
||||
for (var offset = start; offset <= end; offset += Math.Max(1, searchRadiusSamples / 2))
|
||||
{
|
||||
var energy = DirectionalMatchedEnergy(samples.Slice(offset, kernel.Length), kernel);
|
||||
if (energy > bestEnergy)
|
||||
{
|
||||
bestEnergy = energy;
|
||||
bestSymbol = symbol;
|
||||
bestOffset = offset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestSymbol < 0 || bestEnergy < 0.25
|
||||
? null
|
||||
: new MimirChirpletEventObservation(0, bestSymbol, 0.0, bestOffset, bestEnergy);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletEventObservation> SuppressNearbyDetections(
|
||||
IReadOnlyList<MimirChirpletEventObservation> observations,
|
||||
int sampleRate)
|
||||
{
|
||||
if (observations.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var minimumSpacingSamples = MinEventGapSeconds * sampleRate * 0.55;
|
||||
var kept = new List<MimirChirpletEventObservation>();
|
||||
foreach (var observation in observations.OrderByDescending(observation => observation.Energy))
|
||||
{
|
||||
if (kept.Any(existing => Math.Abs(existing.SampleOffset - observation.SampleOffset) < minimumSpacingSamples))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
kept.Add(observation);
|
||||
}
|
||||
|
||||
return kept.OrderBy(observation => observation.SampleOffset).ToArray();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletTransformFrame> SuppressNearbyFrames(
|
||||
IReadOnlyList<MimirChirpletTransformFrame> frames,
|
||||
int sampleRate)
|
||||
|
|
@ -460,110 +272,6 @@ public sealed class MimirChirpletTimeline
|
|||
return kept.OrderBy(frame => frame.SampleOffset).ToArray();
|
||||
}
|
||||
|
||||
private static MimirChirpletTimelinePlacement PlaceObservedSymbols(
|
||||
IReadOnlyList<MimirChirpletEventObservation> observations,
|
||||
int sampleRate)
|
||||
{
|
||||
if (observations.Count < 3)
|
||||
{
|
||||
return new MimirChirpletTimelinePlacement(0.0, 0.0, observations);
|
||||
}
|
||||
|
||||
var best = Array.Empty<MimirChirpletEventObservation>();
|
||||
var bestConfidence = 0.0;
|
||||
for (var index = 0; index <= observations.Count - 3; index++)
|
||||
{
|
||||
var first = observations[index];
|
||||
var second = observations[index + 1];
|
||||
var third = observations[index + 2];
|
||||
if (!IsConsecutiveByTime(first, second, sampleRate) ||
|
||||
!IsConsecutiveByTime(second, third, sampleRate))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var code = TripleCode(first.SymbolId, second.SymbolId, third.SymbolId);
|
||||
if (!TripleToIndex.TryGetValue(code, out var eventIndex))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var placed = new[]
|
||||
{
|
||||
PlaceObservation(first, (ulong)eventIndex),
|
||||
PlaceObservation(second, (ulong)eventIndex + 1UL),
|
||||
PlaceObservation(third, (ulong)eventIndex + 2UL),
|
||||
};
|
||||
var confidence = placed.Average(observation => observation.Energy);
|
||||
if (confidence > bestConfidence)
|
||||
{
|
||||
bestConfidence = confidence;
|
||||
best = placed;
|
||||
}
|
||||
}
|
||||
|
||||
return best.Length == 0
|
||||
? new MimirChirpletTimelinePlacement(0.0, 0.0, observations)
|
||||
: FitTimelinePlacement(best, sampleRate);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletTimelineAnchor> PlaceAllTripletAnchors(
|
||||
IReadOnlyList<MimirChirpletSymbolObservation> symbols,
|
||||
int sampleRate)
|
||||
{
|
||||
if (symbols.Count < TimelineOrder)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var anchors = new List<MimirChirpletTimelineAnchor>();
|
||||
for (var index = 0; index <= symbols.Count - TimelineOrder; index++)
|
||||
{
|
||||
var first = symbols[index];
|
||||
var second = symbols[index + 1];
|
||||
var third = symbols[index + 2];
|
||||
if (!IsConsecutiveByTime(first, second, sampleRate) ||
|
||||
!IsConsecutiveByTime(second, third, sampleRate))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var code = TripleCode(first.SymbolId, second.SymbolId, third.SymbolId);
|
||||
if (!TripleToIndex.TryGetValue(code, out var eventIndex))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var timelineEvent = Default.EventForIndex((ulong)eventIndex);
|
||||
var predictedSecond = Default.EventForIndex((ulong)eventIndex + 1UL);
|
||||
var predictedThird = Default.EventForIndex((ulong)eventIndex + 2UL);
|
||||
var measuredGapA = (second.SampleOffset - first.SampleOffset) / sampleRate;
|
||||
var measuredGapB = (third.SampleOffset - second.SampleOffset) / sampleRate;
|
||||
var expectedGapA = predictedSecond.StartSeconds - timelineEvent.StartSeconds;
|
||||
var expectedGapB = predictedThird.StartSeconds - predictedSecond.StartSeconds;
|
||||
var gapError = Math.Abs(measuredGapA - expectedGapA) + Math.Abs(measuredGapB - expectedGapB);
|
||||
var gapConfidence = 1.0 / (1.0 + gapError / 0.006);
|
||||
if (gapConfidence < 0.45)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var energyConfidence = Math.Clamp((first.Energy + second.Energy + third.Energy) / 3.0, 0.0, 1.0);
|
||||
anchors.Add(new MimirChirpletTimelineAnchor(
|
||||
(ulong)eventIndex,
|
||||
timelineEvent.StartSeconds,
|
||||
first.SampleOffset,
|
||||
gapConfidence * 0.65 + energyConfidence * 0.35,
|
||||
[first, second, third]));
|
||||
}
|
||||
|
||||
return anchors
|
||||
.GroupBy(anchor => anchor.EventIndex)
|
||||
.Select(group => group.OrderByDescending(anchor => anchor.Confidence).First())
|
||||
.OrderBy(anchor => anchor.SampleOffset)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<MimirChirpletTimelineAnchor> DecodeTrellisAnchors(
|
||||
IReadOnlyList<MimirChirpletTransformFrame> frames,
|
||||
int sampleRate)
|
||||
|
|
@ -741,15 +449,6 @@ public sealed class MimirChirpletTimeline
|
|||
meanAbsoluteError);
|
||||
}
|
||||
|
||||
private static bool IsConsecutiveByTime(
|
||||
MimirChirpletEventObservation first,
|
||||
MimirChirpletEventObservation second,
|
||||
int sampleRate)
|
||||
{
|
||||
var seconds = (second.SampleOffset - first.SampleOffset) / sampleRate;
|
||||
return seconds >= MinEventGapSeconds * 0.55 && seconds <= MaxEventGapSeconds * 1.45;
|
||||
}
|
||||
|
||||
private static bool IsConsecutiveByTime(
|
||||
MimirChirpletSymbolObservation first,
|
||||
MimirChirpletSymbolObservation second,
|
||||
|
|
@ -768,90 +467,6 @@ public sealed class MimirChirpletTimeline
|
|||
return seconds >= MinEventGapSeconds * 0.55 && seconds <= MaxEventGapSeconds * 1.45;
|
||||
}
|
||||
|
||||
private static MimirChirpletEventObservation PlaceObservation(
|
||||
MimirChirpletEventObservation observation,
|
||||
ulong eventIndex)
|
||||
{
|
||||
var timelineEvent = Default.EventForIndex(eventIndex);
|
||||
return observation with
|
||||
{
|
||||
EventIndex = eventIndex,
|
||||
SymbolId = timelineEvent.SymbolId,
|
||||
TimelineSeconds = timelineEvent.StartSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
private static MimirChirpletTimelinePlacement FitTimelinePlacement(
|
||||
IReadOnlyList<MimirChirpletEventObservation> observations,
|
||||
int sampleRate)
|
||||
{
|
||||
if (observations.Count == 0)
|
||||
{
|
||||
return new MimirChirpletTimelinePlacement(0.0, 0.0, []);
|
||||
}
|
||||
|
||||
var offsets = observations
|
||||
.Select(observation => observation.TimelineSeconds - observation.SampleOffset / sampleRate)
|
||||
.ToArray();
|
||||
var timelineStart = Median(offsets);
|
||||
var residualSeconds = observations
|
||||
.Average(observation => Math.Abs(observation.TimelineSeconds - observation.SampleOffset / sampleRate - timelineStart));
|
||||
var residualConfidence = 1.0 / (1.0 + residualSeconds / 0.004);
|
||||
var countConfidence = Math.Clamp(observations.Count / 6.0, 0.0, 1.0);
|
||||
var energyConfidence = Math.Clamp(observations.Average(observation => observation.Energy), 0.0, 1.0);
|
||||
return new MimirChirpletTimelinePlacement(
|
||||
timelineStart,
|
||||
residualConfidence * 0.45 + countConfidence * 0.25 + energyConfidence * 0.30,
|
||||
observations);
|
||||
}
|
||||
|
||||
private static MimirChirpletEventObservation? ObserveEvent(
|
||||
ReadOnlySpan<float> samples,
|
||||
int sampleRate,
|
||||
MimirChirpletTimelineEvent timelineEvent,
|
||||
double predictedSample,
|
||||
int searchRadiusSamples)
|
||||
{
|
||||
var kernel = RenderToneKernel(timelineEvent.Tone with { StartSeconds = 0.0 }, sampleRate);
|
||||
if (kernel.Length == 0 || samples.Length < kernel.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var predictedOffset = (int)Math.Round(predictedSample);
|
||||
var start = Math.Max(0, predictedOffset - searchRadiusSamples);
|
||||
var end = Math.Min(samples.Length - kernel.Length, predictedOffset + searchRadiusSamples);
|
||||
if (end < start)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bestOffset = start;
|
||||
var bestEnergy = 0.0;
|
||||
var step = Math.Max(1, sampleRate / 4_000);
|
||||
for (var offset = start; offset <= end; offset += step)
|
||||
{
|
||||
var energy = DirectionalMatchedEnergy(samples.Slice(offset, kernel.Length), kernel);
|
||||
if (energy > bestEnergy)
|
||||
{
|
||||
bestEnergy = energy;
|
||||
bestOffset = offset;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestEnergy < 0.045)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new MimirChirpletEventObservation(
|
||||
timelineEvent.Index,
|
||||
timelineEvent.SymbolId,
|
||||
timelineEvent.StartSeconds,
|
||||
bestOffset,
|
||||
bestEnergy);
|
||||
}
|
||||
|
||||
private static int SymbolForEvent(ulong eventIndex) =>
|
||||
TimelineSymbols[(int)(eventIndex % (ulong)TimelineSymbols.Length)];
|
||||
|
||||
|
|
@ -978,20 +593,6 @@ public sealed class MimirChirpletTimeline
|
|||
private static int TripleCode(int first, int second, int third) =>
|
||||
first * SymbolCount * SymbolCount + second * SymbolCount + third;
|
||||
|
||||
private static double Median(double[] values)
|
||||
{
|
||||
if (values.Length == 0)
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
Array.Sort(values);
|
||||
var middle = values.Length / 2;
|
||||
return values.Length % 2 == 0
|
||||
? (values[middle - 1] + values[middle]) * 0.5
|
||||
: values[middle];
|
||||
}
|
||||
|
||||
private static float[] RenderToneKernel(MimirChirpletTone tone, int sampleRate)
|
||||
{
|
||||
var frameCount = Math.Max(1, (int)Math.Ceiling(tone.DurationSeconds * sampleRate));
|
||||
|
|
@ -1069,41 +670,6 @@ public sealed class MimirChirpletTimeline
|
|||
return denominator > 1.0e-12 ? Math.Max(0.0, dot / denominator) : 0.0;
|
||||
}
|
||||
|
||||
private float[] BuildCoarseEnergyTrace(ReadOnlySpan<float> samples, int sampleRate, int hopSamples)
|
||||
{
|
||||
var traces = new List<float[]>();
|
||||
for (var index = 0; index < CoarseTones.Length; index++)
|
||||
{
|
||||
var tone = CoarseTones[index];
|
||||
var kernel = sampleRate == SampleRate ? coarseKernels[index] : RenderToneKernel(tone, 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 < output.Length; frame++)
|
||||
{
|
||||
var best = 0.0f;
|
||||
foreach (var trace in traces)
|
||||
{
|
||||
best = Math.Max(best, trace[frame]);
|
||||
}
|
||||
|
||||
output[frame] = best;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
private static float[] BuildEnvelopeEnergyTrace(ReadOnlySpan<float> samples, int sampleRate, int hopSamples)
|
||||
{
|
||||
var windowSamples = Math.Max(1, (int)Math.Round(MaxEventDurationSeconds * sampleRate));
|
||||
|
|
@ -1140,23 +706,6 @@ public sealed class MimirChirpletTimeline
|
|||
return output;
|
||||
}
|
||||
|
||||
private static float[] BuildMatchedEnergyTrace(ReadOnlySpan<float> samples, ReadOnlySpan<float> 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 MaxMatchedEnergy(ReadOnlySpan<float> samples, ReadOnlySpan<float> kernel, int hopSamples)
|
||||
{
|
||||
if (samples.Length < kernel.Length || kernel.Length == 0)
|
||||
|
|
|
|||
|
|
@ -68,18 +68,16 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
}
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationReport> AnalyzeAudioSynchronization(
|
||||
string referenceSourceId,
|
||||
double approximateTimelineSeconds = double.PositiveInfinity)
|
||||
string referenceSourceId)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var reports = audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId, approximateTimelineSeconds);
|
||||
var reports = audioSynchronization.Analyze(Buffers.Buffers, referenceSourceId);
|
||||
StoreAudioSynchronizationReports(reports);
|
||||
return reports;
|
||||
}
|
||||
|
||||
public IReadOnlyList<MimirAudioSynchronizationReport> AnalyzeAudioSynchronizationStep(
|
||||
string referenceSourceId,
|
||||
double approximateTimelineSeconds,
|
||||
int maxCandidates = 1)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
|
|
@ -106,25 +104,11 @@ public sealed class MimirSynchronizationHub : IDisposable
|
|||
var reports = audioSynchronization.Analyze(
|
||||
Buffers.Buffers,
|
||||
referenceSourceId,
|
||||
approximateTimelineSeconds,
|
||||
selected);
|
||||
StoreAudioSynchronizationReports(reports);
|
||||
return reports;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
private void StoreAudioSynchronizationReports(IReadOnlyList<MimirAudioSynchronizationReport> reports)
|
||||
|
|
|
|||
|
|
@ -45,3 +45,4 @@
|
|||
{"ts":"2026-05-22T15:20:00+01:00","type":"implementation","status":"partial","note":"Removed hidden re-entrant synchronization analysis from the live app path. MimirRuntime now calls a bounded rotating AnalyzeAudioSynchronizationStep every 0.1s, MimirSynchronizationHub caches per-source reports/states, and UI/telemetry read cached state instead of invoking the analyzer or BuildAlignedAudioFrame. FitDelayFromEvents now collapses duplicate candidate event observations by strongest energy, fixing the real app crash 'An item with the same key has already been added. Key: 0'. Dotnet build passed. A visible Mimir.App run with all configured mics no longer crashed at the earlier 4s wall and produced telemetry through runtime t=17.28s in a 22s wall-time harness; it did not reach a full 20 runtime seconds because startup consumed wall time. All non-loopback mics produced cached reports/states, but delay estimates remained unstable and timeline event refinement was intermittent, so the next live invariant is robust outlier rejection/state filtering before any actuator drives resampling."}
|
||||
{"ts":"2026-05-22T16:05:00+01:00","type":"implementation","status":"partial","note":"Documented the intended decoder as a constrained chirplet transform: known dictionary projection to symbol observations, code-valid de Bruijn triplets to canonical timeline anchors, anchors to affine source clock fits, and delay/SRO from comparing loopback and mic clock fits. Added MimirChirpletStreamDecode records and MimirChirpletStreamDecoder with a bounded PCM window, absolute sample offsets, triplet anchors, and clock fits. MimirAudioSynchronizationAnalyzer now prefers matched decoded timeline anchors before falling back to the older chirplet-energy lag search. Synthetic self-test over two seconds of emitted timeline audio currently decodes 12 symbols and one correct anchor for event 9 at sample 47520 with clock 48000 Hz; this proves the new spine but also proves the symbol likelihood/codebook layer is not finished enough to place every triplet yet."}
|
||||
{"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."}
|
||||
|
|
|
|||
|
|
@ -75,10 +75,9 @@ accepted_design:
|
|||
is the first constrained chirplet-transform receiver: it owns a bounded PCM
|
||||
window, emits transform frames with multiple symbol candidates, decodes
|
||||
code-valid triplet anchors through gap/clock coherence, and fits a
|
||||
per-source sample clock from those anchors. `MimirAudioSynchronizationAnalyzer` now treats
|
||||
`loopback-scarlett-speakers` as timing authority, prefers delay from matched
|
||||
decoded timeline anchors, and keeps the older chirplet-energy lag search as
|
||||
a diagnostic fallback while the decoder is cut over. Positive delay means
|
||||
per-source sample clock from those anchors. `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
|
||||
delay, fractional delay, confidence, and per-band matched energy. `MimirSynchronizationHub`
|
||||
caches the latest per-source reports and `MimirAudioSynchronizationStateTracker`
|
||||
|
|
@ -88,9 +87,6 @@ accepted_design:
|
|||
service on a fixed cadence, while UI and telemetry read cached reports/states
|
||||
instead of invoking analysis. `MIMIR_SYNC_TELEMETRY_SECONDS` prints live
|
||||
buffer/report/state telemetry.
|
||||
`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.
|
||||
|
|
@ -197,9 +193,9 @@ current_status:
|
|||
fits, so the actuator can use decoded time instead of filtered lag guesses.
|
||||
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
|
||||
Mimir.Runtime. Mimir.BufferSmoke still proves live buffers and sync reports
|
||||
for Scarlett loopback, Focusrite mic, Kiyo mic, and Kiyo Pro mic when
|
||||
calibration chirplets are playing. Treat PS3 Eye audio as
|
||||
enumeration/runtime-fragile, not unavailable. Keep the Focusrite away from
|
||||
the Leap USB neighborhood and treat Kiyo Pro as a ~25 fps source until its
|
||||
SuperSpeed negotiation is fixed.
|
||||
|
|
|
|||
Loading…
Reference in a new issue