Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions HiddenBarTests/MenuBarEngineTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3534,3 +3534,45 @@ final class PresentationModeEngineTests: XCTestCase {
}
}


// MARK: - Capture activity listeners (#386)

// Each monitor adds CoreAudio and CoreMediaIO property listeners and removes them
// again, on deinit and on every device change. A removal that does not match its
// add leaves the listener (a malloc block) registered for the life of the app,
// which is how the footprint grew to hundreds of MB over weeks of uptime.
final class CaptureActivityMonitorTests: XCTestCase {
func testRemovedListenersDoNotStayRegistered() throws {
let cycles = 100
// The first monitor loads CoreMediaIO, which keeps its own blocks.
autoreleasepool { _ = CaptureActivityMonitor() }
let before = try liveMallocBlocks()
for _ in 0..<cycles {
autoreleasepool { _ = CaptureActivityMonitor() }
}
let grown = try liveMallocBlocks() - before
// A leak keeps at least one block per system-object listener per cycle
// (2 x cycles), plus one per audio process and camera.
XCTAssertLessThan(grown, cycles / 2, "listener blocks still registered after \(cycles) add/remove cycles: \(grown)")
}

// Live __NSMallocBlock__ count in this process, read with /usr/bin/heap after
// the main queue drains.
private func liveMallocBlocks() throws -> Int {
RunLoop.current.run(until: Date().addingTimeInterval(0.5))
let heap = Process()
heap.executableURL = URL(fileURLWithPath: "/usr/bin/heap")
heap.arguments = ["\(ProcessInfo.processInfo.processIdentifier)"]
let out = Pipe()
heap.standardOutput = out
heap.standardError = Pipe()
try heap.run()
let data = out.fileHandleForReading.readDataToEndOfFile()
heap.waitUntilExit()
let line = String(decoding: data, as: UTF8.self).split(separator: "\n").first { $0.contains("__NSMallocBlock__") }
guard heap.terminationStatus == 0, let count = line?.split(separator: " ").first.flatMap({ Int($0) }) else {
throw XCTSkip("heap could not read this process (status \(heap.terminationStatus))")
}
return count
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,30 +40,61 @@ final class CaptureActivityMonitor: CaptureActivityMonitoring {

private var processes: [AudioObjectID] = []
private var cameras: [CMIOObjectID] = []
private var audioListener: AudioObjectPropertyListenerBlock!
private var cameraListener: CMIOObjectPropertyListenerBlock!

// Listeners use the C function API, not the block API. Swift wraps a closure in
// a new block on every call, so a block remove never matched its add, and every
// listener stayed registered (and allocated) for the life of the app: one per
// audio process and camera on each device change (#386). The C API matches a
// removal by proc and client data. The client data is an id rather than a
// pointer, so a callback still in flight after deinit finds no monitor.
private let id: Int
private var clientData: UnsafeMutableRawPointer? { UnsafeMutableRawPointer(bitPattern: id) }
private static var nextID = 0
private static var live: [Int: WeakMonitor] = [:] // main queue only

private final class WeakMonitor {
weak var monitor: CaptureActivityMonitor?
init(_ monitor: CaptureActivityMonitor) { self.monitor = monitor }
}

private static let audioListener: AudioObjectPropertyListenerProc = { _, _, _, clientData in
CaptureActivityMonitor.notify(clientData)
return noErr
}

private static let cameraListener: CMIOObjectPropertyListenerProc = { _, _, _, clientData in
CaptureActivityMonitor.notify(clientData)
return noErr
}

// Runs on a CoreAudio or CoreMediaIO thread.
private static func notify(_ clientData: UnsafeMutableRawPointer?) {
let id = Int(bitPattern: clientData)
DispatchQueue.main.async { live[id]?.monitor?.devicesDidChange() }
}

init() {
// One block for every registration, so each can be removed again.
audioListener = { [weak self] _, _ in self?.devicesDidChange() }
cameraListener = { [weak self] _, _ in self?.devicesDidChange() }
Self.nextID += 1
id = Self.nextID
Self.live[id] = WeakMonitor(self)
if #available(macOS 14.2, *) {
var processList = Self.audioAddress(kAudioHardwarePropertyProcessObjectList)
AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &processList, .main, audioListener)
AudioObjectAddPropertyListener(AudioObjectID(kAudioObjectSystemObject), &processList, Self.audioListener, clientData)
}
var cameraList = Self.cameraAddress(CMIOObjectPropertySelector(kCMIOHardwarePropertyDevices))
CMIOObjectAddPropertyListenerBlock(CMIOObjectID(kCMIOObjectSystemObject), &cameraList, .main, cameraListener)
CMIOObjectAddPropertyListener(CMIOObjectID(kCMIOObjectSystemObject), &cameraList, Self.cameraListener, clientData)
track()
}

deinit {
untrack()
if #available(macOS 14.2, *) {
var processList = Self.audioAddress(kAudioHardwarePropertyProcessObjectList)
AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &processList, .main, audioListener)
AudioObjectRemovePropertyListener(AudioObjectID(kAudioObjectSystemObject), &processList, Self.audioListener, clientData)
}
var cameraList = Self.cameraAddress(CMIOObjectPropertySelector(kCMIOHardwarePropertyDevices))
CMIOObjectRemovePropertyListenerBlock(CMIOObjectID(kCMIOObjectSystemObject), &cameraList, .main, cameraListener)
CMIOObjectRemovePropertyListener(CMIOObjectID(kCMIOObjectSystemObject), &cameraList, Self.cameraListener, clientData)
Self.live[id] = nil
}

var isActive: Bool {
Expand All @@ -88,13 +119,13 @@ final class CaptureActivityMonitor: CaptureActivityMonitoring {
processes = Self.audioObjects(kAudioHardwarePropertyProcessObjectList)
var running = Self.audioAddress(kAudioProcessPropertyIsRunningInput)
for process in processes {
AudioObjectAddPropertyListenerBlock(process, &running, .main, audioListener)
AudioObjectAddPropertyListener(process, &running, Self.audioListener, clientData)
}
}
cameras = Self.cameraObjects()
var running = Self.cameraAddress(CMIOObjectPropertySelector(kCMIODevicePropertyDeviceIsRunningSomewhere))
for camera in cameras {
CMIOObjectAddPropertyListenerBlock(camera, &running, .main, cameraListener)
CMIOObjectAddPropertyListener(camera, &running, Self.cameraListener, clientData)
}
}

Expand All @@ -103,12 +134,12 @@ final class CaptureActivityMonitor: CaptureActivityMonitoring {
if #available(macOS 14.2, *) {
var running = Self.audioAddress(kAudioProcessPropertyIsRunningInput)
for process in processes {
AudioObjectRemovePropertyListenerBlock(process, &running, .main, audioListener)
AudioObjectRemovePropertyListener(process, &running, Self.audioListener, clientData)
}
}
var running = Self.cameraAddress(CMIOObjectPropertySelector(kCMIODevicePropertyDeviceIsRunningSomewhere))
for camera in cameras {
CMIOObjectRemovePropertyListenerBlock(camera, &running, .main, cameraListener)
CMIOObjectRemovePropertyListener(camera, &running, Self.cameraListener, clientData)
}
processes = []
cameras = []
Expand Down