diff --git a/docs/audio-field.md b/docs/audio-field.md index 608fc8a..fde6874 100644 --- a/docs/audio-field.md +++ b/docs/audio-field.md @@ -90,6 +90,16 @@ not the active runtime sound. The raw profile is kept even when a timing report is rejected, because a failed sync window can still teach us which bands survived the speaker/room/mic path. +`MimirBioacousticProbeScheduler` is now the runtime-side cadence owner for that +feedback loop: it consumes smoothed sync states plus per-band frequency response +residuals, schedules a targeted probe only when confidence pressure and duty +budget allow it, and publishes aggregate/per-source sync and frequency-response +confidence telemetry. `MimirSynchronizationHub.UpdateBioacousticProbeSchedule` +is the live hub surface; `MimirRuntime` prints +`mimir-bioacoustic-probe-schedule` and `mimir-bioacoustic-probe-source` lines so +operators can watch confidence climb as probes are spent. The scheduler owns +when to spend active sound. It does not own the output device: Starfire Realtek +still must be selected explicitly by the eventual live renderer. The receiver must consume persisted models to weight reliable symbols, downweight dead bands, apply phase-coherence weighting, apply first-order group-delay correction, and search joint global delay/frequency-shift hypotheses diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 71ee1b3..db29fef 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -136,6 +136,12 @@ a named invariant that the native runtime cannot protect yet. production-shaped Focusrite path: a native in-process ASIO callback source feeds sample-bearing 192 kHz Float32 blocks directly into `Mimir.Runtime` rolling buffers on one interface clock domain. +- `MimirBioacousticProbeScheduler` closes the first active-probe control loop: + sync confidence and per-band frequency-response confidence decide whether a + targeted probe should be emitted, and `MimirRuntime` publishes live telemetry + for aggregate confidence, deltas, source probe counts, and weak-band pressure. + The scheduler is output-device neutral; a later renderer must explicitly + target Starfire Realtek for physical chirp emission in the current routing. - `src/Mimir.BufferSmoke` loads the runtime config, polls the synchronization hub, and prints the actual rolling buffers. Use `--require-samples` when an empty declared sensor buffer should fail the run. Use `--bioacoustic-self-test` diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 1f7b39b..edfe8dc 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -323,6 +323,17 @@ then about 9.9 kHz weak response, 3.6 kHz phase instability, and 910 Hz magnitude residual. This is the intended first physical strategy: improve shotgun/cardioid confidence at 192 kHz before asking every connected mic to help solve the room field. +`MimirBioacousticProbeScheduler` now owns the first closed-loop cadence layer +above that planner. It reads smoothed sync states plus derived per-band +frequency-response residuals from `MimirSynchronizationHub`, backs probe cadence +off as aggregate sync/frequency confidence rises, emits targeted probe plans +only when the confidence/duty budget says to spend sound, and exposes +`mimir-bioacoustic-probe-schedule` plus per-source telemetry in `MimirRuntime`. +`Mimir.BufferSmoke --bioacoustic-probe-scheduler-smoke` proves the visible +climb: simulated probe feedback raises sync confidence from 0.360 to 0.920 and +frequency-response confidence from 0.558 to 0.955 over four scheduled probes. +The scheduler is not the output-device authority; in the current physical +routing the eventual live renderer must explicitly select Starfire Realtek. The first live run preserves two artifacts: `artifacts/asio/targeted-bioacoustic-live/20260601-030836` at playback gain 1.0 and `artifacts/asio/targeted-bioacoustic-live/20260601-030857` at gain diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index 37d5ce4..211b26a 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -85,6 +85,11 @@ if (args.Any(arg => string.Equals(arg, "--targeted-bioacoustic-probe-smoke", Str return RunTargetedBioacousticProbeSmoke(); } +if (args.Any(arg => string.Equals(arg, "--bioacoustic-probe-scheduler-smoke", StringComparison.OrdinalIgnoreCase))) +{ + return RunBioacousticProbeSchedulerSmoke(); +} + if (args.Any(arg => string.Equals(arg, "--targeted-bioacoustic-probe-live", StringComparison.OrdinalIgnoreCase))) { return RunTargetedBioacousticProbeLive( @@ -3432,6 +3437,74 @@ static int RunTargetedBioacousticProbeSmoke() : 1; } +static int RunBioacousticProbeSchedulerSmoke() +{ + var scheduler = new MimirBioacousticProbeScheduler(new MimirBioacousticProbeSchedulerOptions( + TargetSyncConfidence: 0.88, + TargetFrequencyResponseConfidence: 0.82, + MinimumIntervalSeconds: 0.25, + MaximumIntervalSeconds: 1.25, + MaxProbeBands: 4)); + var residuals = ScarlettProfessionalMicProbeResiduals(); + var pathologies = ScarlettProfessionalMicPathologies(); + var sources = new[] { "asio-ch0-shotgun", "asio-ch1-cardioid" }; + var timestampNs = 10_000_000_000L; + var syncConfidence = 0.38; + var emitted = 0; + MimirScheduledBioacousticProbeFrame? firstEmission = null; + MimirScheduledBioacousticProbeFrame? previous = null; + for (var step = 0; step < 12; step++) + { + var states = sources + .Select((sourceId, index) => NewSyncState( + sourceId, + index == 0 ? 42.0 - step * 1.5 : -25.0 + step, + Math.Clamp(syncConfidence - index * 0.04, 0.0, 1.0))) + .ToArray(); + var frame = scheduler.Update(states, residuals, timestampNs, sources, pathologies); + Console.WriteLine( + $"bioacoustic-probe-scheduler-step step={step} emit={frame.ShouldEmit} reason={frame.Reason} " + + $"sync={frame.AggregateSyncConfidence:0.000} freq={frame.AggregateFrequencyResponseConfidence:0.000} combined={frame.AggregateConfidence:0.000} " + + $"dSync={frame.SyncConfidenceDelta:0.000} dFreq={frame.FrequencyResponseConfidenceDelta:0.000} interval={frame.ScheduledIntervalSeconds:0.000} " + + $"bands={frame.ProbePlan.Bands.Count} probes={string.Join(",", frame.Sources.Select(source => $"{source.SourceId}:{source.ProbeCount}/{source.WeakBandCount}@{source.LowestConfidenceBandHz:0}Hz"))}"); + + if (frame.ShouldEmit) + { + emitted++; + firstEmission ??= frame; + residuals = ImproveResidualsFromProbe(residuals, frame.ProbePlan); + syncConfidence = Math.Min(0.94, syncConfidence + 0.13); + } + else + { + syncConfidence = Math.Min(0.94, syncConfidence + 0.025); + } + + previous = frame; + timestampNs += 375_000_000L; + } + + if (firstEmission == null || previous == null) + { + Console.Error.WriteLine("bioacoustic probe scheduler failed: no frames emitted"); + return 1; + } + + Console.WriteLine( + $"bioacoustic-probe-scheduler-smoke emitted={emitted} firstReason={firstEmission.Reason} " + + $"startSync={firstEmission.AggregateSyncConfidence:0.000} endSync={previous.AggregateSyncConfidence:0.000} " + + $"startFreq={firstEmission.AggregateFrequencyResponseConfidence:0.000} endFreq={previous.AggregateFrequencyResponseConfidence:0.000} " + + $"lastPlanBands={previous.ProbePlan.Bands.Count} sourceProbes={string.Join(",", previous.Sources.Select(source => $"{source.SourceId}:{source.ProbeCount}"))}"); + + return emitted >= 3 && + firstEmission.ProbePlan.Bands.Count > 0 && + previous.AggregateSyncConfidence > firstEmission.AggregateSyncConfidence + 0.25 && + previous.AggregateFrequencyResponseConfidence > firstEmission.AggregateFrequencyResponseConfidence + 0.10 && + previous.Sources.All(source => source.ProbeCount == emitted) + ? 0 + : 1; +} + static int RunTargetedBioacousticProbeLive( string probePath, string outputDirectory, @@ -3818,6 +3891,40 @@ static MimirAudioCalibrationSourcePathology[] ScarlettProfessionalMicPathologies LowHighTiltDb: 4.0), ]; +static MimirAudioCalibrationBandResidual[] ImproveResidualsFromProbe( + IReadOnlyList residuals, + MimirTargetedBioacousticProbePlan plan) +{ + return residuals + .Select(residual => + { + var nearest = plan.Bands + .OrderBy(band => Math.Abs(Math.Log(Math.Max(1.0, residual.CenterHz) / Math.Max(1.0, band.CenterHz)))) + .FirstOrDefault(); + if (nearest == null) + { + return residual; + } + + var distance = Math.Abs(Math.Log(Math.Max(1.0, residual.CenterHz) / Math.Max(1.0, nearest.CenterHz))); + var influence = Math.Clamp(1.0 - distance / 0.16, 0.0, 1.0); + if (influence <= 0.0) + { + return residual; + } + + return residual with + { + Confidence = Math.Clamp(residual.Confidence + 0.20 * influence, 0.0, 0.96), + ResidualDb = residual.ResidualDb * (1.0 - 0.38 * influence), + DelayResidualMicroseconds = residual.DelayResidualMicroseconds * (1.0 - 0.34 * influence), + PhaseResidualRadians = residual.PhaseResidualRadians * (1.0 - 0.35 * influence), + ResponseEnergy = Math.Clamp(residual.ResponseEnergy + 0.10 * influence, 0.0, 1.0), + }; + }) + .ToArray(); +} + static float[] RenderTargetedProbePlan(MimirTargetedBioacousticProbePlan plan) { const double preRollSeconds = 0.08; diff --git a/src/Mimir.Runtime/MimirRuntime.cs b/src/Mimir.Runtime/MimirRuntime.cs index 35ac2b0..b1522c7 100644 --- a/src/Mimir.Runtime/MimirRuntime.cs +++ b/src/Mimir.Runtime/MimirRuntime.cs @@ -83,6 +83,7 @@ public sealed class MimirRuntime : IAquariumRuntime, IAquariumRuntimeServicesRec private IReadOnlyList lastAudioSynchronizationReports = []; private IReadOnlyList lastAudioSpectra = []; private MimirObsStemPublicationSnapshot lastObsStemPublication = MimirObsStemPublicationSnapshot.Empty; + private MimirScheduledBioacousticProbeFrame? lastBioacousticProbeSchedule; private long spectrumHistorySequence; private long audioActuatorFrameSequence; private bool audioActuatorProgramQueued; @@ -1315,6 +1316,8 @@ public sealed class MimirRuntime : IAquariumRuntime, IAquariumRuntimeServicesRec lastAudioSyncAnalysisMilliseconds = stopwatch.Elapsed.TotalMilliseconds; lastAudioSynchronizationReports = synchronization.AudioSynchronizationReports; UpdatePassiveSynchronizationConfidence(lastAudioSynchronizationReports); + lastBioacousticProbeSchedule = synchronization.UpdateBioacousticProbeSchedule( + (long)Math.Round(runtimeSeconds * 1_000_000_000.0)); lastAudioActuatorFrame = audioActuatorBank.Update( synchronization.AudioSynchronizationStates, audioSyncUpdateIntervalSeconds); @@ -1574,6 +1577,17 @@ public sealed class MimirRuntime : IAquariumRuntime, IAquariumRuntimeServicesRec $"mimir-sync-state {state.ReferenceSourceId}->{state.SourceId} delaySamples={state.SmoothedDelaySamples:0.000000} delayUs={state.DelayMicroseconds:0.000} delayMs={state.DelayMilliseconds:0.000} sroPpm={state.SamplingRateOffsetPpm:0.000} confidence={state.Confidence:0.000}"); } + if (lastBioacousticProbeSchedule is { } probe) + { + Console.WriteLine( + $"mimir-bioacoustic-probe-schedule emit={probe.ShouldEmit} reason={probe.Reason} sync={probe.AggregateSyncConfidence:0.000} freq={probe.AggregateFrequencyResponseConfidence:0.000} combined={probe.AggregateConfidence:0.000} dSync={probe.SyncConfidenceDelta:0.000} dFreq={probe.FrequencyResponseConfidenceDelta:0.000} interval={probe.ScheduledIntervalSeconds:0.000} bands={probe.ProbePlan.Bands.Count}"); + foreach (var source in probe.Sources.OrderBy(source => source.SourceId, StringComparer.Ordinal)) + { + Console.WriteLine( + $"mimir-bioacoustic-probe-source source={source.SourceId} sync={source.SyncConfidence:0.000} freq={source.FrequencyResponseConfidence:0.000} combined={source.AggregateConfidence:0.000} probes={source.ProbeCount} weakBands={source.WeakBandCount} weakestHz={source.LowestConfidenceBandHz:0}"); + } + } + if (lastAudioActuatorFrame.Commands.Count > 0) { Console.WriteLine( diff --git a/src/Mimir.Runtime/Synchronization/MimirBioacousticProbeScheduler.cs b/src/Mimir.Runtime/Synchronization/MimirBioacousticProbeScheduler.cs new file mode 100644 index 0000000..d8a1ada --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirBioacousticProbeScheduler.cs @@ -0,0 +1,246 @@ +namespace Mimir.Runtime.Synchronization; + +public enum MimirBioacousticProbeScheduleReason +{ + None, + SyncConfidenceLow, + FrequencyResponseConfidenceLow, + PeriodicRecheck +} + +public sealed record MimirBioacousticProbeSchedulerOptions( + int SampleRate = 192_000, + double TargetSyncConfidence = 0.88, + double TargetFrequencyResponseConfidence = 0.82, + double RecheckSyncConfidence = 0.96, + double RecheckFrequencyResponseConfidence = 0.94, + double MinimumIntervalSeconds = 0.65, + double MaximumIntervalSeconds = 8.0, + int MaxProbeBands = 6); + +public sealed record MimirBioacousticProbeConfidenceState( + string SourceId, + double SyncConfidence, + double FrequencyResponseConfidence, + double AggregateConfidence, + int WeakBandCount, + double LowestConfidenceBandHz, + int ProbeCount, + long LastProbeAtNs, + long NextEligibleProbeAtNs); + +public sealed record MimirScheduledBioacousticProbeFrame( + long TimestampNs, + bool ShouldEmit, + MimirBioacousticProbeScheduleReason Reason, + double AggregateSyncConfidence, + double AggregateFrequencyResponseConfidence, + double AggregateConfidence, + double SyncConfidenceDelta, + double FrequencyResponseConfidenceDelta, + double ScheduledIntervalSeconds, + double SecondsUntilEligible, + IReadOnlyList Sources, + MimirTargetedBioacousticProbePlan ProbePlan, + string Notes); + +public sealed class MimirBioacousticProbeScheduler( + MimirBioacousticProbeSchedulerOptions? options = null, + MimirTargetedBioacousticProbePlanner? planner = null) +{ + private readonly MimirBioacousticProbeSchedulerOptions options = options ?? new(); + private readonly MimirTargetedBioacousticProbePlanner planner = planner ?? new(new MimirTargetedBioacousticProbeOptions( + SampleRate: options?.SampleRate ?? 192_000, + MaxProbeBands: options?.MaxProbeBands ?? 6, + TargetConfidence: options?.TargetFrequencyResponseConfidence ?? 0.82)); + private readonly Dictionary probeCounts = new(StringComparer.Ordinal); + private long lastProbeAtNs = long.MinValue; + private double previousSyncConfidence; + private double previousFrequencyResponseConfidence; + private bool hasPrevious; + + public MimirScheduledBioacousticProbeFrame Update( + IReadOnlyList synchronizationStates, + IReadOnlyList residuals, + long timestampNs, + IReadOnlyList? preferredSourceIds = null, + IReadOnlyList? sourcePathologies = null) + { + var sourceIds = ResolveSourceIds(synchronizationStates, residuals, preferredSourceIds); + var syncBySource = synchronizationStates + .GroupBy(state => state.SourceId, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => Math.Clamp(group.Max(state => state.Confidence), 0.0, 1.0), StringComparer.Ordinal); + var residualsBySource = residuals + .GroupBy(residual => residual.SourceId, StringComparer.Ordinal) + .ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal); + var syncConfidence = AverageOrZero(sourceIds.Select(sourceId => syncBySource.TryGetValue(sourceId, out var confidence) ? confidence : 0.0)); + var frequencyConfidence = AverageOrZero(sourceIds.Select(sourceId => residualsBySource.TryGetValue(sourceId, out var sourceResiduals) + ? FrequencyResponseConfidence(sourceResiduals) + : 0.0)); + var pressure = Math.Max( + Math.Max(0.0, options.TargetSyncConfidence - syncConfidence) / Math.Max(0.001, options.TargetSyncConfidence), + Math.Max(0.0, options.TargetFrequencyResponseConfidence - frequencyConfidence) / Math.Max(0.001, options.TargetFrequencyResponseConfidence)); + var scheduledInterval = options.MaximumIntervalSeconds - + (options.MaximumIntervalSeconds - options.MinimumIntervalSeconds) * Math.Clamp(pressure, 0.0, 1.0); + var nextEligibleAtNs = lastProbeAtNs == long.MinValue + ? timestampNs + : lastProbeAtNs + SecondsToNanoseconds(scheduledInterval); + var secondsUntilEligible = Math.Max(0.0, (nextEligibleAtNs - timestampNs) / 1_000_000_000.0); + var reason = ChooseReason(syncConfidence, frequencyConfidence, pressure, secondsUntilEligible); + var shouldEmit = reason != MimirBioacousticProbeScheduleReason.None && secondsUntilEligible <= 0.0; + var plan = shouldEmit + ? planner.Plan(residuals, sourceIds, sourcePathologies) + : EmptyPlan(sourceIds); + if (shouldEmit && plan.Bands.Count > 0) + { + lastProbeAtNs = timestampNs; + foreach (var sourceId in sourceIds) + { + probeCounts[sourceId] = probeCounts.GetValueOrDefault(sourceId) + 1; + } + + nextEligibleAtNs = timestampNs + SecondsToNanoseconds(scheduledInterval); + secondsUntilEligible = scheduledInterval; + } + else if (shouldEmit) + { + reason = MimirBioacousticProbeScheduleReason.None; + shouldEmit = false; + } + + var sources = sourceIds + .Select(sourceId => BuildSourceState( + sourceId, + syncBySource.TryGetValue(sourceId, out var sourceSync) ? sourceSync : 0.0, + residualsBySource.TryGetValue(sourceId, out var sourceResiduals) ? sourceResiduals : [], + nextEligibleAtNs)) + .ToArray(); + var syncDelta = hasPrevious ? syncConfidence - previousSyncConfidence : 0.0; + var frequencyDelta = hasPrevious ? frequencyConfidence - previousFrequencyResponseConfidence : 0.0; + previousSyncConfidence = syncConfidence; + previousFrequencyResponseConfidence = frequencyConfidence; + hasPrevious = true; + + return new MimirScheduledBioacousticProbeFrame( + timestampNs, + shouldEmit, + reason, + syncConfidence, + frequencyConfidence, + (syncConfidence + frequencyConfidence) * 0.5, + syncDelta, + frequencyDelta, + scheduledInterval, + secondsUntilEligible, + sources, + plan, + "Probe cadence is derived from runtime confidence. The scheduler owns when to spend active sound; render/output paths own how the scheduled probe is emitted."); + } + + private MimirBioacousticProbeScheduleReason ChooseReason( + double syncConfidence, + double frequencyConfidence, + double pressure, + double secondsUntilEligible) + { + if (syncConfidence < options.TargetSyncConfidence) + { + return MimirBioacousticProbeScheduleReason.SyncConfidenceLow; + } + + if (frequencyConfidence < options.TargetFrequencyResponseConfidence) + { + return MimirBioacousticProbeScheduleReason.FrequencyResponseConfidenceLow; + } + + if (secondsUntilEligible <= 0.0 && + pressure <= 0.0 && + (syncConfidence < options.RecheckSyncConfidence || + frequencyConfidence < options.RecheckFrequencyResponseConfidence)) + { + return MimirBioacousticProbeScheduleReason.PeriodicRecheck; + } + + return MimirBioacousticProbeScheduleReason.None; + } + + private MimirBioacousticProbeConfidenceState BuildSourceState( + string sourceId, + double syncConfidence, + IReadOnlyList residuals, + long nextEligibleAtNs) + { + var frequencyConfidence = residuals.Count == 0 ? 0.0 : FrequencyResponseConfidence(residuals); + var weakBands = residuals.Count(residual => BandConfidence(residual) < options.TargetFrequencyResponseConfidence); + var weakest = residuals + .OrderBy(BandConfidence) + .ThenBy(static residual => residual.CenterHz) + .FirstOrDefault(); + return new MimirBioacousticProbeConfidenceState( + sourceId, + syncConfidence, + frequencyConfidence, + (syncConfidence + frequencyConfidence) * 0.5, + weakBands, + weakest?.CenterHz ?? 0.0, + probeCounts.GetValueOrDefault(sourceId), + lastProbeAtNs == long.MinValue ? 0L : lastProbeAtNs, + nextEligibleAtNs); + } + + private static IReadOnlyList ResolveSourceIds( + IReadOnlyList synchronizationStates, + IReadOnlyList residuals, + IReadOnlyList? preferredSourceIds) + { + if (preferredSourceIds is { Count: > 0 }) + { + return preferredSourceIds.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + } + + return synchronizationStates.Select(state => state.SourceId) + .Concat(residuals.Select(residual => residual.SourceId)) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + } + + private MimirTargetedBioacousticProbePlan EmptyPlan(IReadOnlyList sourceIds) => + new( + "targeted-bioacoustic-probe.v1", + options.SampleRate, + sourceIds, + [], + 0.0, + "No active probe is scheduled for this frame."); + + private double FrequencyResponseConfidence(IReadOnlyList residuals) => + AverageOrZero(residuals.Select(BandConfidence)); + + private double BandConfidence(MimirAudioCalibrationBandResidual residual) + { + var magnitudeFitness = 1.0 - Math.Clamp(Math.Max(0.0, Math.Abs(residual.ResidualDb) - 1.5) / 18.0, 0.0, 1.0); + var phaseFitness = 1.0 - Math.Clamp(Math.Max(0.0, Math.Abs(residual.PhaseResidualRadians) - 0.70) / Math.PI, 0.0, 1.0); + var delayFitness = 1.0 - Math.Clamp(Math.Abs(residual.DelayResidualMicroseconds) / 45.0, 0.0, 1.0); + var responseFitness = residual.ResponseEnergy <= 0.0 + ? 0.0 + : Math.Clamp(residual.ResponseEnergy / 0.30, 0.0, 1.0); + return Math.Clamp( + residual.Confidence * 0.44 + + magnitudeFitness * 0.20 + + phaseFitness * 0.14 + + delayFitness * 0.10 + + responseFitness * 0.12, + 0.0, + 1.0); + } + + private static double AverageOrZero(IEnumerable values) + { + var array = values.ToArray(); + return array.Length == 0 ? 0.0 : array.Average(); + } + + private static long SecondsToNanoseconds(double seconds) => + (long)Math.Round(Math.Clamp(seconds, 0.0, 3600.0) * 1_000_000_000.0); +} diff --git a/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs b/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs index d028c2a..35a9a30 100644 --- a/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs +++ b/src/Mimir.Runtime/Synchronization/MimirSynchronizationHub.cs @@ -6,6 +6,7 @@ public sealed class MimirSynchronizationHub : IDisposable private readonly MimirAudioSynchronizationAnalyzer audioSynchronization = new(); private readonly MimirComplexContourRuntimeAnalyzer? complexContourSynchronization; private readonly MimirAudioSynchronizationStateTracker audioSynchronizationState = new(); + private readonly MimirBioacousticProbeScheduler bioacousticProbeScheduler = new(); private readonly Dictionary audioSynchronizationReports = new(StringComparer.Ordinal); private readonly Dictionary complexContourReports = new(StringComparer.Ordinal); private readonly MimirChirpBinCalibrationModel? chirpBinCalibrationModel; @@ -57,6 +58,8 @@ public sealed class MimirSynchronizationHub : IDisposable public bool ComplexContourRuntimeEnabled => complexContourSynchronization != null; + public MimirScheduledBioacousticProbeFrame? LastBioacousticProbeSchedule { get; private set; } + public MimirSynchronizedBufferFrame BuildSynchronizedBufferFrame(TimeSpan? presentationDelay = null) { ObjectDisposedException.ThrowIf(disposed, this); @@ -218,6 +221,22 @@ public sealed class MimirSynchronizationHub : IDisposable return reports; } + public MimirScheduledBioacousticProbeFrame UpdateBioacousticProbeSchedule( + long timestampNs, + IReadOnlyList? preferredSourceIds = null, + IReadOnlyList? sourcePathologies = null) + { + ObjectDisposedException.ThrowIf(disposed, this); + var residuals = BuildProbeResiduals(); + LastBioacousticProbeSchedule = bioacousticProbeScheduler.Update( + audioSynchronizationState.States, + residuals, + timestampNs, + preferredSourceIds, + sourcePathologies); + return LastBioacousticProbeSchedule; + } + private bool disposed; private static MimirChirpBinCalibrationModel? TryLoadCalibrationModel(string path) @@ -240,6 +259,34 @@ public sealed class MimirSynchronizationHub : IDisposable return MimirComplexContourChannelModelDocument.Load(path); } + private IReadOnlyList BuildProbeResiduals() + { + var reports = audioSynchronizationReports.Values + .Concat(complexContourReports.Values) + .GroupBy(report => report.SourceId, StringComparer.Ordinal) + .Select(group => group.OrderByDescending(report => report.AnalysisTimestampNs).First()) + .ToArray(); + var residuals = new List(); + foreach (var report in reports) + { + foreach (var band in report.BandResponses) + { + var response = Math.Clamp(band.Energy, 0.0, 1.0); + var confidence = Math.Clamp(report.Confidence * (0.35 + 0.65 * response), 0.0, 1.0); + var residualDb = -20.0 * Math.Log10(Math.Max(1.0e-4, response)); + residuals.Add(new MimirAudioCalibrationBandResidual( + report.SourceId, + band.CenterHz, + confidence, + residualDb, + PhaseResidualRadians: band.PhaseRadians, + ResponseEnergy: response)); + } + } + + return residuals; + } + private void StoreAudioSynchronizationReports( IReadOnlyList reports, IEnumerable analyzedCandidateIds) diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 345c7c3..318f4d2 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -312,3 +312,4 @@ {"ts": "2026-06-01T03:09:15+01:00", "type": "verification", "status": "ok", "note": "Live targeted bioacoustic probe ran through Focusrite ASIO at 192 kHz with the shotgun/cardioid pair. Gain 1.0 artifact artifacts/asio/targeted-bioacoustic-live/20260601-030836 selected 18.6 kHz, 9.9 kHz, 3.6 kHz, and 910 Hz; shotgun measured low/high tilt 20.199 dB and cardioid 15.082 dB. Gain 2.0 artifact artifacts/asio/targeted-bioacoustic-live/20260601-030857 doubled loopback energy but physical 18.6 kHz remained nearly absent: shotgun -51.475 dB vs loopback, cardioid -56.585 dB. 910 Hz was the strongest physical band, especially shotgun at -21.994 dB. Treat current high-band path as weak/unusable until a better speaker/mic placement or probe shape proves otherwise."} {"ts": "2026-06-01T03:11:14+01:00", "type": "verification", "status": "ok", "note": "Louder targeted bioacoustic probes ran at playback gains 4.0 and 8.0. Gain 4 artifact artifacts/asio/targeted-bioacoustic-live/20260601-031030 had shotgun peak 0.020941 and cardioid peak 0.016305; gain 8 artifact artifacts/asio/targeted-bioacoustic-live/20260601-031051 had shotgun peak 0.140715 and cardioid peak 0.027774, so the pass was audible but not clipped. Even at gain 8, 18.6 kHz stayed unusable: shotgun -54.910 dB and cardioid -63.258 dB vs loopback. Shotgun 910 Hz reached -26.549 dB with 0.237 confidence and 3.6 kHz reached -32.637 dB with 0.082 confidence. Current probe loop should bias usable low/mid anchors while treating ultrasonic/high band as failed path evidence."} {"ts": "2026-06-01T03:13:10+01:00", "type": "decision", "status": "ok", "note": "Routing correction: Starfire system default output is now Scarlett for monitoring, while Starfire Realtek is the intended active chirp-emission and loopback-measurement path. The 20260601 targeted ASIO-output probe artifacts remain useful Scarlett-output diagnostics but are not the intended Realtek chirp path. Next active probe runner must explicitly select Realtek output/loopback and must not assume default output or Scarlett ASIO playback."} +{"ts": "2026-06-01T03:25:48+01:00", "type": "decision", "status": "ok", "note": "Added MimirBioacousticProbeScheduler as the closed-loop cadence owner above targeted probe planning. Runtime now publishes probe schedule/source confidence telemetry; scheduler owns when to spend active probes, while Realtek-specific physical emission remains the next output-device cut."} diff --git a/state/map.yaml b/state/map.yaml index f92015e..64363e1 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -656,6 +656,16 @@ accepted_design: residual. Use the two good mics first; every connected mic can become room field evidence later, but it should not dilute the initial direct-path calibration loop. + `MimirBioacousticProbeScheduler` now closes the first control loop above + that planner: smoothed sync confidence and derived per-band frequency + response confidence decide when active sound is worth spending. The hub + exposes `LastBioacousticProbeSchedule` / `UpdateBioacousticProbeSchedule`, + and `MimirRuntime` logs `mimir-bioacoustic-probe-schedule` plus per-source + probe confidence lines. `Mimir.BufferSmoke --bioacoustic-probe-scheduler-smoke` + proves the visible climb: simulated feedback raises sync confidence from + 0.360 to 0.920 and frequency-response confidence from 0.558 to 0.955 over + four scheduled probes. The scheduler owns cadence and telemetry only; it + does not override the Realtek routing authority for physical emission. The first live targeted probe ran through Focusrite ASIO at 192 kHz. Gain 1.0 artifact `artifacts/asio/targeted-bioacoustic-live/20260601-030836` measured shotgun low/high tilt 20.199 dB and cardioid 15.082 dB. Gain 2.0