Wire complex contour sync into runtime
This commit is contained in:
parent
f8c16c9a69
commit
470efb0003
15 changed files with 614 additions and 7 deletions
|
|
@ -72,6 +72,13 @@ if (args.Any(arg => string.Equals(arg, "--complex-contour-tracker-self-test", St
|
|||
ParseDoubleOption(args, "--reflection-delay-samples", 29.0));
|
||||
}
|
||||
|
||||
if (args.Any(arg => string.Equals(arg, "--complex-contour-runtime-self-test", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return RunComplexContourRuntimeSelfTest(
|
||||
ParseIntOption(args, "--sample-rate", 192_000),
|
||||
ParseDoubleOption(args, "--delay-samples", 693.5));
|
||||
}
|
||||
|
||||
if (args.Any(arg => string.Equals(arg, "--perfect-machine-profile-smoke", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return RunPerfectMachineProfileSmoke();
|
||||
|
|
@ -1154,6 +1161,58 @@ static int RunComplexContourTrackerSelfTest(int sampleRate, double delaySamples,
|
|||
: 1;
|
||||
}
|
||||
|
||||
static int RunComplexContourRuntimeSelfTest(int sampleRate, double delaySamples)
|
||||
{
|
||||
var renderer = new MimirBioacousticContestantRenderer(MimirBioacousticContestants.CanaryPacketTrill);
|
||||
const double runtimeSeconds = 1.75;
|
||||
var reference = renderer.RenderSequenceMonoFloat(runtimeSeconds - 0.5, sampleRate);
|
||||
var candidate = ApplyFractionalDelay(reference, delaySamples);
|
||||
var referenceBuffer = BuildSyntheticAudioBuffer("asio-ch2", sampleRate, reference);
|
||||
var candidateBuffer = BuildSyntheticAudioBuffer("asio-ch1", sampleRate, candidate);
|
||||
var analyzer = new MimirComplexContourRuntimeAnalyzer(
|
||||
new MimirComplexContourRuntimeOptions(
|
||||
ProfileId: MimirBioacousticContestants.CanaryPacketTrill.Id,
|
||||
ScheduleStartSeconds: 0.5,
|
||||
SearchRadiusSeconds: 0.020,
|
||||
ReferenceSearchRadiusSeconds: 0.020));
|
||||
var report = analyzer.Analyze([referenceBuffer, candidateBuffer], "asio-ch2", runtimeSeconds).FirstOrDefault();
|
||||
if (report == null)
|
||||
{
|
||||
Console.WriteLine("complex-contour-runtime-self-test status=no-report");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var errorUs = Math.Abs(report.FractionalDelaySamples - delaySamples) * 1_000_000.0 / sampleRate;
|
||||
Console.WriteLine(
|
||||
$"complex-contour-runtime-self-test delaySamples={report.FractionalDelaySamples:0.000000} expected={delaySamples:0.000000} errorUs={errorUs:0.000} confidence={report.Confidence:0.000} directHits={report.TimelineMatchedEvents}");
|
||||
return errorUs < 20.0 && report.TimelineMatchedEvents >= 8 ? 0 : 1;
|
||||
}
|
||||
|
||||
static MimirRollingStreamBuffer BuildSyntheticAudioBuffer(string sourceId, int sampleRate, float[] samples)
|
||||
{
|
||||
var descriptor = new MimirStreamDescriptor(sourceId, MimirStreamKind.Audio, MimirStreamOrigin.LocalDevice);
|
||||
var buffer = new MimirRollingStreamBuffer(descriptor, TimeSpan.FromSeconds(5));
|
||||
var bytes = new byte[samples.Length * sizeof(float)];
|
||||
Buffer.BlockCopy(samples, 0, bytes, 0, bytes.Length);
|
||||
buffer.Append(new MimirStreamSample(
|
||||
sourceId,
|
||||
MimirStreamKind.Audio,
|
||||
MimirStreamOrigin.LocalDevice,
|
||||
TimestampNs: (long)Math.Round(samples.Length * 1_000_000_000.0 / sampleRate),
|
||||
ArrivalNs: (long)Math.Round(samples.Length * 1_000_000_000.0 / sampleRate),
|
||||
Sequence: 1,
|
||||
PayloadHandle: 0,
|
||||
ByteLength: bytes.Length,
|
||||
Data: bytes,
|
||||
AudioBlock: new MimirAudioBlockDescriptor(
|
||||
sampleRate,
|
||||
1,
|
||||
MimirAudioSampleFormat.Float32,
|
||||
samples.Length,
|
||||
0)));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
static int RunPerfectMachineProfileSmoke()
|
||||
{
|
||||
var profiles = MimirPerfectMachineProfiles.All;
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
private readonly float audioSyncUpdateIntervalSeconds;
|
||||
private readonly float calibrationGain;
|
||||
private readonly float watermarkGain;
|
||||
private readonly MimirBioacousticContestantRenderer? complexContourWitness;
|
||||
private int lastPollCount;
|
||||
private float runtimeSeconds;
|
||||
private float nextAudioSyncSeconds;
|
||||
|
|
@ -61,6 +62,12 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
audioSyncUpdateIntervalSeconds = ParseAudioSyncIntervalSeconds();
|
||||
calibrationGain = settings.Audio.CalibrationGain;
|
||||
watermarkGain = settings.Audio.WatermarkGain;
|
||||
complexContourWitness = settings.Audio.EnableComplexContourRuntime
|
||||
? new MimirBioacousticContestantRenderer(
|
||||
MimirBioacousticContestants.BuiltIn.FirstOrDefault(profile =>
|
||||
string.Equals(profile.Id, settings.Audio.BioacousticWitnessProfileId, StringComparison.OrdinalIgnoreCase))
|
||||
?? MimirBioacousticContestants.CanaryPacketTrill)
|
||||
: null;
|
||||
nextAudioSyncSeconds = audioSyncUpdateIntervalSeconds;
|
||||
nextTelemetrySeconds = telemetryIntervalSeconds;
|
||||
foreach (var source in streamSources)
|
||||
|
|
@ -245,7 +252,7 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
return $"{audioSyncSettings.ReferenceSourceId} {DescribeAudioSyncMode()} bioacoustic timeline {MimirBioacousticTimeline.SegmentSeconds:0.00}s segments emitted to {emittedUntilSeconds:0.00}s passiveConfidence={lastPassiveSynchronizationConfidence:0.000}";
|
||||
}
|
||||
|
||||
private static string RenderCalibrationBatchPcm16Base64(
|
||||
private string RenderCalibrationBatchPcm16Base64(
|
||||
ulong firstSegment,
|
||||
int segmentCount,
|
||||
MimirBioacousticSpeaker speaker,
|
||||
|
|
@ -257,10 +264,16 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
peak = 0.0f;
|
||||
for (var segment = 0; segment < segmentCount; segment++)
|
||||
{
|
||||
var samples = MimirBioacousticTimeline.Default.RenderSegmentMonoFloat(
|
||||
firstSegment + (ulong)segment,
|
||||
MimirBioacousticTimeline.SampleRate,
|
||||
speaker);
|
||||
var samples = complexContourWitness == null
|
||||
? MimirBioacousticTimeline.Default.RenderSegmentMonoFloat(
|
||||
firstSegment + (ulong)segment,
|
||||
MimirBioacousticTimeline.SampleRate,
|
||||
speaker)
|
||||
: complexContourWitness.RenderSegmentMonoFloat(
|
||||
firstSegment + (ulong)segment,
|
||||
MimirBioacousticTimeline.SegmentSeconds,
|
||||
MimirBioacousticTimeline.SampleRate,
|
||||
speaker);
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
{
|
||||
peak = Math.Max(peak, Math.Abs(samples[index]));
|
||||
|
|
@ -287,6 +300,10 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
synchronization.AnalyzeAudioSynchronizationStep(audioSyncSettings.ReferenceSourceId, audioSyncSettings.Mode);
|
||||
if (synchronization.ComplexContourRuntimeEnabled)
|
||||
{
|
||||
synchronization.AnalyzeComplexContourSynchronizationStep(audioSyncSettings.ReferenceSourceId, runtimeSeconds);
|
||||
}
|
||||
stopwatch.Stop();
|
||||
lastAudioSyncAnalysisMilliseconds = stopwatch.Elapsed.TotalMilliseconds;
|
||||
lastAudioSynchronizationReports = synchronization.AudioSynchronizationReports;
|
||||
|
|
@ -313,6 +330,12 @@ public sealed class MimirRuntime : IAquariumRuntime
|
|||
$"mimir-sync-report {report.ReferenceSourceId}->{report.SourceId} evidence={report.EvidenceKind} delaySamples={report.FractionalDelaySamples:0.000000} delayUs={report.DelayMicroseconds:0.000} delayMs={report.DelayMilliseconds:0.000} confidence={report.Confidence:0.000} timelineEvents={report.TimelineMatchedEvents} timelineConfidence={report.TimelineConfidence:0.000}");
|
||||
}
|
||||
|
||||
foreach (var report in synchronization.ComplexContourSynchronizationReports.OrderBy(report => report.SourceId, StringComparer.Ordinal))
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"mimir-complex-contour-report {report.ReferenceSourceId}->{report.SourceId} delaySamples={report.FractionalDelaySamples:0.000000} delayUs={report.DelayMicroseconds:0.000} confidence={report.Confidence:0.000} directHits={report.TimelineMatchedEvents}");
|
||||
}
|
||||
|
||||
foreach (var state in states)
|
||||
{
|
||||
Console.WriteLine(
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in a new issue