diff --git a/slab/menuband/Info.plist b/slab/menuband/Info.plist index 1ceeccb014..4090b53276 100644 --- a/slab/menuband/Info.plist +++ b/slab/menuband/Info.plist @@ -65,7 +65,7 @@ NSCameraUsageDescription Menu Band looks through the camera only while a singing face is on screen, so its eyes can follow the people in the room. No frames are stored or sent anywhere. NSAudioCaptureUsageDescription - Menu Band adjusts system output volume by processing audio from your apps locally. Audio is never stored or sent anywhere. + Menu Band captures audio from the app you choose for playback across your room-audio devices. NSMicrophoneUsageDescription Menu Band records short clips from your microphone when you hold ` so you can play them back as a sampling voice. NSSpeechRecognitionUsageDescription diff --git a/slab/menuband/SCORE.md b/slab/menuband/SCORE.md index 69a0349ac1..3705bd1ee8 100644 --- a/slab/menuband/SCORE.md +++ b/slab/menuband/SCORE.md @@ -23,30 +23,61 @@ MIDI-mode shortcut. The shared chord modifiers work on every layout. Lives at `slab/menuband/`. Distinct from `slab/menubar-swift/` (the Claude session menubar; different status item, different process). -## System output volume - -The direct-download popover's **System** checkbox and slider control all apps -playing through the current stereo system output, including interfaces such as -Scarlett Solo that expose no Core Audio volume property. Requires macOS 14.2+ -and system-audio permission. A child mode of the signed MenuBand executable -excludes its own playback from a device tap, applies a smoothed 0–100% gain, -and sends audio to the same output. Physical microphone inputs are skipped; -audio is never stored or networked. Starts at 25% on first use and remembers -the slider level per device. Enablement is explicit each session. Turning it -off, quitting, or changing output/rate restores the interface's hardware level. -The interface's direct hardware monitoring is outside this software control. -The helper runs directly on the HAL audio thread without a dispatch-queue hop. -For crunching, inspect CoreAudio overloads and the headset menu's IO buffer: -16 frames produced client timeouts on the local Scarlett Solo; 256 frames -cleared the observed overloads. Air masking does not fix missed audio deadlines. - -**Air**, directly below System, adds continuous White, Brown, or Cabin noise -through the same output helper. Cabin is a gently moving low airplane-like -rumble. Filter sweeps a smooth two-stage low-pass from 60–6000 Hz, defaulting -to a dark 160 Hz; it affects only Air and remembers its setting. Air starts -silent, fades smoothly, and follows System volume including mute. Its color is remembered; its level resets to zero when disabled or quit. -This masks distracting noise; it does not remove hiss from speakers or cables. -The pitched ⇧Space Air instrument remains separate. +## Output and Air + +Menu Band plays through the selected macOS output, including a Focusrite +Scarlett, without a volume enable switch. The headset menu can pin another +output for Menu Band. Playback binds to that device before the engine starts. +Device-list and system-output changes recheck the route, with a five-second +audit as a fallback. A pinned interface is resolved by UID after reconnect; +automatic output follows the current system default even if the engine's +temporary speaker fallback is still connected. +Focusing Menu Band does not reset the interface or change its sample rate. +Visualizer and recording taps stay attached; UI visibility only gates their +delivery. A Focusrite output gets one USB stream rebuild three seconds after +startup, reconnect, or an engine-fault recovery settles, using the same reset +that restores a silent Scarlett manually. It restores the original sample +rate, preserves the selected latency, and is capped at three automatic resets +per minute. Repeated enumeration and mouse entry do not request resets. +**Reset Interface** remains available manually. During either kind of reset, +the playback/input watchdogs and buffer listener yield until streams settle; +engine configuration recovery is deferred so it cannot restart IO mid-flip. +The final output node replaces non-finite samples with silence before they +reach CoreAudio's shared mix. Invalid audio or stalled render callbacks trigger +a bounded engine reset on the current output; wake and route changes re-arm +recovery. Intentional idle pauses are excluded. Recovery clears effect tails +and held notes without changing the hardware sample rate. + +For local troubleshooting, enable `MBAudioDiagnosticsEnabled` in the app's +defaults before launch. `~/Library/Logs/MenuBand/audio-diagnostics.jsonl` +contains one-second scalar meters for tones, percussion, the main mix, the +final output guard, and the hardware output unit. Each distinguishes measured +silence from missing callbacks or unavailable buffers, and reports non-finite +samples, peak/RMS, callback gaps, and time since the last signal. Snapshots also +include gains, trigger counts, output/monitor IDs, a hashed persistent device +identity, device clock progress, stream state, rate and buffer size. Route, +reset, overload and active-output-client PID changes are timestamped separately. +These diagnostics do not drive recovery or change routing. No audio, MIDI note +content or microphone recording is retained, and nothing is uploaded. The +current and previous logs are capped at 4 MiB each. Disable the same preference +and relaunch to stop diagnostics. +After a dropout, `bash slab/menuband/bin/audio-diagnostics.sh` collects those +files, recent app events, and ten minutes of USB/CoreAudio error and stream +restart events into a local report directory. An optional argument selects +1–60 minutes. It neither resets audio nor uploads the report. + +The direct-download popover's **Air** slider adds White, Brown, or Cabin +background noise: zero is silent, raising it fades the noise in. It shares +the instrument's output engine and keeps playing when the popover closes. +It does not capture or change other apps' audio, open another output engine, +or require system-audio permission. Air bypasses gesture FX and rewind +capture; its level is independent of the instrument mix. It is included in +the full tape mix, but not the dry instrument or microphone stems. + +Cabin is a gently moving low airplane-like rumble. Filter sweeps a smooth +two-stage low-pass from 60–6000 Hz, defaulting to 160 Hz. Color and filter +are remembered; level starts at zero each launch. The pitched ⇧Space Air +instrument remains separate. ## Drum kits diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index eac8704874..ce6aef8c85 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -150,11 +150,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// One path for "the player is here", whether they arrived by keyboard /// (performance focus) or by mouse (the app came to the front): the - /// monitor is audible while engaged, and the interface's streams are - /// rebuilt on the rising edge (debounced) because the Scarlett's output - /// dies silently under macOS 26 and this is the moment it matters. + /// monitor is audible while engaged. Focus must never reset the shared + /// USB interface or change its sample rate. private var engaged = false - private var lastEngagementReset: TimeInterval = 0 private func refreshEngagement(reason: String) { // Engage on keyboard focus OR the app coming to the front; disengage // only on an explicit focus loss (Esc), never on a mere app switch. @@ -163,14 +161,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { engaged = now NSLog("MenuBand: engagement → \(now ? "on" : "off") (\(reason))") menuBand.setMonitorFocused(now) - if now, MenuBandAudioDevices.focusriteInputPresent() { - let t = ProcessInfo.processInfo.systemUptime - if t - lastEngagementReset > 600 { // refocus is instant; a rebuild here is a rare backstop - lastEngagementReset = t - NSLog("MenuBand: engaged — interface reset") - menuBand.resetAudioInterface() - } - } + menuBand.logAudioBindings(context: "engagement \(now ? "on" : "off")") } /// Periodic check that the status item is actually visible in the @@ -3522,9 +3513,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } func applicationWillTerminate(_ notification: Notification) { - #if !MAC_APP_STORE - MenuBandSystemVolume.shared.stop() - #endif #if MAC_APP_STORE trackpadPlugin.setCaptureEnabled(false) trackpadPlugin.stop() @@ -3972,12 +3960,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Hover private var lastHoverLogTime: TimeInterval = 0 + private var lastHoverAudioLogTime: TimeInterval = 0 private func handleHover(event: NSEvent) { let now = CACurrentMediaTime() if now - lastHoverLogTime > 1.0 { lastHoverLogTime = now debugLog("handleHover (1Hz throttle)") } + if now - lastHoverAudioLogTime > 5 { + lastHoverAudioLogTime = now + menuBand.logAudioBindings(context: "pointer entered") + } handleHoverInner(event: event) } @@ -8279,6 +8272,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } @objc private func systemDidWake(_ note: Notification) { + menuBand.recoverAudioAfterWake() // After sleep/wake the polling timer + KVO observers can // miss the theme flip that happened while we were // suspended, leaving the popover painted in the old theme. diff --git a/slab/menuband/Sources/MenuBand/AudioDiagnosticLog.swift b/slab/menuband/Sources/MenuBand/AudioDiagnosticLog.swift new file mode 100644 index 0000000000..310122e238 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/AudioDiagnosticLog.swift @@ -0,0 +1,51 @@ +import Foundation + +/// Used only on the diagnostics queue. Two bounded local JSONL files; no +/// network transport, audio buffers, MIDI pitches or microphone recordings. +final class AudioDiagnosticLog { + let url: URL + private let previous: URL + private let maximumBytes: UInt64 + private var handle: FileHandle? + private var bytes: UInt64 = 0 + + init(directory: URL, maximumBytes: UInt64 = 4 * 1024 * 1024) { + url = directory.appendingPathComponent("audio-diagnostics.jsonl") + previous = directory.appendingPathComponent("audio-diagnostics.previous.jsonl") + self.maximumBytes = maximumBytes + } + + func append(_ fields: [String: Any]) throws { + var row = fields + row["time"] = ISO8601DateFormatter().string(from: Date()) + row["uptime"] = ProcessInfo.processInfo.systemUptime + row["pid"] = ProcessInfo.processInfo.processIdentifier + var data = try JSONSerialization.data(withJSONObject: row, options: [.sortedKeys]) + data.append(0x0a) + guard UInt64(data.count) <= maximumBytes else { return } + if handle == nil { try open() } + if bytes + UInt64(data.count) > maximumBytes { + try handle?.close(); handle = nil + if FileManager.default.fileExists(atPath: previous.path) { + try FileManager.default.removeItem(at: previous) + } + try FileManager.default.moveItem(at: url, to: previous) + try open() + } + try handle?.write(contentsOf: data) + bytes += UInt64(data.count) + } + + private func open() throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), + withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + if !FileManager.default.fileExists(atPath: url.path) { + FileManager.default.createFile(atPath: url.path, contents: nil, + attributes: [.posixPermissions: 0o600]) + } + handle = try FileHandle(forWritingTo: url) + bytes = try handle!.seekToEnd() + } + + deinit { try? handle?.close() } +} diff --git a/slab/menuband/Sources/MenuBand/AudioSignalMeter.swift b/slab/menuband/Sources/MenuBand/AudioSignalMeter.swift new file mode 100644 index 0000000000..adc5baac54 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/AudioSignalMeter.swift @@ -0,0 +1,84 @@ +import AVFoundation + +/// Scalar diagnostics only. No audio is retained, and the render thread +/// never waits for the reporting thread. Channels are measured independently +/// so opposite-phase stereo cannot be mistaken for silence. +final class AudioSignalMeter { + private let lock = NSLock() + private var callbacks = 0, measuredBuffers = 0, frames = 0, samples = 0 + private var invalid = 0, silentBuffers = 0, errors = 0 + private var peak = 0.0, squares = 0.0, maxGap = 0.0 + private var minFrames = Int.max, maxFrames = 0 + private var lastCallback: TimeInterval?, lastSignal: TimeInterval? + + func observe(_ buffer: AVAudioPCMBuffer) { + guard buffer.format.commonFormat == .pcmFormatFloat32 else { return } + observe(buffer.audioBufferList, frames: Int(buffer.frameLength)) + } + + func observe(_ output: UnsafePointer?, frames count: Int, + silent: Bool = false, error: Bool = false, + at now: TimeInterval = ProcessInfo.processInfo.systemUptime) { + var blockPeak = 0.0, blockSquares = 0.0 + var blockSamples = 0, blockInvalid = 0 + if !error, let output { + for buffer in UnsafeMutableAudioBufferListPointer(UnsafeMutablePointer(mutating: output)) { + guard let data = buffer.mData else { continue } + let n = min(count * Int(buffer.mNumberChannels), Int(buffer.mDataByteSize) / 4) + let values = data.assumingMemoryBound(to: Float.self) + blockSamples += n + if silent { continue } // Contents may be undefined when silence is flagged. + for i in 0.. 0 { measuredBuffers += 1 } + samples += blockSamples + invalid += blockInvalid + if silent { silentBuffers += 1 } + if error { errors += 1 } + peak = max(peak, blockPeak) + squares += blockSquares + minFrames = min(minFrames, count) + maxFrames = max(maxFrames, count) + if let lastCallback { maxGap = max(maxGap, now - lastCallback) } + lastCallback = now + if blockPeak > 0.00001 { lastSignal = now } // -100 dBFS + } + + struct Snapshot: Codable { + let callbacks, measuredBuffers, frames, samples, invalidSamples: Int + let silentFlagBuffers, renderErrors, minFrames, maxFrames: Int + let peakDBFS, rmsDBFS, maxGapMs: Double + let lastCallbackAgeMs, lastSignalAgeMs: Double? + } + + func takeSnapshot(at now: TimeInterval = ProcessInfo.processInfo.systemUptime) -> Snapshot { + lock.lock(); defer { lock.unlock() } + let result = Snapshot(callbacks: callbacks, measuredBuffers: measuredBuffers, + frames: frames, samples: samples, invalidSamples: invalid, + silentFlagBuffers: silentBuffers, renderErrors: errors, + minFrames: minFrames == Int.max ? 0 : minFrames, maxFrames: maxFrames, + peakDBFS: Self.db(peak), rmsDBFS: Self.db(sqrt(squares / Double(max(1, samples)))), + maxGapMs: maxGap * 1000, + lastCallbackAgeMs: lastCallback.map { max(0, now - $0) * 1000 }, + lastSignalAgeMs: lastSignal.map { max(0, now - $0) * 1000 }) + callbacks = 0; measuredBuffers = 0; frames = 0; samples = 0 + invalid = 0; silentBuffers = 0; errors = 0 + peak = 0; squares = 0; maxGap = 0; minFrames = Int.max; maxFrames = 0 + return result + } + + private static func db(_ value: Double) -> Double { + value > 0 ? max(-160, 20 * log10(value)) : -160 + } +} diff --git a/slab/menuband/Sources/MenuBand/InterfaceRecoveryPolicy.swift b/slab/menuband/Sources/MenuBand/InterfaceRecoveryPolicy.swift new file mode 100644 index 0000000000..1cd050fbb3 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/InterfaceRecoveryPolicy.swift @@ -0,0 +1,42 @@ +import Foundation + +/// A stream rebuild follows an actual connection or engine recovery, never +/// pointer entry or periodic device enumeration. Hardware can report healthy +/// callbacks while a Scarlett output stream remains silent. +struct InterfaceRecoveryPolicy { + private var observedDevice: UInt32? + private var pendingDevice: UInt32? + private var readyAt: TimeInterval = 0 + private var resetTimes: [TimeInterval] = [] + + mutating func observeRoute(device: UInt32?, affected: Bool, at now: TimeInterval) { + guard device != observedDevice else { return } + observedDevice = device + pendingDevice = nil + if affected, let device { engineRecovered(device: device, at: now) } + } + + mutating func engineRecovered(device: UInt32, at now: TimeInterval) { + pendingDevice = device + readyAt = now + 3 + } + + mutating func didReset(at now: TimeInterval) { + pendingDevice = nil + resetTimes.removeAll { now - $0 >= 60 } + resetTimes.append(now) + } + + mutating func takeRequest(device: UInt32?, resetting: Bool, at now: TimeInterval) -> UInt32? { + guard let pendingDevice, pendingDevice == device, !resetting, + now >= readyAt else { return nil } + resetTimes.removeAll { now - $0 >= 60 } + // A fault loop must not keep interrupting all clients of the device. + guard resetTimes.count < 3 else { + self.pendingDevice = nil + return nil + } + didReset(at: now) + return pendingDevice + } +} diff --git a/slab/menuband/Sources/MenuBand/MenuBandAmbientAir.swift b/slab/menuband/Sources/MenuBand/MenuBandAmbientAir.swift new file mode 100644 index 0000000000..ad64873389 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/MenuBandAmbientAir.swift @@ -0,0 +1,163 @@ +import AppKit +import AVFoundation + +/// Listening noise on the instrument's existing output engine. Changing Air +/// never opens a device, captures another app, or changes system volume. +final class MenuBandAmbientAir { + private let lock = NSLock() + private var requestedLevel: Float = 0 + private var requestedColor: MenuBandAirColor + private var requestedCutoff: Double + private let defaults: UserDefaults + private var source: AVAudioSourceNode? + private var noise = MenuBandAirNoise() + private var renderLevel: Float = 0 + private var targetLevel: Float = 0 + private var renderColor: MenuBandAirColor = .cabin + private var renderCutoff = MenuBandAirNoise.defaultCutoff + // A fixed source format lets AVAudioEngine resample across device changes. + private let sampleRate: Double = 44_100 + var onChange: (() -> Void)? + var onLevelChange: ((Float) -> Void)? + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + requestedColor = MenuBandAirColor(rawValue: defaults.string(forKey: "systemAirColor") ?? "") ?? .cabin + let saved = defaults.double(forKey: "systemAirCutoff") + requestedCutoff = saved.isFinite && saved >= 60 ? min(6000, saved) : MenuBandAirNoise.defaultCutoff + } + + var level: Float { lock.lock(); defer { lock.unlock() }; return requestedLevel } + var color: MenuBandAirColor { lock.lock(); defer { lock.unlock() }; return requestedColor } + var cutoff: Double { lock.lock(); defer { lock.unlock() }; return requestedCutoff } + + func setLevel(_ value: Float) { + guard value.isFinite else { return } + let value = max(0, min(1, value)) + lock.lock(); let changed = requestedLevel != value; requestedLevel = value; lock.unlock() + if changed { onLevelChange?(value) } + onChange?() + } + + func setColor(_ color: MenuBandAirColor) { + lock.lock(); requestedColor = color; lock.unlock() + defaults.set(color.rawValue, forKey: "systemAirColor") + onChange?() + } + + func setCutoff(_ value: Double) { + guard value.isFinite else { return } + let value = max(60, min(6000, value)) + lock.lock(); requestedCutoff = value; lock.unlock() + defaults.set(value, forKey: "systemAirCutoff") + onChange?() + } + + func attach(to engine: AVAudioEngine, output: AVAudioNode) { + guard source == nil else { return } + let format = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 2)! + let node = AVAudioSourceNode(format: format) { [weak self] silent, _, frames, output in + if let self { + self.render(frames: Int(frames), output: output, silent: silent) + } else { + for buffer in UnsafeMutableAudioBufferListPointer(output) { + if let data = buffer.mData { memset(data, 0, Int(buffer.mDataByteSize)) } + } + silent.pointee = true + } + return noErr + } + engine.attach(node) + engine.connect(node, to: output, format: format) + source = node + } + + private func render(frames: Int, output: UnsafeMutablePointer, + silent: UnsafeMutablePointer) { + // Never wait for the UI on the audio thread; a concurrent slider move + // can be picked up on the next buffer. + if lock.try() { + targetLevel = requestedLevel; renderColor = requestedColor; renderCutoff = requestedCutoff + lock.unlock() + } + let buffers = UnsafeMutableAudioBufferListPointer(output) + if targetLevel == 0 && renderLevel == 0 { + for buffer in buffers { + if let data = buffer.mData { memset(data, 0, Int(buffer.mDataByteSize)) } + } + silent.pointee = true + return + } + silent.pointee = false + let step = Float(1 / (sampleRate * 0.25)) + for frame in 0.. 0 + ? noise.next(color: renderColor, sampleRate: sampleRate, cutoff: renderCutoff) + * renderLevel * renderLevel * 0.12 : 0 + for buffer in buffers { + guard let data = buffer.mData else { continue } + let channels = Int(buffer.mNumberChannels) + let samples = data.assumingMemoryBound(to: Float.self) + for channel in 0.. AudioDeviceID? { + let outputs = devices.filter { $0.outputChannels > 0 } + if let pinnedUID, let pinned = outputs.first(where: { $0.uid == pinnedUID }) { + return pinned.id + } + return outputs.first { $0.id == systemDefaultID }?.id + } + + static func preferredOutputID() -> AudioDeviceID? { + outputTargetID(devices: all(), pinnedUID: pinnedOutputUID, + systemDefaultID: systemDefaultOutputID()) + } + // MARK: - Channel map /// AUHAL channel-map write shared by the duplex-monitor engine and the @@ -169,10 +185,8 @@ enum MenuBandAudioDevices { // MARK: - Preferred interface sample rate - /// The rate Menu Band runs a Focusrite at. 44.1 kHz by default while we - /// test whether the 48 kHz output stream is what dies under usbaudiod - /// (macOS 26). Applied at launch before the engine starts and restored - /// by `resetInterface`. + /// An explicit rate preference for `applyPreferredRate`. Ordinary launch + /// adopts the device's rate and stream resets restore that same rate. static var preferredInterfaceRate: Double { let v = UserDefaults.standard.double(forKey: "notepat.interfaceSampleRate") return v > 0 ? v : 44_100 @@ -218,13 +232,7 @@ enum MenuBandAudioDevices { @discardableResult static func bindToRawOutput(_ engine: AVAudioEngine, label: String) -> Bool { guard let au = engine.outputNode.audioUnit else { return false } - var target: AudioDeviceID = 0 - if let uid = pinnedOutputUID, let dev = device(uid: uid), dev.outputChannels > 0 { - target = dev.id - } else { - target = systemDefaultOutputID() ?? 0 - } - guard target != 0 else { return false } + guard let target = preferredOutputID() else { return false } var current = AudioDeviceID(0) var size = UInt32(MemoryLayout.size) if AudioUnitGetProperty(au, kAudioOutputUnitProperty_CurrentDevice, @@ -247,9 +255,18 @@ enum MenuBandAudioDevices { /// Runs off the main thread; the engine absorbs the resulting /// configuration change like any device switch. private static let resetQueue = DispatchQueue(label: "menuband.interface-reset", qos: .userInitiated) + private static let resetStateLock = NSLock() + private static var resetting = false + static var interfaceResetInProgress: Bool { + resetStateLock.lock(); defer { resetStateLock.unlock() } + return resetting + } private static let resetCoordinator = InterfaceResetCoordinator( perform: { id, completion in performInterfaceReset(id, completion: completion) }, busyChanged: { busy in + resetStateLock.lock() + resetting = busy + resetStateLock.unlock() NotificationCenter.default.post(name: .menuBandInterfaceResetting, object: busy) }) @@ -274,7 +291,7 @@ enum MenuBandAudioDevices { DispatchQueue.main.async { completion(false) } return } - let want = preferredInterfaceRate + let want = rate var other: Double = want == 44_100 ? 48_000 : 44_100 let s1 = AudioObjectSetPropertyData(id, &address, 0, nil, size, &other) // Release the worker during USB teardown. The coordinator keeps @@ -296,19 +313,16 @@ enum MenuBandAudioDevices { } } - // MARK: - Device-list observation + // MARK: - Route observation private static var deviceListQueue = DispatchQueue(label: "menuband.devicelist") private static var deviceListBlock: AudioObjectPropertyListenerBlock? - /// Fire `handler` on the main thread (debounced ~0.8 s) whenever the - /// system's audio device list changes — plug/unplug of an interface. - static func observeDeviceList(_ handler: @escaping () -> Void) { + /// Device arrival and default-output selection are separate events. + /// Observe both: a raw-bound playback AU may emit neither an engine + /// configuration change nor a device-list change when the default moves. + static func observeRoutingChanges(_ handler: @escaping () -> Void) { guard deviceListBlock == nil else { return } - var address = AudioObjectPropertyAddress( - mSelector: kAudioHardwarePropertyDevices, - mScope: kAudioObjectPropertyScopeGlobal, - mElement: kAudioObjectPropertyElementMain) var pending: DispatchWorkItem? let block: AudioObjectPropertyListenerBlock = { _, _ in pending?.cancel() @@ -317,8 +331,13 @@ enum MenuBandAudioDevices { DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: work) } deviceListBlock = block - AudioObjectAddPropertyListenerBlock( - AudioObjectID(kAudioObjectSystemObject), &address, deviceListQueue, block) + for selector in [kAudioHardwarePropertyDevices, kAudioHardwarePropertyDefaultOutputDevice] { + var address = AudioObjectPropertyAddress( + mSelector: selector, mScope: kAudioObjectPropertyScopeGlobal, + mElement: kAudioObjectPropertyElementMain) + AudioObjectAddPropertyListenerBlock( + AudioObjectID(kAudioObjectSystemObject), &address, deviceListQueue, block) + } } /// True when a Focusrite/Scarlett interface with inputs is attached. diff --git a/slab/menuband/Sources/MenuBand/MenuBandAudioTelemetry.swift b/slab/menuband/Sources/MenuBand/MenuBandAudioTelemetry.swift new file mode 100644 index 0000000000..e51aab4d4d --- /dev/null +++ b/slab/menuband/Sources/MenuBand/MenuBandAudioTelemetry.swift @@ -0,0 +1,241 @@ +import AVFoundation +import AudioToolbox +import CoreAudio +import CryptoKit + +/// Explicitly enabled local troubleshooting. Existing taps and render notifies +/// feed scalar meters; a utility queue writes one snapshot per second. +final class MenuBandAudioTelemetry { + static let preferenceKey = "MBAudioDiagnosticsEnabled" + let enabled: Bool + let tones = AudioSignalMeter(), percussion = AudioSignalMeter() + let mix = AudioSignalMeter(), output = AudioSignalMeter(), hardware = AudioSignalMeter() + private let queue = DispatchQueue(label: "menuband.audio-diagnostics", qos: .utility) + private let activityLock = NSLock() + private var melodyTriggers = 0, percussionTriggers = 0 + private var overloads = 0, abnormalStops = 0 + private var lastDeviceFault: TimeInterval = 0 + private var timer: DispatchSourceTimer? + private var hardwareNode: AVAudioOutputNode? + private var observedDevice: AudioDeviceID = 0 + private var deviceListeners: [(AudioObjectPropertyAddress, AudioObjectPropertyListenerBlock)] = [] + private var uidFingerprint = "" + private var lastHardwareSampleTime: Double? + private var lastClientPIDs: [Int32] = [] + private var loggedWriteFailure = false + private let log = AudioDiagnosticLog(directory: FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Logs/MenuBand", isDirectory: true)) + + init(enabled: Bool = UserDefaults.standard.bool(forKey: preferenceKey)) { self.enabled = enabled } + + func trigger(percussion: Bool) { + guard enabled else { return } + activityLock.lock() + if percussion { percussionTriggers += 1 } else { melodyTriggers += 1 } + activityLock.unlock() + } + + func event(_ name: String, _ fields: [String: Any] = [:]) { + guard enabled else { return } + let observedAt = ProcessInfo.processInfo.systemUptime + queue.async { [weak self] in + var row = fields; row["event"] = name; row["observedAt"] = observedAt + self?.write(row) + } + } + + // Overload notifications can originate on the device IO thread even with + // a listener queue supplied. Accumulate scalars there; never dispatch or + // allocate a JSON event from that callback. + private func deviceFault(overload: Bool) { + guard activityLock.try() else { return } + if overload { overloads += 1 } else { abnormalStops += 1 } + lastDeviceFault = ProcessInfo.processInfo.systemUptime + activityLock.unlock() + } + + func attachHardwareProbe(to engine: AVAudioEngine) { + guard enabled, hardwareNode == nil else { return } + let node = engine.outputNode + guard node.inputFormat(forBus: 0).commonFormat == .pcmFormatFloat32, + let au = node.audioUnit else { return } + let status = AudioUnitAddRenderNotify(au, menuBandHardwareTelemetryNotify, + Unmanaged.passUnretained(self).toOpaque()) + if status == noErr { hardwareNode = node } + event("hardware_probe", ["status": status]) + } + + /// The provider supplies only app state and its bound output ID. Device + /// polling and all JSON/file work happen after its engine lock is released. + func start(snapshot: @escaping () -> [String: Any]) { + guard enabled, timer == nil else { return } + event("session_started", ["schema": 1, "sampleAudioStored": false]) + NSLog("MenuBand audio diagnostics: %@", log.url.path) + let timer = DispatchSource.makeTimerSource(queue: queue) + timer.schedule(deadline: .now(), repeating: 1, leeway: .milliseconds(100)) + timer.setEventHandler { [weak self] in + guard let self else { return } + var row = snapshot() + let device = row["outputDevice"] as? UInt32 ?? self.observedDevice + self.observeDevice(device) + row["device"] = self.deviceSnapshot(device) + let meters = ["tones": self.tones.takeSnapshot(), "percussion": self.percussion.takeSnapshot(), + "mix": self.mix.takeSnapshot(), "output": self.output.takeSnapshot(), + "hardware": self.hardware.takeSnapshot()] + if let data = try? JSONEncoder().encode(meters), + let value = try? JSONSerialization.jsonObject(with: data) { row["meters"] = value } + self.activityLock.lock() + let activity = (self.melodyTriggers, self.percussionTriggers, + self.overloads, self.abnormalStops, self.lastDeviceFault) + self.melodyTriggers = 0; self.percussionTriggers = 0 + self.overloads = 0; self.abnormalStops = 0 + self.activityLock.unlock() + row["melodyTriggers"] = activity.0 + row["percussionTriggers"] = activity.1 + row["processorOverloads"] = activity.2 + row["abnormalStops"] = activity.3 + if activity.4 > 0 { row["lastDeviceFaultUptime"] = activity.4 } + row["event"] = "snapshot" + self.write(row) + let clients = self.outputClientPIDs() + if clients != self.lastClientPIDs { + self.lastClientPIDs = clients + self.write(["event": "output_clients_changed", "pids": clients]) + } + } + self.timer = timer + timer.resume() + } + + func stop() { + timer?.cancel(); timer = nil + if let au = hardwareNode?.audioUnit { + AudioUnitRemoveRenderNotify(au, menuBandHardwareTelemetryNotify, + Unmanaged.passUnretained(self).toOpaque()) + } + hardwareNode = nil + queue.async { [weak self] in self?.removeDeviceListeners() } + event("session_stopped") + } + + private func write(_ row: [String: Any]) { + do { try log.append(row) } + catch { + if !loggedWriteFailure { NSLog("MenuBand diagnostics write failed: %@", String(describing: error)) } + loggedWriteFailure = true + } + } + + private func observeDevice(_ device: AudioDeviceID) { + guard observedDevice != device else { return } + removeDeviceListeners() + observedDevice = device + lastHardwareSampleTime = nil + uidFingerprint = MenuBandAudioDevices.uid(for: device).map { + SHA256.hash(data: Data($0.utf8)).prefix(8).map { String(format: "%02x", $0) }.joined() + } ?? "" + write(["event": "bound_device_changed", "device": device, "uidFingerprint": uidFingerprint]) + guard device != 0 else { return } + let properties: [(AudioObjectPropertySelector, String)] = [ + (kAudioDeviceProcessorOverload, "processor_overload"), + (kAudioDevicePropertyIOStoppedAbnormally, "io_stopped_abnormally"), + (kAudioDevicePropertyDeviceIsAlive, "alive_changed"), + (kAudioDevicePropertyDeviceIsRunningSomewhere, "io_running_changed"), + (kAudioDevicePropertyBufferFrameSize, "buffer_changed"), + (kAudioDevicePropertyNominalSampleRate, "rate_changed")] + for (selector, name) in properties { + var address = AudioObjectPropertyAddress(mSelector: selector, + mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) + let block: AudioObjectPropertyListenerBlock = { [weak self] _, _ in + if selector == kAudioDeviceProcessorOverload || selector == kAudioDevicePropertyIOStoppedAbnormally { + self?.deviceFault(overload: selector == kAudioDeviceProcessorOverload) + } else { + self?.event(name, ["device": device]) + } + } + let status = AudioObjectAddPropertyListenerBlock(device, &address, queue, block) + if status == noErr { deviceListeners.append((address, block)) } + else { write(["event": "device_listener_failed", "property": name, "status": status]) } + } + } + + private func removeDeviceListeners() { + for (var address, block) in deviceListeners { + AudioObjectRemovePropertyListenerBlock(observedDevice, &address, queue, block) + } + deviceListeners.removeAll() + } + + // A dictionary's Any-valued subscript otherwise lets Swift infer T = Any. + // CoreAudio would then overwrite an existential container, not a scalar. + private func read(_ object: AudioObjectID, _ selector: AudioObjectPropertySelector, + scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal, + initial: T) -> T? { + var value = initial + var address = AudioObjectPropertyAddress(mSelector: selector, mScope: scope, + mElement: kAudioObjectPropertyElementMain) + var size = UInt32(MemoryLayout.size) + let status = withUnsafeMutableBytes(of: &value) { + AudioObjectGetPropertyData(object, &address, 0, nil, &size, $0.baseAddress!) + } + return status == noErr ? value : nil + } + + private func objects(_ object: AudioObjectID, _ selector: AudioObjectPropertySelector, + scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal) -> [AudioObjectID] { + var address = AudioObjectPropertyAddress(mSelector: selector, mScope: scope, + mElement: kAudioObjectPropertyElementMain) + var size: UInt32 = 0 + guard AudioObjectGetPropertyDataSize(object, &address, 0, nil, &size) == noErr, + size > 0 else { return [] } + var values = [AudioObjectID](repeating: 0, count: Int(size) / 4) + let status = values.withUnsafeMutableBytes { + AudioObjectGetPropertyData(object, &address, 0, nil, &size, $0.baseAddress!) + } + return status == noErr ? values : [] + } + + func deviceSnapshot(_ device: AudioDeviceID) -> [String: Any] { + var row: [String: Any] = ["id": device, "uidFingerprint": uidFingerprint] + row["alive"] = read(device, kAudioDevicePropertyDeviceIsAlive, initial: UInt32(0)) + row["running"] = read(device, kAudioDevicePropertyDeviceIsRunningSomewhere, initial: UInt32(0)) + row["bufferFrames"] = read(device, kAudioDevicePropertyBufferFrameSize, initial: UInt32(0)) + row["rate"] = read(device, kAudioDevicePropertyNominalSampleRate, initial: Float64(0)) + row["hogPID"] = read(device, kAudioDevicePropertyHogMode, initial: Int32(-1)) + row["defaultOutput"] = MenuBandAudioDevices.systemDefaultOutputID() + var clock = AudioTimeStamp() + clock.mFlags = [.sampleTimeValid, .hostTimeValid] + let status = AudioDeviceGetCurrentTime(device, &clock) + row["clockStatus"] = status + if status == noErr, clock.mFlags.contains(.sampleTimeValid), clock.mSampleTime.isFinite { + row["sampleTime"] = clock.mSampleTime + if let lastHardwareSampleTime { row["sampleTimeDelta"] = clock.mSampleTime - lastHardwareSampleTime } + lastHardwareSampleTime = clock.mSampleTime + } + row["outputStreams"] = objects(device, kAudioDevicePropertyStreams, + scope: kAudioDevicePropertyScopeOutput).map { stream -> [String: Any] in + var value: [String: Any] = ["id": stream] + value["active"] = read(stream, kAudioStreamPropertyIsActive, initial: UInt32(0)) + value["startingChannel"] = read(stream, kAudioStreamPropertyStartingChannel, initial: UInt32(0)) + return value + } + return row + } + + private func outputClientPIDs() -> [Int32] { + guard #available(macOS 14.2, *) else { return [] } + return objects(AudioObjectID(kAudioObjectSystemObject), kAudioHardwarePropertyProcessObjectList).compactMap { object in + guard read(object, kAudioProcessPropertyIsRunningOutput, initial: UInt32(0)) == 1 else { return nil } + return read(object, kAudioProcessPropertyPID, initial: Int32(0)) + }.sorted() + } +} + +private let menuBandHardwareTelemetryNotify: AURenderCallback = { context, flags, _, _, frames, data in + guard flags.pointee.contains(.unitRenderAction_PostRender) else { return noErr } + let telemetry = Unmanaged.fromOpaque(context).takeUnretainedValue() + telemetry.hardware.observe(data.map { UnsafePointer($0) }, frames: Int(frames), + silent: flags.pointee.contains(.unitRenderAction_OutputIsSilence), + error: flags.pointee.contains(.unitRenderAction_PostRenderError)) + return noErr +} diff --git a/slab/menuband/Sources/MenuBand/MenuBandController.swift b/slab/menuband/Sources/MenuBand/MenuBandController.swift index a82e51de3d..cc0c39694d 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandController.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandController.swift @@ -29,6 +29,7 @@ extension Float { final class MenuBandController { private let midi = MenuBandMIDI() private let synth = MenuBandSynth() + var ambientAir: MenuBandAmbientAir { synth.ambientAir } private let mixAnalysis = MenuBandMixAnalysis() private var trackpadPerformanceActive = false /// Optional shared room transmitter. It is fed from the synth's existing @@ -87,27 +88,68 @@ final class MenuBandController { func setAudioMonitorChannel(_ channel: Int) { synth.setMonitorInputChannel(channel) } /// Performance focus gates the monitor's audibility (see synth). func setMonitorFocused(_ focused: Bool) { synth.setMonitorFocusMute(!focused) } + func logAudioBindings(context: String) { synth.logAudioBindings(context: context) } + func recoverAudioAfterWake() { synth.systemDidWake() } /// Headset menu → Reset interface: rebuild the current output device's /// USB streams (see `MenuBandAudioDevices.resetInterface`). - private var interfaceResetGeneration = 0 + private var interfaceRecovery = InterfaceRecoveryPolicy() + private var interfaceRecoveryTimer: DispatchSourceTimer? + private var interfaceResetObserver: NSObjectProtocol? private var pendingMonitorBufferChange: DispatchWorkItem? private var pendingMonitorBufferReset: DispatchWorkItem? private var monitorBufferGeneration = 0 func resetAudioInterface() { dispatchPrecondition(condition: .onQueue(.main)) - let id = MenuBandAudioDevices.pinnedOutputUID.flatMap { MenuBandAudioDevices.device(uid: $0)?.id } - ?? MenuBandAudioDevices.systemDefaultOutputID() ?? 0 - guard id != 0 else { return } - interfaceResetGeneration += 1 - let generation = interfaceResetGeneration + guard let id = MenuBandAudioDevices.preferredOutputID() else { return } + interfaceRecovery.didReset(at: ProcessInfo.processInfo.systemUptime) NSLog("MenuBand audio: interface reset requested on \(id)") - MenuBandAudioDevices.resetInterface(id) { [weak self] _ in - guard let self, self.interfaceResetGeneration == generation else { return } - // Completion now includes stream settling. Only the most recent - // request restores the current pick, on the audio-control queue. - self.audioWorkQueue.async { [weak self] in self?.synth.reassertMonitorIOBuffer() } + synth.logAudioBindings(context: "manual interface reset") + MenuBandAudioDevices.resetInterface(id) + } + + private func currentRecoveryOutput() -> MBAudioDevice? { + guard let id = MenuBandAudioDevices.preferredOutputID() else { return nil } + return MenuBandAudioDevices.all().first { $0.id == id } + } + + private func needsStreamRecovery(_ device: MBAudioDevice?) -> Bool { + guard let device else { return false } + return device.name.localizedCaseInsensitiveContains("scarlett") || + device.name.localizedCaseInsensitiveContains("focusrite") + } + + private func observeInterfaceRecoveryRoute() { + let device = currentRecoveryOutput() + interfaceRecovery.observeRoute(device: device?.id, affected: needsStreamRecovery(device), + at: ProcessInfo.processInfo.systemUptime) + } + + private func startInterfaceRecovery() { + observeInterfaceRecoveryRoute() + synth.onPlaybackRecovered = { [weak self] in + guard let self, let device = self.currentRecoveryOutput(), + self.needsStreamRecovery(device) else { return } + self.interfaceRecovery.engineRecovered(device: device.id, + at: ProcessInfo.processInfo.systemUptime) + } + let timer = DispatchSource.makeTimerSource(queue: .main) + timer.schedule(deadline: .now() + 1, repeating: 1) + timer.setEventHandler { [weak self] in + guard let self else { return } + let device = self.currentRecoveryOutput() + let now = ProcessInfo.processInfo.systemUptime + self.interfaceRecovery.observeRoute(device: device?.id, + affected: self.needsStreamRecovery(device), at: now) + guard let id = self.interfaceRecovery.takeRequest(device: device?.id, + resetting: MenuBandAudioDevices.interfaceResetInProgress, + at: now) else { return } + NSLog("MenuBand audio: automatic settled stream reset on \(id)") + self.synth.logAudioBindings(context: "automatic interface reset") + MenuBandAudioDevices.resetInterface(id) } + interfaceRecoveryTimer = timer + timer.resume() } /// Monitor IO cycle in frames (16…256); applies live while monitoring. @@ -1625,17 +1667,6 @@ final class MenuBandController { guard present != inputMonitoringEnabled else { return } NSLog("MenuBand: auto monitor → \(present ? "on (Focusrite present)" : "off (Focusrite gone)")") inputMonitoringEnabled = present - if present { - // Auto-recovery, part 2: an interface that just came back on the - // bus often has a dead output stream while macOS reports it - // active. Kick its streams once things settle (~2.5 s), the same - // flip the headset menu's Reset Interface does. - DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) { [weak self] in - guard let self, MenuBandAudioDevices.focusriteInputPresent() else { return } - NSLog("MenuBand: auto interface reset after reappearance") - self.resetAudioInterface() - } - } } /// The fader positions a take starts from — written into the stems' @@ -1906,6 +1937,7 @@ final class MenuBandController { func rewindLiveInputPeak() -> Float { synth.rewindLiveInputPeak() } func setBend(amount: Float, allChannels: Bool = false) { + guard amount.isFinite else { return } // The live voice monitor's wet sends follow the wheel in every mode // (MIDI mode included), so it's fed before any branching below. synth.setMonitorPitchBend(amount: amount) @@ -2582,13 +2614,26 @@ final class MenuBandController { if UserDefaults.standard.object(forKey: melodicProgramKey) == nil { UserDefaults.standard.set(78, forKey: melodicProgramKey) } - // Own the interface's sample rate before the engine negotiates - // against it (usbaudiod resets a Focusrite to 48 kHz whenever its - // last client leaves). - if MenuBandAudioDevices.focusriteInputPresent(), - let out = MenuBandAudioDevices.systemDefaultOutputID() { - MenuBandAudioDevices.applyPreferredRate(to: out) + interfaceResetObserver = NotificationCenter.default.addObserver( + forName: .menuBandInterfaceResetting, object: nil, queue: .main + ) { [weak self] note in + guard let self else { return } + if (note.object as? Bool) == true { + self.synth.setInterfaceResetting(true) + } else { + self.audioWorkQueue.async { [weak self] in + guard let self else { return } + self.synth.reassertMonitorIOBuffer() + DispatchQueue.main.async { [weak self] in + guard let self, !MenuBandAudioDevices.interfaceResetInProgress else { return } + self.synth.setInterfaceResetting(false) + self.synth.auditBindings() + } + } + } } + // Adopt the existing rate. The affected Scarlett stream is rebuilt + // once after startup settles, with the original rate restored. synth.start() debugLog("bootstrap: post-synth.start") synth.setMelodicProgram(melodicProgram) @@ -2655,18 +2700,14 @@ final class MenuBandController { // now, on every device-list change (plug/unplug), and whenever the // app comes to the front; unplugging turns the monitor back off. synth.startBindingAudit() - // Auto-recovery, part 3: a fresh process on the Scarlett got a dead - // output stream at every launch today (macOS 26 usbaudiod) until its - // streams were rebuilt. Kick them once the engine has settled. - DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { [weak self] in - guard let self, MenuBandAudioDevices.focusriteInputPresent() else { return } - NSLog("MenuBand: auto interface reset at launch") - self.resetAudioInterface() - } - MenuBandAudioDevices.observeDeviceList { [weak self] in + synth.logAudioBindings(context: "startup") + MenuBandAudioDevices.observeRoutingChanges { [weak self] in self?.synth.resetBindingAudit() + self?.synth.auditBindings() + self?.synth.logAudioBindings(context: "route changed") self?.audioWorkQueue.async { self?.synth.refreshMonitorDevice() } self?.autoMonitorForInterface() + self?.observeInterfaceRecoveryRoute() } NotificationCenter.default.addObserver( forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main @@ -2715,6 +2756,7 @@ final class MenuBandController { // (enableMIDIMode triggers a loopback self-test; result lands in // /tmp/menuband-debug.log and updates the popover's status row.) debugLog("bootstrap: end") + startInterfaceRecovery() } func toggleMIDIMode() { @@ -2737,6 +2779,13 @@ final class MenuBandController { } func shutdown() { + interfaceRecoveryTimer?.cancel() + interfaceRecoveryTimer = nil + if let interfaceResetObserver { + NotificationCenter.default.removeObserver(interfaceResetObserver) + self.interfaceResetObserver = nil + } + synth.onPlaybackRecovered = nil releaseAllHardwareMIDINotes() midi.stopHardwareInput() disableTypeMode() diff --git a/slab/menuband/Sources/MenuBand/MenuBandInputMonitor.swift b/slab/menuband/Sources/MenuBand/MenuBandInputMonitor.swift index a35cf98e38..28efd803a2 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandInputMonitor.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandInputMonitor.swift @@ -318,7 +318,8 @@ final class MenuBandInputMonitor { mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) let block: AudioObjectPropertyListenerBlock = { [weak self] _, _ in - guard let self, self.attached, self.inputDevice != 0 else { return } + guard let self, self.attached, self.inputDevice != 0, + !MenuBandAudioDevices.interfaceResetInProgress else { return } var now: UInt32 = 0 var size: UInt32 = 4 var a = AudioObjectPropertyAddress( @@ -770,9 +771,11 @@ final class MenuBandInputMonitor { pulls = 0 nanScrubbed = 0 os_unfair_lock_unlock(ringLock) - if let ticket = recovery.request(captures: c, now: now) { + if !MenuBandAudioDevices.interfaceResetInProgress, + let ticket = recovery.request(captures: c, now: now) { DispatchQueue.main.async { [weak self] in - guard let self, let attempt = self.recovery.claim(ticket) else { return } + guard let self, !MenuBandAudioDevices.interfaceResetInProgress, + let attempt = self.recovery.claim(ticket) else { return } NSLog("MenuBand monitor: WATCHDOG — no input callbacks; recovery \(attempt)/\(InputMonitorRecovery.maximumAttempts)") self.restartInput() if attempt == InputMonitorRecovery.maximumAttempts { diff --git a/slab/menuband/Sources/MenuBand/MenuBandMixAnalysis.swift b/slab/menuband/Sources/MenuBand/MenuBandMixAnalysis.swift index 91832f1fb6..fb5d6a0085 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandMixAnalysis.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandMixAnalysis.swift @@ -8,6 +8,7 @@ final class MenuBandMixAnalysis { private struct Capture { let kind: String var frames = 0 + var invalidFrames = 0 var sumSquares = 0.0 var peak = 0.0 var lowSquares = 0.0 @@ -55,12 +56,18 @@ final class MenuBandMixAnalysis { mono += Double(channels[channel][frame]) } mono /= Double(channelCount) + current.frames += 1 + guard mono.isFinite else { + current.invalidFrames += 1 + lowState = 0 + fourKState = 0 + continue + } lowState += lowA * (mono - lowState) fourKState += fourKA * (mono - fourKState) let low = lowState let mid = fourKState - lowState let high = mono - fourKState - current.frames += 1 current.sumSquares += mono * mono current.lowSquares += low * low current.midSquares += mid * mid @@ -86,10 +93,11 @@ final class MenuBandMixAnalysis { let lowPercent = 100 * current.lowSquares / bandTotal let highPercent = 100 * current.highSquares / bandTotal let kind = current.kind + let invalidFrames = current.invalidFrames DispatchQueue.main.async { NSLog(String(format: - "MenuBand mix attack kind=%@ peak=%.2f dBFS rms=%.2f dBFS crest=%.2f dB lowPct=%.1f highPct=%.1f", - kind, peakDB, rmsDB, crestDB, lowPercent, highPercent)) + "MenuBand mix attack kind=%@ peak=%.2f dBFS rms=%.2f dBFS crest=%.2f dB lowPct=%.1f highPct=%.1f invalidFrames=%d", + kind, peakDB, rmsDB, crestDB, lowPercent, highPercent, invalidFrames)) } } diff --git a/slab/menuband/Sources/MenuBand/MenuBandOutputGuard.swift b/slab/menuband/Sources/MenuBand/MenuBandOutputGuard.swift new file mode 100644 index 0000000000..ba9bb859fa --- /dev/null +++ b/slab/menuband/Sources/MenuBand/MenuBandOutputGuard.swift @@ -0,0 +1,65 @@ +import AVFoundation +import AudioToolbox + +/// Last node before hardware: contain invalid samples before CoreAudio mixes +/// this app with other clients. Taps are observers, not an output filter. +final class MenuBandOutputGuard { + private let unit = AVAudioUnitEQ(numberOfBands: 1) + let health = MenuBandPlaybackHealth() + var telemetry: MenuBandAudioTelemetry? + + init() { + unit.bands[0].bypass = true + unit.globalGain = 0 + } + + func attach(to engine: AVAudioEngine) { + engine.attach(unit) + engine.connect(engine.mainMixerNode, to: unit, format: nil) + engine.connect(unit, to: engine.outputNode, format: nil) + let status = AudioUnitAddRenderNotify( + unit.audioUnit, menuBandOutputGuardNotify, + Unmanaged.passUnretained(self).toOpaque()) + if status != noErr { NSLog("MenuBand: output guard install failed: \(status)") } + health.begin() + } + + /// Render-thread only: no allocation, logging, dispatch or waiting. + func inspect(_ output: UnsafeMutablePointer, frames: UInt32, silent: Bool) { + if let telemetry, telemetry.enabled { + telemetry.output.observe(UnsafePointer(output), frames: Int(frames), silent: silent) + } + var invalid = 0 + for buffer in UnsafeMutableAudioBufferListPointer(output) { + guard let data = buffer.mData else { continue } + if silent { + memset(data, 0, Int(buffer.mDataByteSize)) + continue + } + let samples = data.assumingMemoryBound(to: Float.self) + let count = min(Int(frames) * Int(buffer.mNumberChannels), + Int(buffer.mDataByteSize) / MemoryLayout.size) + for i in 0...fromOpaque(context).takeUnretainedValue() + .inspect(output, frames: frames, + silent: flags.pointee.contains(.unitRenderAction_OutputIsSilence)) + return noErr +} diff --git a/slab/menuband/Sources/MenuBand/MenuBandPlaybackHealth.swift b/slab/menuband/Sources/MenuBand/MenuBandPlaybackHealth.swift new file mode 100644 index 0000000000..c0a562972e --- /dev/null +++ b/slab/menuband/Sources/MenuBand/MenuBandPlaybackHealth.swift @@ -0,0 +1,74 @@ +import Foundation + +/// Watches the actual output stream, independently of the popover and meters. +/// A valid device ID and isRunning can both survive a dead render stream. +final class MenuBandPlaybackHealth { + private let lock = NSLock() + private var lastBuffer: TimeInterval = 0 + private var healthySince: TimeInterval? + private var invalidSamples = 0 + private var notBefore: TimeInterval = 0 + private var attempts = 0 + private var interfaceResetting = false + + func setInterfaceResetting(_ active: Bool, + at now: TimeInterval = ProcessInfo.processInfo.systemUptime) { + lock.lock(); defer { lock.unlock() } + interfaceResetting = active + // Rate changes can briefly stop callbacks and produce invalid frames. + // Containment stays active, but don't restart the engine mid-reset. + lastBuffer = now + invalidSamples = 0 + healthySince = nil + notBefore = now + 2 + } + + func begin(at now: TimeInterval = ProcessInfo.processInfo.systemUptime, + renewBudget: Bool = false) { + lock.lock(); defer { lock.unlock() } + lastBuffer = now + healthySince = nil + invalidSamples = 0 + notBefore = now + 2 + if renewBudget { attempts = 0 } + } + + /// The callback never waits for the control thread. Missing one observation + /// is harmless: the timeout spans seconds, not individual audio buffers. + func observe(invalid: Int, at now: TimeInterval) { + guard lock.try() else { return } + defer { lock.unlock() } + lastBuffer = now + if invalid > 0 { + invalidSamples += invalid + healthySince = nil + } else if invalidSamples == 0 { + if healthySince == nil { healthySince = now } + if now - (healthySince ?? now) >= 10 { attempts = 0 } + } + } + + /// Claim one bounded recovery. Intentional idle pauses never count as a + /// failure; a route change or wake renews the budget if IO stayed broken. + func recoveryReason(at now: TimeInterval = ProcessInfo.processInfo.systemUptime, + shouldRun: Bool, isRunning: Bool) -> String? { + lock.lock(); defer { lock.unlock() } + guard shouldRun, !interfaceResetting, now >= notBefore, attempts < 3 else { return nil } + let reason: String + if invalidSamples > 0 { + reason = "\(invalidSamples) non-finite output samples" + } else if !isRunning { + reason = "engine stopped unexpectedly" + } else if now - lastBuffer > 2 { + reason = "output callbacks stopped" + } else { + return nil + } + attempts += 1 + notBefore = now + 5 + lastBuffer = now + invalidSamples = 0 + healthySince = nil + return "\(reason) (recovery \(attempts)/3)" + } +} diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index 8bf8cdaeb8..2a00a2287a 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -584,7 +584,7 @@ final class MenuBandPopoverViewController: NSViewController { titleRow.addArrangedSubview(octaveStepper) // hidden, value model only #if !MAC_APP_STORE - titleRow.addArrangedSubview(MenuBandSystemVolumeView()) + if let menuBand { titleRow.addArrangedSubview(MenuBandAirView(control: menuBand.ambientAir)) } #endif // Spacer lives in the middle so the octave widget pins LEFT and diff --git a/slab/menuband/Sources/MenuBand/MenuBandRewindVoice.swift b/slab/menuband/Sources/MenuBand/MenuBandRewindVoice.swift index 12d6e77acd..9f37c8a423 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandRewindVoice.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandRewindVoice.swift @@ -224,6 +224,11 @@ final class MenuBandRewindVoice { let channels = Int(buffer.format.channelCount) let rate = buffer.format.sampleRate if rate <= 0 { return } + // Do not preserve a broken render block in the reverse tape after + // output recovery has cleared the engine's effect history. + for channel in 0.. = [] + private let outputCaptureLock = NSLock() + private var outputCaptureActive = false /// Apple's DLS bank — present on every macOS install since 10.x. private static let bankURL = URL( @@ -799,6 +803,14 @@ final class MenuBandSynth { surfaceCue.attach(to: engine, output: tonesBus) // Air: same bus, so the woosh is echoed and spaced with the notes. airVoice.attach(to: engine, output: tonesBus) + // Listening Air shares the instrument's output without the gesture FX, + // rewind capture, or a second device/tap that could mute playback. + ambientAir.attach(to: engine, output: engine.mainMixerNode) + ambientAir.onLevelChange = { [weak self] level in + guard let self else { return } + if level > 0 { _ = self.resumeAudioEngineIfNeeded() } + else { self.scheduleIdleSuspendIfNeeded() } + } // Percussion: same pre-limiter sum bus. Renders silence until the // right-hand split fires a drum, so it's free while inactive. // Percussion routes to the DRY post-fx mixer, NOT preLimiterMixer — @@ -834,6 +846,11 @@ final class MenuBandSynth { // NOT recaptured and the ring can keep recording continuously // (including notes played WHILE reversing) without a feedback loop. rewindVoice.attach(to: engine) + outputGuard.telemetry = audioTelemetry + outputGuard.attach(to: engine) + // Bind before starting IO so a Scarlett starts on its actual output, + // without first opening AVAudioEngine's private aggregate device. + applyOutputDeviceOverride() engine.prepare() // Request a smaller hardware IO buffer BEFORE the engine starts, // so the first render cycle is already at the low-latency size. @@ -844,6 +861,7 @@ final class MenuBandSynth { // channel-map write, so the persisted monitor-channel pick lands // here (no-op unless the user ever picked one). applyInputChannelMap() + installWaveformTapIfNeeded() do { try engine.start() started = true @@ -857,6 +875,8 @@ final class MenuBandSynth { // the graph. Idempotent per unit. MenuBandMonoFold.enabled = UserDefaults.standard.bool(forKey: "notepat.monoOutput") MenuBandMonoFold.install(on: engine, label: "synth") + audioTelemetry.attachHardwareProbe(to: engine) + audioTelemetry.start { [weak self] in self?.audioDiagnosticSnapshot() ?? [:] } // Dedicated rewind-capture tap on the limiter (pre-mainMixer, so the // reverse playback is excluded). Always-on: the ring keeps recording // everything the user plays, even while a reverse is sounding. @@ -934,7 +954,14 @@ final class MenuBandSynth { engineLock.lock() defer { engineLock.unlock() } guard started else { return } + if interfaceResetting { + audioTelemetry.event("configuration_change_deferred") + configurationChangeDeferredForReset = true + return + } audioConfigEpoch &+= 1 + audioTelemetry.event("configuration_change", ["epoch": audioConfigEpoch]) + idleSuspended = false NSLog("MenuBand: audio engine configuration changed (device switch \(audioConfigEpoch)) — recovering") // Mark the bank dirty no matter which recovery branch runs below — // the immediate reapply can be overwritten as the reconfig settles, @@ -951,6 +978,8 @@ final class MenuBandSynth { // input AUHAL only accepts in this stopped window. syncInputMonitorGraph() applyInputChannelMap() + applyOutputDeviceOverride() + outputGuard.health.begin() do { try engine.start() } catch { NSLog("MenuBand: engine start after device change failed: \(error)") } } @@ -1004,7 +1033,7 @@ final class MenuBandSynth { // Another switch landed while we waited — the device is still moving. // Re-arm for the newer epoch so the preload only runs once a full // settle window passes with no further change. - if armedEpoch != audioConfigEpoch { + if interfaceResetting || armedEpoch != audioConfigEpoch { armMIDISynthRebuildTimer() return } @@ -1013,6 +1042,7 @@ final class MenuBandSynth { if !engine.isRunning { syncInputMonitorGraph() applyInputChannelMap() + applyOutputDeviceOverride() do { try engine.start() } catch { NSLog("MenuBand: engine start before MIDISynth rebuild failed: \(error)") } } @@ -1506,14 +1536,18 @@ final class MenuBandSynth { // is true, so `engine.isRunning` short-circuits below. engineLock.lock() defer { engineLock.unlock() } + guard !interfaceResetting else { return engine.isRunning } idleSuspendWorkItem?.cancel() idleSuspendWorkItem = nil + if !idleSuspended { recoverPlaybackIfNeeded() } + idleSuspended = false if engine.isRunning { return true } do { - try engine.start() applyOutputDeviceOverride() + outputGuard.health.begin() + try engine.start() // MIDISynth's per-channel program is unreliable across an // engine pause→start cycle — coming back from idle-suspend // (or any other engine restart) can leave each channel @@ -1602,7 +1636,7 @@ final class MenuBandSynth { private func scheduleIdleSuspendIfNeeded() { guard started, !waveformCaptureEnabled, waveformTapPinReasons.isEmpty, !keepEngineWarm, activeNotes.isEmpty, - !sampleRecordingActive, !inputMonitor.isAttached else { return } + !sampleRecordingActive, !inputMonitor.isAttached, ambientAir.level == 0 else { return } idleSuspendWorkItem?.cancel() let workItem = DispatchWorkItem { [weak self] in self?.suspendAudioEngineForHiddenIdleIfNeeded() @@ -1619,9 +1653,10 @@ final class MenuBandSynth { // (AVAudioPlayerNode.play() then throws — two crashes on 2026-09-25). guard started, engine.isRunning, !waveformCaptureEnabled, waveformTapPinReasons.isEmpty, activeNotes.isEmpty, - !sampleRecordingActive, !keepEngineWarm, !inputMonitor.isAttached else { return } - removeWaveformTapIfNeeded() + !sampleRecordingActive, !keepEngineWarm, !inputMonitor.isAttached, + ambientAir.level == 0 else { return } engine.pause() + idleSuspended = true } /// True between `startSampleRecording` and `stopSampleRecording` — @@ -1740,38 +1775,15 @@ final class MenuBandSynth { /// AVAudioEngine's AUHAL layer bypasses Multi-Output / Aggregate devices /// and connects directly to the underlying clock-source hardware device, /// so audio never reaches secondary members (e.g. BlackHole). Explicitly - /// setting CurrentDevice after every engine start forces the engine to + /// setting CurrentDevice before startup and after recovery forces the engine to /// honour the full virtual device and its routing. The device is the /// user's pinned output pick when one is set, otherwise the system /// default (the original behavior). private func applyOutputDeviceOverride() { - // With the duplex monitor wired, AVAudioEngine hosts input + output - // on a PRIVATE AGGREGATE device even when both sides are the same - // interface (frisbee, 2026-09-25: engine on 122 while the Scarlett - // itself was 88). Re-binding the output AU to the raw device then - // silences the whole engine — no synth, no monitor — so leave the - // aggregate alone; `duplexMonitorEligible` already guarantees it - // resolves to the user's pick (or the default) on both sides. + // Monitoring has its own input-only AUHAL. Playback can bind directly + // to the selected output without a private input/output aggregate. guard let au = engine.outputNode.audioUnit else { return } - var deviceID = AudioDeviceID(0) - // A user pick from the headphone icon's right-click menu wins over - // the system default — but only while that device is actually - // attached; a stale pin (interface unplugged) falls through to the - // default so the engine never binds into a void. - if let uid = MenuBandAudioDevices.pinnedOutputUID, - let pinned = MenuBandAudioDevices.device(uid: uid), - pinned.outputChannels > 0 { - deviceID = pinned.id - } else { - var addr = AudioObjectPropertyAddress( - mSelector: kAudioHardwarePropertyDefaultOutputDevice, - mScope: kAudioObjectPropertyScopeGlobal, - mElement: kAudioObjectPropertyElementMain) - var size = UInt32(MemoryLayout.size) - guard AudioObjectGetPropertyData( - AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &deviceID - ) == noErr, deviceID != 0 else { return } - } + guard var deviceID = MenuBandAudioDevices.preferredOutputID() else { return } // Skip the write when the AU is already bound to the default device — // a redundant CurrentDevice set can still emit a configuration-change // notification, and this is called from the settle-window rebuild @@ -1793,20 +1805,68 @@ final class MenuBandSynth { } } - /// Auto-recovery, part 1: every 5 s, make sure the device the engine - /// renders into still exists. After a USB blink the interface can come - /// back under a new id while this process keeps a ghost of the old one - /// (frisbee, 2026-09-25: engine on 142, the live Scarlett was 89 — silence - /// while every meter looked healthy). A ghost → the normal device-switch - /// recovery, which rebinds output and monitor to the live device. + /// Check both device existence and the current route. A USB blink can + /// leave a ghost ID, or a valid speaker fallback after the interface + /// returns. Both need the normal device-switch recovery. private var bindingAuditTimer: DispatchSourceTimer? private var bindingAuditStrikes = 0 - /// A real device-list change gives the audit its tries back. + private var interfaceResetting = false + private var configurationChangeDeferredForReset = false + var onPlaybackRecovered: (() -> Void)? + + func setInterfaceResetting(_ active: Bool) { + engineLock.lock(); defer { engineLock.unlock() } + audioTelemetry.event("interface_reset", ["active": active]) + interfaceResetting = active + outputGuard.health.setInterfaceResetting(active) + if !active, configurationChangeDeferredForReset { + configurationChangeDeferredForReset = false + handleEngineConfigurationChange() + } + } + /// A device-list or default-output change gives the audit its tries back. func resetBindingAudit() { + engineLock.lock(); defer { engineLock.unlock() } bindingAuditStrikes = 0 + outputGuard.health.begin(renewBudget: true) inputMonitor.resetRecoveryForDeviceChange() } + /// Wake can leave a valid device binding with stopped or stale IO. Allow + /// hardware to settle, then verify real render callbacks with the audit. + func systemDidWake() { + engineLock.lock(); defer { engineLock.unlock() } + guard started else { return } + resetBindingAudit() + auditBindings() + if !idleSuspended && !engine.isRunning { handleEngineConfigurationChange() } + } + + private func recoverPlaybackIfNeeded() { + guard started, let reason = outputGuard.health.recoveryReason( + shouldRun: !idleSuspended, isRunning: engine.isRunning) else { return } + NSLog("MenuBand: playback unhealthy — \(reason); restarting audio on the current output") + audioTelemetry.event("playback_recovery", ["reason": reason]) + engine.stop() + // Clear poisoned effect history as well as the stopped hardware IO. + // Custom source-node voices own their state outside AVAudioEngine. + panic() + rewindVoice.release() + engine.reset() + audioConfigEpoch &+= 1 + midiSynthBankDirty = true + applyOutputDeviceOverride() + do { + try engine.start() + reapplyCurrentPrograms() + } catch { + NSLog("MenuBand: playback recovery failed: \(error)") + } + scheduleMIDISynthRebuild() + logAudioBindings(context: "playback recovery") + DispatchQueue.main.async { [weak self] in self?.onPlaybackRecovered?() } + } + /// After a plug-in/unplug: if the monitor is open on a device that the /// automatic/pinned pick no longer resolves to (the laptop mic while a /// Scarlett just arrived), reopen it on the right one. @@ -1826,27 +1886,35 @@ final class MenuBandSynth { t.resume() bindingAuditTimer = t } - private func auditBindings() { + func auditBindings() { + engineLock.lock(); defer { engineLock.unlock() } + guard !interfaceResetting else { return } + recoverPlaybackIfNeeded() guard started, let au = engine.outputNode.audioUnit else { return } var outID = AudioDeviceID(0) var size = UInt32(MemoryLayout.size) guard AudioUnitGetProperty(au, kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, 0, &outID, &size) == noErr, outID != 0 else { return } + kAudioUnitScope_Global, 0, &outID, &size) == noErr else { return } let live = MenuBandAudioDevices.all() + guard !live.isEmpty else { return } // CoreAudio may be restarting. + let target = MenuBandAudioDevices.outputTargetID( + devices: live, pinnedUID: MenuBandAudioDevices.pinnedOutputUID, + systemDefaultID: MenuBandAudioDevices.systemDefaultOutputID()) + let wrongOutput = target.map { $0 != outID } ?? false let ghost = !live.contains { $0.id == outID } let monitorGhost = inputMonitor.isAttached && !live.contains { $0.id == inputMonitor.boundDeviceID } - if ghost || monitorGhost { + if wrongOutput || ghost || monitorGhost { bindingAuditStrikes += 1 // Three tries, then stop hammering: a recovery that can't shake // the ghost restarts the engine every 5 s forever (4,857 times // one morning). The next real device-list change resets this. guard bindingAuditStrikes <= 3 else { if bindingAuditStrikes == 4 { - NSLog("MenuBand audit: ghost persists after 3 recoveries — backing off until the device list changes") + NSLog("MenuBand audit: binding mismatch persists after 3 recoveries — backing off until the route changes") } return } - NSLog("MenuBand audit: bound device is a ghost (output \(outID) ghost=\(ghost), monitor \(inputMonitor.boundDeviceID) ghost=\(monitorGhost)); strike \(bindingAuditStrikes) — running device-switch recovery") + NSLog("MenuBand audit: binding mismatch (output \(outID), target \(target ?? 0), ghost=\(ghost); monitor \(inputMonitor.boundDeviceID) ghost=\(monitorGhost)); strike \(bindingAuditStrikes) — running device-switch recovery") handleEngineConfigurationChange() } else { bindingAuditStrikes = 0 @@ -1857,15 +1925,53 @@ final class MenuBandSynth { /// name, plus the monitor's input device — the first thing to read when /// the interface flaps and the app goes quiet. func logAudioBindings(context: String) { + engineLock.lock(); defer { engineLock.unlock() } var outID = AudioDeviceID(0) + var renderError: OSStatus = noErr var size = UInt32(MemoryLayout.size) if let au = engine.outputNode.audioUnit { AudioUnitGetProperty(au, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &outID, &size) + var errorSize = UInt32(MemoryLayout.size) + AudioUnitGetProperty(au, kAudioUnitProperty_LastRenderError, + kAudioUnitScope_Global, 0, &renderError, &errorSize) } let outName = MenuBandAudioDevices.all().first { $0.id == outID }?.name ?? "(not in device list)" let sysOut = MenuBandAudioDevices.systemDefaultOutputID() ?? 0 - NSLog("MenuBand bindings \(context): engine output → \(outID) \(outName); system default output \(sysOut); running=\(engine.isRunning); monitor input → \(inputMonitor.boundDeviceDescription)") + NSLog("MenuBand bindings \(context): engine output → \(outID) \(outName); system default output \(sysOut); running=\(engine.isRunning); renderError=\(renderError); rate=\(MenuBandAudioDevices.nominalRate(of: outID)); monitor input → \(inputMonitor.boundDeviceDescription)") + audioTelemetry.event("bindings", ["context": context, "outputDevice": outID, + "defaultOutput": sysOut, "running": engine.isRunning, "renderError": renderError]) + } + + private func audioDiagnosticSnapshot() -> [String: Any] { + guard engineLock.try() else { return ["controlBusy": true] } + defer { engineLock.unlock() } + var output: AudioDeviceID = 0 + var error: OSStatus = noErr + var size = UInt32(MemoryLayout.size) + if let au = engine.outputNode.audioUnit { + AudioUnitGetProperty(au, kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, 0, &output, &size) + size = UInt32(MemoryLayout.size) + AudioUnitGetProperty(au, kAudioUnitProperty_LastRenderError, + kAudioUnitScope_Global, 0, &error, &size) + } + let gains: [String: Float] = ["master": postFxMixer.outputVolume, + "tones": tonesFader.outputVolume, "percussion": percFader.outputVolume, + "duck": melodicDuckMixer.outputVolume, "headroom": preLimiterMixer.outputVolume, + "dry": dryFxMixer.outputVolume, "echoSend": echoSendMixer.outputVolume, + "reverbSend": reverbSendMixer.outputVolume, "air": ambientAir.level] + return ["outputDevice": output, "running": engine.isRunning, + "idleSuspended": idleSuspended, "renderError": error, + "resetting": interfaceResetting, "epoch": audioConfigEpoch, + "monitorInputDevice": inputMonitor.boundDeviceID, + "monitorWanted": inputMonitoringWanted, "monitorFocusMuted": monitorFocusMuted, + "program": currentMelodicProgram, + "backend": usingACPianoVoice ? "acPiano" : usingWhistleVoice ? "whistle" : + usingCompositeVoice ? "composite" : usingFluoddityVoice ? "fluoddity" : + usingSampleBackend ? "sample" : usingPluginInstrument ? "plugin" : + gmRoutable(currentMelodicProgram) ? "acGM" : "midiSynth", + "gains": gains.mapValues { $0.isFinite ? Double($0) as Any : String(describing: $0) as Any }] } // MARK: - Device picks (headphone icon right-click menu) @@ -2158,51 +2264,67 @@ final class MenuBandSynth { // MARK: - Audio tap for visualizer func setWaveformCaptureEnabled(_ enabled: Bool) { + engineLock.lock(); defer { engineLock.unlock() } guard started else { return } waveformCaptureEnabled = enabled + updateOutputCaptureGate() if enabled { guard resumeAudioEngineIfNeeded() else { waveformCaptureEnabled = false + updateOutputCaptureGate() return } - installWaveformTapIfNeeded() } else if waveformTapPinReasons.isEmpty { - removeWaveformTapIfNeeded() scheduleIdleSuspendIfNeeded() } } - /// Pin the mainMixer tap on for a reason (currently: the tape - /// recorder needs the synth output stream while RECORDING or - /// PLAYING). Idempotent. Pair with `removeWaveformTapPin` so the - /// tap goes away once both the visualizer AND every pin reason - /// have released it. + /// Keep output delivery active for recording, playback, or room audio, + /// independently of any visible waveform. The taps themselves stay put. func addWaveformTapPin(_ reason: String) { + engineLock.lock(); defer { engineLock.unlock() } guard started else { return } let wasEmpty = waveformTapPinReasons.isEmpty waveformTapPinReasons.insert(reason) + updateOutputCaptureGate() if wasEmpty { _ = resumeAudioEngineIfNeeded() - installWaveformTapIfNeeded() } } func removeWaveformTapPin(_ reason: String) { + engineLock.lock(); defer { engineLock.unlock() } waveformTapPinReasons.remove(reason) + updateOutputCaptureGate() if waveformTapPinReasons.isEmpty && !waveformCaptureEnabled { - removeWaveformTapIfNeeded() scheduleIdleSuspendIfNeeded() } } + private func updateOutputCaptureGate() { + outputCaptureLock.lock() + outputCaptureActive = waveformCaptureEnabled || !waveformTapPinReasons.isEmpty + outputCaptureLock.unlock() + } + + private func shouldDeliverOutputCapture() -> Bool { + // Never block rendering. A coincident UI change may deliver one + // extra buffer; recording consumers still apply their own gates. + guard outputCaptureLock.try() else { return true } + defer { outputCaptureLock.unlock() } + return outputCaptureActive + } + private func installWaveformTapIfNeeded() { guard !waveformTapInstalled else { return } let mixer = engine.mainMixerNode - let format = mixer.outputFormat(forBus: 0) // 256 frames ≈ 5.8 ms at 44.1 kHz — small buffer = fresh samples // for the visualizer without burning the audio thread. - mixer.installTap(onBus: 0, bufferSize: 256, format: format) { [weak self] buffer, _ in - self?.ingestWaveformBuffer(buffer) + mixer.installTap(onBus: 0, bufferSize: 256, format: nil) { [weak self] buffer, _ in + guard let self else { return } + if self.audioTelemetry.enabled { self.audioTelemetry.mix.observe(buffer) } + guard self.shouldDeliverOutputCapture() else { return } + self.ingestWaveformBuffer(buffer) } waveformTapInstalled = true installStemTapsIfNeeded() @@ -2218,17 +2340,17 @@ final class MenuBandSynth { /// Pre-fader taps on the tones + percussion buses — the tape's raw stems. private func installStemTapsIfNeeded() { guard !stemTapsInstalled else { return } - let tf = tonesBus.outputFormat(forBus: 0) - let pf = percBus.outputFormat(forBus: 0) - guard tf.channelCount > 0, pf.channelCount > 0 else { - NSLog("MenuBand: stem taps skipped — bus format not negotiated yet") - return - } - tonesBus.installTap(onBus: 0, bufferSize: 256, format: tf) { [weak self] buffer, _ in - self?.onTonesBuffer?(buffer) + tonesBus.installTap(onBus: 0, bufferSize: 256, format: nil) { [weak self] buffer, _ in + guard let self else { return } + if self.audioTelemetry.enabled { self.audioTelemetry.tones.observe(buffer) } + guard self.shouldDeliverOutputCapture() else { return } + self.onTonesBuffer?(buffer) } - percBus.installTap(onBus: 0, bufferSize: 256, format: pf) { [weak self] buffer, _ in - self?.onPercussionBuffer?(buffer) + percBus.installTap(onBus: 0, bufferSize: 256, format: nil) { [weak self] buffer, _ in + guard let self else { return } + if self.audioTelemetry.enabled { self.audioTelemetry.percussion.observe(buffer) } + guard self.shouldDeliverOutputCapture() else { return } + self.onPercussionBuffer?(buffer) } stemTapsInstalled = true } @@ -2822,6 +2944,10 @@ final class MenuBandSynth { func stop() { engineLock.lock(); defer { engineLock.unlock() } + bindingAuditTimer?.cancel() + bindingAuditTimer = nil + ambientAir.onLevelChange = nil + ambientAir.setLevel(0) // The microphone uses SampleVoice's separate input-only engine, so it // must be torn down even if the synth output engine never started or // has already stopped. This is synchronous: application termination @@ -2848,13 +2974,14 @@ final class MenuBandSynth { } idleSuspendWorkItem?.cancel() idleSuspendWorkItem = nil - removeWaveformTapIfNeeded() // Release the device BEFORE stopping the engine so other apps // see the unhog event before they try to recover. Stopping the // engine first would leave a brief window where the device is // ours-but-idle, and Music.app etc. tend to give up retrying. releaseHogModeIfNeeded() engine.stop() + audioTelemetry.stop() + removeWaveformTapIfNeeded() melodicHeadroomTimer?.invalidate() melodicHeadroomTimer = nil melodicHeadroom.reset() @@ -2891,6 +3018,7 @@ final class MenuBandSynth { /// node wants. func playPercussion(_ drum: MenuBandPercussion.Drum, velocity: UInt8, pan: UInt8) { guard started else { return } + audioTelemetry.trigger(percussion: true) // Drums don't register in `activeNotes`, so the idle-suspend logic // would otherwise leave the engine paused and the hit silent. Wake // it (and cancel any pending suspend) before staging the voices. @@ -2921,6 +3049,7 @@ final class MenuBandSynth { /// two-finger upper-half gesture. func playReverseKick(velocity: UInt8, pan: UInt8) { guard started else { return } + audioTelemetry.trigger(percussion: true) _ = resumeAudioEngineIfNeeded() rewindVoice.resetReverseAnchor() let p = max(-1.0, min(1.0, (Double(pan) - 64.0) / 63.0)) @@ -2931,6 +3060,7 @@ final class MenuBandSynth { func playDrumSkin(strike: CGPoint, anchors: [CGPoint], velocity: UInt8) { guard started else { return } + audioTelemetry.trigger(percussion: true) _ = resumeAudioEngineIfNeeded() rewindVoice.resetReverseAnchor() let zone = MenuBandPercussion.drumSkinZone(at: strike) @@ -2944,6 +3074,7 @@ final class MenuBandSynth { func playSynthSurface(strike: CGPoint, anchors: [CGPoint], velocity: UInt8) { guard started else { return } + audioTelemetry.trigger(percussion: true) _ = resumeAudioEngineIfNeeded() rewindVoice.resetReverseAnchor() let zone = MenuBandPercussion.drumSkinZone(at: strike) @@ -2956,6 +3087,7 @@ final class MenuBandSynth { func playSurfaceLift(at point: CGPoint, anchors: [CGPoint], velocity: UInt8, synthetic: Bool) { guard started else { return } + audioTelemetry.trigger(percussion: true) _ = resumeAudioEngineIfNeeded() rewindVoice.resetReverseAnchor() triggerMelodicDuck(depth: 0.10, velocity: velocity, hold: 0.04) @@ -2987,6 +3119,7 @@ final class MenuBandSynth { func percussionNoteOn(_ drum: MenuBandPercussion.Drum, velocity: UInt8, pan: UInt8, accent: Bool = false) -> UInt64 { guard started else { return 0 } + audioTelemetry.trigger(percussion: true) // Warm path (split armed): the engine is already running and won't // idle-suspend, so skip the resume lock AND the idle reschedule — // the only work on a hit is staging the voices. Cold path keeps the @@ -3065,6 +3198,7 @@ final class MenuBandSynth { func noteOn(_ midi: UInt8, velocity: UInt8 = 100, channel: UInt8 = 0) { guard started else { return } guard resumeAudioEngineIfNeeded() else { return } + audioTelemetry.trigger(percussion: channel == 9) onNoteEvent?(midi, velocity, true, channel, channelPan[Int(channel & 0x0F)]) // Roomward: every sounding note also pulses the DMX fixture (no-op // without a widget). Hooked here, past the guards, so the light @@ -3237,7 +3371,8 @@ final class MenuBandSynth { /// default IO size; put the user's pick back on it. func reassertMonitorIOBuffer() { engineLock.lock(); defer { engineLock.unlock() } - guard started, inputMonitor.isAttached else { return } + guard started, inputMonitor.isAttached, + !MenuBandAudioDevices.interfaceResetInProgress else { return } forceIOBufferFrames(Self.monitorIOBufferFrames) inputMonitor.preferredIOBufferFrames = Self.monitorIOBufferFrames inputMonitor.assertDeviceBuffer() diff --git a/slab/menuband/Sources/MenuBand/MenuBandSystemVolume.swift b/slab/menuband/Sources/MenuBand/MenuBandSystemVolume.swift deleted file mode 100644 index 740722ebc4..0000000000 --- a/slab/menuband/Sources/MenuBand/MenuBandSystemVolume.swift +++ /dev/null @@ -1,441 +0,0 @@ -import AppKit -import CoreAudio -import AudioToolbox - -/// A separate process keeps the playback callback out of its own tap while -/// still capturing every Menu Band engine. No audio is recorded or networked. -#if !MAC_APP_STORE -@available(macOS 14.2, *) -final class MenuBandSystemVolumeHelper { - private var device: AudioDeviceID = 0 - private var aggregate: AudioDeviceID = 0 - private var tap: AudioObjectID = 0 - private var primer: AudioDeviceIOProcID? - private var render: AudioDeviceIOProcID? - private let gainLock = NSLock() - private var requestedGain: Float = 0.25 - private var renderGain: Float = 0.25 - private var targetGain: Float = 0.25 - private var requestedAir: Float = 0 - private var targetAir: Float = 0 - private var renderAir: Float = 0 - private var requestedColor: MenuBandAirColor = .cabin - private var color: MenuBandAirColor = .cabin - private var requestedCutoff = MenuBandAirNoise.defaultCutoff - private var cutoff = MenuBandAirNoise.defaultCutoff - private var noise = MenuBandAirNoise() - private var physicalInputChannels = 0 - private var sampleRate: Double = 44100 - - init(inputChannels: Int = 0, gain: Float = 0.25, sampleRate: Double = 44100) { - physicalInputChannels = inputChannels - self.sampleRate = sampleRate - let initial: Float = gain.isFinite ? max(0, min(1, gain)) : 0.25 - requestedGain = initial; renderGain = initial; targetGain = initial - } - - enum Failure: LocalizedError { - case message(String) - var errorDescription: String? { if case .message(let text) = self { return text }; return nil } - } - private func check(_ status: OSStatus, _ operation: String) throws { - guard status == noErr else { throw Failure.message("\(operation) (\(status))") } - } - private func read(_ id: AudioObjectID, _ selector: AudioObjectPropertySelector, - _ initial: T, scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal) throws -> T { - var address = AudioObjectPropertyAddress(mSelector: selector, mScope: scope, mElement: 0) - var size = UInt32(MemoryLayout.size), result = initial - try withUnsafeMutableBytes(of: &result) { - try check(AudioObjectGetPropertyData(id, &address, 0, nil, &size, $0.baseAddress!), "Read audio property") - } - return result - } - private func channels(_ id: AudioDeviceID, _ scope: AudioObjectPropertyScope) throws -> Int { - var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreamConfiguration, mScope: scope, mElement: 0) - var bytes: UInt32 = 0 - try check(AudioObjectGetPropertyDataSize(id, &address, 0, nil, &bytes), "Read channel count") - let storage = UnsafeMutableRawPointer.allocate(byteCount: Int(bytes), alignment: MemoryLayout.alignment) - defer { storage.deallocate() } - try check(AudioObjectGetPropertyData(id, &address, 0, nil, &bytes, storage), "Read channels") - return UnsafeMutableAudioBufferListPointer(storage.assumingMemoryBound(to: AudioBufferList.self)).reduce(0) { $0 + Int($1.mNumberChannels) } - } - private func validateOutputFormat(_ id: AudioDeviceID) throws { - var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreams, - mScope: kAudioDevicePropertyScopeOutput, mElement: 0) - var bytes: UInt32 = 0 - try check(AudioObjectGetPropertyDataSize(id, &address, 0, nil, &bytes), "Read output streams") - var streams = [AudioStreamID](repeating: 0, count: Int(bytes) / MemoryLayout.size) - try check(AudioObjectGetPropertyData(id, &address, 0, nil, &bytes, &streams), "Read output streams") - for stream in streams { - let format = try read(stream, kAudioStreamPropertyVirtualFormat, AudioStreamBasicDescription()) - guard format.mFormatID == kAudioFormatLinearPCM, - format.mFormatFlags & kAudioFormatFlagIsFloat != 0, - format.mFormatFlags & kAudioFormatFlagIsBigEndian == 0, - format.mBitsPerChannel == 32 else { - throw Failure.message("The output does not provide native Float32 audio") - } - } - } - func setGain(_ value: Float) { - guard value.isFinite else { return } - gainLock.lock(); requestedGain = max(0, min(1, value)); gainLock.unlock() - } - func setAir(_ value: Float, color: MenuBandAirColor, cutoff: Double = MenuBandAirNoise.defaultCutoff) { - guard value.isFinite else { return } - gainLock.lock() - requestedAir = max(0, min(1, value)); requestedColor = color - if cutoff.isFinite { requestedCutoff = max(60, min(6000, cutoff)) } - gainLock.unlock() - } - func start(uid: String, gain: Float) throws { - setGain(gain); renderGain = requestedGain; targetGain = requestedGain - device = try read(AudioObjectID(kAudioObjectSystemObject), kAudioHardwarePropertyDefaultOutputDevice, AudioDeviceID(0)) - let actualUID: CFString? = try read(device, kAudioDevicePropertyDeviceUID, Optional.none) - guard actualUID as String? == uid else { throw Failure.message("System output changed; enable volume again") } - guard try channels(device, kAudioDevicePropertyScopeOutput) == 2 else { - throw Failure.message("System volume currently supports stereo outputs") - } - physicalInputChannels = try channels(device, kAudioDevicePropertyScopeInput) - sampleRate = try read(device, kAudioDevicePropertyNominalSampleRate, Double(44100)) - // Register this helper as an audio process before resolving its ID. - try check(AudioDeviceCreateIOProcIDWithBlock(&primer, device, nil) { _, _, _, output, _ in - for buffer in UnsafeMutableAudioBufferListPointer(output) { - if let data = buffer.mData { memset(data, 0, Int(buffer.mDataByteSize)) } - } - }, "Prepare output") - try check(AudioDeviceStart(device, primer), "Start output") - var pid = getpid(), process = AudioObjectID(0), bytes = UInt32(MemoryLayout.size) - var address = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyTranslatePIDToProcessObject, - mScope: kAudioObjectPropertyScopeGlobal, mElement: 0) - try check(AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, - UInt32(MemoryLayout.size), &pid, &bytes, &process), "Identify volume helper") - guard process != 0 else { throw Failure.message("Could not exclude output helper from capture") } - let description = CATapDescription(excludingProcesses: [process], deviceUID: uid, stream: 0) - description.name = "Menu Band System Volume" - description.uuid = UUID(); description.isPrivate = true - description.muteBehavior = .mutedWhenTapped - try check(AudioHardwareCreateProcessTap(description, &tap), "Allow Menu Band system audio access") - let format = try read(tap, kAudioTapPropertyFormat, AudioStreamBasicDescription()) - guard format.mFormatID == kAudioFormatLinearPCM, - format.mFormatFlags & kAudioFormatFlagIsFloat != 0, - format.mBitsPerChannel == 32, format.mChannelsPerFrame == 2 else { - throw Failure.message("The output tap did not provide stereo Float32 audio") - } - let spec: [String: Any] = [ - kAudioAggregateDeviceNameKey: "Menu Band System Volume", - kAudioAggregateDeviceUIDKey: "computer.aesthetic.menuband.volume.\(UUID().uuidString)", - kAudioAggregateDeviceIsPrivateKey: true, - kAudioAggregateDeviceIsStackedKey: false, - kAudioAggregateDeviceMainSubDeviceKey: uid, - kAudioAggregateDeviceSubDeviceListKey: [[kAudioSubDeviceUIDKey: uid]], - kAudioAggregateDeviceTapAutoStartKey: true, - kAudioAggregateDeviceTapListKey: [[kAudioSubTapUIDKey: description.uuid.uuidString, - kAudioSubTapDriftCompensationKey: true]], - ] - try check(AudioHardwareCreateAggregateDevice(spec as CFDictionary, &aggregate), "Prepare system volume") - // Physical inputs precede the tap. Never copy the microphone channels. - let inputs = try channels(aggregate, kAudioDevicePropertyScopeInput) - guard inputs == physicalInputChannels + 2, - try channels(aggregate, kAudioDevicePropertyScopeOutput) == 2 else { - throw Failure.message("Unexpected system-volume channel layout") - } - try validateOutputFormat(aggregate) - // Run directly on the HAL audio thread; a dispatch hop adds scheduling - // jitter to every device cycle, especially at very small IO buffers. - try check(AudioDeviceCreateIOProcIDWithBlock(&render, aggregate, nil) { [weak self] _, input, _, output, _ in - self?.process(input: input, output: output) - }, "Prepare volume callback") - try check(AudioDeviceStart(aggregate, render), "Start system volume") - } - func process(input: UnsafePointer, output: UnsafeMutablePointer) { - // No allocation or blocking lock on the audio callback. A slider write - // that overlaps this buffer is simply picked up by the next buffer. - if gainLock.try() { - targetGain = requestedGain; targetAir = requestedAir; color = requestedColor; cutoff = requestedCutoff - gainLock.unlock() - } - let ins = UnsafeMutableAudioBufferListPointer(UnsafeMutablePointer(mutating: input)) - let outs = UnsafeMutableAudioBufferListPointer(output) - for buffer in outs { if let data = buffer.mData { memset(data, 0, Int(buffer.mDataByteSize)) } } - var channelOffset = 0 - for source in ins { - let width = Int(source.mNumberChannels) - defer { channelOffset += width } - guard width > 0, let data = source.mData else { continue } - let frames = Int(source.mDataByteSize) / (4 * width) - for channel in 0..= offset, stereoChannel < offset + outWidth, - let outData = destination.mData else { continue } - let count = min(frames, Int(destination.mDataByteSize) / (4 * outWidth)) - let src = data.assumingMemoryBound(to: Float.self) - let dst = outData.assumingMemoryBound(to: Float.self) - for frame in 0.. 0 && destination.mData != nil { - frames = min(frames, Int(destination.mDataByteSize) / (4 * Int(destination.mNumberChannels))) - } - if frames == Int.max { frames = 0 } - let gainStep: Float = 1 / Float(max(1, sampleRate * 0.015)) - let airStep: Float = 1 / Float(max(1, sampleRate * 0.25)) - for frame in 0.. 0 - ? noise.next(color: color, sampleRate: sampleRate, cutoff: cutoff) * renderAir * renderAir * 0.12 : 0 - for destination in outs { - guard let data = destination.mData else { continue } - let width = Int(destination.mNumberChannels) - let samples = data.assumingMemoryBound(to: Float.self) - for channel in 0.. Bool { - guard args.count > 1, args[1] == "--system-volume-helper" else { return false } - guard args.count == 4, let gain = Float(args[3]), gain.isFinite else { return true } - let helper = MenuBandSystemVolumeHelper() - do { - try helper.start(uid: args[2], gain: gain) - print("READY"); fflush(stdout) - // EOF ties lifetime to the UI parent. A crash/quit cannot strand - // the mute tap. The helper never persists a system routing change. - while let line = readLine() { - if line == "STOP" { break } - let parts = line.split(separator: " ") - if parts.count == 4, parts[0] == "AIR", - let color = MenuBandAirColor(rawValue: String(parts[1])), let value = Float(parts[2]), - let cutoff = Double(parts[3]) { - helper.setAir(value, color: color, cutoff: cutoff); continue - } - if let value = Float(line) { helper.setGain(value) } - } - } catch { - print("ERROR \(error.localizedDescription)"); fflush(stdout) - } - helper.stop() - return true - } -} - -final class MenuBandSystemVolume: NSObject { - static let shared = MenuBandSystemVolume() - private var helper: Process? - private var commands: FileHandle? - private var response = "" - private var output: FileHandle? - private var deviceUID: String? - private var deviceRate: Double = 0 - private var watchdog: Timer? - private(set) var active = false - private(set) var starting = false - private(set) var error: String? - private(set) var gain: Float = 0.25 - private(set) var airLevel: Float = 0 - private(set) var airColor = MenuBandAirColor(rawValue: UserDefaults.standard.string(forKey: "systemAirColor") ?? "") ?? .cabin - private(set) var airCutoff: Double = { - let saved = UserDefaults.standard.double(forKey: "systemAirCutoff") - return saved.isFinite && saved >= 60 ? min(6000, saved) : MenuBandAirNoise.defaultCutoff - }() - var onChange: (() -> Void)? - - func setGain(_ value: Float) { - guard value.isFinite else { return } - gain = max(0, min(1, value)) - if let deviceUID { UserDefaults.standard.set(gain, forKey: "systemVolume.\(deviceUID)") } - do { try commands?.write(contentsOf: Data("\(gain)\n".utf8)) } - catch { stop(); self.error = "System volume disconnected" } - onChange?() - } - func setAir(_ value: Float, color: MenuBandAirColor? = nil) { - guard value.isFinite else { return } - airLevel = max(0, min(1, value)) - if let color { airColor = color; UserDefaults.standard.set(color.rawValue, forKey: "systemAirColor") } - do { try commands?.write(contentsOf: Data("AIR \(airColor.rawValue) \(airLevel) \(airCutoff)\n".utf8)) } - catch { stop(); self.error = "System volume disconnected" } - onChange?() - } - func setAirCutoff(_ value: Double) { - guard value.isFinite else { return } - airCutoff = max(60, min(6000, value)) - UserDefaults.standard.set(airCutoff, forKey: "systemAirCutoff") - setAir(airLevel) - } - func start() { - guard helper == nil else { return } - guard #available(macOS 14.2, *) else { error = "Requires macOS 14.2 or newer"; onChange?(); return } - guard let id = MenuBandAudioDevices.systemDefaultOutputID(), - let device = MenuBandAudioDevices.all().first(where: { $0.id == id }), - let executable = Bundle.main.executableURL else { return } - deviceUID = device.uid - deviceRate = MenuBandAudioDevices.nominalRate(of: id) - signal(SIGPIPE, SIG_IGN) // A stopped helper turns writes into errors, not an app crash. - let key = "systemVolume.\(device.uid)" - gain = UserDefaults.standard.object(forKey: key) == nil ? 0.25 : Float(UserDefaults.standard.double(forKey: key)) - gain = gain.isFinite ? max(0, min(1, gain)) : 0.25 - let process = Process(), input = Pipe(), output = Pipe() - process.executableURL = executable - process.arguments = ["--system-volume-helper", device.uid, String(gain)] - process.standardInput = input; process.standardOutput = output - self.output = output.fileHandleForReading - self.commands = input.fileHandleForWriting - response = ""; error = nil; starting = true; helper = process - output.fileHandleForReading.readabilityHandler = { [weak self, weak process] handle in - let data = handle.availableData - guard !data.isEmpty else { handle.readabilityHandler = nil; return } - DispatchQueue.main.async { - guard let self, let process, self.helper === process else { return } - self.receive(String(decoding: data, as: UTF8.self)) - } - } - process.terminationHandler = { [weak self] child in - DispatchQueue.main.async { - guard let self, self.helper === child else { return } - self.stop(); self.error = "System volume stopped; hardware level restored"; self.onChange?() - } - } - do { - try process.run() - watchdog = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in - guard let self else { return } - let id = MenuBandAudioDevices.systemDefaultOutputID() - if id.flatMap({ MenuBandAudioDevices.uid(for: $0) }) != self.deviceUID { - self.stop(); self.error = "Output changed; enable volume again"; self.onChange?() - } else if let id, abs(MenuBandAudioDevices.nominalRate(of: id) - self.deviceRate) > 1 { - self.stop(); self.error = "Output rate changed; enable volume again"; self.onChange?() - } - } - } catch { stop(); self.error = error.localizedDescription } - onChange?() - } - private func receive(_ text: String) { - response += text - while let end = response.firstIndex(of: "\n") { - let line = String(response[.. `. // Short-circuits app startup so conformance harnesses can call the same // binary without launching a status item. diff --git a/slab/menuband/Tests/MenuBandTests/AmbientAirTests.swift b/slab/menuband/Tests/MenuBandTests/AmbientAirTests.swift new file mode 100644 index 0000000000..53532608f1 --- /dev/null +++ b/slab/menuband/Tests/MenuBandTests/AmbientAirTests.swift @@ -0,0 +1,90 @@ +import AVFoundation +import XCTest +@testable import MenuBand + +final class AmbientAirTests: XCTestCase { + /// Render the real source and mixer without opening audio hardware. + private func withEngine(rate: Double = 48_000, tone: Float = 0, + _ check: (MenuBandAmbientAir, (Int) throws -> [Float]) throws -> Void) throws { + let suite = "MenuBandAmbientAirTests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let air = MenuBandAmbientAir(defaults: defaults) + let engine = AVAudioEngine() + let format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)! + try engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: 512) + air.attach(to: engine, output: engine.mainMixerNode) + let instrument = AVAudioSourceNode(format: format) { _, _, frames, output in + for buffer in UnsafeMutableAudioBufferListPointer(output) { + let samples = buffer.mData!.assumingMemoryBound(to: Float.self) + for i in 0..<(Int(frames) * Int(buffer.mNumberChannels)) { samples[i] = tone } + } + return noErr + } + engine.attach(instrument) + engine.connect(instrument, to: engine.mainMixerNode, format: format) + try engine.start() + defer { engine.stop() } + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 512)! + try check(air) { frames in + var result: [Float] = [] + while result.count < frames { + let count = AVAudioFrameCount(min(512, frames - result.count)) + let status = try engine.renderOffline(count, to: buffer) + guard status == .success else { + throw NSError(domain: "AmbientAirTests.render", code: Int(status.rawValue)) + } + let left = buffer.floatChannelData![0], right = buffer.floatChannelData![1] + for i in 0.. MBAudioDevice { + MBAudioDevice(id: id, uid: "scarlett", name: "Scarlett Solo USB", + inputChannels: 2, outputChannels: 2) + } + + func testPinnedInterfaceReturnsWithNewIDAfterSpeakerFallback() { + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers, scarlett(87)], pinnedUID: "scarlett", systemDefaultID: 73), 87) + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers], pinnedUID: "scarlett", systemDefaultID: 73), 73) + // The fallback still exists and remains the system default. The pin + // must reclaim the interface using its new ID, without a user pick. + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers, scarlett(157)], pinnedUID: "scarlett", systemDefaultID: 73), 157) + } + + func testAutomaticOutputFollowsDefaultThatChangesAfterDeviceArrival() { + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers, scarlett(87)], pinnedUID: nil, systemDefaultID: 87), 87) + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers], pinnedUID: nil, systemDefaultID: 73), 73) + let reconnected = [speakers, scarlett(157)] + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: reconnected, pinnedUID: nil, systemDefaultID: 73), 73) + // No second device-list event: only the default output changes. + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: reconnected, pinnedUID: nil, systemDefaultID: 157), 157) + } + + func testExplicitSpeakerPickSurvivesSystemDefaultChange() { + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers, scarlett(157)], pinnedUID: "speakers", systemDefaultID: 157), 73) + } + + func testUnavailableOrInputOnlyTargetsAreNotBound() { + let mic = MBAudioDevice(id: 80, uid: "mic", name: "Microphone", + inputChannels: 1, outputChannels: 0) + XCTAssertEqual(MenuBandAudioDevices.outputTargetID( + devices: [speakers, mic], pinnedUID: "mic", systemDefaultID: 73), 73) + XCTAssertNil(MenuBandAudioDevices.outputTargetID( + devices: [speakers], pinnedUID: nil, systemDefaultID: 87)) + XCTAssertNil(MenuBandAudioDevices.outputTargetID( + devices: [], pinnedUID: "scarlett", systemDefaultID: nil)) + } +} diff --git a/slab/menuband/Tests/MenuBandTests/AudioTelemetryTests.swift b/slab/menuband/Tests/MenuBandTests/AudioTelemetryTests.swift new file mode 100644 index 0000000000..8a146460ba --- /dev/null +++ b/slab/menuband/Tests/MenuBandTests/AudioTelemetryTests.swift @@ -0,0 +1,108 @@ +import AVFoundation +import XCTest +@testable import MenuBand + +final class AudioTelemetryTests: XCTestCase { + func testLiveDevicePropertiesRemainScalarsWhenStoredInAnyDictionary() throws { + guard let device = MenuBandAudioDevices.systemDefaultOutputID(), device != 0 else { + throw XCTSkip("No audio output device available") + } + let telemetry = MenuBandAudioTelemetry(enabled: false) + for _ in 0..<3 { + let snapshot = telemetry.deviceSnapshot(device) + XCTAssertNotNil(snapshot["alive"] as? UInt32) + XCTAssertNotNil(snapshot["bufferFrames"] as? UInt32) + XCTAssertNotNil(snapshot["rate"] as? Double) + XCTAssertNoThrow(try JSONSerialization.data(withJSONObject: snapshot)) + } + } + + private func buffer(_ left: [Float], _ right: [Float]) -> AVAudioPCMBuffer { + let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)! + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(left.count))! + buffer.frameLength = buffer.frameCapacity + for i in left.indices { + buffer.floatChannelData![0][i] = left[i] + buffer.floatChannelData![1][i] = right[i] + } + return buffer + } + + func testOppositePhaseStereoIsNotReportedAsSilence() throws { + let meter = AudioSignalMeter() + let audio = buffer([0.5, 0.5], [-0.5, -0.5]) + meter.observe(audio.audioBufferList, frames: 2, at: 10) + let snapshot = meter.takeSnapshot(at: 11) + XCTAssertEqual(snapshot.peakDBFS, -6.0206, accuracy: 0.001) + XCTAssertEqual(snapshot.rmsDBFS, -6.0206, accuracy: 0.001) + XCTAssertEqual(snapshot.measuredBuffers, 1) + XCTAssertEqual(snapshot.lastSignalAgeMs, 1000) + } + + func testInvalidSamplesAreCountedWithoutPoisoningJSONOrFiniteSignal() throws { + let meter = AudioSignalMeter() + let audio = buffer([.nan, 0.25], [.infinity, -.infinity]) + meter.observe(audio.audioBufferList, frames: 2, at: 0) + let snapshot = meter.takeSnapshot(at: 1) + XCTAssertEqual(snapshot.invalidSamples, 3) + XCTAssertEqual(snapshot.peakDBFS, -12.0412, accuracy: 0.001) + XCTAssertNoThrow(try JSONEncoder().encode(snapshot)) + } + + func testSilentFlagIgnoresUndefinedContentsButTracksCallbacks() { + let meter = AudioSignalMeter() + let audio = buffer([.nan, 1], [.nan, 1]) + meter.observe(audio.audioBufferList, frames: 2, silent: true, at: 0) + let snapshot = meter.takeSnapshot(at: 1) + XCTAssertEqual(snapshot.callbacks, 1) + XCTAssertEqual(snapshot.measuredBuffers, 1) + XCTAssertEqual(snapshot.peakDBFS, -160) + XCTAssertEqual(snapshot.invalidSamples, 0) + XCTAssertEqual(snapshot.silentFlagBuffers, 1) + XCTAssertNil(snapshot.lastSignalAgeMs) + } + + func testMissingHardwareBufferIsUnknownRatherThanMeasuredSilence() { + let meter = AudioSignalMeter() + meter.observe(nil, frames: 16, error: true, at: 0) + let snapshot = meter.takeSnapshot(at: 1) + XCTAssertEqual(snapshot.callbacks, 1) + XCTAssertEqual(snapshot.measuredBuffers, 0) + XCTAssertEqual(snapshot.samples, 0) + XCTAssertEqual(snapshot.renderErrors, 1) + } + + func testIntervalCountersResetButStallAndLastSignalAgeSurvive() { + let meter = AudioSignalMeter() + let audio = buffer([0.5], [0]) + meter.observe(audio.audioBufferList, frames: 1, at: 10) + _ = meter.takeSnapshot(at: 11) + let stopped = meter.takeSnapshot(at: 13) + XCTAssertEqual(stopped.callbacks, 0) + XCTAssertEqual(stopped.lastCallbackAgeMs, 3000) + XCTAssertEqual(stopped.lastSignalAgeMs, 3000) + meter.observe(audio.audioBufferList, frames: 1, silent: true, at: 14) + let resumed = meter.takeSnapshot(at: 15) + XCTAssertEqual(resumed.maxGapMs, 4000) + XCTAssertEqual(resumed.lastSignalAgeMs, 5000) + } + + func testDiagnosticFilesRotateAndEveryLineRemainsValidJSON() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let log = AudioDiagnosticLog(directory: directory, maximumBytes: 512) + for i in 0..<40 { try log.append(["event": "snapshot", "sequence": i]) } + let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + XCTAssertEqual(files.count, 2) + for file in files { + let data = try Data(contentsOf: file) + XCTAssertLessThanOrEqual(data.count, 512) + for line in data.split(separator: 0x0a) { + XCTAssertNoThrow(try JSONSerialization.jsonObject(with: Data(line))) + } + } + let last = try String(contentsOf: log.url).split(separator: "\n").last! + let row = try JSONSerialization.jsonObject(with: Data(last.utf8)) as! [String: Any] + XCTAssertEqual(row["sequence"] as? Int, 39) + } +} diff --git a/slab/menuband/Tests/MenuBandTests/InterfaceRecoveryPolicyTests.swift b/slab/menuband/Tests/MenuBandTests/InterfaceRecoveryPolicyTests.swift new file mode 100644 index 0000000000..2837a52d05 --- /dev/null +++ b/slab/menuband/Tests/MenuBandTests/InterfaceRecoveryPolicyTests.swift @@ -0,0 +1,49 @@ +import XCTest +@testable import MenuBand + +final class InterfaceRecoveryPolicyTests: XCTestCase { + func testStartupWaitsAndRepeatedEnumerationDoesNotResetAgain() { + var policy = InterfaceRecoveryPolicy() + policy.observeRoute(device: 87, affected: true, at: 0) + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: 2)) + XCTAssertEqual(policy.takeRequest(device: 87, resetting: false, at: 3), 87) + for time in 4...20 { + policy.observeRoute(device: 87, affected: true, at: Double(time)) + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: Double(time))) + } + } + + func testReplugResolvesNewIDAndNeverResetsSpeakerFallback() { + var policy = InterfaceRecoveryPolicy() + policy.observeRoute(device: 87, affected: true, at: 0) + policy.observeRoute(device: 73, affected: false, at: 1) + XCTAssertNil(policy.takeRequest(device: 73, resetting: false, at: 5)) + policy.observeRoute(device: 145, affected: true, at: 6) + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: 9)) + XCTAssertEqual(policy.takeRequest(device: 145, resetting: false, at: 9), 145) + } + + func testManualResetSatisfiesPendingAutomaticRecovery() { + var policy = InterfaceRecoveryPolicy() + policy.observeRoute(device: 87, affected: true, at: 0) + XCTAssertNil(policy.takeRequest(device: 87, resetting: true, at: 4)) + policy.didReset(at: 4) + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: 7)) + } + + func testRecoveryBurstCoalescesAndRepeatedFailureIsBounded() { + var policy = InterfaceRecoveryPolicy() + for time in 0...4 { policy.engineRecovered(device: 87, at: Double(time)) } + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: 6)) + XCTAssertEqual(policy.takeRequest(device: 87, resetting: false, at: 7), 87) + for time in [10.0, 20] { + policy.engineRecovered(device: 87, at: time) + XCTAssertEqual(policy.takeRequest(device: 87, resetting: false, at: time + 3), 87) + } + policy.engineRecovered(device: 87, at: 30) + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: 33)) + XCTAssertNil(policy.takeRequest(device: 87, resetting: false, at: 100)) + policy.engineRecovered(device: 87, at: 101) + XCTAssertEqual(policy.takeRequest(device: 87, resetting: false, at: 104), 87) + } +} diff --git a/slab/menuband/Tests/MenuBandTests/OutputGuardTests.swift b/slab/menuband/Tests/MenuBandTests/OutputGuardTests.swift new file mode 100644 index 0000000000..9d7f46d212 --- /dev/null +++ b/slab/menuband/Tests/MenuBandTests/OutputGuardTests.swift @@ -0,0 +1,81 @@ +import AVFoundation +import XCTest +@testable import MenuBand + +final class OutputGuardTests: XCTestCase { + func testSilentRenderingDoesNotLookLikeAStalledEngine() throws { + let engine = AVAudioEngine() + let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 2)! + try engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: 512) + let source = AVAudioSourceNode(format: format) { silent, _, _, output in + silent.pointee = true + for audio in UnsafeMutableAudioBufferListPointer(output) { + if let data = audio.mData { memset(data, 0, Int(audio.mDataByteSize)) } + } + return noErr + } + engine.attach(source) + engine.connect(source, to: engine.mainMixerNode, format: format) + let guardNode = MenuBandOutputGuard() + guardNode.attach(to: engine) + try engine.start() + defer { engine.stop() } + guardNode.health.begin(at: 0) + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 512)! + for _ in 0..<10 { XCTAssertEqual(try engine.renderOffline(512, to: buffer), .success) } + XCTAssertNil(guardNode.health.recoveryReason(shouldRun: true, isRunning: true)) + } + + func testFinalRenderContainsInvalidSamplesAndSurvivesEngineRecovery() throws { + for rate in [44_100.0, 48_000.0, 96_000.0] { + let engine = AVAudioEngine() + let format = AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)! + try engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: 512) + var injectFault = false + let source = AVAudioSourceNode(format: format) { _, _, frames, output in + for audio in UnsafeMutableAudioBufferListPointer(output) { + let samples = audio.mData!.assumingMemoryBound(to: Float.self) + for i in 0.. [Float] { + XCTAssertEqual(try engine.renderOffline(512, to: buffer), .success) + return (0..<2).flatMap { channel in + Array(UnsafeBufferPointer(start: buffer.floatChannelData![channel], + count: Int(buffer.frameLength))) + } + } + // nil graph formats deliberately follow the device. At a different + // offline rate the converter needs a few blocks to prime its filter. + for _ in 0..<4 { _ = try render() } + XCTAssertTrue(try render().allSatisfy { abs($0 - 0.125) < 0.00001 }, "rate \(rate)") + injectFault = true + let contained = try render() + XCTAssertTrue(contained.allSatisfy(\.isFinite)) + let reason = guardNode.health.recoveryReason( + at: ProcessInfo.processInfo.systemUptime + 3, shouldRun: true, isRunning: true) + XCTAssertTrue(reason?.contains("non-finite") == true) + injectFault = false + engine.stop() + engine.reset() + try engine.start() + // The real post-render callback still runs after stop/reset/start, + // and valid instrument audio passes through at its original gain. + for _ in 0..<4 { _ = try render() } + XCTAssertTrue(try render().allSatisfy { abs($0 - 0.125) < 0.00001 }, "rate \(rate)") + injectFault = true + XCTAssertTrue(try render().allSatisfy(\.isFinite)) + } + } +} diff --git a/slab/menuband/Tests/MenuBandTests/PlaybackHealthTests.swift b/slab/menuband/Tests/MenuBandTests/PlaybackHealthTests.swift new file mode 100644 index 0000000000..00862a36a0 --- /dev/null +++ b/slab/menuband/Tests/MenuBandTests/PlaybackHealthTests.swift @@ -0,0 +1,69 @@ +import XCTest +@testable import MenuBand + +final class PlaybackHealthTests: XCTestCase { + func testUSBResetSuppressesCompetingRecoveryUntilStreamsSettle() { + let health = MenuBandPlaybackHealth() + health.begin(at: 0) + health.setInterfaceResetting(true, at: 2) + health.observe(invalid: 832, at: 3) + XCTAssertNil(health.recoveryReason(at: 10, shouldRun: true, isRunning: false)) + health.setInterfaceResetting(false, at: 11) + health.observe(invalid: 0, at: 12) + XCTAssertNil(health.recoveryReason(at: 13, shouldRun: true, isRunning: true)) + // A real fault after the settling interval still gets repaired. + health.observe(invalid: 64, at: 14) + XCTAssertTrue(health.recoveryReason(at: 14, shouldRun: true, isRunning: true)! + .contains("64 non-finite")) + } + + func testRunningFlagCannotHideStalledOutput() { + let health = MenuBandPlaybackHealth() + health.begin(at: 0) + health.observe(invalid: 0, at: 1) + XCTAssertNil(health.recoveryReason(at: 2, shouldRun: true, isRunning: true)) + XCTAssertTrue(health.recoveryReason(at: 4, shouldRun: true, isRunning: true)! + .contains("callbacks stopped")) + } + + func testIdleIsAllowedButUnexpectedStopRecovers() { + let health = MenuBandPlaybackHealth() + health.begin(at: 0) + XCTAssertNil(health.recoveryReason(at: 60, shouldRun: false, isRunning: false)) + XCTAssertTrue(health.recoveryReason(at: 61, shouldRun: true, isRunning: false)! + .contains("engine stopped")) + } + + func testInvalidSamplesTriggerRecoveryEvenIfCallbacksContinue() { + let health = MenuBandPlaybackHealth() + health.begin(at: 0) + health.observe(invalid: 32, at: 2) + health.observe(invalid: 0, at: 3) + XCTAssertTrue(health.recoveryReason(at: 3, shouldRun: true, isRunning: true)! + .contains("32 non-finite")) + XCTAssertNil(health.recoveryReason(at: 4, shouldRun: true, isRunning: true)) + } + + func testFailedRecoveryBacksOffUntilWakeOrDeviceChange() { + let health = MenuBandPlaybackHealth() + health.begin(at: 0) + for time in [3.0, 8, 13] { + XCTAssertNotNil(health.recoveryReason(at: time, shouldRun: true, isRunning: false)) + } + XCTAssertNil(health.recoveryReason(at: 100, shouldRun: true, isRunning: false)) + health.begin(at: 100, renewBudget: true) + XCTAssertNil(health.recoveryReason(at: 101, shouldRun: true, isRunning: false)) + XCTAssertNotNil(health.recoveryReason(at: 103, shouldRun: true, isRunning: false)) + } + + func testSustainedHealthyRenderingRenewsRecoveryBudget() { + let health = MenuBandPlaybackHealth() + health.begin(at: 0) + for time in [3.0, 8, 13] { + XCTAssertNotNil(health.recoveryReason(at: time, shouldRun: true, isRunning: false)) + } + for time in 14...25 { health.observe(invalid: 0, at: Double(time)) } + health.observe(invalid: 1, at: 26) + XCTAssertNotNil(health.recoveryReason(at: 26, shouldRun: true, isRunning: true)) + } +} diff --git a/slab/menuband/Tests/MenuBandTests/SystemVolumeTests.swift b/slab/menuband/Tests/MenuBandTests/SystemVolumeTests.swift deleted file mode 100644 index 6622514151..0000000000 --- a/slab/menuband/Tests/MenuBandTests/SystemVolumeTests.swift +++ /dev/null @@ -1,63 +0,0 @@ -import XCTest -import CoreAudio -@testable import MenuBand - -#if !MAC_APP_STORE -@available(macOS 14.2, *) -final class SystemVolumeTests: XCTestCase { - /// Buffers represent physical microphone channels followed by the tap; - /// the renderer must never monitor those microphone samples. - private func render(_ samples: [[Float]], widths: [UInt32], inputChannels: Int, - gain: Float, nextGain: Float? = nil, outputWidths: [UInt32] = [2], air: Float = 0) -> [[Float]] { - let frames = samples.last!.count / Int(widths.last!) - func list(_ values: [[Float]], _ channels: [UInt32]) -> UnsafeMutableAudioBufferListPointer { - let list = AudioBufferList.allocate(maximumBuffers: values.count) - list.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(values.count) - for i in values.indices { - let p = UnsafeMutablePointer.allocate(capacity: values[i].count) - p.initialize(from: values[i], count: values[i].count) - list[i] = AudioBuffer(mNumberChannels: channels[i], mDataByteSize: UInt32(values[i].count * 4), mData: p) - } - return list - } - let input = list(samples, widths) - let output = list(outputWidths.map { Array(repeating: Float(99), count: frames * Int($0)) }, outputWidths) - defer { - for b in input { b.mData!.deallocate() }; input.unsafeMutablePointer.deallocate() - for b in output { b.mData!.deallocate() }; output.unsafeMutablePointer.deallocate() - } - let helper = MenuBandSystemVolumeHelper(inputChannels: inputChannels, gain: gain) - helper.setAir(air, color: .cabin) - if let nextGain { helper.setGain(nextGain) } - helper.process(input: UnsafePointer(input.unsafeMutablePointer), output: output.unsafeMutablePointer) - return output.map { Array(UnsafeBufferPointer(start: $0.mData!.assumingMemoryBound(to: Float.self), count: Int($0.mDataByteSize) / 4)) } - } - func testPhysicalMicrophoneNeverReachesOutput() { - XCTAssertEqual(render([[99,99,99,99], [0.8,-0.4,0.4,-0.8]], widths: [2,2], inputChannels: 2, gain: 0.25)[0], [0.2,-0.1,0.1,-0.2]) - } - func testPlanarTapAndPlanarOutput() { - XCTAssertEqual(render([[99,99], [99,99], [0.8,0.4], [-0.4,-0.8]], widths: [1,1,1,1], inputChannels: 2, gain: 0.25, outputWidths: [1,1]), [[0.2,0.1],[-0.1,-0.2]]) - } - func testSilentTapDoesNotLeakMicOrPreviousOutput() { - XCTAssertEqual(render([[99,99,99,99], [0,0,0,0]], widths: [2,2], inputChannels: 2, gain: 0.25)[0], [0,0,0,0]) - } - func testInvalidSamplesAreSilencedAndGainCannotAmplify() { - XCTAssertEqual(render([[Float.nan, Float.infinity, 0.5, -0.5]], widths: [2], inputChannels: 0, gain: 9)[0], [0,0,0.5,-0.5]) - } - func testGainChangeRampsBothChannelsTogetherAndReachesMute() { - let result = render([Array(repeating: 1, count: 2048)], widths: [2], inputChannels: 0, gain: 0.5, nextGain: 0)[0] - XCTAssertGreaterThan(result[0], 0.49) - XCTAssertEqual(result[0], result[1]) - XCTAssertEqual(result.suffix(2), [0,0]) - for frame in 1..<1024 { XCTAssertLessThanOrEqual(result[frame*2], result[(frame-1)*2]) } - } - func testAirWorksWithoutMusicAndSystemMuteIncludesAir() { - let silence = [Array(repeating: Float(0), count: 8192)] - let air = render(silence, widths: [2], inputChannels: 0, gain: 0.25, air: 0.7)[0] - XCTAssertGreaterThan(air.map { abs($0) }.max()!, 0.0001) - XCTAssertLessThan(air.map { abs($0) }.max()!, 0.03) - for frame in 0..<4096 { XCTAssertEqual(air[frame*2], air[frame*2+1]) } - XCTAssertTrue(render(silence, widths: [2], inputChannels: 0, gain: 0, air: 1)[0].allSatisfy { $0 == 0 }) - } -} -#endif diff --git a/slab/menuband/bin/audio-diagnostics.sh b/slab/menuband/bin/audio-diagnostics.sh new file mode 100644 index 0000000000..774aa90748 --- /dev/null +++ b/slab/menuband/bin/audio-diagnostics.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Collect local evidence after a dropout; does not reset audio or upload data. +set -euo pipefail +minutes="${1:-10}" +if ! [[ "$minutes" =~ ^[1-9][0-9]?$ ]] || (( minutes > 60 )); then + printf 'Usage: bash audio-diagnostics.sh [minutes: 1..60]\n' >&2 + exit 2 +fi +diagnostic_root="$HOME/Library/Logs/MenuBand" +mkdir -p "$diagnostic_root" +diagnostic_dir="$(mktemp -d "$diagnostic_root/report-$(date '+%Y%m%d-%H%M%S').XXXXXX")" +for name in audio-diagnostics.jsonl audio-diagnostics.previous.jsonl; do + if [[ -f "$diagnostic_root/$name" ]]; then + cp "$diagnostic_root/$name" "$diagnostic_dir/$name" + fi +done +if [[ -f /tmp/menuband.err ]]; then + tail -n 400 /tmp/menuband.err > "$diagnostic_dir/app.log" +fi +/usr/bin/log show --last "${minutes}m" --style compact --predicate ' + (process == "usbaudiod" AND + (eventMessage CONTAINS "transaction status error" OR + eventMessage CONTAINS "requestConfigurationChange" OR + eventMessage CONTAINS "performStartIO" OR + eventMessage CONTAINS "performStopIO")) OR + (process == "coreaudiod" AND + (eventMessage CONTAINS "HandlePlugIn_RequestConfigChange" OR + eventMessage CONTAINS "IO Stopped Context" OR + eventMessage CONTAINS "Overload possibly" OR + eventMessage CONTAINS "NonFinites" OR + eventMessage CONTAINS "ClientTimeoutStart")) +' > "$diagnostic_dir/driver.log" +printf '%s\n' "$diagnostic_dir"