Wire complex contour sync into runtime

This commit is contained in:
Meta Vens 2026-05-25 06:28:20 +01:00
commit 470efb0003
15 changed files with 614 additions and 7 deletions

View file

@ -266,6 +266,32 @@ public sealed class MimirBioacousticContestantRenderer(MimirBioacousticContestan
return samples;
}
public float[] RenderSegmentMonoFloat(ulong segmentIndex, double segmentSeconds, int sampleRate, MimirBioacousticSpeaker? speaker = null)
{
var segmentStartSeconds = segmentIndex * segmentSeconds;
var samples = new float[Math.Max(1, (int)Math.Round(segmentSeconds * sampleRate))];
var firstEvent = Math.Max(0, (long)Math.Floor((segmentStartSeconds - MimirBioacousticContestants.FirstEventSeconds - Profile.MotifDurationSeconds) / Profile.EventSpacingSeconds) - 2);
var lastEvent = Math.Max(firstEvent, (long)Math.Ceiling((segmentStartSeconds + segmentSeconds - MimirBioacousticContestants.FirstEventSeconds) / Profile.EventSpacingSeconds) + 2);
for (var eventIndex = firstEvent; eventIndex <= lastEvent; eventIndex++)
{
var eventStart = EventStartSeconds((ulong)eventIndex);
if (eventStart >= segmentStartSeconds + segmentSeconds ||
eventStart + Profile.MotifDurationSeconds <= segmentStartSeconds)
{
continue;
}
if (speaker != null && SpeakerForEvent((ulong)eventIndex) != speaker.Value)
{
continue;
}
AddEvent(samples, sampleRate, (ulong)eventIndex, PayloadSymbolForEvent((ulong)eventIndex), eventStart, segmentStartSeconds);
}
return samples;
}
public int ExpectedEventCount(double seconds) =>
Math.Max(0, (int)Math.Floor((seconds - MimirBioacousticContestants.FirstEventSeconds - Profile.MotifDurationSeconds) / Profile.EventSpacingSeconds) + 1);
@ -371,6 +397,9 @@ public sealed class MimirBioacousticContestantRenderer(MimirBioacousticContestan
private static int SymbolForEvent(ulong eventIndex) =>
(int)((eventIndex * 73UL + eventIndex / 5UL * 19UL) % MimirBioacousticContestants.SymbolCount);
private static MimirBioacousticSpeaker SpeakerForEvent(ulong eventIndex) =>
(eventIndex & 1UL) == 0UL ? MimirBioacousticSpeaker.Left : MimirBioacousticSpeaker.Right;
private double RootForSymbol(int symbolId)
{
var t = symbolId / (double)(MimirBioacousticContestants.SymbolCount - 1);

View file

@ -0,0 +1,86 @@
using System.Text.Json;
namespace Mimir.Runtime.Synchronization;
public sealed record MimirComplexContourChannelModelDocument(
string Schema,
DateTimeOffset CreatedUtc,
string SourceReceiptPath,
IReadOnlyList<MimirComplexContourPathChannelModel> Paths)
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
};
public static MimirComplexContourChannelModelDocument Load(string path) =>
JsonSerializer.Deserialize<MimirComplexContourChannelModelDocument>(
File.ReadAllText(path),
JsonOptions) ?? new MimirComplexContourChannelModelDocument(
"mimir.bioacoustic.complex-contour-channel-model.v1",
DateTimeOffset.MinValue,
"",
[]);
public MimirComplexContourPathChannelModel? PathFor(string referenceSourceId, string sourceId, int sampleRate)
{
var referenceChannel = ParseAsioChannel(referenceSourceId);
var candidateChannel = ParseAsioChannel(sourceId);
if (referenceChannel == null || candidateChannel == null)
{
return null;
}
return Paths.FirstOrDefault(path =>
path.SampleRate == sampleRate &&
path.ReferenceChannel == referenceChannel.Value &&
path.CandidateChannel == candidateChannel.Value);
}
private static int? ParseAsioChannel(string sourceId)
{
const string prefix = "asio-ch";
return sourceId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
int.TryParse(sourceId[prefix.Length..], out var channel)
? channel
: null;
}
}
public sealed record MimirComplexContourPathChannelModel(
string PathId,
int SampleRate,
int ReferenceChannel,
int CandidateChannel,
IReadOnlyList<string> CaseIds,
IReadOnlyList<MimirComplexContourBandCorrection> Corrections,
IReadOnlyList<MimirComplexContourReflectionCorrection> ReflectionTaps,
int UsableBandCount,
double Reliability,
double DelaySpreadSamples)
{
public MimirDirectPathChannelModel ToRuntimeModel() =>
new(Corrections
.Where(correction => correction.Usable)
.Select(correction => new MimirDirectPathBandCorrection(
correction.CenterHz,
correction.DelayCorrectionSamples,
correction.PhaseCorrectionRadians,
correction.Weight * correction.Reliability))
.ToArray());
}
public sealed record MimirComplexContourBandCorrection(
double CenterHz,
double DelayCorrectionSamples,
double PhaseCorrectionRadians,
double Weight,
int ObservationCount,
double DelayStdDevSamples,
double Reliability,
bool Usable);
public sealed record MimirComplexContourReflectionCorrection(
double RelativeDelaySamples,
int ObservationCount,
double MeanRelativeDelaySamples);

View file

@ -0,0 +1,205 @@
using System.Buffers.Binary;
namespace Mimir.Runtime.Synchronization;
public sealed record MimirComplexContourRuntimeOptions(
string ProfileId = "canary-packet-trill",
double ScheduleStartSeconds = 0.5,
double SearchRadiusSeconds = 0.080,
double ReferenceSearchRadiusSeconds = 0.120);
public sealed class MimirComplexContourRuntimeAnalyzer(
MimirComplexContourRuntimeOptions? options = null,
MimirComplexContourChannelModelDocument? channelModel = null)
{
private const double MaxWindowSeconds = 1.25;
private readonly MimirComplexContourRuntimeOptions options = options ?? new();
private readonly MimirBioacousticContestantProfile profile = MimirBioacousticContestants.BuiltIn.FirstOrDefault(profile =>
string.Equals(profile.Id, (options ?? new MimirComplexContourRuntimeOptions()).ProfileId, StringComparison.OrdinalIgnoreCase))
?? MimirBioacousticContestants.CanaryPacketTrill;
private readonly MimirComplexContourChannelModelDocument? channelModel = channelModel;
private readonly Dictionary<int, MimirComplexContourMatchedFilterBank> banks = [];
public IReadOnlyList<MimirAudioSynchronizationReport> Analyze(
IEnumerable<MimirRollingStreamBuffer> buffers,
string referenceSourceId,
double runtimeSeconds,
IReadOnlyDictionary<string, MimirAudioSynchronizationState>? predictedStates = null,
IReadOnlySet<string>? candidateSourceIds = null)
{
var audioBuffers = buffers
.Where(buffer => buffer.Descriptor.Kind == MimirStreamKind.Audio)
.ToArray();
var reference = audioBuffers.FirstOrDefault(buffer =>
string.Equals(buffer.Descriptor.SourceId, referenceSourceId, StringComparison.Ordinal));
if (reference == null || reference.Latest?.AudioBlock == null)
{
return [];
}
var referenceSamples = ExtractFloatMonoWindow(reference, out var referenceBlock);
if (referenceSamples.Length == 0 || referenceBlock == null)
{
return [];
}
var reports = new List<MimirAudioSynchronizationReport>();
foreach (var buffer in audioBuffers)
{
if (ReferenceEquals(buffer, reference) ||
candidateSourceIds != null && !candidateSourceIds.Contains(buffer.Descriptor.SourceId))
{
continue;
}
var candidateSamples = ExtractFloatMonoWindow(buffer, out var candidateBlock);
if (candidateSamples.Length == 0 || candidateBlock == null)
{
continue;
}
if (candidateBlock.SampleRate != referenceBlock.SampleRate)
{
continue;
}
var compared = Math.Min(referenceSamples.Length, candidateSamples.Length);
if (compared < referenceBlock.SampleRate * profile.MotifDurationSeconds * 2.0)
{
continue;
}
var sampleRate = referenceBlock.SampleRate;
var referenceWindow = referenceSamples.AsSpan(^compared..).ToArray();
var candidateWindow = candidateSamples.AsSpan(^compared..).ToArray();
var captureDurationSeconds = compared / (double)sampleRate;
var windowStartSeconds = Math.Max(
0.0,
runtimeSeconds - options.ScheduleStartSeconds - captureDurationSeconds - options.ReferenceSearchRadiusSeconds);
var windowEndSeconds = Math.Max(0.0, runtimeSeconds - options.ScheduleStartSeconds) + options.ReferenceSearchRadiusSeconds;
var firstEvent = Math.Max(0, (long)Math.Floor((windowStartSeconds - MimirBioacousticContestants.FirstEventSeconds - profile.MotifDurationSeconds) / profile.EventSpacingSeconds) - 2);
var lastEvent = Math.Max(firstEvent, (long)Math.Ceiling((windowEndSeconds - MimirBioacousticContestants.FirstEventSeconds) / profile.EventSpacingSeconds) + 2);
var eventIndices = Enumerable.Range((int)firstEvent, (int)(lastEvent - firstEvent + 1))
.Select(index => (ulong)index)
.ToArray();
if (eventIndices.Length == 0)
{
continue;
}
var predictedDelay = predictedStates != null &&
predictedStates.TryGetValue(buffer.Descriptor.SourceId, out var state)
? state.SmoothedDelaySamples
: 0.0;
var sourceOffset = -windowStartSeconds * sampleRate;
var bank = BankFor(sampleRate);
var referenceHits = bank.AnalyzeEvents(
referenceWindow,
eventIndices,
sourceOffset,
Math.Max(8, (int)Math.Round(options.ReferenceSearchRadiusSeconds * sampleRate)));
var candidateHits = bank.AnalyzeEvents(
candidateWindow,
eventIndices,
sourceOffset + predictedDelay,
Math.Max(16, (int)Math.Round(options.SearchRadiusSeconds * sampleRate)));
var model = channelModel?
.PathFor(referenceSourceId, buffer.Descriptor.SourceId, sampleRate)?
.ToRuntimeModel();
var estimate = new MimirDirectPathTracker(
sampleRate,
new MimirDirectPathTrackerOptions(
PredictionGateSamples: Math.Max(16.0, options.SearchRadiusSeconds * sampleRate),
ChannelModel: model)).Update(referenceHits, candidateHits, predictedDelay);
if (estimate == null)
{
continue;
}
reports.Add(new MimirAudioSynchronizationReport(
referenceSourceId,
buffer.Descriptor.SourceId,
sampleRate,
(int)Math.Round(estimate.DelaySamples),
estimate.DelaySamples,
estimate.DelaySamples * 1000.0 / sampleRate,
estimate.Confidence,
estimate.BandObservations
.GroupBy(observation => Math.Round(observation.CenterHz / 250.0) * 250.0)
.Select(group => new MimirChirpletBandResponse(
group.Key,
group.Sum(observation => observation.Weight)))
.OrderBy(response => response.CenterHz)
.ToArray(),
Math.Min(reference.Latest?.TimestampNs ?? 0, buffer.Latest?.TimestampNs ?? 0),
compared,
reference.Latest?.Sequence ?? 0,
buffer.Latest?.Sequence ?? 0,
estimate.DirectHitCount,
estimate.Confidence,
"complex-contour"));
}
return reports;
}
private MimirComplexContourMatchedFilterBank BankFor(int sampleRate)
{
if (!banks.TryGetValue(sampleRate, out var bank))
{
bank = new MimirComplexContourMatchedFilterBank(new MimirBioacousticContestantRenderer(profile), sampleRate);
banks[sampleRate] = bank;
}
return bank;
}
private static float[] ExtractFloatMonoWindow(MimirRollingStreamBuffer buffer, out MimirAudioBlockDescriptor? latestBlock)
{
latestBlock = buffer.Latest?.AudioBlock;
if (latestBlock == null)
{
return [];
}
var maxSamples = Math.Max(1, (int)Math.Ceiling(latestBlock.SampleRate * MaxWindowSeconds));
var samples = new List<float>(maxSamples);
foreach (var sample in buffer.Snapshot()
.Where(sample => sample.AudioBlock is { SampleFormat: MimirAudioSampleFormat.Float32 } && !sample.Data.IsEmpty)
.Reverse())
{
var block = sample.AudioBlock!;
var mono = ExtractFirstFloatChannel(sample.Data.Span, block.Channels);
for (var index = mono.Length - 1; index >= 0 && samples.Count < maxSamples; index--)
{
samples.Add(mono[index]);
}
if (samples.Count >= maxSamples)
{
break;
}
}
samples.Reverse();
return samples.ToArray();
}
private static float[] ExtractFirstFloatChannel(ReadOnlySpan<byte> data, int channels)
{
if (channels <= 0)
{
return [];
}
var frames = data.Length / (sizeof(float) * channels);
var output = new float[frames];
for (var frame = 0; frame < frames; frame++)
{
var offset = frame * channels * sizeof(float);
output[frame] = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(data.Slice(offset, sizeof(float))));
}
return output;
}
}

View file

@ -221,6 +221,12 @@ public sealed class MimirAudioSyncConfig
public string CalibrationModelPath { get; set; } = "";
public string ComplexContourChannelModelPath { get; set; } = "";
public string BioacousticWitnessProfileId { get; set; } = "";
public bool EnableComplexContourRuntime { get; set; }
public MimirAudioSynchronizationSettings ToSettings(MimirAudioSynchronizationSettings fallback)
{
return new MimirAudioSynchronizationSettings
@ -238,6 +244,13 @@ public sealed class MimirAudioSyncConfig
CalibrationModelPath = string.IsNullOrWhiteSpace(CalibrationModelPath)
? fallback.CalibrationModelPath
: CalibrationModelPath.Trim(),
ComplexContourChannelModelPath = string.IsNullOrWhiteSpace(ComplexContourChannelModelPath)
? fallback.ComplexContourChannelModelPath
: ComplexContourChannelModelPath.Trim(),
BioacousticWitnessProfileId = string.IsNullOrWhiteSpace(BioacousticWitnessProfileId)
? fallback.BioacousticWitnessProfileId
: BioacousticWitnessProfileId.Trim(),
EnableComplexContourRuntime = EnableComplexContourRuntime || fallback.EnableComplexContourRuntime,
};
}
}

View file

@ -4,8 +4,10 @@ public sealed class MimirSynchronizationHub : IDisposable
{
private readonly List<IMimirStreamSource> sources = [];
private readonly MimirAudioSynchronizationAnalyzer audioSynchronization = new();
private readonly MimirComplexContourRuntimeAnalyzer? complexContourSynchronization;
private readonly MimirAudioSynchronizationStateTracker audioSynchronizationState = new();
private readonly Dictionary<string, MimirAudioSynchronizationReport> audioSynchronizationReports = new(StringComparer.Ordinal);
private readonly Dictionary<string, MimirAudioSynchronizationReport> complexContourReports = new(StringComparer.Ordinal);
private readonly MimirChirpBinCalibrationModel? chirpBinCalibrationModel;
private ulong ingestedSamples;
private int nextAudioSynchronizationCandidate;
@ -15,6 +17,11 @@ public sealed class MimirSynchronizationHub : IDisposable
Settings = settings;
Buffers = new MimirStreamBufferSet(settings.BufferDuration);
chirpBinCalibrationModel = TryLoadCalibrationModel(settings.Audio.CalibrationModelPath);
complexContourSynchronization = settings.Audio.EnableComplexContourRuntime
? new MimirComplexContourRuntimeAnalyzer(
new MimirComplexContourRuntimeOptions(settings.Audio.BioacousticWitnessProfileId),
TryLoadComplexContourChannelModel(settings.Audio.ComplexContourChannelModelPath))
: null;
foreach (var stream in settings.Streams.Where(stream => stream.Enabled))
{
Buffers.EnsureBuffer(stream);
@ -35,6 +42,9 @@ public sealed class MimirSynchronizationHub : IDisposable
public IReadOnlyList<MimirAudioSynchronizationReport> AudioSynchronizationReports =>
audioSynchronizationReports.Values.OrderBy(report => report.SourceId, StringComparer.Ordinal).ToArray();
public IReadOnlyList<MimirAudioSynchronizationReport> ComplexContourSynchronizationReports =>
complexContourReports.Values.OrderBy(report => report.SourceId, StringComparer.Ordinal).ToArray();
public IReadOnlyList<MimirAudioSynchronizationDecodeTrace> AudioSynchronizationDecodeTraces =>
audioSynchronization.LastDecodeTraces;
@ -44,6 +54,8 @@ public sealed class MimirSynchronizationHub : IDisposable
public MimirChirpBinCodebookPlan? ChirpBinEmissionPlan =>
chirpBinCalibrationModel?.EmissionPlan;
public bool ComplexContourRuntimeEnabled => complexContourSynchronization != null;
public void AddSource(IMimirStreamSource source)
{
ObjectDisposedException.ThrowIf(disposed, this);
@ -131,6 +143,53 @@ public sealed class MimirSynchronizationHub : IDisposable
return reports;
}
public IReadOnlyList<MimirAudioSynchronizationReport> AnalyzeComplexContourSynchronizationStep(
string referenceSourceId,
double runtimeSeconds,
int maxCandidates = 1)
{
ObjectDisposedException.ThrowIf(disposed, this);
if (complexContourSynchronization == null)
{
return [];
}
var candidates = Buffers.Buffers
.Where(buffer =>
buffer.Descriptor.Kind == MimirStreamKind.Audio &&
!string.Equals(buffer.Descriptor.SourceId, referenceSourceId, StringComparison.Ordinal) &&
buffer.Latest?.AudioBlock is { SampleFormat: MimirAudioSampleFormat.Float32 })
.OrderBy(buffer => buffer.Descriptor.SourceId, StringComparer.Ordinal)
.Select(buffer => buffer.Descriptor.SourceId)
.ToArray();
if (candidates.Length == 0)
{
return [];
}
var selected = new HashSet<string>(StringComparer.Ordinal);
for (var count = 0; count < Math.Min(maxCandidates, candidates.Length); count++)
{
selected.Add(candidates[nextAudioSynchronizationCandidate % candidates.Length]);
nextAudioSynchronizationCandidate++;
}
var predicted = audioSynchronizationState.States.ToDictionary(state => state.SourceId, StringComparer.Ordinal);
var reports = complexContourSynchronization.Analyze(
Buffers.Buffers,
referenceSourceId,
runtimeSeconds,
predicted,
selected);
StoreComplexContourReports(reports, selected);
if (reports.Count > 0)
{
audioSynchronizationState.Update(reports);
}
return reports;
}
private bool disposed;
private static MimirChirpBinCalibrationModel? TryLoadCalibrationModel(string path)
@ -143,6 +202,16 @@ public sealed class MimirSynchronizationHub : IDisposable
return MimirChirpBinCalibrationModel.Load(path);
}
private static MimirComplexContourChannelModelDocument? TryLoadComplexContourChannelModel(string path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
{
return null;
}
return MimirComplexContourChannelModelDocument.Load(path);
}
private void StoreAudioSynchronizationReports(
IReadOnlyList<MimirAudioSynchronizationReport> reports,
IEnumerable<string> analyzedCandidateIds)
@ -172,6 +241,26 @@ public sealed class MimirSynchronizationHub : IDisposable
}
}
private void StoreComplexContourReports(
IReadOnlyList<MimirAudioSynchronizationReport> reports,
IEnumerable<string> analyzedCandidateIds)
{
var reportIds = new HashSet<string>(reports.Select(report => report.SourceId), StringComparer.Ordinal);
foreach (var sourceId in analyzedCandidateIds)
{
if (!reportIds.Contains(sourceId))
{
complexContourReports.Remove(sourceId);
}
}
foreach (var report in reports)
{
complexContourReports[report.SourceId] = report;
audioSynchronizationReports[report.SourceId] = report;
}
}
public void Dispose()
{
if (disposed)

View file

@ -68,6 +68,12 @@ public sealed class MimirAudioSynchronizationSettings
public string CalibrationModelPath { get; init; } = "";
public string ComplexContourChannelModelPath { get; init; } = "";
public string BioacousticWitnessProfileId { get; init; } = MimirBioacousticContestants.CurrentBirdcall.Id;
public bool EnableComplexContourRuntime { get; init; }
public static MimirAudioSynchronizationSettings FromEnvironment()
{
return new MimirAudioSynchronizationSettings().WithEnvironmentOverrides();
@ -82,6 +88,9 @@ public sealed class MimirAudioSynchronizationSettings
CalibrationGain = ReadCalibrationGain(CalibrationGain),
WatermarkGain = ReadWatermarkGain(WatermarkGain),
CalibrationModelPath = ReadCalibrationModelPath(CalibrationModelPath),
ComplexContourChannelModelPath = ReadComplexContourChannelModelPath(ComplexContourChannelModelPath),
BioacousticWitnessProfileId = ReadBioacousticWitnessProfileId(BioacousticWitnessProfileId),
EnableComplexContourRuntime = ReadEnableComplexContourRuntime(EnableComplexContourRuntime),
};
}
@ -128,6 +137,26 @@ public sealed class MimirAudioSynchronizationSettings
var path = Environment.GetEnvironmentVariable("MIMIR_CHIRP_BIN_CALIBRATION");
return string.IsNullOrWhiteSpace(path) ? fallback : path.Trim();
}
private static string ReadComplexContourChannelModelPath(string fallback)
{
var path = Environment.GetEnvironmentVariable("MIMIR_COMPLEX_CONTOUR_CHANNEL_MODEL");
return string.IsNullOrWhiteSpace(path) ? fallback : path.Trim();
}
private static string ReadBioacousticWitnessProfileId(string fallback)
{
var profile = Environment.GetEnvironmentVariable("MIMIR_BIOACOUSTIC_PROFILE");
return string.IsNullOrWhiteSpace(profile) ? fallback : profile.Trim();
}
private static bool ReadEnableComplexContourRuntime(bool fallback)
{
var raw = Environment.GetEnvironmentVariable("MIMIR_COMPLEX_CONTOUR_RUNTIME");
return string.IsNullOrWhiteSpace(raw)
? fallback
: raw is "1" or "true" or "TRUE" or "yes" or "YES";
}
}
public enum MimirAudioSyncMode