Run a virtual iPhone on an Apple Silicon Mac.
Swift
HomePod audio
Guilherme Rambo79cc81c0f84c
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 085740ea..0fc17666 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,27 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **HomePod audio port (2026-10-22, live routing validation).**+> New `preboot-homepod-exp-audio_product` restores the donor's exact 20-byte+> `/product/product-id` in Preboot through the existing reversible repair+> composition; new HomePod boot trees receive it too. MobileGestalt then resolves+> HomePod mini's native VirtualAudio product 4 instead of the VM's unknown 0.+> `homepod-mini` selects the shared virtio-snd HAL driver, retargeted/resealed+> for tvOS, publishing its output as the native `PuffinOutput` endpoint. It does+> not apply the iPhone 8010 override or VirtualAudio instruction/tuning patches.+> Other presets keep the new identity repair off and TV excludes the driver.+> First live run proves native product 4, B520 tuning selection and driver load;+> routing requires the HomePod-only raw UInt32 `mode/glob/0` custom property.+> The driver advertises this through `cust`, retains the native `defa`/`raww`/+> `tphn`/`meas` mode and reports changes. Corrected build `61d08ba5` routes to+> `PuffinOutput`; six playback cycles have zero starvation/drop counters.+> Final build `b284734a` plays ordinary-session test tones on the Mac's selected+> Studio Display speakers; the owner confirms clear tones.+> Live silence traced to B520 speaker DSP buffer overruns at 44.1 kHz.+> HomePod output now advertises only its 48 kHz wire rate; forcing a 48 kHz+> session removes the errors and produces nonzero PCM in a scoped host tap.+> iPhone/iPad retain their alternate-rate support.+> No new instruction patch. See [native evidence and validation](Guest/homepod_audio.md).+> **HomePod setup completion and controls (2026-10-22, live validation).**> New `system-homepod-exp-setup_bypass` is HomePod-only, restricted to 27.x,> and selected only by `homepod-mini`. It installs the System markerdiff --git a/Research/Firmware/homepod_mini_support.md b/Research/Firmware/homepod_mini_support.mdindex 047d9575..98a2ef6b 100644--- a/Research/Firmware/homepod_mini_support.md+++ b/Research/Firmware/homepod_mini_support.md@@ -41,8 +41,10 @@ family. The HomePod mini uses the existing TVOS-retargeted vphoned executable.`homepod-mini` selects the existing 27 userland/kernel compatibility patchesand vphoned. GPU injection, iPhone audio/camera/sensor/environment hooks,-Apple TV OTA replacement and plain-arm64 TPRO workarounds stay off. HomePod-audio routing and physical accessory transports require separate validation.+Apple TV OTA replacement and plain-arm64 TPRO workarounds stay off. The shared+virtio-snd driver and donor product identity repair now load on HomePod;+[audio routing and live findings](../Guest/homepod_audio.md) track the remaining+output work. Physical accessory transports require separate validation.The new `devicetree-cfw-homepod_product` declaration copies `horseman`,`siri-hub` and app architecture from the actual donor tree, only for B520's@@ -114,8 +116,10 @@ The research VM is `~/.vphone/machines/homepod-mini`. Evidence is retained underprocess lists and boot results); its console is`~/Library/Logs/vphone-launchpad/homepod-mini.log`.-Audio output and microphone capture, Siri, AirPlay playback, activation and-pairing with the Home app have not been validated. The top-cap UI described+Local audio output is verified on the Mac's selected speakers; see+[HomePod audio](../Guest/homepod_audio.md) for the native identity, HAL mode+and 48 kHz endpoint requirements. Microphone capture, Siri, AirPlay playback,+activation and pairing with the Home app have not been validated. The top-cap UI describedbelow replaces the diagnostic framebuffer for interactive HomePod windows.## Top-cap display@@ -179,7 +183,7 @@ Frame generation and native report submission remain Apple's. The adapter usesa signed load command in SoundBoard andpreserves its original entitlements.-The Mac window displays a circular diffuser using runtime-compiled Metal 4+The Mac window defaults to 480 × 480 points and displays a circular diffuser using runtime-compiled Metal 4shaders (with the same shader on the macOS 15 Metal compatibility path). It addsboth guest light layers, blends neighboring emitters through a normalizedtwo-scale point-spread function, attenuates the opaque edge, and draws the@@ -190,7 +194,8 @@ Xcode Metal compiler download is needed to build the application. Delivery keepsin flight at up to 60 Hz, drops intermediate frames, blanks on connection loss,and pauses requests while minimized. No host animation substitutes for output.The accessible +/- controls send consumer volume HID down/up (0xE9/0xEA),-including holds and immediate releases on focus loss. Quick taps last at least+including holds and immediate releases on focus loss. They omit focus rings+while retaining keyboard and accessibility activation. Quick taps last at least700 ms after the guest acknowledges key-down. Timing from the mouse event cancollapse a tap's down/up into adjacent RPCs when input delivery is delayed.This preserves a usable consumer-key hold for instantaneous mouse/AX taps.diff --git a/Research/Guest/homepod_audio.md b/Research/Guest/homepod_audio.mdnew file mode 100644index 00000000..a9f56a0a--- /dev/null+++ b/Research/Guest/homepod_audio.md@@ -0,0 +1,256 @@+# HomePod mini audio through virtio-snd++## Scope and current boundary++This ports the existing iPhone/iPad virtio-snd output transport to HomePod mini+(`AudioAccessory5,1`, B520, HomePod Software 27.0 / 24J361). The host already+configures `VZHostAudioOutputStreamSink`; the missing pieces are guest HAL+publication, tvOS bundle compatibility, and native routing identity. This work+does not add an audio-over-RPC stream or substitute host playback for guest PCM.++The owner authorized live tests. Launchpad installed the final+`2.11.0-local.b284734a`, passed host preflight, and updated `homepod-mini`'s+guest environment. Ordinary AVAudioPlayer playback reaches the Mac's selected+Studio Display speakers, and the owner confirmed **“Yes, clear tones.”**+Native HomePod identity, B520 routing, the tvOS HAL driver and the 48 kHz+physical endpoint are verified. Both 48 kHz and 44.1 kHz source WAVs play+without a preferred-sample-rate override. The earlier failed iterations and+their discriminating probes are retained below.++## Native reveal procedure++The donor filesystem is the already-extracted IPSW image+`.build/homepod-research/043-04683-522.dmg`, mounted read-only for inspection.+`VirtualAudio.plugin/VirtualAudio` SHA-256 is+`fb9a18193dc49b14ef93dd4cc961f36ab4432db2aa55f520fb72665bf2e55774`.++1. Inspect `ProductIDOverride` and the product resolver at `0x26d4ec`, then its+ native product mapping at `0x6ce44`. The existing VM reports native product+ `0`; startup logs select unknown handlers and route the default VAD through+ `Null_Device`. The temporary mobile probe confirms `caulkShortModel=B520`,+ `hw.model=B520AP`, `ProductType=AudioAccessory5,1`, and caulk device class 7,+ but `MGGetProductType=0xe474c033`. Correct model strings alone are insufficient.+2. Read the donor's actual 20-byte `/product/product-id`. In the donor+ libMobileGestalt product table it matches row 17 at `0x1817b4680`; its+ product enum is `0xc79439ac`. `_MGGetProductType` returns the matched row's+ field at offset `0x18`. This comes from the donor tree, not a guessed value+ or a replacement instruction. libMobileGestalt SHA-256 is+ `48385776b53ca8ebc5705dd3d1efa2c5b316a22d5de7ace74c71c108b2df96ba`.+3. Follow the VirtualAudio comparison at `0x6dcd4` through `0x6dce4`: this enum+ maps to native VirtualAudio product **4**. The factory at `0x20063c` sends+ products 4/5 through `0x413698` into the B238 settings implementation at+ `0x40b508`. It reads the short hardware model to find the B520 tunings the+ donor already ships. There is no HomePod use of the iPhone `8010` override.+4. Follow the physical device factory's `PuffinOutput` entry (`0xbf62c`) and+ Puffin output creation (`0x1fed4c`). It requires an output stream and creates+ the built-in speaker port. Publish the existing virtio output under this+ recognized UID. An arbitrary `VPhoneVirtIOSound:0` UID is not that endpoint.+5. Extract HomePod's AudioServerDriver and compare every class/selector used by+ the driver. All nine imported Objective-C classes are exported. The native+ stream sample-rate callback returns `BOOL`, the stream-format initializer+ takes an ASBD pointer, the Boolean control uses a Boolean value, and the+ selector-control setter returns `BOOL`. Those declarations and call sites+ now match. AudioServerDriver SHA-256 is+ `4f380fe557715e18c2bf51259d80f637537d32396a19b5cd5669cfb95fdf37d4`.++REA evidence includes `ev_57bf62b3753a8091e7ca4878988639c3e722480486db12880a57a79dc54313a3`+(product resolver), `ev_2ab6df5ddf4508042cc86b9e0cc85e060b88a7e91125531712a9b0b53adebde1`+(native product mapping), `ev_e1343681ede554b3c1e31304a7e18c2462007a5a28246e9f6b41611f5d4d1609`+(routing factory), `ev_031fc0505e106fc2a833b178bbc8ceab3e632e120cd7cae3edcb05012e557da7`+(B238 settings), `ev_d22194fc9033bb221486cd06fc6817a89125cd5c6745345c004a923d9d4a7681`+(device factory), and `ev_f61b6d22824277dae53b78ba7d327f86ec86644495e86c2b282deb1bfe1bbdc9`+(Puffin output creation). These are reconstructed static control flow. Native+disassembly and exact donor table reads corroborate the steps; they do not+establish successful execution of the changed route.++The ledger, donor hashes, original disassembly, extracted ASD method encodings,+reproducible product-table probe, native diagnostic records, and closed REA+snapshot are retained under `.build/homepod-audio-research/`.++## Implementation++`preboot-homepod-exp-audio_product` copies the validated donor product digest+into the restored Preboot device tree. It is declared, optional, HomePod-only,+27.x-gated, and selected only by `homepod-mini`. It joins the existing Preboot+repair composition and its inverse rather than overwriting unrelated tree+repairs. New boot trees also receive that digest through the HomePod product+patch. The literal donor digest is never embedded in patch logic.++`homepod-mini` also selects the existing `system-virtiosound-cfw-hal_plugin`.+Installation retargets the shared arm64e driver to tvOS, sets its supported+platform metadata to `AppleTVOS`, signs the edited binary and reseals the whole+HAL bundle. iPhone/iPad installation retains the original payload. Deselecting+the driver removes the added bundle; deselecting the identity repair restores+the baseline product property through Preboot repair composition. An older+guest's baseline contains the old virtual product token. A newly restored+guest whose boot-tree product patch already copied the donor token retains+that correct token on repair opt-out; changing that boot-chain choice requires+firmware patching and restore.++The output UID is `PuffinOutput` for exactly `AudioAccessory5,1`, independent of+the iPhone routing override. Existing explicit UID preferences still win. The+shared float PCM, resampler, queue ownership, volume/mute controls, start/stop+drain and idle-timer behavior are reused. HomePod microphone routing is not+ported and its input is not presented as a physical Puffin microphone array.+Apple TV retains its original exclusions; none of the iPhone VirtualAudio+instruction or tuning patches is enabled for HomePod.++HomePod output advertises only its 48 kHz wire rate in both device and stream+formats. The native B520 speaker graph overruns its 1024-frame input at a+44.1 kHz physical rate. CoreAudio converts 44.1 kHz source audio before the+physical endpoint; iPhone/iPad retain the driver's alternate physical rate.++The HomePod cap separately uses a 480 × 480-point default content size and+suppresses volume-button focus rings while retaining keyboard, pointer and+accessibility input semantics.++## Validation++The existing four virtio transport/clock/converter/latency harnesses pass. The+ASD declaration corrections build for arm64e with `-Werror` and verify as a+signed HAL bundle. Xcode MCP builds the enlarged cap and focus-ring changes.+All 65 focused firmware identity, repair composition, platform and preset tests+passed in Xcode. The complete signed VPhone bundle builds and passes strict+signature verification. A copy of the actual stopped guest's Preboot IMG4+passed dry-run, exact 20-byte substitution, metadata preservation and repeated+application checks; the mounted source was read-only and remained untouched.++The actual cap view and Metal 4 renderer also passed a host UI probe at+480 × 480 points: no focus ring while active or focused, named accessibility+buttons, paired Space/Return presses and releases, accessibility activation,+and immediate release on focus loss. The pre-existing Tab chain loses its+explicit next link when attached to an AppKit content view; this change does+not modify keyboard traversal.++### First updated-bundle live findings++The guest answered vphoned after five seconds. A native mobile probe reports+`MGGetProductType=0xc79439ac`, `caulkShortModel=B520`, and+`hw.model=B520AP`. audiomxd reports `ProductID to int is: 4`, loads B520 graph+configurations, initializes VirtualAudio with status 0, and activates the+driver's `PuffinOutput` with its volume and mute controls. It publishes a+`pspk` port for that endpoint.++Route construction then throws `who?` while reading `[mode/glob/0]` from+`PuffinOutput` (`RoutingHandlerUtilities_Aspen.cpp:385`), leaving the aggregate+on `Null_Device`. A temporary AVAudioPlayer probe accepted 48 kHz, 44.1 kHz+and repeated 48 kHz tone playback, but reported an empty output route; the+virtio log contains no output writes. Those API success values do not establish+sound. This identified the next property contract to repair.++The native remote-property callback at `0x25784c` reads a four-byte UInt32+(`0x257988…0x2579d0`), then throws at source line 385 on a failed read or+incorrect size. B238 constructs the `mode/glob/0` property at `0x4149c8` and+`0x414a3c` with synchronous updates. Its desired values are the native FourCCs+`defa` (`0x40e220`), `raww` (`0x40e26c`), `tphn` (`0x40e2b8`) and `meas`+(`0x40e304`). The driver now exposes this raw-byte custom property only on+HomePod output, appends its 12-byte `{mode, raww, 0}` descriptor to the inherited `cust` list,+preserves synchronous readback atomically, rejects other modes, and notifies+through the verified `ASDPlugin changedProperty:forObject:` method. This+represents physical processing-mode selection; it does not apply board DSP in+the host transport.+The native ASD `addCustomProperty:` rejects a zero payload data type; its+`cust` getter emits `raww` without translating it to the public SDK's zero+`None` value (`ASDObject` `0x1a93d9398…0x1a93d93c0`). No new private class+initializer or property callback subclass is needed.++### Corrected mode-property live findings++Launchpad installed `2.11.0-local.61d08ba5` and updated only `homepod-mini`;+the library default remains 2.10.1. The guest answered vphoned after five+seconds. After a diagnostic audiomxd restart (PID 184), the driver receives+`mode/glob/0` queries and native routing builds a `PuffinOutput` aggregate.+AVAudioPlayer reports a real `Speaker` output with UID `PuffinOutput` for+48 kHz, 44.1 kHz and repeated 48 kHz source WAV files. The HAL selects+44.1 kHz for this playback category; the existing converter produces 48 kHz+virtio output. This verifies both source formats, not a forced switch of the+physical device to both nominal rates.++Two three-tone runs completed six separate start/stop cycles. Their stream+summaries report 56, 64, 58, 55, 63 and 59 writes respectively, with **zero+starved and zero bytes dropped in every cycle**. The short-run host-rate+estimate varies, so these counters do not establish long-duration clock+accuracy. The guest's software volume control accepts 0.35 and was restored+to its original 0.53; its route remains `PuffinOutput`. audiomxd is still+running as PID 184 after both runs, and no audiomxd report appears in the+mobile CrashReporter inventory. This iteration still lacked host listening+confirmation. The Mac output was unmuted at 3%; the host volume+was not changed. The temporary playback job, binary and result were removed+after preserving the host evidence, and guest volume was restored to 0.53.++Evidence: `live-mode-{install,update}.log`, `live-mode-boot.json`,+`live-mode-play-results.json`, `live-mode-repeat-driver.json`,+`live-mode-repeat-volume.json`, and `live-mode-audiomxd-service.json` under+`.build/homepod-audio-research/`.++### Silence diagnosis and 48 kHz endpoint correction++The owner reported no audible tones. Guest transfer counters alone had been+insufficient: the captured native `b520_speaker_general` graph logs contain+315 buffer overruns in the first run and 435 in the repeat. Each attempts to+copy 4,460 bytes from a 4,096-byte buffer (`Utils.cpp:517`). This is 1,115+Float32 frames, the rounded 1024 × 48000/44100 conversion. Mute and policy+mute were cleared; the driver gain was 1. The source WAV sample rate had not+changed the 44.1 kHz physical rate.++A temporary probe explicitly requested a 48 kHz AVAudioSession before+activation. All three source WAVs then report `sessionSampleRate=48000`,+native DSP buffer errors drop to zero, and virtio reports 63/59/54 writes with+zero starvation and drops. A private CoreAudio process tap captured only+`vphone-vm` and its virtualization service, with `CATapUnmuted`, preserving+normal playback. Over 30 seconds it measured 1,139,358 nonzero Float32 samples,+peak 0.00630998 and RMS 0.00211070. The tap and temporary aggregate were+destroyed afterward. This establishes nonzero PCM reaching the Mac audio+service for that explicitly configured session.++The driver now withholds the 44.1 kHz physical format only for HomePod output,+so an ordinary session cannot select the failing rate. It leaves iPhone/iPad+rate support and HomePod input unchanged. The finished bundle builds and+passes strict signature verification. The subsequent ordinary-session test+below verifies the permanent change. Evidence:+`silence-dsp-findings.md`, `live-force-48k-{results,syslog,driver}.json`, and+`host-tap-48k.log` in the evidence directory.++### Final ordinary-session playback++Final build `2.11.0-local.b284734a` boots to vphoned after five seconds. The+driver advertises `48000 Hz nominal (48000 wire, 0 advertised too)` for+`PuffinOutput`. The unmodified playback-session policy selects 48 kHz for+48/44.1/48 kHz source WAVs; every run reports a `Speaker` output with UID+`PuffinOutput`. There is no `setPreferredSampleRate:` call in this final probe.+Its three start/stop summaries show 58/54/63 writes, zero starved buffers and+zero dropped bytes. A repeat exercises the same path after stopping.++The VM-scoped host tap measures 1,153,218 nonzero Float32 samples over about+12 seconds of tone content, peak 0.00630807 and RMS 0.00230651. CoreAudio+identifies the active output of the virtualization process as **Studio+Display Speakers**. The owner confirms clear tones on that output at their+chosen 31% Mac volume. The tap's simple zero-crossing statistic is affected by+low-level DSP output and is not used as a pitch measurement.++The full-level unified log reached its 5,000-entry cap, so its zero matching+DSP overruns is only a bounded observation. A separate error-level repeat+was interrupted by an unrelated host console auto-scroll crash; no complete+error log is claimed for that repeat. The crash stack reaches+`VPhoneConsoleView.scrollToNewest` during a SwiftUI table update. The owner+explicitly deferred this crash, and console code is unchanged. The temporary probe job and files are+removed after host evidence is retained. The host tap and private aggregate+are destroyed at probe exit. The research VM remains on the final bundle;+the library default and other VMs retain their prior bundles.+After the deferred console crash, the same bundle booted again to vphoned+after four seconds. All three temporary probe paths were confirmed absent,+and `audio.state` reported an unmuted Audio/Video volume of 0.63. Evidence is+in `live-cleanup-boot.json` and `live-final-audio-state.json`.++Final evidence: `live-fixed-rate-{install,update}.log`,+`live-fixed-rate-boot.json`, `live-default-final-{results,driver,syslog}.json`,+`host-tap-default-final.log`, and `host-processes-default-final.json`.++### Coverage limits++This validates local output, two source sample rates, repeated playback and+the observed software-volume path. It does not validate long-duration clock+accuracy, every native mode/category, HomePod microphone routing, Siri,+AirPlay, or Home pairing. Identity/driver selection and the shared Preboot+inverse are covered by preset/repair tests and an actual Preboot-copy smoke;+live opt-out/re-enable cycling has not been performed.diff --git a/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift b/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swiftindex ab0becd0..cf195363 100644--- a/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift+++ b/VPhoneDaemon/Daemon/GuestVirtualAudioProduct.swift@@ -47,7 +47,8 @@ enum GuestVirtualAudioProduct {}/// The same answer as the plugin's `VPGuestProductID`: 8010 on an iPad or- /// iPhone guest, 0 (none) on anything else, unless one was chosen.+ /// iPhone guest, 0 (no override) on anything else, unless one was chosen.+ /// HomePod mini keeps native routing through its donor product identity.static func product(machine: String, chosen: Int?) -> Int {if let chosen, chosen >= 0 {return chosendiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex 81f901d1..d13351eb 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -126,6 +126,28 @@ public enum CustomFirmwarePostRestoreDeviceTree {}}+ /// Restore only the HomePod mini donor's native MobileGestalt audio product+ /// token, keeping personalized IMG4 data and the payload compression.+ @discardableResult+ public static func presentHomePodAudioProduct(+ at url: URL,+ board boardURL: URL,+ dryRun: Bool = false,+ verbose: Bool = true,+ ) throws -> Outcome {+ let boardData: Data+ do {+ boardData = try Data(contentsOf: boardURL)+ } catch {+ throw PatcherError.fileNotFound(boardURL.path)+ }+ let board = try openDeviceTree(boardData, path: boardURL.path).blob+ return try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in+ let (newBlob, changes, delta) = try withHomePodAudioProduct(blob, board: board)+ return (newBlob, changes, blob.count + delta)+ }+ }+/// Remove `/product/haptics` from a guest's `devicetree.img4` (or bare/// `.im4p`), in place. See `DeviceTreePatcher.removeHaptics(from:)`.@discardableResult@@ -407,6 +429,17 @@ public enum CustomFirmwarePostRestoreDeviceTree {return (serializeNode(root), records, delta)}+ public static func withHomePodAudioProduct(_ blob: Data, board: Data) throws -> (Data, [Change], Int) {+ let root = try parseTree(blob, label: "DT")+ let source = try parseTree(board, label: "HomePod board DT")+ guard let change = try DeviceTreePatcher.presentHomePodAudioProduct(in: root, from: source) else {+ return (blob, [], 0)+ }+ let record = Change(property: "product/product-id", before: change.before?.hex ?? "absent", after: change.after.hex)+ let delta = align4(change.after.count) - (change.before.map { align4($0.count) } ?? -36)+ return (serializeNode(root), [record], delta)+ }+/// `blob` without `/product/haptics`, through/// `DeviceTreePatcher.removeHaptics(from:)`, which fw patch uses for every/// new guest. Returns the size change with the changes, as `withBoardAudio`diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex 992d31a4..8bee2b1f 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -37,6 +37,7 @@// server the node promises. See `removeHaptics(from:)`.import Foundation+import Img4toolimport VPhoneCoreKitimport VPhonePatchKit@@ -184,6 +185,8 @@ extension DeviceTreePatcher {edits.append(GuestEdit(nodePath: product, property: name,action: action, patchID: homePodProductPatch))}+ edits.append(GuestEdit(nodePath: product, property: "product-id",+ action: .set(try homePodAudioProductID(from: source)), patchID: homePodProductPatch))}for (name, patchID) in copiedProductProperties {@@ -243,6 +246,67 @@ extension DeviceTreePatcher {// MARK: - Audio+ /// MobileGestalt matches this exact 20-byte donor token against its product+ /// table; VirtualAudio uses that result to select the HomePod mini's enum 4+ /// routing. Root model strings alone do not select the native audio family.+ /// Accept a retained donor IM4P or its decoded flat payload, never a payload+ /// invented from the product name or an iPhone ProductIDOverride.+ public static func homePodAudioProductID(from data: Data) throws -> Data {+ let payload: Data+ if let im4p = try? IM4P(data) {+ guard im4p.fourcc == "dtre", !im4p.isEncrypted else {+ throw PatcherError.invalidFormat("HomePod audio product: expected an unencrypted dtre IM4P")+ }+ payload = try im4p.payload()+ } else {+ payload = data+ }+ let parser = DeviceTreePatcher(data: payload, verbose: false)+ return try homePodAudioProductID(from: parser.parsePayload(payload))+ }++ private static func requireHomePodMini(_ root: DTNode) throws {+ let models = root.properties.filter { $0.name == "model" }+ guard models.count == 1, let model = models.first, model.flags == 0,+ String(decoding: model.value.prefix { $0 != 0 }, as: UTF8.self) == "AudioAccessory5,1"+ else {+ throw PatcherError.invalidFormat("HomePod audio product: expected the AudioAccessory5,1 board tree")+ }+ }++ static func homePodAudioProductID(from source: DTNode) throws -> Data {+ try requireHomePodMini(source)+ let product = try child(of: source, named: "product")+ let properties = product.properties.filter { $0.name == "product-id" }+ guard properties.count == 1, let property = properties.first,+ property.flags == 0, property.value.count == 20+ else {+ throw PatcherError.invalidFormat("HomePod audio product: donor product-id must be one concrete 20-byte value")+ }+ return property.value+ }++ /// Replace only the HomePod's audio product token. The Preboot repair uses+ /// this independently of the board-audio-node repair and keeps the VM's+ /// virtual audio hardware and unrelated product capabilities unchanged.+ static func presentHomePodAudioProduct(in root: DTNode, from source: DTNode) throws -> (before: Data?, after: Data)? {+ try requireHomePodMini(root)+ let value = try homePodAudioProductID(from: source)+ let product = try child(of: root, named: "product")+ guard product.properties.filter({ $0.name == "product-id" }).count <= 1 else {+ throw PatcherError.invalidFormat("HomePod audio product: installed product-id is duplicated")+ }+ if let existing = product.properties.first(where: { $0.name == "product-id" }) {+ guard existing.value != value || existing.flags != 0 else { return nil }+ let before = existing.value+ existing.value = value+ existing.flags = 0+ return (before, value)+ }+ product.properties.append(DTProperty(name: "product-id", flags: 0, value: value, valueOffset: 0))+ return (nil, value)+ }+/// What `presentBoardAudio` changed: the audio node's serialized bytes/// before and after, empty when there was no node.struct BoardAudioChange {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swiftindex f0fd4ff2..268dcd30 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareDeviceTreePatchSet.swift@@ -218,7 +218,7 @@ public enum FirmwareDeviceTreePatchSet {property("devicetree-cfw-homepod_product","HomePod product capabilities",- "Copies the HomePod mini's horseman, siri-hub and app architecture properties from its own board tree, so MobileGestalt recognizes an audio accessory. Other boards and the restore tree are unchanged.",+ "Copies the HomePod mini's horseman, siri-hub, app architecture and concrete 20-byte product-id properties from its own board tree, so MobileGestalt recognizes the accessory and selects its native audio family. Other boards and the restore tree are unchanged.",),// MARK: TV Guestdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftindex f59d56f2..87cc610e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -51,7 +51,8 @@ public enum FirmwareGuestPatchResolution {/// Apple TV OTA swap, GPU injection, or plain-arm64 dyld workarounds.public static let homePodSupportedGuestPatches = tvSupportedGuestPatches.subtracting([FirmwareGuestSystemPatchSet.tvTPRO])- .union([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])+ .union([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass,+ FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.virtioSoundDriver]).union(FirmwarePatchSetCatalog.tvOS27UserlandPatches)public static func unvalidatedHomePodGuestPatches(enabled: Set<String>) -> [String] {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 34db9401..e8f0845e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -492,6 +492,13 @@ public enum FirmwareGuestSystemPatchSet {""",target: .prebootDeviceTree,),+ VPhonePatchDeclaration(+ identifier: homePodAudioProduct,+ title: "HomePod native audio identity",+ summary: "Copies the HomePod mini donor's concrete 20-byte product-id into its installed Preboot device tree. MobileGestalt then selects the native HomePod audio family instead of the virtual phone's, without an iPhone ProductIDOverride. Rebuilt from the shared Preboot repair backup when disabled.",+ target: .prebootDeviceTree,+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),+ ),VPhonePatchDeclaration(identifier: prebootIPhoneProduct,title: "iPhone product description",@@ -590,6 +597,7 @@ public enum FirmwareGuestSystemPatchSet {public static let homePodSetupPath = "/usr/share/vphone/HomePodSetup.plist"public static let prebootBoardAudio = "preboot-cfw-devicetree_board_audio"+ public static let homePodAudioProduct = "preboot-homepod-exp-audio_product"/// The iPhone product description in the restored Preboot device tree,/// taken from the iPhone's own tree: see `DeviceTreePatcher.presentPhoneProduct`.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 0e5da88d..b867110c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -61,7 +61,7 @@ public enum FirmwarePatchSetCatalog {Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier)).union(hypervisorConcealmentPatches).union(experimentalIdentityPatches)- .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])+ .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct]).union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland])/// ProMotion: the 120 Hz timing for the paravirtual display.@@ -219,7 +219,7 @@ public enum FirmwarePatchSetCatalog {freshly restored 26.4 guest does not survive. The HomePod-only top cap is off.""",patchSets: bundledReferences,- selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass]),+ selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct]),)/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no@@ -317,15 +317,16 @@ public enum FirmwarePatchSetCatalog {/// HomePod mini uses its own monolithic arm64e TVOS IPSW. Keep the 27/// kernel compatibility patches, but never swap in an Apple TV OTA or- /// install the iPhone GPU/audio environment on this headless accessory.+ /// install the iPhone GPU/routing environment. The shared virtio audio+ /// driver uses HomePod's own product identity and routing implementation.public static let homePodMiniPreset = VPhonePatchPreset(identifier: VPhonePatchPreset.homePodMiniIdentifier,title: "HomePod mini",- summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap and local setup completion, without Apple TV OTA replacement or iPhone display, camera and audio hooks.",+ summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion and virtio audio using its native identity, without Apple TV OTA replacement or iPhone display, camera and routing hooks.",patchSets: bundledReferences,selection: .block(- manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])- .union(tvOSBlockedPatches.subtracting(tvOS27UserlandPatches)),+ manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct])+ .union(tvOSBlockedPatches.subtracting(tvOS27UserlandPatches).subtracting([FirmwareGuestSystemPatchSet.virtioSoundDriver])),),)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swiftindex 2abbbeb3..e8b5d0da 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/DeviceTreeGuestDeviceTests.swift@@ -186,6 +186,7 @@ struct DeviceTreeGuestDeviceTests {.string("fdr-product-type", model),.string("sub-product-type", model),.string("unique-model", "B520AP"),+ Property(name: "product-id", flags: 0, value: Data(base64Encoded: "l2aw/kQAaW9zNqWJvWMfJJjJKt0=")!),placeholderCapabilities ? .placeholder("horseman", "hrsm"): .integer("horseman", 1),placeholderCapabilities ? .placeholder("siri-hub", "shub")@@ -329,7 +330,9 @@ struct DeviceTreeGuestDeviceTests {#expect(hub.0 == 0 && hub.1.isEmpty)#expect(Self.string(product["app-macho-architecture"]) == "arm64")#expect(product["app-macho-architecture"]?.0 == 0)- #expect(records.filter { $0.patchID == DeviceTreePatcher.homePodProductPatch }.count == 3)+ #expect(product["product-id"]?.1 == Data(base64Encoded: "l2aw/kQAaW9zNqWJvWMfJJjJKt0="))+ #expect(product["product-id"]?.0 == 0)+ #expect(records.filter { $0.patchID == DeviceTreePatcher.homePodProductPatch }.count == 4)#expect(!records.contains { $0.patchID == DeviceTreePatcher.tvAppArchitecturePatch })// Restore sees the same virtual board and product as before HomePod support.let restore = DeviceTreePatcher(@@ -357,7 +360,7 @@ struct DeviceTreeGuestDeviceTests {patcher.gate = VPhonePatchGate(declared: declared, enabled: declared.subtracting([identifier]))let records = try patcher.findAll()let product = try #require(Self.read(patcher.patchedData)["device-tree/product"])- for name in ["horseman", "siri-hub", "app-macho-architecture"] {+ for name in ["horseman", "siri-hub", "app-macho-architecture", "product-id"] {#expect(product[name] == nil)}#expect(!records.contains { $0.patchID == identifier })diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swiftindex 6cbab839..f7507e4c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift@@ -175,3 +175,119 @@ struct HomePodDisplayMetadataTests {}}}++@Suite("HomePod native audio product identity")+struct HomePodAudioProductTests {+ private typealias Node = FlatDeviceTreeNode++ // B520AP / AudioAccessory5,1 27.0 (24J361) /product/product-id.+ // MobileGestalt table row 17 maps these bytes to 0xc79439ac; VirtualAudio+ // maps that to its native enum 4. Runtime code always reads the donor.+ private static let donorID = Data(base64Encoded: "l2aw/kQAaW9zNqWJvWMfJJjJKt0=")!+ private static let virtualID = Data(repeating: 0xA5, count: 20)++ private static func tree(model: String = "AudioAccessory5,1", token: Data? = donorID,+ flags: UInt16 = 0, acousticID: UInt32 = 0) -> Data {+ var properties: [(String, Data)] = [("graphics-featureset-class", Data("APPLE7\0".utf8))]+ if let token { properties.append(("product-id", token)) }+ return Node("device-tree", [("model", Data((model + "\0").utf8))], children: [+ Node("product", properties, flags: ["product-id": flags], children: [+ Node("audio", [("acoustic-id", Node.uint32(acousticID))]),+ ]),+ Node("arm-io", [("virtual-hardware", Node.uint32(1))]),+ ]).serialized+ }++ @Test func `copies exactly the donor token and leaves virtual audio hardware unchanged`() throws {+ let original = Self.tree(token: Self.virtualID)+ let board = Self.tree(acousticID: 99)+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(original, board: board)+ #expect(patched == Self.tree())+ #expect(delta == 0 && patched.count == original.count)+ #expect(changes.map(\.property) == ["product/product-id"])+ #expect(changes.first?.before == Self.virtualID.map { String(format: "%02x", $0) }.joined())+ #expect(try DeviceTreePatcher.homePodAudioProductID(from: patched) == Self.donorID)+ let (again, noChanges, noDelta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(patched, board: board)+ #expect(again == patched && noChanges.isEmpty && noDelta == 0)+ }++ @Test func `adds a missing token and clears only its placeholder flag`() throws {+ let board = Self.tree()+ let missing = Self.tree(token: nil)+ let (added, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(missing, board: board)+ #expect(added == board && delta == 56 && changes.first?.before == "absent")+ let placeholder = Self.tree(token: Self.donorID, flags: 0x8000)+ let (filled, flaggedChanges, flaggedDelta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(placeholder, board: board)+ #expect(filled == board && flaggedChanges.count == 1 && flaggedDelta == 0)+ }++ @Test func `rejects uninspected families malformed and unresolved donor tokens`() throws {+ let original = Self.tree(token: Self.virtualID)+ for donor in [Self.tree(model: "iPhone17,3"), Self.tree(model: "AudioAccessory6,1"),+ Self.tree(token: nil), Self.tree(token: Data(repeating: 0, count: 19)),+ Self.tree(token: Data(repeating: 0, count: 21)), Self.tree(flags: 0x8000)] {+ #expect(throws: (any Error).self) {+ try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(original, board: donor)+ }+ #expect(throws: (any Error).self) { try DeviceTreePatcher.homePodAudioProductID(from: donor) }+ }+ for model in ["iPhone99,11", "iPhone17,3", "AppleTV14,1", "AudioAccessory6,1"] {+ #expect(throws: (any Error).self) {+ try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(Self.tree(model: model), board: Self.tree())+ }+ }+ let duplicate = Node("device-tree", [("model", Data("AudioAccessory5,1\0".utf8))], children: [+ Node("product", [("product-id", Self.donorID), ("product-id", Self.donorID)]),+ ]).serialized+ #expect(throws: (any Error).self) { try DeviceTreePatcher.homePodAudioProductID(from: duplicate) }+ #expect(throws: (any Error).self) {+ try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(duplicate, board: Self.tree())+ }+ }++ @Test func `shared repair backup composes audio node and identity independently in both directions`() throws {+ let backup = Self.tree(token: Self.virtualID)+ let board = Self.tree(acousticID: 99)+ let (audioOnly, _, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(backup, board: board)+ let (both, _, _) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(audioOnly, board: board)+ #expect(both == board)+ // Opt out of identity: rebuild from the same clean inverse and keep the+ // still-selected audio-node repair. No previous repaired output is its own inverse.+ let (identityOff, _, _) = try CustomFirmwarePostRestoreDeviceTree.withBoardAudio(backup, board: board)+ #expect(identityOff == Self.tree(token: Self.virtualID, acousticID: 99))+ let (reenabled, _, _) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(identityOff, board: board)+ #expect(reenabled == both)+ // Opt out of audio-node repair while retaining identity.+ let (audioOff, _, _) = try CustomFirmwarePostRestoreDeviceTree.withHomePodAudioProduct(backup, board: board)+ #expect(audioOff == Self.tree())+ #expect(backup == Self.tree(token: Self.virtualID))+ }++ @Test func `installed IMG4 retains personalized metadata and supports dry run and repeat application`() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let target = directory.appendingPathComponent("devicetree.img4")+ let donor = directory.appendingPathComponent("donor.im4p")+ let oldPayload = Self.tree(token: Self.virtualID)+ let im4p = try IM4P(fourcc: "dtre", description: "HomePod native identity test", payload: oldPayload).data+ let manifest = DERTestEncoder.element(tag: 0xA0, value: Data(repeating: 0x71, count: 47))+ let restoreInfo = DERTestEncoder.element(tag: 0xA1, value: Data(repeating: 0x29, count: 19))+ let original = DERTestEncoder.sequence([DERTestEncoder.ia5String("IMG4"), im4p, manifest, restoreInfo])+ try original.write(to: target)+ try IM4P(fourcc: "dtre", description: "B520 donor", payload: Self.tree()).data.write(to: donor)+ #expect(try DeviceTreePatcher.homePodAudioProductID(from: Data(contentsOf: donor)) == Self.donorID)+ let dry = try CustomFirmwarePostRestoreDeviceTree.presentHomePodAudioProduct(at: target, board: donor, dryRun: true, verbose: false)+ let afterDryRun = try Data(contentsOf: target)+ #expect(!dry.wrote && dry.changes.count == 1 && afterDryRun == original)+ let applied = try CustomFirmwarePostRestoreDeviceTree.presentHomePodAudioProduct(at: target, board: donor, verbose: false)+ #expect(applied.wrote)+ let output = try Data(contentsOf: target)+ let children = try DERTestEncoder.children(of: output)+ #expect(children[2] == manifest && children[3] == restoreInfo)+ #expect(try IM4P(children[1]).payload() == Self.tree())+ let repeatOutcome = try CustomFirmwarePostRestoreDeviceTree.presentHomePodAudioProduct(at: target, board: donor, verbose: false)+ #expect(!repeatOutcome.wrote && repeatOutcome.changes.isEmpty)+ #expect(try Data(contentsOf: target) == output)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftindex 8729bc44..fe3be52d 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -26,8 +26,8 @@ struct FirmwareGuestPatchResolutionTests {#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true) == [identifier])}- @Test func `HomePod setup bypass is version gated and never selected for other devices`() throws {- let identifier = FirmwareGuestSystemPatchSet.homePodSetupBypass+ @Test(arguments: [FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct])+ func `HomePod optional guest repairs are version gated and never selected for other devices`(identifier: String) throws {for base in ["26.4", "27.0", "27.1"] {for preset in FirmwarePatchSetCatalog.builtInPresets {let plan = try VPhonePatchPlan.resolve(@@ -150,6 +150,32 @@ struct FirmwareGuestPatchResolutionTests {#expect(tv4K.enabled.symmetricDifference(tvHD.enabled) == tpro.union([gpu, ota]))}+ @Test+ func `HomePod audio uses its native identity and shared driver without iPhone routing patches`() throws {+ let driver = FirmwareGuestSystemPatchSet.virtioSoundDriver+ let product = FirmwareGuestSystemPatchSet.homePodAudioProduct+ let plan = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.homePodMiniPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("27.0"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(plan.isEnabled(driver))+ #expect(plan.isEnabled(product))+ #expect(FirmwareGuestPatchResolution.unvalidatedHomePodGuestPatches(enabled: [driver, product]).isEmpty)+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [driver]) == [driver])+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [driver], arm64eUserland: true) == [driver])+ let iPhoneRouting: Set<String> = [+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerRouteThrows,+ FirmwareGuestSystemPatchSet.virtualAudioMuteSetThrow,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerProtectionGate,+ FirmwareGuestSystemPatchSet.virtualAudioVolumeModePrecondition,+ FirmwareGuestSystemPatchSet.virtualAudioGraphConfigurations,+ FirmwareGuestSystemPatchSet.virtualAudioSpeakerRawChains,+ FirmwareGuestSystemPatchSet.virtualAudioMicrophoneChains,+ ]+ #expect(plan.enabled.isDisjoint(with: iPhoneRouting))+ }+@Testfunc `HomePod rejects explicit TV payloads while admitting its daemon and 27 compatibility patches`() {let supported: Set<String> = [diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex edf99e3a..f963463f 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -198,6 +198,7 @@ struct FirmwarePatchSetCatalogTests {FirmwarePatchSetCatalog.manualOnlyPatches.contains($0.identifier)&& $0.identifier != FirmwareGuestSystemPatchSet.homePodTopCap&& $0.identifier != FirmwareGuestSystemPatchSet.homePodSetupBypass+ && $0.identifier != FirmwareGuestSystemPatchSet.homePodAudioProduct&& $0.applicability.matches(iOSBase: version, cloudOS: cloud)}.map(\.identifier))#expect(experimental.enabled.subtracting(standard.enabled) == applicableManual)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex e68c2d4e..d68a88ea 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -206,6 +206,9 @@ struct VPhoneCustomFirmwareInstaller {if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodSetupBypass), device.family != .homePod {throw ValidationError("The HomePod setup-completion patch is supported only for a HomePod guest.")}+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodAudioProduct), device.family != .homePod {+ throw ValidationError("The HomePod audio-product patch is supported only for a HomePod guest.")+ }// Research: an Apple TV 4K userland staged from its OTA, which// `system-tv-exp-ota_userland` puts in place of the restored one.let hasOTAUserland = (try? bundleDirectory.isDirectory(VPhoneOTAArchive.userlandDirectoryName)) == true@@ -266,6 +269,14 @@ struct VPhoneCustomFirmwareInstaller {}try requireFreeSpace(at: [bundlePath, work.url.path])let boardDeviceTree = try stageBoardDeviceTree(in: bundleDirectory, work: work, device: device)+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodAudioProduct) {+ guard let boardDeviceTree else {+ throw ValidationError("HomePod audio identity needs the original board device tree in FirmwareOriginals. Recover it from this VM's IPSW before updating the environment.")+ }+ // Validate the exact donor model and token before cloning or+ // writing any guest filesystem, including malformed/placeholder data.+ _ = try DeviceTreePatcher.homePodAudioProductID(from: Data(contentsOf: boardDeviceTree))+ }let homePodDisplay: Data?if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodTopCap) {guard let boardDeviceTree else {@@ -502,6 +513,9 @@ struct VPhoneCustomFirmwareInstaller {if device.family != .iPhone {notApplicableGuest.insert(FirmwareGuestSystemPatchSet.prebootIPhoneProduct)}+ if device.family != .homePod {+ notApplicableGuest.insert(FirmwareGuestSystemPatchSet.homePodAudioProduct)+ }if !device.usesTVOS {notApplicableGuest.insert(FirmwareGuestSystemPatchSet.tvTPRO)}@@ -1583,7 +1597,7 @@ struct VPhoneCustomFirmwareInstaller {if on(FirmwareGuestSystemPatchSet.virtioSoundDriver) {isolate([FirmwareGuestSystemPatchSet.virtioSoundDriver]) {- try installVirtioSoundDriver(system: system)+ try installVirtioSoundDriver(system: system, work: work, guestDevice: guestDevice)live.insert(FirmwareGuestSystemPatchSet.virtioSoundDriver)}} else {@@ -2510,7 +2524,7 @@ struct VPhoneCustomFirmwareInstaller {/// the kernel driver, AppleVirtIOSound, but no plugin for it, so audiomxd/// has nothing to play through. The bundle is replaced whole; its/// signature seals the binary and Info.plist together.- private func installVirtioSoundDriver(system: VPhoneConfinedDirectory) throws {+ private func installVirtioSoundDriver(system: VPhoneConfinedDirectory, work: WorkDirectory, guestDevice: VPhoneGuestDevice) throws {let name = "VPhoneVirtIOSound.driver"let source = try VPhoneConfinedDirectory(root: VPhoneGuestBinaries.resolve(name).path)let target = "System/Library/Audio/Plug-Ins/HAL/\(name)"@@ -2523,6 +2537,31 @@ struct VPhoneCustomFirmwareInstaller {for file in ["\(target)/Info.plist", "\(target)/_CodeSignature/CodeResources"] {try system.setMode(file, 0o644)}+ if guestDevice.family == .homePod {+ // The shared driver is built for iOS. HomePod's arm64e TVOS ASD+ // has the same verified interfaces, but dyld requires its platform+ // and CFBundle metadata to agree with the loading process.+ let name = "VPhoneVirtIOSound-tvos"+ try work.directory.removeItem(name)+ try system.copyFile(from: "\(target)/VPhoneVirtIOSound", to: name, in: work.directory)+ let staged = work.file(name)+ var data = try Data(contentsOf: staged)+ try MachOBuildPlatform.set(MachOBuildPlatform.tvOS, in: &data)+ try data.write(to: staged)+ try VPhoneSigner.sign(+ fileAt: staged,+ options: .init(identifier: nil, entitlements: nil, mergesExisting: true, style: .appleAdHoc),+ )+ try system.replaceFile("\(target)/VPhoneVirtIOSound", fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)+ let infoPath = "\(target)/Info.plist"+ guard var info = try PropertyListSerialization.propertyList(from: system.readData(infoPath), format: nil) as? [String: Any] else {+ throw ValidationError("The virtio sound driver has no valid bundle metadata.")+ }+ info["CFBundleSupportedPlatforms"] = ["AppleTVOS"]+ try system.writeFile(infoPath, contents: PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0), mode: 0o644, owner: Self.guestOwner)+ try sealGuestBundle(system: system, bundle: target)+ print(" [+] Virtio sound driver retargeted to tvOS")+ }print(" [+] /\(target)")}@@ -2677,6 +2716,15 @@ struct VPhoneCustomFirmwareInstaller {repairGroup.append((FirmwareGuestSystemPatchSet.prebootIPhoneProduct, "patch-dt-iphone-product", [boardDeviceTree.path]))}}+ if guestDevice.family == .homePod {+ // Keep the repair in the inverse composition even with no donor+ // when it is off: restoring the clean backup needs no source tree.+ if enabled(FirmwareGuestSystemPatchSet.homePodAudioProduct), boardDeviceTree == nil {+ throw ValidationError("HomePod audio identity needs its original donor device tree.")+ }+ repairGroup.append((FirmwareGuestSystemPatchSet.homePodAudioProduct, "patch-dt-homepod-audio-product",+ boardDeviceTree.map { [$0.path] } ?? []))+ }repairGroup.append((FirmwareGuestSystemPatchSet.prebootHaptics, "patch-dt-haptics", []))repairGroup.append((FirmwareGuestSystemPatchSet.prebootMicrophoneArray, "patch-dt-microphone-array", []))let repairsOn = repairGroup.filter { enabled($0.id) }@@ -2902,6 +2950,8 @@ struct VPhoneCustomFirmwareInstaller {/// which MobileGestalt reads Siri, Camera Control, the Action Button and the/// model name as absent; `fw patch` does not keep the iPhone17,3's, so it/// always comes from here.+ /// A HomePod mini also needs its donor's native product-id token for audio+ /// routing; its selected repair refuses to proceed without a valid donor.////// The IPSW cache and the VM folder are the caller's, so the search and/// the write run with the caller's credentials, as `cfw install` records@@ -2910,8 +2960,9 @@ struct VPhoneCustomFirmwareInstaller {/// The write still goes through the pinned VM folder, and the tree is then/// staged from there like one `fw patch` kept.///- /// Never fails the run: without the tree only the repair is left out, and- /// that is said in one `[!]` line naming what is missing and the fix.+ /// Recovery itself never fails the run: it reports the missing source and+ /// fix. Selected repairs that require validated donor data check it before+ /// guest filesystem writes.private func recoverBoardDeviceTree(in bundleDirectory: VPhoneConfinedDirectory,restore: VPhoneConfinedDirectory?,@@ -2919,11 +2970,15 @@ struct VPhoneCustomFirmwareInstaller {invokingUser: VPhoneInvokingUser?,) {let device = configuredGuestDevice(in: bundleDirectory) ?? guestDevice(of: restore)- let repair = device.presentsBoard ? FirmwareGuestSystemPatchSet.prebootBoardAudio : FirmwareGuestSystemPatchSet.prebootIPhoneProduct- guard plan?.isEnabled(repair) ?? true else { return }+ let repairs = device.family == .homePod+ ? [FirmwareGuestSystemPatchSet.prebootBoardAudio, FirmwareGuestSystemPatchSet.homePodAudioProduct]+ : [device.presentsBoard ? FirmwareGuestSystemPatchSet.prebootBoardAudio : FirmwareGuestSystemPatchSet.prebootIPhoneProduct]+ guard repairs.contains(where: { plan?.isEnabled($0) ?? true }) else { return }let tree = (device.boardDeviceTreePath as NSString).lastPathComponentlet originals = VPhoneBundleOperations.firmwareOriginalsDirectoryName- let skipped = device.presentsBoard+ let skipped = device.family == .homePod+ ? "[!] HomePod audio identity repair skipped, so native audio routing may not initialize:"+ : device.presentsBoard? "[!] Board audio repair skipped, so this \(device.productType) guest will have no sound:": "[!] iPhone product repair skipped, so this \(device.productType) guest will have no Siri, Camera Control, Action Button or Model Name:"do {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swiftindex 68e48053..af5d284b 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift@@ -491,6 +491,31 @@ struct VPhoneCustomFirmwarePatchBoardAudioCommand: ParsableCommand {}}+// MARK: - patch-dt-homepod-audio-product++struct VPhoneCustomFirmwarePatchHomePodAudioProductCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-dt-homepod-audio-product",+ abstract: "Give a HomePod mini device tree its donor's native audio product identity",+ discussion: "Copies only the concrete 20-byte /product/product-id from the HomePod mini's own DeviceTree IM4P. Refuses other models, placeholders and malformed values; preserves the installed IMG4 manifest, restore info and compression.",+ )++ @Argument(help: "Path to devicetree.img4 or devicetree.im4p", transform: URL.init(fileURLWithPath:))+ var deviceTree: URL++ @Argument(help: "Path to the HomePod mini's DeviceTree.<board>.im4p", transform: URL.init(fileURLWithPath:))+ var board: URL++ @Flag(name: .customLong("dry-run"), help: "Report what would change and exit")+ var dryRun = false++ func run() throws {+ try CustomFirmwarePostRestoreDeviceTree.presentHomePodAudioProduct(+ at: deviceTree, board: board, dryRun: dryRun, verbose: true,+ )+ }+}+// MARK: - patch-dt-iphone-productstruct VPhoneCustomFirmwarePatchIPhoneProductCommand: ParsableCommand {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 3ca3ffa1..33358fc0 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -253,6 +253,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {VPhoneCustomFirmwarePatchCampoEntitlementsCommand.self,VPhoneCustomFirmwarePatchPostRestoreDeviceTreeCommand.self,VPhoneCustomFirmwarePatchBoardAudioCommand.self,+ VPhoneCustomFirmwarePatchHomePodAudioProductCommand.self,VPhoneCustomFirmwarePatchIPhoneProductCommand.self,VPhoneCustomFirmwarePatchHapticsCommand.self,VPhoneCustomFirmwarePatchMicrophoneArrayCommand.self,diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plistindex 26d26fe2..08fb8fe7 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist@@ -89,6 +89,7 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>preboot-homepod-exp-audio_product</string></array></dict></dict>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plistindex 40da7039..7e467865 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist@@ -116,7 +116,6 @@<string>system-paravirt_gpu-cfw-heap_index_offset</string><string>system-systemhook-cfw-metal_cache_reuse</string><string>system-systemversion-cfw-build_version</string>- <string>system-virtiosound-cfw-hal_plugin</string><string>system-virtualaudio-cfw-microphone_graph_chains</string><string>system-virtualaudio-cfw-mute_set_throw</string><string>system-virtualaudio-cfw-speaker_graph_chains</string>@@ -129,7 +128,7 @@</array></dict><key>Summary</key>- <string>Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap and local setup completion, without Apple TV OTA replacement or iPhone display, camera and audio hooks.</string>+ <string>Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion and virtio audio using its native identity, without Apple TV OTA replacement or iPhone display, camera and routing hooks.</string><key>Title</key><string>HomePod mini</string></dict>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex 5d13d5f6..bc88604f 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -69,6 +69,7 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>preboot-homepod-exp-audio_product</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-exp-frida_vm_map_delete_immutable_code</string><string>kernel-exp-hv_vmm</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex 78bc9351..727f3bc7 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -69,6 +69,7 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>preboot-homepod-exp-audio_product</string><string>system-exp-ota_userland</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-cfw-paravirt_gpu_task3</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex 090833df..a37de04a 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -69,6 +69,7 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>preboot-homepod-exp-audio_product</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-cfw-paravirt_gpu_task3</string><string>kernel-exp-frida_vm_map_delete_immutable_code</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swiftindex f6faef8d..90da7327 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift@@ -7,6 +7,8 @@ import VPhoneCoreKit/// from the latest guest frame; this view has no autonomous animation clock.@MainActorfinal class VPhoneHomePodDisplayView: NSView {+ static let defaultContentSize = NSSize(width: 480, height: 480)+enum Control: Hashable {case volumeDowncase volumeUp@@ -62,7 +64,7 @@ final class VPhoneHomePodDisplayView: NSView {required init?(coder: NSCoder) { nil }override var isFlipped: Bool { true }- override var intrinsicContentSize: NSSize { NSSize(width: 360, height: 360) }+ override var intrinsicContentSize: NSSize { Self.defaultContentSize }/// A geometry change invalidates the previous frame. Never retain old LED/// indices against a new device layout, or display a partial snapshot.@@ -146,7 +148,7 @@ private final class VPhoneHomePodCapControl: NSButton {override var acceptsFirstResponder: Bool { true }override var canBecomeKeyView: Bool { true }override var isFlipped: Bool { true }- override var focusRingType: NSFocusRingType { get { .exterior } set {} }+ override var focusRingType: NSFocusRingType { get { .none } set {} }override func hitTest(_ point: NSPoint) -> NSView? {let local = convert(point, from: superview)@@ -210,9 +212,6 @@ private final class VPhoneHomePodCapControl: NSButton {}// Visual markings belong to the optical shader; these views supply native- // button semantics and the system focus ring above the Metal surface.+ // button, keyboard, and accessibility semantics above the Metal surface.override func draw(_ dirtyRect: NSRect) {}-- override func drawFocusRingMask() { NSBezierPath(ovalIn: bounds.insetBy(dx: 2, dy: 2)).fill() }- override var focusRingMaskBounds: NSRect { bounds }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swiftindex 9eef0f1a..cbba6626 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift@@ -57,7 +57,7 @@ class VPhoneVirtualMachineWindowController: NSObject, NSWindowDelegate {view.clipboardSync = VPhoneClipboardSync(control: control)virtualMachineView = viewlet scale = CGFloat(screenScale)- let windowSize = homePodGuest ? NSSize(width: 360, height: 360) : NSSize(+ let windowSize = homePodGuest ? VPhoneHomePodDisplayView.defaultContentSize : NSSize(width: CGFloat(screenWidth) / scale,height: CGFloat(screenHeight) / scale,)diff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.h b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.hindex 5e6e9d3d..dba7da32 100644--- a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.h+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundAudioServerDriver.h@@ -119,6 +119,7 @@ static const ASDStreamDirection ASDStreamDirectionInput = kAudioObjectPropertySc- (void)halInitializeWithPluginHost:(AudioServerPlugInHostRef)host;- (void)addAudioDevice:(id)device;- (NSArray *)audioDevices;+- (void)changedProperty:(const AudioObjectPropertyAddress *)address forObject:(ASDObject *)object;@end/// Signatures from the macOS plugin's block type encodings.@@ -224,8 +225,8 @@ typedef int (^ASDIOBlock)(inScope:(UInt32)scopewithPlugin:(ASDPlugin *)pluginandObjectClassID:(UInt32)classID;-@property (nonatomic, readonly, getter=booleanValue) BOOL booleanValue;-- (void)setValue:(UInt32)value;+@property (nonatomic, readonly) BOOL value;+- (void)setValue:(BOOL)value;/// As `changeDecibelValue:` above, for a set of the control's value.- (BOOL)changeValue:(BOOL)value;@end@@ -246,7 +247,7 @@ typedef int (^ASDIOBlock)(withPlugin:(ASDPlugin *)pluginandObjectClassID:(UInt32)classID;- (void)addValue:(ASDSelectorValue *)value;-- (void)setSelectedValues:(NSArray<ASDSelectorValue *> *)values;+- (BOOL)setSelectedValues:(NSArray<ASDSelectorValue *> *)values;@end@interface ASDAudioDevice (Controls)@@ -254,7 +255,7 @@ typedef int (^ASDIOBlock)(@end@interface ASDStreamFormat : NSObject <NSCopying>-- (instancetype)initWithAudioStreamBasicDescription:(AudioStreamBasicDescription)description;+- (instancetype)initWithAudioStreamBasicDescription:(const AudioStreamBasicDescription *)description;@property (nonatomic) double sampleRate;@property (nonatomic) double minimumSampleRate;@property (nonatomic) double maximumSampleRate;@@ -270,7 +271,7 @@ typedef int (^ASDIOBlock)(@property (copy, nonatomic) ASDIOBlock writeMixBlock;/// Sent to every stream when the device's nominal sample rate changed; the/// default implementation reconciles the physical format with the new rate.-- (void)deviceChangedToSamplingRate:(double)rate;+- (BOOL)deviceChangedToSamplingRate:(double)rate;- (void)startStream;- (void)stopStream;@enddiff --git a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.mindex bd44aac7..b516435e 100644--- a/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m+++ b/VPhoneGuestComponents/VirtIOSound/VPVirtIOSoundPlugin.m@@ -21,7 +21,7 @@// once when audiomxd loads the plugin:// VPhoneVirtIOSoundTransportType four-character transport ("usb ", "bltn")// VPhoneVirtIOSoundDeviceUID speaker device UID (default "PuffinOutput"-// on an iPad or iPhone guest,+// on iPad, iPhone and HomePod mini guests,// "VPhoneVirtIOSound:0" elsewhere)// VPhoneVirtIOSoundInputDeviceUID microphone device UID (default "Digital// Mic" on an iPad or iPhone guest,@@ -263,8 +263,9 @@ static const char *VPMachine(void) {return machine;}-/// The ProductID VirtualAudio should route this guest with, or 0 for a guest-/// the speaker route has not been set up and verified on.+/// A VirtualAudio routing override, or 0 to retain native product selection.+/// HomePod mini selects its own routing from the donor product digest; only+/// its output device UID is adapted below, without using an iPhone override.////// VirtualAudio derives its ProductID from a MobileGestalt class answer, and/// vphone600 lands on a simulator class — 196 presenting an iPad, 195 an@@ -313,6 +314,13 @@ static NSString *VPDeviceUID(ASDStreamDirection direction, unsigned index) {// sub-ports for. Under any name of our own a device is claimed by nothing.// Only where the route is set up: a speaker route on a VirtualAudio that// was not deadlocked audiomxd and crash-looped it across launches.+ // HomePod mini's native B238 routing also claims PuffinOutput. Its+ // ProductID comes from the donor product digest in the installed tree,+ // not the iPhone routing override. Leave its input unclaimed: microphone+ // routing needs the physical array and is not part of this output port.+ if (!input && index == 0 && strcmp(VPMachine(), "AudioAccessory5,1") == 0) {+ return @"PuffinOutput";+ }if (index == 0 && VPGuestProductID() != 0) {return input ? @"Digital Mic" : @"PuffinOutput";}@@ -688,7 +696,7 @@ typedef struct {.mChannelsPerFrame = _format.channels,.mBitsPerChannel = _format.bitsPerChannel,};- ASDStreamFormat *format = [[ASDStreamFormat alloc] initWithAudioStreamBasicDescription:description];+ ASDStreamFormat *format = [[ASDStreamFormat alloc] initWithAudioStreamBasicDescription:&description];format.minimumSampleRate = rate;format.maximumSampleRate = rate;return format;@@ -936,7 +944,7 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI// virtio stream itself stays at the wire rate; the mix resamples. The// current format follows the nominal-rate override so the device boots// already answering 44100, matching how the vdef composes.- if (format.sampleRate == 48000.0) {+ if (self.offersAlternateRate) {ASDStreamFormat *reduced = [self physicalFormatAtRate:kVPAlternateRate];self.physicalFormats = @[self.physicalFormat, reduced];self.physicalFormatSettable = YES;@@ -978,17 +986,28 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UI}- (BOOL)offersAlternateRate {- return _format.sampleRate == 48000.0;+ // B520's speaker DSP requires a 48 kHz physical endpoint. Advertising+ // 44.1 kHz makes its 1024-frame graph read 1115 frames from that buffer,+ // producing silence before the PCM reaches us. Source audio at 44.1 kHz+ // still plays through CoreAudio's converter with the endpoint at 48 kHz.+ return _format.sampleRate == 48000.0 && strcmp(VPMachine(), "AudioAccessory5,1") != 0;}// MARK: Rate changes-- (void)deviceChangedToSamplingRate:(double)rate {+- (BOOL)deviceChangedToSamplingRate:(double)rate {+ // ASD returns YES even when no physical format supports the new rate.+ // Only accept rates this stream actually configured above.+ if (rate != _format.sampleRate && !(rate == kVPAlternateRate && self.offersAlternateRate)) {+ return NO;+ }os_log(VPLog(), "rate-probe: stream %u deviceChangedToSamplingRate %.0f (hal %.0f, format %.0f)",_streamID, rate, (double)atomic_load(&_halRate), self.physicalFormat.sampleRate);VPLogToFile("rate-probe: stream %u deviceChangedToSamplingRate %.0f (hal %.0f, format %.0f)",_streamID, rate, (double)atomic_load(&_halRate), self.physicalFormat.sampleRate);- [super deviceChangedToSamplingRate:rate];+ if (![super deviceChangedToSamplingRate:rate] || self.physicalFormat.sampleRate != rate) {+ return NO;+ }uint32_t previous = atomic_load(&_halRate);if (rate > 0 && (uint32_t)rate != previous) {atomic_store(&_halRate, (uint32_t)rate);@@ -996,6 +1015,7 @@ static void VPWriteCompleted(void *refcon, IOReturn result, void **arguments, UIos_log(VPLog(), "stream %u: device rate %.0f -> %.0f, physical format %.0f Hz",_streamID, (double)previous, rate, self.physicalFormat.sampleRate);}+ return YES;}// MARK: Device commands@@ -1485,8 +1505,13 @@ static void VPCaptureRead(VPCaptureState *capture, void *buffer, UInt32 frameCou// MARK: Rate changes-- (void)deviceChangedToSamplingRate:(double)rate {- [super deviceChangedToSamplingRate:rate];+- (BOOL)deviceChangedToSamplingRate:(double)rate {+ if (rate != _format.sampleRate && !(rate == kVPAlternateRate && self.offersAlternateRate)) {+ return NO;+ }+ if (![super deviceChangedToSamplingRate:rate] || self.physicalFormat.sampleRate != rate) {+ return NO;+ }uint32_t previous = atomic_load(&_capture.halRate);if (rate > 0 && (uint32_t)rate != previous) {atomic_store(&_capture.halRate, (uint32_t)rate);@@ -1495,6 +1520,7 @@ static void VPCaptureRead(VPCaptureState *capture, void *buffer, UInt32 frameCouVPLogToFile("stream %u: device rate %.0f -> %.0f, physical format %.0f Hz",_streamID, (double)previous, rate, self.physicalFormat.sampleRate);}+ return YES;}/// What the reader keeps between the host's capture and the guest's read.@@ -1912,6 +1938,10 @@ static void VPCaptureRead(VPCaptureState *capture, void *buffer, UInt32 frameCou/// control because the control's own value is only reachable through its/// 'bcvl' property, whose getter shape the guest ASD does not publish.UInt32 _muteState;+ /// B520 routing selects a hardware processing mode on PuffinOutput.+ /// The virtual device has no board DSP; retain the requested native mode+ /// as a synchronous HAL property while the host receives ordinary PCM.+ _Atomic UInt32 _homePodMode;/// The speaker's output latency and its parts, on `_latencyQueue`: what/// the stream keeps queued ahead of the host (wire frames), what the/// Mac's output device adds (seconds), and the figure last handed to the@@ -1934,6 +1964,7 @@ static void VPCaptureRead(VPCaptureState *capture, void *buffer, UInt32 frameCou}_connection = connection;_direction = direction;+ atomic_init(&_homePodMode, 'defa');BOOL input = direction == ASDStreamDirectionInput;double sampleRate = 0;@@ -2224,9 +2255,36 @@ static BOOL VPIsDeviceRateAddress(const AudioObjectPropertyAddress *address) {|| address->mElement == 0);}+- (BOOL)isHomePodModeAddress:(const AudioObjectPropertyAddress *)address {+ return _direction == ASDStreamDirectionOutput+ && strcmp(VPMachine(), "AudioAccessory5,1") == 0+ && address->mSelector == 'mode'+ && address->mScope == kAudioObjectPropertyScopeGlobal+ && address->mElement == kAudioObjectPropertyElementMain;+}++/// The HAL host marshals unknown selectors only when 'cust' advertises+/// them. All three fields match AudioServerPlugInCustomPropertyInfo. The+/// guest ASD emits 'raww' for raw payloads and zero for no qualifier; its+/// addCustomProperty: rejects a zero payload type.+typedef struct {+ UInt32 selector;+ UInt32 propertyDataType;+ UInt32 qualifierDataType;+} VPHomePodCustomPropertyInfo;++- (BOOL)isHomePodCustomPropertiesAddress:(const AudioObjectPropertyAddress *)address {+ return _direction == ASDStreamDirectionOutput+ && strcmp(VPMachine(), "AudioAccessory5,1") == 0+ && address->mSelector == 'cust'+ && address->mScope == kAudioObjectPropertyScopeGlobal+ && address->mElement == kAudioObjectPropertyElementMain;+}+- (BOOL)hasProperty:(AudioObjectPropertyAddress *)address {VPLogSelectorQuery("has", address);- if (VPIsDeviceMuteAddress(address, _direction)) {+ if (VPIsDeviceMuteAddress(address, _direction) || [self isHomePodModeAddress:address]+ || [self isHomePodCustomPropertiesAddress:address]) {return YES;}return [super hasProperty:address];@@ -2234,7 +2292,11 @@ static BOOL VPIsDeviceRateAddress(const AudioObjectPropertyAddress *address) {- (BOOL)isPropertySettable:(AudioObjectPropertyAddress *)address {VPLogSelectorQuery("settable", address);- if (VPIsDeviceMuteAddress(address, _direction) || VPIsDeviceRateAddress(address)) {+ if ([self isHomePodCustomPropertiesAddress:address]) {+ return NO;+ }+ if (VPIsDeviceMuteAddress(address, _direction) || VPIsDeviceRateAddress(address)+ || [self isHomePodModeAddress:address]) {return YES;}return [super isPropertySettable:address];@@ -2244,7 +2306,11 @@ static BOOL VPIsDeviceRateAddress(const AudioObjectPropertyAddress *address) {withQualifierSize:(UInt32)qualifierSizeandQualifierData:(const void *)qualifierData {VPLogSelectorQuery("size", address);- if (VPIsDeviceMuteAddress(address, _direction)) {+ if ([self isHomePodCustomPropertiesAddress:address]) {+ return [super dataSizeForProperty:address withQualifierSize:qualifierSize+ andQualifierData:qualifierData] + sizeof(VPHomePodCustomPropertyInfo);+ }+ if (VPIsDeviceMuteAddress(address, _direction) || [self isHomePodModeAddress:address]) {return sizeof(UInt32);}return [super dataSizeForProperty:address withQualifierSize:qualifierSize@@ -2258,6 +2324,32 @@ static BOOL VPIsDeviceRateAddress(const AudioObjectPropertyAddress *address) {andData:(void *)dataforClient:(UInt32)clientID {VPLogSelectorQuery("get", address);+ if ([self isHomePodCustomPropertiesAddress:address]) {+ UInt32 inheritedSize = [super dataSizeForProperty:address withQualifierSize:qualifierSize+ andQualifierData:qualifierData];+ UInt32 requiredSize = inheritedSize + sizeof(VPHomePodCustomPropertyInfo);+ if (dataSize == NULL || *dataSize < requiredSize || data == NULL) {+ return NO;+ }+ UInt32 actualSize = inheritedSize;+ if (inheritedSize != 0 && (![super getProperty:address withQualifierSize:qualifierSize+ qualifierData:qualifierData dataSize:&actualSize andData:data forClient:clientID]+ || actualSize != inheritedSize)) {+ return NO;+ }+ const VPHomePodCustomPropertyInfo mode = {'mode', 'raww', 0};+ memcpy((uint8_t *)data + inheritedSize, &mode, sizeof(mode));+ *dataSize = requiredSize;+ return YES;+ }+ if ([self isHomePodModeAddress:address]) {+ if (dataSize == NULL || *dataSize < sizeof(UInt32) || data == NULL) {+ return NO;+ }+ *(UInt32 *)data = atomic_load(&_homePodMode);+ *dataSize = sizeof(UInt32);+ return YES;+ }if (VPIsDeviceMuteAddress(address, _direction)) {if (dataSize == NULL || *dataSize < sizeof(UInt32)) {return NO;@@ -2298,6 +2390,23 @@ static BOOL VPIsDeviceRateAddress(const AudioObjectPropertyAddress *address) {andData:(const void *)dataforClient:(UInt32)clientID {VPLogSelectorQuery("set", address);+ if ([self isHomePodModeAddress:address]) {+ if (dataSize != sizeof(UInt32) || data == NULL) {+ return NO;+ }+ UInt32 mode = *(const UInt32 *)data;+ if (mode != 'defa' && mode != 'raww' && mode != 'tphn' && mode != 'meas') {+ return NO;+ }+ UInt32 previous = atomic_exchange(&_homePodMode, mode);+ if (previous != mode) {+ [self.plugin changedProperty:address forObject:self];+ VPLogToFile("HomePod speaker mode '%c%c%c%c'",+ (int)(mode >> 24), (int)((mode >> 16) & 0xff),+ (int)((mode >> 8) & 0xff), (int)(mode & 0xff));+ }+ return YES;+ }if (VPIsDeviceMuteAddress(address, _direction)) {if (dataSize < sizeof(UInt32) || data == NULL) {return NO;