Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Send the Mac's output latency to the guest speaker

Jacky603c1fbb7d32
diff --git a/Research/Guest/virtio_sound.md b/Research/Guest/virtio_sound.md
index a6419e62..be75eecb 100644
--- a/Research/Guest/virtio_sound.md
+++ b/Research/Guest/virtio_sound.md
@@ -455,7 +455,8 @@ the one before it finished is a gap. Measured with the clock already fixed:
The stream now queues `VPhoneVirtIOSoundLeadPeriods` periods of silence
(default 2, 171 ms) ahead of each run, and the device reports the lead plus
one period as `outputLatency` so video is presented against when the sound is
-heard. Measured: 0 of 499 and 0 of 237 writes starved.
+heard (at least that much; it now follows what the host keeps, see "Picture
+against sound" below). Measured: 0 of 499 and 0 of 237 writes starved.
**Restarts lost the lead.** A tone switch restarts the stream while the device
is still draining the last one. Queued at `startStream`, the lead was rounded
@@ -500,8 +501,73 @@ frames a second). The time from each flash to its beep:
The guest is within a frame of a player native to the Mac, so the reported
latency is what the queue adds. The capture is taken at the Mac's compositor
and mixer; the display and the output device after them are the same for
-both players and are not in the numbers. Only the built-in output was
-measured: no USB or Bluetooth output was attached.
+both players and are not in the numbers.
+
+**Bluetooth output.** The same measurement with the Mac playing through
+AirPods Pro (48 kHz output), 2026-10-04:
+
+| Player | Beep after flash | Notes |
+| --- | --- | --- |
+| AVPlayer in a window on the Mac itself | -140 ms | AVFoundation sends the sound early by the output's latency |
+| Safari in the guest | +365 to +372 ms (sd 6) | `in flight` 3-5 periods, up to 8; 0 starved; host +18 ppm |
+
+At the mixer the guest's sound was 370 ms late where the native player's was
+140 ms early, so at the ear about half a second late. Two things the
+reported latency left out: Virtualization's host sink keeps more in flight
+for a Bluetooth output (3-5 periods against 1-2 on the built-in speakers,
+each 85 ms more than the lead assumed), and the output's own latency after
+the mixer, which a native player compensates and the guest never heard of.
+
+The speaker's output latency now follows both
+(`VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundLatency.h`):
+
+- *Queued ahead of the host.* The output stream takes the most in flight
+ any write found per five-second window, once a run has been going five
+ seconds, plus the period being filled; never less than the lead plus one
+ period. It moves up after two windows in a row that ask for more (to the
+ lesser of them, so one burst does not count) and down after twelve, a
+ minute, that ask for less.
+- *The Mac's output.* `vphone-vm` reads the default output device from
+ CoreAudio, the device Virtualization's `VZHostAudioOutputStreamSink` plays
+ to ("the same device that AudioQueueNewOutput uses", its header): device
+ latency + safety offset + its output stream's latency + IO buffer, at its
+ nominal rate (`VPhoneHostAudioLatencySync`). The headers sum the device
+ and stream latency, the time after the HAL's output time; the native
+ player's 14.5 ms on the built-in speakers is that part (15.6 ms there).
+ The safety offset and buffer lie between the mix and that output time,
+ after Virtualization hands the guest its write back, so from the guest
+ they count too. Built-in speakers of a MacBook Pro: 60 + 48 + 690 + 512
+ frames, 27.3 ms. It sends the figure after every connect and whenever the
+ default output device or its latency, safety offset, buffer size, rate or
+ streams change, with `audio.host_latency` (`Research/vphoned_http_api.md`);
+ vphoned stores it as `VPhoneVirtIOSoundHostLatency` in
+ `com.apple.coreaudio` for user mobile and posts
+ `com.vphone.audio.host-latency`. The plugin reads the key at load, on that
+ notification and at each start of the speaker's I/O.
+
+The device's `outputLatency` is the sum, in frames of its nominal rate. A
+change goes through `requestConfigurationChange:`: AudioServerPlugIn.h
+requires RequestDeviceConfigurationChange for a change of presentation
+latency, and the host performs it with I/O stopped and restarts I/O after,
+so a player hears a short break when it moves. ASD's `setOutputLatency:`
+(disassembled, guest AudioServerDriver) stores the value and calls
+`changedProperty:forObject:` with 'ltnc'/'outp', which the plugin turns into
+the host's PropertiesChanged. Not yet confirmed on a guest: that the HAL in
+audiomxd performs the change, and that a player already playing picks the
+new latency up rather than only the next one.
+
+What to expect, from the measurements above: on the built-in speakers the
+queued part stays at 3 periods and the host adds 27.3 ms, so the guest's
+sound moves from 8 ms to about 36 ms ahead of its picture at the mixer
+(native: 14.5 ms). On AirPods the queued part should settle at 6 periods
+(512 ms) and the host add about 150 ms, about 400 ms more than before,
+which would leave the guest roughly 100 ms late at the ear unless
+Virtualization's sink buffers less than the half second measured. The
+plugin logs each step to `vpquery.log`: `speaker latency … frames at …
+Hz` at load, `stream 0: queued ahead of the host 3 -> N periods`, `host
+latency notification: … ms stored`, `speaker latency A -> B frames …
+requesting a configuration change`, then `speaker latency B frames
+applied` once the host performed it.
### Nothing left to set by hand
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 22f8b6c1..532160a9 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -1,4 +1,4 @@
-# vphoned HTTP/WebSocket API
+`audio.volume {value?, category?}`, `audio.state`, `audio.host_latency {seconds?}` (`{seconds}`, plus `changed` after a set: the Mac output latency the sound plugin adds, see below; capability `audio_host_latency`) |# vphoned HTTP/WebSocket API
## Transport and ownership
@@ -344,6 +344,21 @@ back to timed. Both add `changed`. `vphone-vm` sends the Mac's zone after
every connect and whenever the Mac's zone changes (`VPhoneTimeZoneSync`), so
the guest's clock reads the same local time as the host.
+`audio.host_latency` (capability `audio_host_latency`) reads or sets what the
+Mac's output device adds after its mixer, in seconds, which the guest's
+sound plugin adds to its speaker's output latency so a player in the guest
+holds its picture back by as much (`VPhoneDaemon/Daemon/GuestAPI+AudioLatency.swift`).
+Without `seconds` it returns `{seconds}`, the stored value or 0. `{seconds}`
+(0 to 1) stores it as `VPhoneVirtIOSoundHostLatency` in `com.apple.coreaudio`
+for user mobile, posts the Darwin notification
+`com.vphone.audio.host-latency` so a running audiomxd reads it again, and
+returns `{seconds, changed}`; a value within 10 µs of the stored one is
+neither written nor posted (`changed: false`). `vphone-vm` sends the default
+output device's device latency + safety offset + output stream latency + IO
+buffer after every connect and whenever the default output device or one of
+those changes (`VPhoneHostAudioLatencySync`). See
+`Research/Guest/virtio_sound.md` §6, "Picture against sound".
+
`network.ipv4.get` and `network.ipv4.set` read and write the IPv4 settings of
one interface (default `en0`) in configd's network preferences,
`/var/preferences/SystemConfiguration/preferences.plist`, through SCPreferences
diff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.md
index 5e75582b..9505151a 100644
--- a/Skills/vphone-guest-control/references/rpc-methods.md
+++ b/Skills/vphone-guest-control/references/rpc-methods.md
@@ -51,6 +51,7 @@ invalid-request error, read the source named there instead of guessing keys.
| `device.snapshot`, `device.screen`, `device.network` | none | Smaller views of the same |
| `screen.screenshot` | none | Base64 JPEG with `mime_type`, `width`, `height` (1290×2796) |
| `display.brightness`, `audio.volume` | `value?` | Omit `value` to read |
+| `audio.host_latency` | `seconds?` (0-1) | The Mac output latency the guest speaker adds; omit to read. The VM sends it on every connect and output change |
| `display.rotation`, `display.orientation` | `orientation?` | |
| `display.auto_lock` | none | Auto-Lock in seconds (`never` when it is Never) and the Lock Screen timeout vphoned sets to match |
| `screen.unlock` | `passcode?`, `timeout?` (10) | Display on and Lock Screen passed, from any state; `guest unlock <machine>` calls it. `passcode` only for a guest that has one, entered once |
diff --git a/VPhoneDaemon/Daemon/GuestAPI+AudioLatency.swift b/VPhoneDaemon/Daemon/GuestAPI+AudioLatency.swift
new file mode 100644
index 00000000..68b42db4
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+AudioLatency.swift
@@ -0,0 +1,56 @@
+import Foundation
+import IcliKit
+
+// MARK: - Host Audio Latency
+
+/// What the Mac's output device adds after its mixer, which the sound plugin
+/// adds to the speaker's output latency so a guest player holds its picture
+/// back by as much as the sound is late. vphone-vm reads it from CoreAudio
+/// and sends it after every connect and whenever the Mac's output changes.
+///
+/// It is stored as `VPhoneVirtIOSoundHostLatency` in `com.apple.coreaudio`
+/// for user mobile, the domain the plugin reads its settings from in
+/// audiomxd, and `com.vphone.audio.host-latency` is posted so a running
+/// audiomxd reads it again. Each answer is `{seconds}`, plus `changed` after
+/// a set; an unchanged value is neither written nor posted.
+///
+/// See Research/Guest/virtio_sound.md §6 (Picture against sound).
+extension GuestAPI {
+ private static let hostLatencyDomain = "com.apple.coreaudio"
+ private static let hostLatencyKey = "VPhoneVirtIOSoundHostLatency"
+ private static let hostLatencyNotification = "com.vphone.audio.host-latency"
+
+ static func executeAudioLatency(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ guard method == "audio.host_latency" else { return nil }
+ let stored = storedHostLatency()
+ guard params["seconds"] != nil else {
+ return ["seconds": stored]
+ }
+ let seconds = try requiredNumber(params, "seconds")
+ // The plugin takes at most one second; a Bluetooth output is a few
+ // hundred milliseconds.
+ guard seconds >= 0, seconds <= 1 else {
+ throw GuestAPIError.invalidRequest("seconds must be between 0 and 1")
+ }
+ // CoreAudio's figure for one device does not move by less than a
+ // frame; anything closer than that is the value already stored.
+ guard abs(seconds - stored) >= 0.000_01 else {
+ return ["seconds": stored, "changed": false]
+ }
+ _ = try writePreference(
+ domain: hostLatencyDomain,
+ key: hostLatencyKey,
+ value: .float(seconds),
+ notify: hostLatencyNotification,
+ )
+ NSLog("vphoned: host audio latency %.1f ms -> %.1f ms", stored * 1000, seconds * 1000)
+ return ["seconds": seconds, "changed": true]
+ }
+
+ private static func storedHostLatency() -> Double {
+ let value = CFPreferencesCopyValue(
+ hostLatencyKey as CFString, hostLatencyDomain as CFString, "mobile" as CFString, kCFPreferencesAnyHost,
+ )
+ return (value as? NSNumber)?.doubleValue ?? 0
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
index 008bb6ac..dd61a077 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -17,6 +17,7 @@ extension GuestAPI {
executeDeviceIdentity,
executeSetupAssistant,
executeTimeZone,
+ executeAudioLatency,
]
for area in areas {
if let result = try area(method, params) {
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index d1e2cd50..77cd99f7 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -122,6 +122,7 @@ enum GuestAPI {
"network_static_names",
"network_resolve",
"timezone",
+ "audio_host_latency",
],
]
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
index f2ed33c2..2a4bb2c6 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
@@ -48,4 +48,13 @@ extension VPhoneGuestControl {
let result = try await call("time.timezone", params: ["identifier": identifier])
return result["changed"] as? Bool ?? false
}
+
+ // MARK: - Audio
+
+ /// Tells the guest's sound plugin what the Mac's output device adds after
+ /// its mixer, in seconds. Returns false when the guest already had it.
+ func setHostAudioLatency(_ seconds: Double) async throws -> Bool {
+ let result = try await call("audio.host_latency", params: ["seconds": seconds])
+ return result["changed"] as? Bool ?? false
+ }
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneHostAudioLatencySync.swift b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneHostAudioLatencySync.swift
new file mode 100644
index 00000000..7bcb3b49
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneHostAudioLatencySync.swift
@@ -0,0 +1,227 @@
+import CoreAudio
+import Foundation
+
+/// What the Mac's output device adds after its mixer: the frames between the
+/// mix of an IO cycle and the listener's ear, at the device's nominal rate.
+///
+/// The CoreAudio headers sum the device's and its stream's latency
+/// (`kAudioDevicePropertyLatency`, `kAudioStreamPropertyLatency`): the time
+/// from the HAL's output time to the ear. A player native to the Mac holds
+/// its picture back by that: measured on one clock at the Mac's mixer, an
+/// AVPlayer window plays its sound 14.5 ms early on the built-in speakers,
+/// whose device and stream latency come to 15.6 ms, and 140 ms early on
+/// AirPods. The HAL mixes each cycle the safety offset plus one IO buffer
+/// ahead of that output time. The guest sees its writes come back from
+/// Virtualization's queue, which (Virtualization does not say; assumed) is
+/// no later than the queue's buffer is mixed, so from the guest those two
+/// count as well and the figure is all four. On a MacBook Pro's speakers:
+/// 60 + 48 + 690 + 512 frames, 27.3 ms.
+struct VPhoneHostAudioLatency: Equatable {
+ var deviceFrames: UInt32
+ var safetyOffsetFrames: UInt32
+ var streamFrames: UInt32
+ var bufferFrames: UInt32
+ var sampleRate: Double
+
+ var frames: UInt64 {
+ UInt64(deviceFrames) + UInt64(safetyOffsetFrames) + UInt64(streamFrames) + UInt64(bufferFrames)
+ }
+
+ var seconds: Double {
+ sampleRate > 0 ? Double(frames) / sampleRate : 0
+ }
+
+ var summary: String {
+ String(
+ format: "%.1f ms (device %u + safety offset %u + stream %u + buffer %u frames at %.0f Hz)",
+ seconds * 1000, deviceFrames, safetyOffsetFrames, streamFrames, bufferFrames, sampleRate,
+ )
+ }
+}
+
+/// Keeps the guest's sound plugin told what the Mac's output device adds
+/// after its mixer, so the guest's speaker reports the whole latency and a
+/// player in the guest keeps its picture with the sound also on a Bluetooth
+/// output. See Research/Guest/virtio_sound.md §6 (Picture against sound).
+///
+/// The VM's `VZHostAudioOutputStreamSink` plays to "the same device that
+/// AudioQueueNewOutput uses" (its header), and an output queue created
+/// without a device UID plays to the default output device: that is the
+/// device measured here. Virtualization's own buffering before the mixer is
+/// not in this figure; the plugin measures that part itself.
+///
+/// Call `start()` when the guest reports the "audio_host_latency" capability,
+/// on every connect: it sends the current figure, then again whenever the
+/// default output device, or its latency, safety offset, buffer, rate or
+/// streams, change. Changes come in bursts while a Bluetooth device
+/// connects, so a send waits for them to settle.
+@MainActor
+class VPhoneHostAudioLatencySync {
+ private static let settleDelay: Duration = .milliseconds(500)
+
+ private let control: VPhoneGuestControl
+ private var observedDevice = AudioObjectID(kAudioObjectUnknown)
+ private var listener: AudioObjectPropertyListenerBlock?
+ private var pending: Task<Void, Never>?
+ private var sending: Task<Void, Never>?
+ private var lastSent: Double?
+
+ init(control: VPhoneGuestControl) {
+ self.control = control
+ }
+
+ func start() {
+ if listener == nil {
+ let listener: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ MainActor.assumeIsolated {
+ self?.scheduleSend()
+ }
+ }
+ self.listener = listener
+ var address = Self.address(kAudioHardwarePropertyDefaultOutputDevice)
+ AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, .main, listener)
+ }
+ // A new connection may be a new guest: send even an unchanged figure.
+ lastSent = nil
+ send()
+ }
+
+ func stop() {
+ pending?.cancel()
+ pending = nil
+ sending?.cancel()
+ sending = nil
+ if let listener {
+ var address = Self.address(kAudioHardwarePropertyDefaultOutputDevice)
+ AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, .main, listener)
+ observe(device: AudioObjectID(kAudioObjectUnknown))
+ }
+ listener = nil
+ }
+
+ private func scheduleSend() {
+ pending?.cancel()
+ pending = Task { [weak self] in
+ try? await Task.sleep(for: Self.settleDelay)
+ guard !Task.isCancelled else { return }
+ self?.send()
+ }
+ }
+
+ private func send() {
+ let device = Self.defaultOutputDevice()
+ observe(device: device)
+ guard device != kAudioObjectUnknown, let latency = Self.latency(of: device) else {
+ print("[audio] no default output device to measure")
+ return
+ }
+ let seconds = latency.seconds
+ guard seconds != lastSent else { return }
+ lastSent = seconds
+ let name = Self.name(of: device) ?? "device \(device)"
+ let previous = sending
+ sending = Task { [control] in
+ // Two quick changes on the Mac must reach the guest in order.
+ await previous?.value
+ guard !Task.isCancelled else { return }
+ do {
+ let changed = try await control.setHostAudioLatency(seconds)
+ print("[audio] \(name): \(latency.summary), guest \(changed ? "updated" : "already had it")")
+ } catch {
+ print("[audio] could not send the output latency of \(name): \(error)")
+ }
+ }
+ }
+
+ // MARK: - Device listeners
+
+ private static let deviceSelectors: [(AudioObjectPropertySelector, AudioObjectPropertyScope)] = [
+ (kAudioDevicePropertyLatency, kAudioObjectPropertyScopeOutput),
+ (kAudioDevicePropertySafetyOffset, kAudioObjectPropertyScopeOutput),
+ (kAudioDevicePropertyBufferFrameSize, kAudioObjectPropertyScopeGlobal),
+ (kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal),
+ (kAudioDevicePropertyStreams, kAudioObjectPropertyScopeOutput),
+ ]
+
+ /// Moves the device listeners to `device`, or removes them for
+ /// `kAudioObjectUnknown`.
+ private func observe(device: AudioObjectID) {
+ guard device != observedDevice, let listener else { return }
+ for (selector, scope) in Self.deviceSelectors {
+ if observedDevice != kAudioObjectUnknown {
+ var address = Self.address(selector, scope)
+ AudioObjectRemovePropertyListenerBlock(observedDevice, &address, .main, listener)
+ }
+ if device != kAudioObjectUnknown {
+ var address = Self.address(selector, scope)
+ AudioObjectAddPropertyListenerBlock(device, &address, .main, listener)
+ }
+ }
+ observedDevice = device
+ }
+
+ // MARK: - CoreAudio
+
+ private static func address(
+ _ selector: AudioObjectPropertySelector,
+ _ scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal,
+ ) -> AudioObjectPropertyAddress {
+ AudioObjectPropertyAddress(mSelector: selector, mScope: scope, mElement: kAudioObjectPropertyElementMain)
+ }
+
+ private static func value<T: BitwiseCopyable>(
+ _ object: AudioObjectID,
+ _ selector: AudioObjectPropertySelector,
+ _ scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal,
+ initial: T,
+ ) -> T? {
+ var address = address(selector, scope)
+ var value = initial
+ var size = UInt32(MemoryLayout<T>.size)
+ let status = AudioObjectGetPropertyData(object, &address, 0, nil, &size, &value)
+ return status == noErr ? value : nil
+ }
+
+ static func defaultOutputDevice() -> AudioObjectID {
+ value(
+ AudioObjectID(kAudioObjectSystemObject), kAudioHardwarePropertyDefaultOutputDevice,
+ initial: AudioObjectID(kAudioObjectUnknown),
+ ) ?? AudioObjectID(kAudioObjectUnknown)
+ }
+
+ /// The device's figure; the stream latency is the largest of its output
+ /// streams'. Nil when the device does not answer its rate.
+ static func latency(of device: AudioObjectID) -> VPhoneHostAudioLatency? {
+ let output = kAudioObjectPropertyScopeOutput
+ guard let rate = value(device, kAudioDevicePropertyNominalSampleRate, initial: Float64(0)), rate > 0 else {
+ return nil
+ }
+ let streamFrames = outputStreams(of: device)
+ .compactMap { value($0, kAudioStreamPropertyLatency, initial: UInt32(0)) }
+ .max() ?? 0
+ return VPhoneHostAudioLatency(
+ deviceFrames: value(device, kAudioDevicePropertyLatency, output, initial: UInt32(0)) ?? 0,
+ safetyOffsetFrames: value(device, kAudioDevicePropertySafetyOffset, output, initial: UInt32(0)) ?? 0,
+ streamFrames: streamFrames,
+ bufferFrames: value(device, kAudioDevicePropertyBufferFrameSize, initial: UInt32(0)) ?? 0,
+ sampleRate: rate,
+ )
+ }
+
+ private static func outputStreams(of device: AudioObjectID) -> [AudioStreamID] {
+ var address = address(kAudioDevicePropertyStreams, kAudioObjectPropertyScopeOutput)
+ var size: UInt32 = 0
+ guard AudioObjectGetPropertyDataSize(device, &address, 0, nil, &size) == noErr, size > 0 else { return [] }
+ var streams = [AudioStreamID](repeating: 0, count: Int(size) / MemoryLayout<AudioStreamID>.size)
+ guard AudioObjectGetPropertyData(device, &address, 0, nil, &size, &streams) == noErr else { return [] }
+ return Array(streams.prefix(Int(size) / MemoryLayout<AudioStreamID>.size))
+ }
+
+ private static func name(of device: AudioObjectID) -> String? {
+ var address = address(kAudioObjectPropertyName)
+ var name: Unmanaged<CFString>?
+ var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
+ guard AudioObjectGetPropertyData(device, &address, 0, nil, &size, &name) == noErr else { return nil }
+ return name?.takeRetainedValue() as String?
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index 5647b2bb..4717fd2b 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -14,6 +14,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
private var appWindowController: VPhoneAppWindowController?
private var locationProvider: VPhoneLocationProvider?
private var timeZoneSync: VPhoneTimeZoneSync?
+ private var hostAudioLatencySync: VPhoneHostAudioLatencySync?
private var hostAutomationServer: VPhoneHostAutomationServer?
private var cameraServer: VPhoneCameraServer?
private var apiProxy: VPhoneAPIProxy?
@@ -103,6 +104,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
let provider = VPhoneLocationProvider(control: control)
locationProvider = provider
timeZoneSync = VPhoneTimeZoneSync(control: control)
+ hostAudioLatencySync = VPhoneHostAudioLatencySync(control: control)
let camServer = VPhoneCameraServer()
cameraServer = camServer
@@ -216,7 +218,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
menuController = mc
// Wire location toggle through onConnect/onDisconnect
- control.onConnect = { [weak self, weak mc, weak provider = locationProvider, weak timeZoneSync] caps in
+ control.onConnect = { [weak self, weak mc, weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] caps in
mc?.updateConnectAvailability(available: true)
mc?.updateInstallAvailability(available: caps.contains("ipa_install"))
mc?.updateBootstrapAvailability(available: caps.contains("bootstrap_install"))
@@ -242,11 +244,14 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
if caps.contains("timezone") {
timeZoneSync?.start()
}
+ if caps.contains("audio_host_latency") {
+ hostAudioLatencySync?.start()
+ }
Task { @MainActor [weak self] in
await self?.installPackageIfRequested(caps: caps)
}
}
- control.onDisconnect = { [weak mc, weak provider = locationProvider, weak timeZoneSync] in
+ control.onDisconnect = { [weak mc, weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] in
mc?.updateConnectAvailability(available: false)
mc?.updateInstallAvailability(available: false)
mc?.updateBootstrapAvailability(available: false)
@@ -262,10 +267,11 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
provider?.stopForwarding()
mc?.updateLocationCapability(available: false)
timeZoneSync?.stop()
+ hostAudioLatencySync?.stop()
}
} else if !command.dfu {
// Headless mode: auto-start location as before (no menu exists)
- control.onConnect = { [weak self, weak provider = locationProvider, weak timeZoneSync] caps in
+ control.onConnect = { [weak self, weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] caps in
if caps.contains("location") {
provider?.startForwarding()
} else {
@@ -274,14 +280,18 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
if caps.contains("timezone") {
timeZoneSync?.start()
}
+ if caps.contains("audio_host_latency") {
+ hostAudioLatencySync?.start()
+ }
Task { @MainActor [weak self] in
await self?.installPackageIfRequested(caps: caps)
}
}
- control.onDisconnect = { [weak provider = locationProvider, weak timeZoneSync] in
+ control.onDisconnect = { [weak provider = locationProvider, weak timeZoneSync, weak hostAudioLatencySync] in
provider?.stopReplay()
provider?.stopForwarding()
timeZoneSync?.stop()
+ hostAudioLatencySync?.stop()
}
}
@@ -403,6 +413,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
locationProvider?.stopForwarding()
locationProvider?.stopReplay()
timeZoneSync?.stop()
+ hostAudioLatencySync?.stop()
cameraServer?.disconnect()
menuController?.stopBatteryMonitoring()
windowController?.closeForRestart()
@@ -418,6 +429,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
appWindowController = nil
locationProvider = nil
timeZoneSync = nil
+ hostAudioLatencySync = nil
cameraServer = nil
hostAutomationServer = nil
apiProxy = nil